Merge 0.10->trunk
[prosody.git] / plugins / mod_storage_sql.lua
1
2 -- luacheck: ignore 212/self
3
4 local json = require "util.json";
5 local sql = require "util.sql";
6 local xml_parse = require "util.xml".parse;
7 local uuid = require "util.uuid";
8 local resolve_relative_path = require "util.paths".resolve_relative_path;
9
10 local stanza_mt = require"util.stanza".stanza_mt;
11 local getmetatable = getmetatable;
12 local t_concat = table.concat;
13 local function is_stanza(x) return getmetatable(x) == stanza_mt; end
14
15 local noop = function() end
16 local unpack = unpack
17 local function iterator(result)
18         return function(result_)
19                 local row = result_();
20                 if row ~= nil then
21                         return unpack(row);
22                 end
23         end, result, nil;
24 end
25
26 local default_params = { driver = "SQLite3" };
27
28 local engine;
29
30 local function serialize(value)
31         local t = type(value);
32         if t == "string" or t == "boolean" or t == "number" then
33                 return t, tostring(value);
34         elseif is_stanza(value) then
35                 return "xml", tostring(value);
36         elseif t == "table" then
37                 local value,err = json.encode(value);
38                 if value then return "json", value; end
39                 return nil, err;
40         end
41         return nil, "Unhandled value type: "..t;
42 end
43 local function deserialize(t, value)
44         if t == "string" then return value;
45         elseif t == "boolean" then
46                 if value == "true" then return true;
47                 elseif value == "false" then return false; end
48         elseif t == "number" then return tonumber(value);
49         elseif t == "json" then
50                 return json.decode(value);
51         elseif t == "xml" then
52                 return xml_parse(value);
53         end
54 end
55
56 local host = module.host;
57 local user, store;
58
59 local function keyval_store_get()
60         local haveany;
61         local result = {};
62         for row in engine:select("SELECT `key`,`type`,`value` FROM `prosody` WHERE `host`=? AND `user`=? AND `store`=?", host, user or "", store) do
63                 haveany = true;
64                 local k = row[1];
65                 local v = deserialize(row[2], row[3]);
66                 if k and v then
67                         if k ~= "" then result[k] = v; elseif type(v) == "table" then
68                                 for a,b in pairs(v) do
69                                         result[a] = b;
70                                 end
71                         end
72                 end
73         end
74         if haveany then
75                 return result;
76         end
77 end
78 local function keyval_store_set(data)
79         engine:delete("DELETE FROM `prosody` WHERE `host`=? AND `user`=? AND `store`=?", host, user or "", store);
80
81         if data and next(data) ~= nil then
82                 local extradata = {};
83                 for key, value in pairs(data) do
84                         if type(key) == "string" and key ~= "" then
85                                 local t, value = serialize(value);
86                                 assert(t, value);
87                                 engine:insert("INSERT INTO `prosody` (`host`,`user`,`store`,`key`,`type`,`value`) VALUES (?,?,?,?,?,?)", host, user or "", store, key, t, value);
88                         else
89                                 extradata[key] = value;
90                         end
91                 end
92                 if next(extradata) ~= nil then
93                         local t, extradata = serialize(extradata);
94                         assert(t, extradata);
95                         engine:insert("INSERT INTO `prosody` (`host`,`user`,`store`,`key`,`type`,`value`) VALUES (?,?,?,?,?,?)", host, user or "", store, "", t, extradata);
96                 end
97         end
98         return true;
99 end
100
101 --- Key/value store API (default store type)
102
103 local keyval_store = {};
104 keyval_store.__index = keyval_store;
105 function keyval_store:get(username)
106         user, store = username, self.store;
107         local ok, result = engine:transaction(keyval_store_get);
108         if not ok then
109                 module:log("error", "Unable to read from database %s store for %s: %s", store, username or "<host>", result);
110                 return nil, result;
111         end
112         return result;
113 end
114 function keyval_store:set(username, data)
115         user,store = username,self.store;
116         return engine:transaction(function()
117                 return keyval_store_set(data);
118         end);
119 end
120 function keyval_store:users()
121         local ok, result = engine:transaction(function()
122                 return engine:select("SELECT DISTINCT `user` FROM `prosody` WHERE `host`=? AND `store`=?", host, self.store);
123         end);
124         if not ok then return ok, result end
125         return iterator(result);
126 end
127
128 --- Archive store API
129
130 -- luacheck: ignore 512 431/user 431/store
131 local map_store = {};
132 map_store.__index = map_store;
133 map_store.remove = {};
134 function map_store:get(username, key)
135         local ok, result = engine:transaction(function()
136                 if type(key) == "string" and key ~= "" then
137                         for row in engine:select("SELECT `type`, `value` FROM `prosody` WHERE `host`=? AND `user`=? AND `store`=? AND `key`=?", host, username or "", self.store, key) do
138                                 return deserialize(row[1], row[2]);
139                         end
140                 else
141                         for row in engine:select("SELECT `type`, `value` FROM `prosody` WHERE `host`=? AND `user`=? AND `store`=? AND `key`=?", host, username or "", self.store, "") do
142                                 local data = deserialize(row[1], row[2]);
143                                 return data and data[key] or nil;
144                         end
145                 end
146         end);
147         if not ok then return nil, result; end
148         return result;
149 end
150 function map_store:set(username, key, data)
151         if data == nil then data = self.remove; end
152         return self:set_keys(username, { [key] = data });
153 end
154 function map_store:set_keys(username, keydatas)
155         local ok, result = engine:transaction(function()
156                 for key, data in pairs(keydatas) do
157                         if type(key) == "string" and key ~= "" then
158                                 engine:delete("DELETE FROM `prosody` WHERE `host`=? AND `user`=? AND `store`=? AND `key`=?",
159                                         host, username or "", self.store, key);
160                                 if data ~= self.remove then
161                                         local t, value = assert(serialize(data));
162                                         engine:insert("INSERT INTO `prosody` (`host`,`user`,`store`,`key`,`type`,`value`) VALUES (?,?,?,?,?,?)", host, username or "", self.store, key, t, value);
163                                 end
164                         else
165                                 local extradata = {};
166                                 for row in engine:select("SELECT `type`, `value` FROM `prosody` WHERE `host`=? AND `user`=? AND `store`=? AND `key`=?", host, username or "", self.store, "") do
167                                         extradata = deserialize(row[1], row[2]);
168                                         break;
169                                 end
170                                 engine:delete("DELETE FROM `prosody` WHERE `host`=? AND `user`=? AND `store`=? AND `key`=?",
171                                         host, username or "", self.store, "");
172                                 extradata[key] = data;
173                                 local t, value = assert(serialize(extradata));
174                                 engine:insert("INSERT INTO `prosody` (`host`,`user`,`store`,`key`,`type`,`value`) VALUES (?,?,?,?,?,?)", host, username or "", self.store, "", t, value);
175                         end
176                 end
177                 return true;
178         end);
179         if not ok then return nil, result; end
180         return result;
181 end
182
183 local archive_store = {}
184 archive_store.caps = {
185         total = true;
186 };
187 archive_store.__index = archive_store
188 function archive_store:append(username, key, value, when, with)
189         if type(when) ~= "number" then
190                 when, with, value = value, when, with;
191         end
192         local user,store = username,self.store;
193         return engine:transaction(function()
194                 if key then
195                         engine:delete("DELETE FROM `prosodyarchive` WHERE `host`=? AND `user`=? AND `store`=? AND `key`=?", host, user or "", store, key);
196                 else
197                         key = uuid.generate();
198                 end
199                 local t, value = serialize(value);
200                 engine:insert("INSERT INTO `prosodyarchive` (`host`, `user`, `store`, `when`, `with`, `key`, `type`, `value`) VALUES (?,?,?,?,?,?,?,?)", host, user or "", store, when, with, key, t, value);
201                 return key;
202         end);
203 end
204
205 -- Helpers for building the WHERE clause
206 local function archive_where(query, args, where)
207         -- Time range, inclusive
208         if query.start then
209                 args[#args+1] = query.start
210                 where[#where+1] = "`when` >= ?"
211         end
212
213         if query["end"] then
214                 args[#args+1] = query["end"];
215                 if query.start then
216                         where[#where] = "`when` BETWEEN ? AND ?" -- is this inclusive?
217                 else
218                         where[#where+1] = "`when` <= ?"
219                 end
220         end
221
222         -- Related name
223         if query.with then
224                 where[#where+1] = "`with` = ?";
225                 args[#args+1] = query.with
226         end
227
228         -- Unique id
229         if query.key then
230                 where[#where+1] = "`key` = ?";
231                 args[#args+1] = query.key
232         end
233 end
234 local function archive_where_id_range(query, args, where)
235         local args_len = #args
236         -- Before or after specific item, exclusive
237         if query.after then  -- keys better be unique!
238                 where[#where+1] = "`sort_id` > (SELECT `sort_id` FROM `prosodyarchive` WHERE `key` = ? AND `host` = ? AND `user` = ? AND `store` = ? LIMIT 1)"
239                 args[args_len+1], args[args_len+2], args[args_len+3], args[args_len+4] = query.after, args[1], args[2], args[3];
240                 args_len = args_len + 4
241         end
242         if query.before then
243                 where[#where+1] = "`sort_id` < (SELECT `sort_id` FROM `prosodyarchive` WHERE `key` = ? AND `host` = ? AND `user` = ? AND `store` = ? LIMIT 1)"
244                 args[args_len+1], args[args_len+2], args[args_len+3], args[args_len+4] = query.before, args[1], args[2], args[3];
245         end
246 end
247
248 function archive_store:find(username, query)
249         query = query or {};
250         local user,store = username,self.store;
251         local total;
252         local ok, result = engine:transaction(function()
253                 local sql_query = "SELECT `key`, `type`, `value`, `when`, `with` FROM `prosodyarchive` WHERE %s ORDER BY `sort_id` %s%s;";
254                 local args = { host, user or "", store, };
255                 local where = { "`host` = ?", "`user` = ?", "`store` = ?", };
256
257                 archive_where(query, args, where);
258
259                 -- Total matching
260                 if query.total then
261                         local stats = engine:select("SELECT COUNT(*) FROM `prosodyarchive` WHERE " .. t_concat(where, " AND "), unpack(args));
262                         if stats then
263                                 local _total = stats()
264                                 total = _total and _total[1];
265                         end
266                         if query.limit == 0 then -- Skip the real query
267                                 return noop, total;
268                         end
269                 end
270
271                 archive_where_id_range(query, args, where);
272
273                 if query.limit then
274                         args[#args+1] = query.limit;
275                 end
276
277                 sql_query = sql_query:format(t_concat(where, " AND "), query.reverse and "DESC" or "ASC", query.limit and " LIMIT ?" or "");
278                 module:log("debug", sql_query);
279                 return engine:select(sql_query, unpack(args));
280         end);
281         if not ok then return ok, result end
282         return function()
283                 local row = result();
284                 if row ~= nil then
285                         return row[1], deserialize(row[2], row[3]), row[4], row[5];
286                 end
287         end, total;
288 end
289
290 function archive_store:delete(username, query)
291         query = query or {};
292         local user,store = username,self.store;
293         return engine:transaction(function()
294                 local sql_query = "DELETE FROM `prosodyarchive` WHERE %s;";
295                 local args = { host, user or "", store, };
296                 local where = { "`host` = ?", "`user` = ?", "`store` = ?", };
297                 if user == true then
298                         table.remove(args, 2);
299                         table.remove(where, 2);
300                 end
301                 archive_where(query, args, where);
302                 archive_where_id_range(query, args, where);
303                 sql_query = sql_query:format(t_concat(where, " AND "));
304                 module:log("debug", sql_query);
305                 return engine:delete(sql_query, unpack(args));
306         end);
307 end
308
309 local stores = {
310         keyval = keyval_store;
311         map = map_store;
312         archive = archive_store;
313 };
314
315 --- Implement storage driver API
316
317 -- FIXME: Some of these operations need to operate on the archive store(s) too
318
319 local driver = {};
320
321 function driver:open(store, typ)
322         local store_mt = stores[typ or "keyval"];
323         if store_mt then
324                 return setmetatable({ store = store }, store_mt);
325         end
326         return nil, "unsupported-store";
327 end
328
329 function driver:stores(username)
330         local query = "SELECT DISTINCT `store` FROM `prosody` WHERE `host`=? AND `user`" ..
331                 (username == true and "!=?" or "=?");
332         if username == true or not username then
333                 username = "";
334         end
335         local ok, result = engine:transaction(function()
336                 return engine:select(query, host, username);
337         end);
338         if not ok then return ok, result end
339         return iterator(result);
340 end
341
342 function driver:purge(username)
343         return engine:transaction(function()
344                 local stmt,err = engine:delete("DELETE FROM `prosody` WHERE `host`=? AND `user`=?", host, username);
345                 return true, err;
346         end);
347 end
348
349 --- Initialization
350
351
352 local function create_table(name)
353         local Table, Column, Index = sql.Table, sql.Column, sql.Index;
354
355         local ProsodyTable = Table {
356                 name= name or "prosody";
357                 Column { name="host", type="TEXT", nullable=false };
358                 Column { name="user", type="TEXT", nullable=false };
359                 Column { name="store", type="TEXT", nullable=false };
360                 Column { name="key", type="TEXT", nullable=false };
361                 Column { name="type", type="TEXT", nullable=false };
362                 Column { name="value", type="MEDIUMTEXT", nullable=false };
363                 Index { name="prosody_index", "host", "user", "store", "key" };
364         };
365         engine:transaction(function()
366                 ProsodyTable:create(engine);
367         end);
368
369         local ProsodyArchiveTable = Table {
370                 name="prosodyarchive";
371                 Column { name="sort_id", type="INTEGER", primary_key=true, auto_increment=true };
372                 Column { name="host", type="TEXT", nullable=false };
373                 Column { name="user", type="TEXT", nullable=false };
374                 Column { name="store", type="TEXT", nullable=false };
375                 Column { name="key", type="TEXT", nullable=false }; -- item id
376                 Column { name="when", type="INTEGER", nullable=false }; -- timestamp
377                 Column { name="with", type="TEXT", nullable=false }; -- related id
378                 Column { name="type", type="TEXT", nullable=false };
379                 Column { name="value", type="MEDIUMTEXT", nullable=false };
380                 Index { name="prosodyarchive_index", unique = true, "host", "user", "store", "key" };
381         };
382         engine:transaction(function()
383                 ProsodyArchiveTable:create(engine);
384         end);
385 end
386
387 local function upgrade_table(params, apply_changes)
388         local changes = false;
389         if params.driver == "MySQL" then
390                 local success,err = engine:transaction(function()
391                         local result = engine:execute("SHOW COLUMNS FROM prosody WHERE Field='value' and Type='text'");
392                         if result:rowcount() > 0 then
393                                 changes = true;
394                                 if apply_changes then
395                                         module:log("info", "Upgrading database schema...");
396                                         engine:execute("ALTER TABLE prosody MODIFY COLUMN `value` MEDIUMTEXT");
397                                         module:log("info", "Database table automatically upgraded");
398                                 end
399                         end
400                         return true;
401                 end);
402                 if not success then
403                         module:log("error", "Failed to check/upgrade database schema (%s), please see "
404                                 .."http://prosody.im/doc/mysql for help",
405                                 err or "unknown error");
406                         return false;
407                 end
408
409                 -- COMPAT w/pre-0.10: Upgrade table to UTF-8 if not already
410                 local check_encoding_query = "SELECT `COLUMN_NAME`,`COLUMN_TYPE`,`TABLE_NAME` FROM `information_schema`.`columns` WHERE `TABLE_NAME` LIKE 'prosody%%' AND ( `CHARACTER_SET_NAME`!='%s' OR `COLLATION_NAME`!='%s_bin' );";
411                 check_encoding_query = check_encoding_query:format(engine.charset, engine.charset);
412                 success,err = engine:transaction(function()
413                         local result = engine:execute(check_encoding_query);
414                         local n_bad_columns = result:rowcount();
415                         if n_bad_columns > 0 then
416                                 changes = true;
417                                 if apply_changes then
418                                         module:log("warn", "Found %d columns in prosody table requiring encoding change, updating now...", n_bad_columns);
419                                         local fix_column_query1 = "ALTER TABLE `%s` CHANGE `%s` `%s` BLOB;";
420                                         local fix_column_query2 = "ALTER TABLE `%s` CHANGE `%s` `%s` %s CHARACTER SET '%s' COLLATE '%s_bin';";
421                                         for row in result:rows() do
422                                                 local column_name, column_type, table_name  = unpack(row);
423                                                 module:log("debug", "Fixing column %s in table %s", column_name, table_name);
424                                                 engine:execute(fix_column_query1:format(table_name, column_name, column_name));
425                                                 engine:execute(fix_column_query2:format(table_name, column_name, column_name, column_type, engine.charset, engine.charset));
426                                         end
427                                         module:log("info", "Database encoding upgrade complete!");
428                                 end
429                         end
430                 end);
431                 success,err = engine:transaction(function() return engine:execute(check_encoding_query); end);
432                 if not success then
433                         module:log("error", "Failed to check/upgrade database encoding: %s", err or "unknown error");
434                         return false;
435                 end
436         end
437         return changes;
438 end
439
440 local function normalize_params(params)
441         if params.driver == "SQLite3" then
442                 if params.database ~= ":memory:" then
443                         params.database = resolve_relative_path(prosody.paths.data or ".", params.database or "prosody.sqlite");
444                 end
445         end
446         assert(params.driver and params.database, "Configuration error: Both the SQL driver and the database need to be specified");
447         return params;
448 end
449
450 function module.load()
451         if prosody.prosodyctl then return; end
452         local engines = module:shared("/*/sql/connections");
453         local params = normalize_params(module:get_option("sql", default_params));
454         engine = engines[sql.db2uri(params)];
455         if not engine then
456                 module:log("info", "Creating new engine");
457                 engine = sql:create_engine(params, function (engine)
458                         if module:get_option("sql_manage_tables", true) then
459                                 -- Automatically create table, ignore failure (table probably already exists)
460                                 -- FIXME: we should check in information_schema, etc.
461                                 create_table();
462                                 -- Check whether the table needs upgrading
463                                 if upgrade_table(params, false) then
464                                         module:log("error", "Old database format detected. Please run: prosodyctl mod_%s upgrade", module.name);
465                                         return false, "database upgrade needed";
466                                 end
467                         end
468                 end);
469                 engines[sql.db2uri(params)] = engine;
470         end
471
472         module:provides("storage", driver);
473 end
474
475 function module.command(arg)
476         local config = require "core.configmanager";
477         local prosodyctl = require "util.prosodyctl";
478         local command = table.remove(arg, 1);
479         if command == "upgrade" then
480                 -- We need to find every unique dburi in the config
481                 local uris = {};
482                 for host in pairs(prosody.hosts) do
483                         local params = config.get(host, "sql") or default_params;
484                         uris[sql.db2uri(params)] = params;
485                 end
486                 print("We will check and upgrade the following databases:\n");
487                 for _, params in pairs(uris) do
488                         print("", "["..params.driver.."] "..params.database..(params.host and " on "..params.host or ""));
489                 end
490                 print("");
491                 print("Ensure you have working backups of the above databases before continuing! ");
492                 if not prosodyctl.show_yesno("Continue with the database upgrade? [yN]") then
493                         print("Ok, no upgrade. But you do have backups, don't you? ...don't you?? :-)");
494                         return;
495                 end
496                 -- Upgrade each one
497                 for _, params in pairs(uris) do
498                         print("Checking "..params.database.."...");
499                         engine = sql:create_engine(params);
500                         upgrade_table(params, true);
501                 end
502                 print("All done!");
503         else
504                 print("Unknown command: "..command);
505         end
506 end