Wed, 26 Nov 2008 10:46:42 +0000
Fixed missing return.
1 | 1 | #!/usr/bin/lua |
2 | ||
3 | module('DBI', package.seeall) | |
4 | ||
2 | 5 | -- Driver to module mapping |
1 | 6 | local name_to_module = { |
7 | MySQL = 'dbdmysql', | |
8 | PostgreSQL = 'dbdpostgresql', | |
9 | SQLite3 = 'dbdsqlite3', | |
10 | } | |
11 | ||
12 | local string = require('string') | |
13 | ||
2 | 14 | -- Returns a list of available drivers |
15 | -- based on run time loading | |
1 | 16 | local function available_drivers() |
17 | local available = {} | |
18 | ||
19 | for driver, modulefile in pairs(name_to_module) do | |
20 | local m, err = pcall(require, modulefile) | |
21 | ||
22 | if m then | |
23 | table.insert(available, driver) | |
24 | end | |
25 | end | |
26 | ||
2 | 27 | -- no drivers available |
1 | 28 | if table.maxn(available) < 1 then |
29 | return '(None)' | |
30 | end | |
31 | ||
32 | return table.concat(available, ',') | |
33 | end | |
34 | ||
2 | 35 | -- High level DB connection function |
36 | -- This should be used rather than DBD.{Driver}.New | |
1 | 37 | function Connect(driver, name, username, password, host, port) |
38 | local modulefile = name_to_module[driver] | |
39 | ||
40 | if not modulefile then | |
41 | error(string.format("Driver '%s' not found. Available drivers are: %s", driver, available_drivers())) | |
42 | end | |
43 | ||
44 | local m, err = pcall(require, modulefile) | |
45 | ||
46 | if not m then | |
2 | 47 | -- cannot load the module, we cannot continue |
1 | 48 | error(string.format('Cannot load driver %s. Available drivers are: %s', driver, available_drivers())) |
49 | end | |
50 | ||
51 | local class_str = string.format('DBD.%s.Connection', driver) | |
52 | ||
53 | local connection_class = package.loaded[class_str] | |
54 | ||
2 | 55 | -- Calls DBD.{Driver}.New(...) |
1 | 56 | return connection_class.New(name, username, password, host, port) |
57 | end | |
58 | ||
4 | 59 | -- Help function to do prepare and execute in |
60 | -- a single step | |
3 | 61 | function Do(dbh, sql, ...) |
62 | local sth,err = dbh:prepare(sql) | |
63 | ||
64 | if not sth then | |
65 | return false, err | |
66 | end | |
67 | ||
68 | return sth:execute(...) | |
69 | end |