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