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