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 if data == nil then data = self.remove; end
152 return self:set_keys(username, { [key] = data });
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);
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]);
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);
179 if not ok then return nil, result; end
183 local archive_store = {}
184 archive_store.caps = {
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;
192 local user,store = username,self.store;
193 return engine:transaction(function()
195 engine:delete("DELETE FROM `prosodyarchive` WHERE `host`=? AND `user`=? AND `store`=? AND `key`=?", host, user or "", store, key);
197 key = uuid.generate();
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);
205 -- Helpers for building the WHERE clause
206 local function archive_where(query, args, where)
207 -- Time range, inclusive
209 args[#args+1] = query.start
210 where[#where+1] = "`when` >= ?"
214 args[#args+1] = query["end"];
216 where[#where] = "`when` BETWEEN ? AND ?" -- is this inclusive?
218 where[#where+1] = "`when` <= ?"
224 where[#where+1] = "`with` = ?";
225 args[#args+1] = query.with
230 where[#where+1] = "`key` = ?";
231 args[#args+1] = query.key
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
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];
248 function archive_store:find(username, query)
250 local user,store = username,self.store;
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` = ?", };
257 archive_where(query, args, where);
261 local stats = engine:select("SELECT COUNT(*) FROM `prosodyarchive` WHERE " .. t_concat(where, " AND "), unpack(args));
263 local _total = stats()
264 total = _total and _total[1];
266 if query.limit == 0 then -- Skip the real query
271 archive_where_id_range(query, args, where);
274 args[#args+1] = query.limit;
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));
281 if not ok then return ok, result end
283 local row = result();
285 return row[1], deserialize(row[2], row[3]), row[4], row[5];
290 function archive_store:delete(username, query)
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` = ?", };
298 table.remove(args, 2);
299 table.remove(where, 2);
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));
310 keyval = keyval_store;
312 archive = archive_store;
315 --- Implement storage driver API
317 -- FIXME: Some of these operations need to operate on the archive store(s) too
321 function driver:open(store, typ)
322 local store_mt = stores[typ or "keyval"];
324 return setmetatable({ store = store }, store_mt);
326 return nil, "unsupported-store";
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
335 local ok, result = engine:transaction(function()
336 return engine:select(query, host, username);
338 if not ok then return ok, result end
339 return iterator(result);
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);
352 local function create_table(name)
353 local Table, Column, Index = sql.Table, sql.Column, sql.Index;
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" };
365 engine:transaction(function()
366 ProsodyTable:create(engine);
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" };
382 engine:transaction(function()
383 ProsodyArchiveTable:create(engine);
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
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");
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");
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
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));
427 module:log("info", "Database encoding upgrade complete!");
431 success,err = engine:transaction(function() return engine:execute(check_encoding_query); end);
433 module:log("error", "Failed to check/upgrade database encoding: %s", err or "unknown error");
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");
446 assert(params.driver and params.database, "Configuration error: Both the SQL driver and the database need to be specified");
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)];
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.
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";
469 engines[sql.db2uri(params)] = engine;
472 module:provides("storage", driver);
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
482 for host in pairs(prosody.hosts) do
483 local params = config.get(host, "sql") or default_params;
484 uris[sql.db2uri(params)] = params;
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 ""));
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?? :-)");
497 for _, params in pairs(uris) do
498 print("Checking "..params.database.."...");
499 engine = sql:create_engine(params);
500 upgrade_table(params, true);
504 print("Unknown command: "..command);