2 local json = require "util.json";
3 local xml_parse = require "util.xml".parse;
4 local uuid = require "util.uuid";
5 local resolve_relative_path = require "util.paths".resolve_relative_path;
7 local stanza_mt = require"util.stanza".stanza_mt;
8 local getmetatable = getmetatable;
9 local t_concat = table.concat;
10 local function is_stanza(x) return getmetatable(x) == stanza_mt; end
12 local noop = function() end
14 local function iterator(result)
15 return function(result)
23 local mod_sql = module:require("sql");
24 local params = module:get_option("sql");
26 local engine; -- TODO create engine
28 local function create_table()
29 local Table,Column,Index = mod_sql.Table,mod_sql.Column,mod_sql.Index;
31 local ProsodyTable = Table {
33 Column { name="host", type="TEXT", nullable=false };
34 Column { name="user", type="TEXT", nullable=false };
35 Column { name="store", type="TEXT", nullable=false };
36 Column { name="key", type="TEXT", nullable=false };
37 Column { name="type", type="TEXT", nullable=false };
38 Column { name="value", type="MEDIUMTEXT", nullable=false };
39 Index { name="prosody_index", "host", "user", "store", "key" };
41 engine:transaction(function()
42 ProsodyTable:create(engine);
45 local ProsodyArchiveTable = Table {
46 name="prosodyarchive";
47 Column { name="sort_id", type="INTEGER", primary_key=true, auto_increment=true };
48 Column { name="host", type="TEXT", nullable=false };
49 Column { name="user", type="TEXT", nullable=false };
50 Column { name="store", type="TEXT", nullable=false };
51 Column { name="key", type="TEXT", nullable=false }; -- item id
52 Column { name="when", type="INTEGER", nullable=false }; -- timestamp
53 Column { name="with", type="TEXT", nullable=false }; -- related id
54 Column { name="type", type="TEXT", nullable=false };
55 Column { name="value", type="MEDIUMTEXT", nullable=false };
56 Index { name="prosodyarchive_index", unique = true, "host", "user", "store", "key" };
58 engine:transaction(function()
59 ProsodyArchiveTable:create(engine);
63 local function upgrade_table()
64 if params.driver == "MySQL" then
65 local success,err = engine:transaction(function()
66 local result = engine:execute("SHOW COLUMNS FROM prosody WHERE Field='value' and Type='text'");
67 if result:rowcount() > 0 then
68 module:log("info", "Upgrading database schema...");
69 engine:execute("ALTER TABLE prosody MODIFY COLUMN `value` MEDIUMTEXT");
70 module:log("info", "Database table automatically upgraded");
75 module:log("error", "Failed to check/upgrade database schema (%s), please see "
76 .."http://prosody.im/doc/mysql for help",
77 err or "unknown error");
80 -- COMPAT w/pre-0.9: Upgrade tables to UTF-8 if not already
81 local check_encoding_query = "SELECT `COLUMN_NAME`,`COLUMN_TYPE` FROM `information_schema`.`columns` WHERE `TABLE_NAME`='prosody' AND ( `CHARACTER_SET_NAME`!='utf8' OR `COLLATION_NAME`!='utf8_bin' );";
82 success,err = engine:transaction(function()
83 local result = engine:execute(check_encoding_query);
84 local n_bad_columns = result:rowcount();
85 if n_bad_columns > 0 then
86 module:log("warn", "Found %d columns in prosody table requiring encoding change, updating now...", n_bad_columns);
87 local fix_column_query1 = "ALTER TABLE `prosody` CHANGE `%s` `%s` BLOB;";
88 local fix_column_query2 = "ALTER TABLE `prosody` CHANGE `%s` `%s` %s CHARACTER SET 'utf8' COLLATE 'utf8_bin';";
89 for row in result:rows() do
90 local column_name, column_type = unpack(row);
91 engine:execute(fix_column_query1:format(column_name, column_name));
92 engine:execute(fix_column_query2:format(column_name, column_name, column_type));
94 module:log("info", "Database encoding upgrade complete!");
97 success,err = engine:transaction(function() return engine:execute(check_encoding_query); end);
99 module:log("error", "Failed to check/upgrade database encoding: %s", err or "unknown error");
104 do -- process options to get a db connection
105 params = params or { driver = "SQLite3" };
107 if params.driver == "SQLite3" then
108 params.database = resolve_relative_path(prosody.paths.data or ".", params.database or "prosody.sqlite");
111 assert(params.driver and params.database, "Both the SQL driver and the database need to be specified");
113 --local dburi = db2uri(params);
114 engine = mod_sql:create_engine(params);
116 if module:get_option("sql_manage_tables", true) then
117 -- Automatically create table, ignore failure (table probably already exists)
124 local function serialize(value)
125 local t = type(value);
126 if t == "string" or t == "boolean" or t == "number" then
127 return t, tostring(value);
128 elseif is_stanza(value) then
129 return "xml", tostring(value);
130 elseif t == "table" then
131 local value,err = json.encode(value);
132 if value then return "json", value; end
135 return nil, "Unhandled value type: "..t;
137 local function deserialize(t, value)
138 if t == "string" then return value;
139 elseif t == "boolean" then
140 if value == "true" then return true;
141 elseif value == "false" then return false; end
142 elseif t == "number" then return tonumber(value);
143 elseif t == "json" then
144 return json.decode(value);
145 elseif t == "xml" then
146 return xml_parse(value);
150 local host = module.host;
153 local function keyval_store_get()
156 for row in engine:select("SELECT `key`,`type`,`value` FROM `prosody` WHERE `host`=? AND `user`=? AND `store`=?", host, user or "", store) do
159 local v = deserialize(row[2], row[3]);
161 if k ~= "" then result[k] = v; elseif type(v) == "table" then
162 for a,b in pairs(v) do
172 local function keyval_store_set(data)
173 engine:delete("DELETE FROM `prosody` WHERE `host`=? AND `user`=? AND `store`=?", host, user or "", store);
175 if data and next(data) ~= nil then
176 local extradata = {};
177 for key, value in pairs(data) do
178 if type(key) == "string" and key ~= "" then
179 local t, value = serialize(value);
181 engine:insert("INSERT INTO `prosody` (`host`,`user`,`store`,`key`,`type`,`value`) VALUES (?,?,?,?,?,?)", host, user or "", store, key, t, value);
183 extradata[key] = value;
186 if next(extradata) ~= nil then
187 local t, extradata = serialize(extradata);
188 assert(t, extradata);
189 engine:insert("INSERT INTO `prosody` (`host`,`user`,`store`,`key`,`type`,`value`) VALUES (?,?,?,?,?,?)", host, user or "", store, "", t, extradata);
195 local keyval_store = {};
196 keyval_store.__index = keyval_store;
197 function keyval_store:get(username)
198 user,store = username,self.store;
199 local ok, result = engine:transaction(keyval_store_get);
200 if not ok then return ok, result; end
203 function keyval_store:set(username, data)
204 user,store = username,self.store;
205 return engine:transaction(function()
206 return keyval_store_set(data);
209 function keyval_store:users()
210 local ok, result = engine:transaction(function()
211 return engine:select("SELECT DISTINCT `user` FROM `prosody` WHERE `host`=? AND `store`=?", host, self.store);
213 if not ok then return ok, result end
214 return iterator(result);
217 local map_store = {};
218 map_store.__index = map_store;
219 function map_store:get(username, key)
220 local ok, result = engine:transaction(function()
221 if type(key) == "string" and key ~= "" then
222 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
223 return deserialize(row[1], row[2]);
226 error("TODO: non-string keys");
229 if not ok then return nil, result; end
232 function map_store:set(username, key, data)
233 local ok, result = engine:transaction(function()
234 if type(key) == "string" and key ~= "" then
235 engine:delete("DELETE FROM `prosody` WHERE `host`=? AND `user`=? AND `store`=? AND `key`=?",
236 host, username or "", self.store, key);
238 local t, value = assert(serialize(data));
239 engine:insert("INSERT INTO `prosody` (`host`,`user`,`store`,`key`,`type`,`value`) VALUES (?,?,?,?,?,?)", host, username or "", self.store, key, t, value);
242 error("TODO: non-string keys");
246 if not ok then return nil, result; end
250 local archive_store = {}
251 archive_store.__index = archive_store
252 function archive_store:append(username, key, when, with, value)
253 if value == nil then -- COMPAT early versions
254 when, with, value, key = key, when, with, value
256 local user,store = username,self.store;
257 return engine:transaction(function()
259 engine:delete("DELETE FROM `prosodyarchive` WHERE `host`=? AND `user`=? AND `store`=? AND `key`=?", host, user or "", store, key);
261 key = uuid.generate();
263 local t, value = serialize(value);
264 engine:insert("INSERT INTO `prosodyarchive` (`host`, `user`, `store`, `when`, `with`, `key`, `type`, `value`) VALUES (?,?,?,?,?,?,?,?)", host, user or "", store, when, with, key, t, value);
269 -- Helpers for building the WHERE clause
270 local function archive_where(query, args, where)
271 -- Time range, inclusive
273 args[#args+1] = query.start
274 where[#where+1] = "`when` >= ?"
278 args[#args+1] = query["end"];
280 where[#where] = "`when` BETWEEN ? AND ?" -- is this inclusive?
282 where[#where+1] = "`when` <= ?"
288 where[#where+1] = "`with` = ?";
289 args[#args+1] = query.with
294 where[#where+1] = "`key` = ?";
295 args[#args+1] = query.key
298 local function archive_where_id_range(query, args, where)
299 local args_len = #args
300 -- Before or after specific item, exclusive
301 if query.after then -- keys better be unique!
302 where[#where+1] = "`sort_id` > (SELECT `sort_id` FROM `prosodyarchive` WHERE `key` = ? AND `host` = ? AND `user` = ? AND `store` = ? LIMIT 1)"
303 args[args_len+1], args[args_len+2], args[args_len+3], args[args_len+4] = query.after, args[1], args[2], args[3];
304 args_len = args_len + 4
307 where[#where+1] = "`sort_id` < (SELECT `sort_id` FROM `prosodyarchive` WHERE `key` = ? AND `host` = ? AND `user` = ? AND `store` = ? LIMIT 1)"
308 args[args_len+1], args[args_len+2], args[args_len+3], args[args_len+4] = query.before, args[1], args[2], args[3];
312 function archive_store:find(username, query)
314 local user,store = username,self.store;
316 local ok, result = engine:transaction(function()
317 local sql_query = "SELECT `key`, `type`, `value`, `when` FROM `prosodyarchive` WHERE %s ORDER BY `sort_id` %s%s;";
318 local args = { host, user or "", store, };
319 local where = { "`host` = ?", "`user` = ?", "`store` = ?", };
321 archive_where(query, args, where);
325 local stats = engine:select("SELECT COUNT(*) FROM `prosodyarchive` WHERE " .. t_concat(where, " AND "), unpack(args));
327 local _total = stats()
328 total = _total and _total[1];
330 if query.limit == 0 then -- Skip the real query
335 archive_where_id_range(query, args, where);
338 args[#args+1] = query.limit;
341 sql_query = sql_query:format(t_concat(where, " AND "), query.reverse and "DESC" or "ASC", query.limit and " LIMIT ?" or "");
342 module:log("debug", sql_query);
343 return engine:select(sql_query, unpack(args));
345 if not ok then return ok, result end
347 local row = result();
349 return row[1], deserialize(row[2], row[3]), row[4];
354 function archive_store:delete(username, query)
356 local user,store = username,self.store;
357 return engine:transaction(function()
358 local sql_query = "DELETE FROM `prosodyarchive` WHERE %s;";
359 local args = { host, user or "", store, };
360 local where = { "`host` = ?", "`user` = ?", "`store` = ?", };
362 table.remove(args, 2);
363 table.remove(where, 2);
365 archive_where(query, args, where);
366 archive_where_id_range(query, args, where);
367 sql_query = sql_query:format(t_concat(where, " AND "));
368 module:log("debug", sql_query);
369 return engine:delete(sql_query, unpack(args));
374 keyval = keyval_store;
376 archive = archive_store;
381 function driver:open(store, typ)
382 local store_mt = stores[typ or "keyval"];
384 return setmetatable({ store = store }, store_mt);
386 return nil, "unsupported-store";
389 function driver:stores(username)
390 local sql = "SELECT DISTINCT `store` FROM `prosody` WHERE `host`=? AND `user`" ..
391 (username == true and "!=?" or "=?");
392 if username == true or not username then
395 local ok, result = engine:transaction(function()
396 return engine:select(sql, host, username);
398 if not ok then return ok, result end
399 return iterator(result);
402 function driver:purge(username)
403 return engine:transaction(function()
404 local stmt,err = engine:delete("DELETE FROM `prosody` WHERE `host`=? AND `user`=?", host, username);
409 module:provides("storage", driver);