2 -- luacheck: ignore 212/self
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;
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
15 local noop = function() end
17 local function iterator(result)
18 return function(result_)
19 local row = result_();
26 local default_params = { driver = "SQLite3" };
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
41 return nil, "Unhandled value type: "..t;
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);
56 local host = module.host;
59 local function keyval_store_get()
62 for row in engine:select("SELECT `key`,`type`,`value` FROM `prosody` WHERE `host`=? AND `user`=? AND `store`=?", host, user or "", store) do
65 local v = deserialize(row[2], row[3]);
67 if k ~= "" then result[k] = v; elseif type(v) == "table" then
68 for a,b in pairs(v) do
78 local function keyval_store_set(data)
79 engine:delete("DELETE FROM `prosody` WHERE `host`=? AND `user`=? AND `store`=?", host, user or "", store);
81 if data and next(data) ~= nil then
83 for key, value in pairs(data) do
84 if type(key) == "string" and key ~= "" then
85 local t, value = serialize(value);
87 engine:insert("INSERT INTO `prosody` (`host`,`user`,`store`,`key`,`type`,`value`) VALUES (?,?,?,?,?,?)", host, user or "", store, key, t, value);
89 extradata[key] = value;
92 if next(extradata) ~= nil then
93 local t, extradata = serialize(extradata);
95 engine:insert("INSERT INTO `prosody` (`host`,`user`,`store`,`key`,`type`,`value`) VALUES (?,?,?,?,?,?)", host, user or "", store, "", t, extradata);
101 --- Key/value store API (default store type)
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);
109 module:log("error", "Unable to read from database %s store for %s: %s", store, username or "<host>", result);
114 function keyval_store:set(username, data)
115 user,store = username,self.store;
116 return engine:transaction(function()
117 return keyval_store_set(data);
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);
124 if not ok then return ok, result end
125 return iterator(result);
128 --- Archive store API
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]);
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;
147 if not ok then return nil, result; end
150 function map_store:set(username, key, data)
151 return self:set_keys(username, { [key] = data or self.remove });
153 function map_store:set_keys(username, keydatas)
154 local ok, result = engine:transaction(function()
155 for key, data in pairs(keydatas) do
156 if type(key) == "string" and key ~= "" then
157 engine:delete("DELETE FROM `prosody` WHERE `host`=? AND `user`=? AND `store`=? AND `key`=?",
158 host, username or "", self.store, key);
159 if data ~= self.remove then
160 local t, value = assert(serialize(data));
161 engine:insert("INSERT INTO `prosody` (`host`,`user`,`store`,`key`,`type`,`value`) VALUES (?,?,?,?,?,?)", host, username or "", self.store, key, t, value);
164 local extradata = {};
165 for row in engine:select("SELECT `type`, `value` FROM `prosody` WHERE `host`=? AND `user`=? AND `store`=? AND `key`=?", host, username or "", self.store, "") do
166 extradata = deserialize(row[1], row[2]);
169 engine:delete("DELETE FROM `prosody` WHERE `host`=? AND `user`=? AND `store`=? AND `key`=?",
170 host, username or "", self.store, "");
171 extradata[key] = data;
172 local t, value = assert(serialize(extradata));
173 engine:insert("INSERT INTO `prosody` (`host`,`user`,`store`,`key`,`type`,`value`) VALUES (?,?,?,?,?,?)", host, username or "", self.store, "", t, value);
178 if not ok then return nil, result; end
182 local archive_store = {}
183 archive_store.caps = {
186 archive_store.__index = archive_store
187 function archive_store:append(username, key, value, when, with)
188 if type(when) ~= "number" then
189 when, with, value = value, when, with;
191 local user,store = username,self.store;
192 return engine:transaction(function()
194 engine:delete("DELETE FROM `prosodyarchive` WHERE `host`=? AND `user`=? AND `store`=? AND `key`=?", host, user or "", store, key);
196 key = uuid.generate();
198 local t, value = serialize(value);
199 engine:insert("INSERT INTO `prosodyarchive` (`host`, `user`, `store`, `when`, `with`, `key`, `type`, `value`) VALUES (?,?,?,?,?,?,?,?)", host, user or "", store, when, with, key, t, value);
204 -- Helpers for building the WHERE clause
205 local function archive_where(query, args, where)
206 -- Time range, inclusive
208 args[#args+1] = query.start
209 where[#where+1] = "`when` >= ?"
213 args[#args+1] = query["end"];
215 where[#where] = "`when` BETWEEN ? AND ?" -- is this inclusive?
217 where[#where+1] = "`when` <= ?"
223 where[#where+1] = "`with` = ?";
224 args[#args+1] = query.with
229 where[#where+1] = "`key` = ?";
230 args[#args+1] = query.key
233 local function archive_where_id_range(query, args, where)
234 local args_len = #args
235 -- Before or after specific item, exclusive
236 if query.after then -- keys better be unique!
237 where[#where+1] = "`sort_id` > (SELECT `sort_id` FROM `prosodyarchive` WHERE `key` = ? AND `host` = ? AND `user` = ? AND `store` = ? LIMIT 1)"
238 args[args_len+1], args[args_len+2], args[args_len+3], args[args_len+4] = query.after, args[1], args[2], args[3];
239 args_len = args_len + 4
242 where[#where+1] = "`sort_id` < (SELECT `sort_id` FROM `prosodyarchive` WHERE `key` = ? AND `host` = ? AND `user` = ? AND `store` = ? LIMIT 1)"
243 args[args_len+1], args[args_len+2], args[args_len+3], args[args_len+4] = query.before, args[1], args[2], args[3];
247 function archive_store:find(username, query)
249 local user,store = username,self.store;
251 local ok, result = engine:transaction(function()
252 local sql_query = "SELECT `key`, `type`, `value`, `when`, `with` FROM `prosodyarchive` WHERE %s ORDER BY `sort_id` %s%s;";
253 local args = { host, user or "", store, };
254 local where = { "`host` = ?", "`user` = ?", "`store` = ?", };
256 archive_where(query, args, where);
260 local stats = engine:select("SELECT COUNT(*) FROM `prosodyarchive` WHERE " .. t_concat(where, " AND "), unpack(args));
262 local _total = stats()
263 total = _total and _total[1];
265 if query.limit == 0 then -- Skip the real query
270 archive_where_id_range(query, args, where);
273 args[#args+1] = query.limit;
276 sql_query = sql_query:format(t_concat(where, " AND "), query.reverse and "DESC" or "ASC", query.limit and " LIMIT ?" or "");
277 module:log("debug", sql_query);
278 return engine:select(sql_query, unpack(args));
280 if not ok then return ok, result end
282 local row = result();
284 return row[1], deserialize(row[2], row[3]), row[4], row[5];
289 function archive_store:delete(username, query)
291 local user,store = username,self.store;
292 return engine:transaction(function()
293 local sql_query = "DELETE FROM `prosodyarchive` WHERE %s;";
294 local args = { host, user or "", store, };
295 local where = { "`host` = ?", "`user` = ?", "`store` = ?", };
297 table.remove(args, 2);
298 table.remove(where, 2);
300 archive_where(query, args, where);
301 archive_where_id_range(query, args, where);
302 sql_query = sql_query:format(t_concat(where, " AND "));
303 module:log("debug", sql_query);
304 return engine:delete(sql_query, unpack(args));
309 keyval = keyval_store;
311 archive = archive_store;
314 --- Implement storage driver API
316 -- FIXME: Some of these operations need to operate on the archive store(s) too
320 function driver:open(store, typ)
321 local store_mt = stores[typ or "keyval"];
323 return setmetatable({ store = store }, store_mt);
325 return nil, "unsupported-store";
328 function driver:stores(username)
329 local query = "SELECT DISTINCT `store` FROM `prosody` WHERE `host`=? AND `user`" ..
330 (username == true and "!=?" or "=?");
331 if username == true or not username then
334 local ok, result = engine:transaction(function()
335 return engine:select(query, host, username);
337 if not ok then return ok, result end
338 return iterator(result);
341 function driver:purge(username)
342 return engine:transaction(function()
343 local stmt,err = engine:delete("DELETE FROM `prosody` WHERE `host`=? AND `user`=?", host, username);
351 local function create_table(name)
352 local Table, Column, Index = sql.Table, sql.Column, sql.Index;
354 local ProsodyTable = Table {
355 name= name or "prosody";
356 Column { name="host", type="TEXT", nullable=false };
357 Column { name="user", type="TEXT", nullable=false };
358 Column { name="store", type="TEXT", nullable=false };
359 Column { name="key", type="TEXT", nullable=false };
360 Column { name="type", type="TEXT", nullable=false };
361 Column { name="value", type="MEDIUMTEXT", nullable=false };
362 Index { name="prosody_index", "host", "user", "store", "key" };
364 engine:transaction(function()
365 ProsodyTable:create(engine);
368 local ProsodyArchiveTable = Table {
369 name="prosodyarchive";
370 Column { name="sort_id", type="INTEGER", primary_key=true, auto_increment=true };
371 Column { name="host", type="TEXT", nullable=false };
372 Column { name="user", type="TEXT", nullable=false };
373 Column { name="store", type="TEXT", nullable=false };
374 Column { name="key", type="TEXT", nullable=false }; -- item id
375 Column { name="when", type="INTEGER", nullable=false }; -- timestamp
376 Column { name="with", type="TEXT", nullable=false }; -- related id
377 Column { name="type", type="TEXT", nullable=false };
378 Column { name="value", type="MEDIUMTEXT", nullable=false };
379 Index { name="prosodyarchive_index", unique = true, "host", "user", "store", "key" };
381 engine:transaction(function()
382 ProsodyArchiveTable:create(engine);
386 local function upgrade_table(params, apply_changes)
387 local changes = false;
388 if params.driver == "MySQL" then
389 local success,err = engine:transaction(function()
390 local result = engine:execute("SHOW COLUMNS FROM prosody WHERE Field='value' and Type='text'");
391 if result:rowcount() > 0 then
393 if apply_changes then
394 module:log("info", "Upgrading database schema...");
395 engine:execute("ALTER TABLE prosody MODIFY COLUMN `value` MEDIUMTEXT");
396 module:log("info", "Database table automatically upgraded");
402 module:log("error", "Failed to check/upgrade database schema (%s), please see "
403 .."http://prosody.im/doc/mysql for help",
404 err or "unknown error");
408 -- COMPAT w/pre-0.10: Upgrade table to UTF-8 if not already
409 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' );";
410 check_encoding_query = check_encoding_query:format(engine.charset, engine.charset);
411 success,err = engine:transaction(function()
412 local result = engine:execute(check_encoding_query);
413 local n_bad_columns = result:rowcount();
414 if n_bad_columns > 0 then
416 if apply_changes then
417 module:log("warn", "Found %d columns in prosody table requiring encoding change, updating now...", n_bad_columns);
418 local fix_column_query1 = "ALTER TABLE `%s` CHANGE `%s` `%s` BLOB;";
419 local fix_column_query2 = "ALTER TABLE `%s` CHANGE `%s` `%s` %s CHARACTER SET '%s' COLLATE '%s_bin';";
420 for row in result:rows() do
421 local column_name, column_type, table_name = unpack(row);
422 module:log("debug", "Fixing column %s in table %s", column_name, table_name);
423 engine:execute(fix_column_query1:format(table_name, column_name, column_name));
424 engine:execute(fix_column_query2:format(table_name, column_name, column_name, column_type, engine.charset, engine.charset));
426 module:log("info", "Database encoding upgrade complete!");
430 success,err = engine:transaction(function() return engine:execute(check_encoding_query); end);
432 module:log("error", "Failed to check/upgrade database encoding: %s", err or "unknown error");
439 local function normalize_params(params)
440 if params.driver == "SQLite3" then
441 if params.database ~= ":memory:" then
442 params.database = resolve_relative_path(prosody.paths.data or ".", params.database or "prosody.sqlite");
445 assert(params.driver and params.database, "Configuration error: Both the SQL driver and the database need to be specified");
449 function module.load()
450 if prosody.prosodyctl then return; end
451 local params = normalize_params(module:get_option("sql", default_params));
452 engine = sql:create_engine(params, function (engine)
453 if module:get_option("sql_manage_tables", true) then
454 -- Automatically create table, ignore failure (table probably already exists)
455 -- FIXME: we should check in information_schema, etc.
457 -- Check whether the table needs upgrading
458 if upgrade_table(params, false) then
459 module:log("error", "Old database format detected. Please run: prosodyctl mod_%s upgrade", module.name);
460 return false, "database upgrade needed";
465 module:provides("storage", driver);
468 function module.command(arg)
469 local config = require "core.configmanager";
470 local prosodyctl = require "util.prosodyctl";
471 local command = table.remove(arg, 1);
472 if command == "upgrade" then
473 -- We need to find every unique dburi in the config
475 for host in pairs(prosody.hosts) do
476 local params = config.get(host, "sql") or default_params;
477 uris[sql.db2uri(params)] = params;
479 print("We will check and upgrade the following databases:\n");
480 for _, params in pairs(uris) do
481 print("", "["..params.driver.."] "..params.database..(params.host and " on "..params.host or ""));
484 print("Ensure you have working backups of the above databases before continuing! ");
485 if not prosodyctl.show_yesno("Continue with the database upgrade? [yN]") then
486 print("Ok, no upgrade. But you do have backups, don't you? ...don't you?? :-)");
490 for _, params in pairs(uris) do
491 print("Checking "..params.database.."...");
492 engine = sql:create_engine(params);
493 upgrade_table(params, true);
497 print("Unknown command: "..command);