util.sql: Call onconnect, provide noop dummy if not set
[prosody.git] / util / sql.lua
1
2 local setmetatable, getmetatable = setmetatable, getmetatable;
3 local ipairs, unpack, select = ipairs, unpack, select;
4 local tonumber, tostring = tonumber, tostring;
5 local assert, xpcall, debug_traceback = assert, xpcall, debug.traceback;
6 local t_concat = table.concat;
7 local s_char = string.char;
8 local log = require "util.logger".init("sql");
9
10 local DBI = require "DBI";
11 -- This loads all available drivers while globals are unlocked
12 -- LuaDBI should be fixed to not set globals.
13 DBI.Drivers();
14 local build_url = require "socket.url".build;
15
16 module("sql")
17
18 local column_mt = {};
19 local table_mt = {};
20 local query_mt = {};
21 --local op_mt = {};
22 local index_mt = {};
23
24 function is_column(x) return getmetatable(x)==column_mt; end
25 function is_index(x) return getmetatable(x)==index_mt; end
26 function is_table(x) return getmetatable(x)==table_mt; end
27 function is_query(x) return getmetatable(x)==query_mt; end
28 function Integer(n) return "Integer()" end
29 function String(n) return "String()" end
30
31 function Column(definition)
32         return setmetatable(definition, column_mt);
33 end
34 function Table(definition)
35         local c = {}
36         for i,col in ipairs(definition) do
37                 if is_column(col) then
38                         c[i], c[col.name] = col, col;
39                 elseif is_index(col) then
40                         col.table = definition.name;
41                 end
42         end
43         return setmetatable({ __table__ = definition, c = c, name = definition.name }, table_mt);
44 end
45 function Index(definition)
46         return setmetatable(definition, index_mt);
47 end
48
49 function table_mt:__tostring()
50         local s = { 'name="'..self.__table__.name..'"' }
51         for i,col in ipairs(self.__table__) do
52                 s[#s+1] = tostring(col);
53         end
54         return 'Table{ '..t_concat(s, ", ")..' }'
55 end
56 table_mt.__index = {};
57 function table_mt.__index:create(engine)
58         return engine:_create_table(self);
59 end
60 function table_mt:__call(...)
61         -- TODO
62 end
63 function column_mt:__tostring()
64         return 'Column{ name="'..self.name..'", type="'..self.type..'" }'
65 end
66 function index_mt:__tostring()
67         local s = 'Index{ name="'..self.name..'"';
68         for i=1,#self do s = s..', "'..self[i]:gsub("[\\\"]", "\\%1")..'"'; end
69         return s..' }';
70 --      return 'Index{ name="'..self.name..'", type="'..self.type..'" }'
71 end
72
73 local function urldecode(s) return s and (s:gsub("%%(%x%x)", function (c) return s_char(tonumber(c,16)); end)); end
74 local function parse_url(url)
75         local scheme, secondpart, database = url:match("^([%w%+]+)://([^/]*)/?(.*)");
76         assert(scheme, "Invalid URL format");
77         local username, password, host, port;
78         local authpart, hostpart = secondpart:match("([^@]+)@([^@+])");
79         if not authpart then hostpart = secondpart; end
80         if authpart then
81                 username, password = authpart:match("([^:]*):(.*)");
82                 username = username or authpart;
83                 password = password and urldecode(password);
84         end
85         if hostpart then
86                 host, port = hostpart:match("([^:]*):(.*)");
87                 host = host or hostpart;
88                 port = port and assert(tonumber(port), "Invalid URL format");
89         end
90         return {
91                 scheme = scheme:lower();
92                 username = username; password = password;
93                 host = host; port = port;
94                 database = #database > 0 and database or nil;
95         };
96 end
97
98 local engine = {};
99 function engine:connect()
100         if self.conn then return true; end
101
102         local params = self.params;
103         assert(params.driver, "no driver")
104         local dbh, err = DBI.Connect(
105                 params.driver, params.database,
106                 params.username, params.password,
107                 params.host, params.port
108         );
109         if not dbh then return nil, err; end
110         dbh:autocommit(false); -- don't commit automatically
111         self.conn = dbh;
112         self.prepared = {};
113         self:set_encoding();
114         self:onconnect();
115         return true;
116 end
117 function engine:onconnect()
118         -- Override from create_engine()
119 end
120 function engine:execute(sql, ...)
121         local success, err = self:connect();
122         if not success then return success, err; end
123         local prepared = self.prepared;
124
125         local stmt = prepared[sql];
126         if not stmt then
127                 local err;
128                 stmt, err = self.conn:prepare(sql);
129                 if not stmt then return stmt, err; end
130                 prepared[sql] = stmt;
131         end
132
133         local success, err = stmt:execute(...);
134         if not success then return success, err; end
135         return stmt;
136 end
137
138 local result_mt = { __index = {
139         affected = function(self) return self.__stmt:affected(); end;
140         rowcount = function(self) return self.__stmt:rowcount(); end;
141 } };
142
143 function engine:execute_query(sql, ...)
144         if self.params.driver == "PostgreSQL" then
145                 sql = sql:gsub("`", "\"");
146         end
147         local stmt = assert(self.conn:prepare(sql));
148         assert(stmt:execute(...));
149         return stmt:rows();
150 end
151 function engine:execute_update(sql, ...)
152         if self.params.driver == "PostgreSQL" then
153                 sql = sql:gsub("`", "\"");
154         end
155         local prepared = self.prepared;
156         local stmt = prepared[sql];
157         if not stmt then
158                 stmt = assert(self.conn:prepare(sql));
159                 prepared[sql] = stmt;
160         end
161         assert(stmt:execute(...));
162         return setmetatable({ __stmt = stmt }, result_mt);
163 end
164 engine.insert = engine.execute_update;
165 engine.select = engine.execute_query;
166 engine.delete = engine.execute_update;
167 engine.update = engine.execute_update;
168 function engine:_transaction(func, ...)
169         if not self.conn then
170                 local ok, err = self:connect();
171                 if not ok then return ok, err; end
172         end
173         --assert(not self.__transaction, "Recursive transactions not allowed");
174         local args, n_args = {...}, select("#", ...);
175         local function f() return func(unpack(args, 1, n_args)); end
176         self.__transaction = true;
177         local success, a, b, c = xpcall(f, debug_traceback);
178         self.__transaction = nil;
179         if success then
180                 log("debug", "SQL transaction success [%s]", tostring(func));
181                 local ok, err = self.conn:commit();
182                 if not ok then return ok, err; end -- commit failed
183                 return success, a, b, c;
184         else
185                 log("debug", "SQL transaction failure [%s]: %s", tostring(func), a);
186                 if self.conn then self.conn:rollback(); end
187                 return success, a;
188         end
189 end
190 function engine:transaction(...)
191         local ok, ret = self:_transaction(...);
192         if not ok then
193                 local conn = self.conn;
194                 if not conn or not conn:ping() then
195                         self.conn = nil;
196                         ok, ret = self:_transaction(...);
197                 end
198         end
199         return ok, ret;
200 end
201 function engine:_create_index(index)
202         local sql = "CREATE INDEX `"..index.name.."` ON `"..index.table.."` (";
203         for i=1,#index do
204                 sql = sql.."`"..index[i].."`";
205                 if i ~= #index then sql = sql..", "; end
206         end
207         sql = sql..");"
208         if self.params.driver == "PostgreSQL" then
209                 sql = sql:gsub("`", "\"");
210         elseif self.params.driver == "MySQL" then
211                 sql = sql:gsub("`([,)])", "`(20)%1");
212         end
213         if index.unique then
214                 sql = sql:gsub("^CREATE", "CREATE UNIQUE");
215         end
216         --print(sql);
217         return self:execute(sql);
218 end
219 function engine:_create_table(table)
220         local sql = "CREATE TABLE `"..table.name.."` (";
221         for i,col in ipairs(table.c) do
222                 local col_type = col.type;
223                 if col_type == "MEDIUMTEXT" and self.params.driver ~= "MySQL" then
224                         col_type = "TEXT"; -- MEDIUMTEXT is MySQL-specific
225                 end
226                 if col.auto_increment == true and self.params.driver == "PostgreSQL" then
227                         col_type = "BIGSERIAL";
228                 end
229                 sql = sql.."`"..col.name.."` "..col_type;
230                 if col.nullable == false then sql = sql.." NOT NULL"; end
231                 if col.primary_key == true then sql = sql.." PRIMARY KEY"; end
232                 if col.auto_increment == true then
233                         if self.params.driver == "MySQL" then
234                                 sql = sql.." AUTO_INCREMENT";
235                         elseif self.params.driver == "SQLite3" then
236                                 sql = sql.." AUTOINCREMENT";
237                         end
238                 end
239                 if i ~= #table.c then sql = sql..", "; end
240         end
241         sql = sql.. ");"
242         if self.params.driver == "PostgreSQL" then
243                 sql = sql:gsub("`", "\"");
244         elseif self.params.driver == "MySQL" then
245                 sql = sql:gsub(";$", " CHARACTER SET 'utf8' COLLATE 'utf8_bin';");
246         end
247         local success,err = self:execute(sql);
248         if not success then return success,err; end
249         for i,v in ipairs(table.__table__) do
250                 if is_index(v) then
251                         self:_create_index(v);
252                 end
253         end
254         return success;
255 end
256 function engine:set_encoding() -- to UTF-8
257         local driver = self.params.driver;
258         if driver == "SQLite3" then
259                 return self:transaction(function()
260                         if self:select"PRAGMA encoding;"()[1] == "UTF-8" then
261                                 self.charset = "utf8";
262                         end
263                 end);
264         end
265         local set_names_query = "SET NAMES '%s';"
266         local charset = "utf8";
267         if driver == "MySQL" then
268                 set_names_query = set_names_query:gsub(";$", " COLLATE 'utf8_bin';");
269                 local ok, charsets = self:transaction(function()
270                         return self:select"SELECT `CHARACTER_SET_NAME` FROM `information_schema`.`CHARACTER_SETS` WHERE `CHARACTER_SET_NAME` LIKE 'utf8%' ORDER BY MAXLEN DESC LIMIT 1;";
271                 end);
272                 local row = ok and charsets();
273                 charset = row and row[1] or charset;
274         end
275         self.charset = charset;
276         return self:transaction(function() return self:execute(set_names_query:format(charset)); end);
277 end
278 local engine_mt = { __index = engine };
279
280 function db2uri(params)
281         return build_url{
282                 scheme = params.driver,
283                 user = params.username,
284                 password = params.password,
285                 host = params.host,
286                 port = params.port,
287                 path = params.database,
288         };
289 end
290
291 function create_engine(self, params, onconnect)
292         return setmetatable({ url = db2uri(params), params = params, onconnect = onconnect }, engine_mt);
293 end
294
295 return _M;