net.websocket.frames, util.datetime, util.json, util.prosodyctl, util.rfc6724: Remove...
[prosody.git] / util / sql.lua
1
2 local setmetatable, getmetatable = setmetatable, getmetatable;
3 local ipairs, unpack, select = ipairs, table.unpack or unpack, select; --luacheck: ignore 113
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 local _ENV = nil;
17
18 local column_mt = {};
19 local table_mt = {};
20 local query_mt = {};
21 --local op_mt = {};
22 local index_mt = {};
23
24 local function is_column(x) return getmetatable(x)==column_mt; end
25 local function is_index(x) return getmetatable(x)==index_mt; end
26 local function is_table(x) return getmetatable(x)==table_mt; end
27 local function is_query(x) return getmetatable(x)==query_mt; end
28 local function Integer(n) return "Integer()" end
29 local function String(n) return "String()" end
30
31 local function Column(definition)
32         return setmetatable(definition, column_mt);
33 end
34 local 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 local 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         log("debug", "Connecting to [%s] %s...", params.driver, params.database);
105         local dbh, err = DBI.Connect(
106                 params.driver, params.database,
107                 params.username, params.password,
108                 params.host, params.port
109         );
110         if not dbh then return nil, err; end
111         dbh:autocommit(false); -- don't commit automatically
112         self.conn = dbh;
113         self.prepared = {};
114         local ok, err = self:set_encoding();
115         if not ok then
116                 return ok, err;
117         end
118         local ok, err = self:onconnect();
119         if ok == false then
120                 return ok, err;
121         end
122         return true;
123 end
124 function engine:onconnect()
125         -- Override from create_engine()
126 end
127 function engine:execute(sql, ...)
128         local success, err = self:connect();
129         if not success then return success, err; end
130         local prepared = self.prepared;
131
132         local stmt = prepared[sql];
133         if not stmt then
134                 local err;
135                 stmt, err = self.conn:prepare(sql);
136                 if not stmt then return stmt, err; end
137                 prepared[sql] = stmt;
138         end
139
140         local success, err = stmt:execute(...);
141         if not success then return success, err; end
142         return stmt;
143 end
144
145 local result_mt = { __index = {
146         affected = function(self) return self.__stmt:affected(); end;
147         rowcount = function(self) return self.__stmt:rowcount(); end;
148 } };
149
150 local function debugquery(where, sql, ...)
151         local i = 0; local a = {...}
152         log("debug", "[%s] %s", where, sql:gsub("%?", function () i = i + 1; local v = a[i]; if type(v) == "string" then v = ("%q"):format(v); end return tostring(v); end));
153 end
154
155 function engine:execute_query(sql, ...)
156         if self.params.driver == "PostgreSQL" then
157                 sql = sql:gsub("`", "\"");
158         end
159         local stmt = assert(self.conn:prepare(sql));
160         assert(stmt:execute(...));
161         return stmt:rows();
162 end
163 function engine:execute_update(sql, ...)
164         if self.params.driver == "PostgreSQL" then
165                 sql = sql:gsub("`", "\"");
166         end
167         local prepared = self.prepared;
168         local stmt = prepared[sql];
169         if not stmt then
170                 stmt = assert(self.conn:prepare(sql));
171                 prepared[sql] = stmt;
172         end
173         assert(stmt:execute(...));
174         return setmetatable({ __stmt = stmt }, result_mt);
175 end
176 engine.insert = engine.execute_update;
177 engine.select = engine.execute_query;
178 engine.delete = engine.execute_update;
179 engine.update = engine.execute_update;
180 local function debugwrap(name, f)
181         return function (self, sql, ...)
182                 debugquery(name, sql, ...)
183                 return f(self, sql, ...)
184         end
185 end
186 function engine:debug(enable)
187         self._debug = enable;
188         if enable then
189                 engine.insert = debugwrap("insert", engine.execute_update);
190                 engine.select = debugwrap("select", engine.execute_query);
191                 engine.delete = debugwrap("delete", engine.execute_update);
192                 engine.update = debugwrap("update", engine.execute_update);
193         else
194                 engine.insert = engine.execute_update;
195                 engine.select = engine.execute_query;
196                 engine.delete = engine.execute_update;
197                 engine.update = engine.execute_update;
198         end
199 end
200 function engine:_transaction(func, ...)
201         if not self.conn then
202                 local ok, err = self:connect();
203                 if not ok then return ok, err; end
204         end
205         --assert(not self.__transaction, "Recursive transactions not allowed");
206         local args, n_args = {...}, select("#", ...);
207         local function f() return func(unpack(args, 1, n_args)); end
208         log("debug", "SQL transaction begin [%s]", tostring(func));
209         self.__transaction = true;
210         local success, a, b, c = xpcall(f, debug_traceback);
211         self.__transaction = nil;
212         if success then
213                 log("debug", "SQL transaction success [%s]", tostring(func));
214                 local ok, err = self.conn:commit();
215                 if not ok then return ok, err; end -- commit failed
216                 return success, a, b, c;
217         else
218                 log("debug", "SQL transaction failure [%s]: %s", tostring(func), a);
219                 if self.conn then self.conn:rollback(); end
220                 return success, a;
221         end
222 end
223 function engine:transaction(...)
224         local ok, ret = self:_transaction(...);
225         if not ok then
226                 local conn = self.conn;
227                 if not conn or not conn:ping() then
228                         self.conn = nil;
229                         ok, ret = self:_transaction(...);
230                 end
231         end
232         return ok, ret;
233 end
234 function engine:_create_index(index)
235         local sql = "CREATE INDEX `"..index.name.."` ON `"..index.table.."` (";
236         for i=1,#index do
237                 sql = sql.."`"..index[i].."`";
238                 if i ~= #index then sql = sql..", "; end
239         end
240         sql = sql..");"
241         if self.params.driver == "PostgreSQL" then
242                 sql = sql:gsub("`", "\"");
243         elseif self.params.driver == "MySQL" then
244                 sql = sql:gsub("`([,)])", "`(20)%1");
245         end
246         if index.unique then
247                 sql = sql:gsub("^CREATE", "CREATE UNIQUE");
248         end
249         if self._debug then
250                 debugquery("create", sql);
251         end
252         return self:execute(sql);
253 end
254 function engine:_create_table(table)
255         local sql = "CREATE TABLE `"..table.name.."` (";
256         for i,col in ipairs(table.c) do
257                 local col_type = col.type;
258                 if col_type == "MEDIUMTEXT" and self.params.driver ~= "MySQL" then
259                         col_type = "TEXT"; -- MEDIUMTEXT is MySQL-specific
260                 end
261                 if col.auto_increment == true and self.params.driver == "PostgreSQL" then
262                         col_type = "BIGSERIAL";
263                 end
264                 sql = sql.."`"..col.name.."` "..col_type;
265                 if col.nullable == false then sql = sql.." NOT NULL"; end
266                 if col.primary_key == true then sql = sql.." PRIMARY KEY"; end
267                 if col.auto_increment == true then
268                         if self.params.driver == "MySQL" then
269                                 sql = sql.." AUTO_INCREMENT";
270                         elseif self.params.driver == "SQLite3" then
271                                 sql = sql.." AUTOINCREMENT";
272                         end
273                 end
274                 if i ~= #table.c then sql = sql..", "; end
275         end
276         sql = sql.. ");"
277         if self.params.driver == "PostgreSQL" then
278                 sql = sql:gsub("`", "\"");
279         elseif self.params.driver == "MySQL" then
280                 sql = sql:gsub(";$", (" CHARACTER SET '%s' COLLATE '%s_bin';"):format(self.charset, self.charset));
281         end
282         if self._debug then
283                 debugquery("create", sql);
284         end
285         local success,err = self:execute(sql);
286         if not success then return success,err; end
287         for i,v in ipairs(table.__table__) do
288                 if is_index(v) then
289                         self:_create_index(v);
290                 end
291         end
292         return success;
293 end
294 function engine:set_encoding() -- to UTF-8
295         local driver = self.params.driver;
296         if driver == "SQLite3" then
297                 return self:transaction(function()
298                         if self:select"PRAGMA encoding;"()[1] == "UTF-8" then
299                                 self.charset = "utf8";
300                         end
301                 end);
302         end
303         local set_names_query = "SET NAMES '%s';"
304         local charset = "utf8";
305         if driver == "MySQL" then
306                 local ok, charsets = self:transaction(function()
307                         return self:select"SELECT `CHARACTER_SET_NAME` FROM `information_schema`.`CHARACTER_SETS` WHERE `CHARACTER_SET_NAME` LIKE 'utf8%' ORDER BY MAXLEN DESC LIMIT 1;";
308                 end);
309                 local row = ok and charsets();
310                 charset = row and row[1] or charset;
311                 set_names_query = set_names_query:gsub(";$", (" COLLATE '%s';"):format(charset.."_bin"));
312         end
313         self.charset = charset;
314         log("debug", "Using encoding '%s' for database connection", charset);
315         local ok, err = self:transaction(function() return self:execute(set_names_query:format(charset)); end);
316         if not ok then
317                 return ok, err;
318         end
319
320         if driver == "MySQL" then
321                 local ok, actual_charset = self:transaction(function ()
322                         return self:select"SHOW SESSION VARIABLES LIKE 'character_set_client'";
323                 end);
324                 for row in actual_charset do
325                         if row[2] ~= charset then
326                                 log("error", "MySQL %s is actually %q (expected %q)", row[1], row[2], charset);
327                                 return false, "Failed to set connection encoding";
328                         end
329                 end
330         end
331
332         return true;
333 end
334 local engine_mt = { __index = engine };
335
336 local function db2uri(params)
337         return build_url{
338                 scheme = params.driver,
339                 user = params.username,
340                 password = params.password,
341                 host = params.host,
342                 port = params.port,
343                 path = params.database,
344         };
345 end
346
347 local function create_engine(self, params, onconnect)
348         return setmetatable({ url = db2uri(params), params = params, onconnect = onconnect }, engine_mt);
349 end
350
351 return {
352         is_column = is_column;
353         is_index = is_index;
354         is_table = is_table;
355         is_query = is_query;
356         Integer = Integer;
357         String = String;
358         Column = Column;
359         Table = Table;
360         Index = Index;
361         create_engine = create_engine;
362         db2uri = db2uri;
363 };