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