70f1ab83c3a2f40a91f201821a00f7cb21f55ac8
[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                 local data;
137                 if type(key) == "string" and key ~= "" then
138                         for row in engine:select("SELECT `type`, `value` FROM `prosody` WHERE `host`=? AND `user`=? AND `store`=? AND `key`=? LIMIT 1", host, username or "", self.store, key) do
139                                 data = deserialize(row[1], row[2]);
140                         end
141                         return data;
142                 else
143                         for row in engine:select("SELECT `type`, `value` FROM `prosody` WHERE `host`=? AND `user`=? AND `store`=? AND `key`=? LIMIT 1", host, username or "", self.store, "") do
144                                 data = deserialize(row[1], row[2]);
145                         end
146                         return data and data[key] or nil;
147                 end
148         end);
149         if not ok then return nil, result; end
150         return result;
151 end
152 function map_store:set(username, key, data)
153         if data == nil then data = self.remove; end
154         return self:set_keys(username, { [key] = data });
155 end
156 function map_store:set_keys(username, keydatas)
157         local ok, result = engine:transaction(function()
158                 for key, data in pairs(keydatas) do
159                         if type(key) == "string" and key ~= "" then
160                                 engine:delete("DELETE FROM `prosody` WHERE `host`=? AND `user`=? AND `store`=? AND `key`=?",
161                                         host, username or "", self.store, key);
162                                 if data ~= self.remove then
163                                         local t, value = assert(serialize(data));
164                                         engine:insert("INSERT INTO `prosody` (`host`,`user`,`store`,`key`,`type`,`value`) VALUES (?,?,?,?,?,?)", host, username or "", self.store, key, t, value);
165                                 end
166                         else
167                                 local extradata = {};
168                                 for row in engine:select("SELECT `type`, `value` FROM `prosody` WHERE `host`=? AND `user`=? AND `store`=? AND `key`=? LIMIT 1", host, username or "", self.store, "") do
169                                         extradata = deserialize(row[1], row[2]);
170                                 end
171                                 engine:delete("DELETE FROM `prosody` WHERE `host`=? AND `user`=? AND `store`=? AND `key`=?",
172                                         host, username or "", self.store, "");
173                                 extradata[key] = data;
174                                 local t, value = assert(serialize(extradata));
175                                 engine:insert("INSERT INTO `prosody` (`host`,`user`,`store`,`key`,`type`,`value`) VALUES (?,?,?,?,?,?)", host, username or "", self.store, "", t, value);
176                         end
177                 end
178                 return true;
179         end);
180         if not ok then return nil, result; end
181         return result;
182 end
183
184 local archive_store = {}
185 archive_store.caps = {
186         total = true;
187 };
188 archive_store.__index = archive_store
189 function archive_store:append(username, key, value, when, with)
190         if type(when) ~= "number" then
191                 when, with, value = value, when, with;
192         end
193         local user,store = username,self.store;
194         return engine:transaction(function()
195                 if key then
196                         engine:delete("DELETE FROM `prosodyarchive` WHERE `host`=? AND `user`=? AND `store`=? AND `key`=?", host, user or "", store, key);
197                 else
198                         key = uuid.generate();
199                 end
200                 local t, value = serialize(value);
201                 engine:insert("INSERT INTO `prosodyarchive` (`host`, `user`, `store`, `when`, `with`, `key`, `type`, `value`) VALUES (?,?,?,?,?,?,?,?)", host, user or "", store, when, with, key, t, value);
202                 return key;
203         end);
204 end
205
206 -- Helpers for building the WHERE clause
207 local function archive_where(query, args, where)
208         -- Time range, inclusive
209         if query.start then
210                 args[#args+1] = query.start
211                 where[#where+1] = "`when` >= ?"
212         end
213
214         if query["end"] then
215                 args[#args+1] = query["end"];
216                 if query.start then
217                         where[#where] = "`when` BETWEEN ? AND ?" -- is this inclusive?
218                 else
219                         where[#where+1] = "`when` <= ?"
220                 end
221         end
222
223         -- Related name
224         if query.with then
225                 where[#where+1] = "`with` = ?";
226                 args[#args+1] = query.with
227         end
228
229         -- Unique id
230         if query.key then
231                 where[#where+1] = "`key` = ?";
232                 args[#args+1] = query.key
233         end
234 end
235 local function archive_where_id_range(query, args, where)
236         local args_len = #args
237         -- Before or after specific item, exclusive
238         if query.after then  -- keys better be unique!
239                 where[#where+1] = "`sort_id` > COALESCE((SELECT `sort_id` FROM `prosodyarchive` WHERE `key` = ? AND `host` = ? AND `user` = ? AND `store` = ? LIMIT 1), 0)"
240                 args[args_len+1], args[args_len+2], args[args_len+3], args[args_len+4] = query.after, args[1], args[2], args[3];
241                 args_len = args_len + 4
242         end
243         if query.before then
244                 where[#where+1] = "`sort_id` < COALESCE((SELECT `sort_id` FROM `prosodyarchive` WHERE `key` = ? AND `host` = ? AND `user` = ? AND `store` = ? LIMIT 1), (SELECT MAX(`sort_id`)+1 FROM `prosodyarchive`))"
245                 args[args_len+1], args[args_len+2], args[args_len+3], args[args_len+4] = query.before, args[1], args[2], args[3];
246         end
247 end
248
249 function archive_store:find(username, query)
250         query = query or {};
251         local user,store = username,self.store;
252         local total;
253         local ok, result = engine:transaction(function()
254                 local sql_query = "SELECT `key`, `type`, `value`, `when`, `with` FROM `prosodyarchive` WHERE %s ORDER BY `sort_id` %s%s;";
255                 local args = { host, user or "", store, };
256                 local where = { "`host` = ?", "`user` = ?", "`store` = ?", };
257
258                 archive_where(query, args, where);
259
260                 -- Total matching
261                 if query.total then
262                         local stats = engine:select("SELECT COUNT(*) FROM `prosodyarchive` WHERE " .. t_concat(where, " AND "), unpack(args));
263                         if stats then
264                                 for row in stats do
265                                         total = row[1];
266                                 end
267                         end
268                         if query.limit == 0 then -- Skip the real query
269                                 return noop, total;
270                         end
271                 end
272
273                 archive_where_id_range(query, args, where);
274
275                 if query.limit then
276                         args[#args+1] = query.limit;
277                 end
278
279                 sql_query = sql_query:format(t_concat(where, " AND "), query.reverse and "DESC" or "ASC", query.limit and " LIMIT ?" or "");
280                 return engine:select(sql_query, unpack(args));
281         end);
282         if not ok then return ok, result end
283         return function()
284                 local row = result();
285                 if row ~= nil then
286                         return row[1], deserialize(row[2], row[3]), row[4], row[5];
287                 end
288         end, total;
289 end
290
291 function archive_store:delete(username, query)
292         query = query or {};
293         local user,store = username,self.store;
294         return engine:transaction(function()
295                 local sql_query = "DELETE FROM `prosodyarchive` WHERE %s;";
296                 local args = { host, user or "", store, };
297                 local where = { "`host` = ?", "`user` = ?", "`store` = ?", };
298                 if user == true then
299                         table.remove(args, 2);
300                         table.remove(where, 2);
301                 end
302                 archive_where(query, args, where);
303                 archive_where_id_range(query, args, where);
304                 sql_query = sql_query:format(t_concat(where, " AND "));
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("debug", "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