mod_storage_sql2: Some reformatting and variable name improvements
[prosody.git] / plugins / mod_storage_sql2.lua
1
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;
6
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
11
12 local noop = function() end
13 local unpack = unpack
14 local function iterator(result)
15         return function(result)
16                 local row = result();
17                 if row ~= nil then
18                         return unpack(row);
19                 end
20         end, result, nil;
21 end
22
23 local mod_sql = module:require("sql");
24 local params = module:get_option("sql");
25
26 local engine; -- TODO create engine
27
28 local function create_table()
29         local Table,Column,Index = mod_sql.Table,mod_sql.Column,mod_sql.Index;
30
31         local ProsodyTable = Table {
32                 name="prosody";
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" };
40         };
41         engine:transaction(function()
42                 ProsodyTable:create(engine);
43         end);
44
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" };
57         };
58         engine:transaction(function()
59                 ProsodyArchiveTable:create(engine);
60         end);
61 end
62
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");
71                         end
72                         return true;
73                 end);
74                 if not success then
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");
78                         return false;
79                 end
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));
93                                 end
94                                 module:log("info", "Database encoding upgrade complete!");
95                         end
96                 end);
97                 success,err = engine:transaction(function() return engine:execute(check_encoding_query); end);
98                 if not success then
99                         module:log("error", "Failed to check/upgrade database encoding: %s", err or "unknown error");
100                 end
101         end
102 end
103
104 do -- process options to get a db connection
105         params = params or { driver = "SQLite3" };
106
107         if params.driver == "SQLite3" then
108                 params.database = resolve_relative_path(prosody.paths.data or ".", params.database or "prosody.sqlite");
109         end
110
111         assert(params.driver and params.database, "Both the SQL driver and the database need to be specified");
112
113         --local dburi = db2uri(params);
114         engine = mod_sql:create_engine(params);
115
116         if module:get_option("sql_manage_tables", true) then
117                 -- Automatically create table, ignore failure (table probably already exists)
118                 create_table();
119                 -- Encoding mess
120                 upgrade_table();
121         end
122 end
123
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
133                 return nil, err;
134         end
135         return nil, "Unhandled value type: "..t;
136 end
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);
147         end
148 end
149
150 local host = module.host;
151 local user, store;
152
153 local function keyval_store_get()
154         local haveany;
155         local result = {};
156         for row in engine:select("SELECT `key`,`type`,`value` FROM `prosody` WHERE `host`=? AND `user`=? AND `store`=?", host, user or "", store) do
157                 haveany = true;
158                 local k = row[1];
159                 local v = deserialize(row[2], row[3]);
160                 if k and v then
161                         if k ~= "" then result[k] = v; elseif type(v) == "table" then
162                                 for a,b in pairs(v) do
163                                         result[a] = b;
164                                 end
165                         end
166                 end
167         end
168         if haveany then
169                 return result;
170         end
171 end
172 local function keyval_store_set(data)
173         engine:delete("DELETE FROM `prosody` WHERE `host`=? AND `user`=? AND `store`=?", host, user or "", store);
174
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);
180                                 assert(t, value);
181                                 engine:insert("INSERT INTO `prosody` (`host`,`user`,`store`,`key`,`type`,`value`) VALUES (?,?,?,?,?,?)", host, user or "", store, key, t, value);
182                         else
183                                 extradata[key] = value;
184                         end
185                 end
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);
190                 end
191         end
192         return true;
193 end
194
195 --- Key/value store API (default store type)
196
197 local keyval_store = {};
198 keyval_store.__index = keyval_store;
199 function keyval_store:get(username)
200         user, store = username, self.store;
201         local ok, result = engine:transaction(keyval_store_get);
202         if not ok then return ok, result; end
203         return result;
204 end
205 function keyval_store:set(username, data)
206         user,store = username,self.store;
207         return engine:transaction(function()
208                 return keyval_store_set(data);
209         end);
210 end
211 function keyval_store:users()
212         local ok, result = engine:transaction(function()
213                 return engine:select("SELECT DISTINCT `user` FROM `prosody` WHERE `host`=? AND `store`=?", host, self.store);
214         end);
215         if not ok then return ok, result end
216         return iterator(result);
217 end
218
219 --- Archive store API
220
221 local archive_store = {}
222 archive_store.__index = archive_store
223 function archive_store:append(username, key, when, with, value)
224         if value == nil then -- COMPAT early versions
225                 when, with, value, key = key, when, with, value
226         end
227         local user,store = username,self.store;
228         return engine:transaction(function()
229                 if key then
230                         engine:delete("DELETE FROM `prosodyarchive` WHERE `host`=? AND `user`=? AND `store`=? AND `key`=?", host, user or "", store, key);
231                 else
232                         key = uuid.generate();
233                 end
234                 local t, value = serialize(value);
235                 engine:insert("INSERT INTO `prosodyarchive` (`host`, `user`, `store`, `when`, `with`, `key`, `type`, `value`) VALUES (?,?,?,?,?,?,?,?)", host, user or "", store, when, with, key, t, value);
236                 return key;
237         end);
238 end
239
240 -- Helpers for building the WHERE clause
241 local function archive_where(query, args, where)
242         -- Time range, inclusive
243         if query.start then
244                 args[#args+1] = query.start
245                 where[#where+1] = "`when` >= ?"
246         end
247
248         if query["end"] then
249                 args[#args+1] = query["end"];
250                 if query.start then
251                         where[#where] = "`when` BETWEEN ? AND ?" -- is this inclusive?
252                 else
253                         where[#where+1] = "`when` <= ?"
254                 end
255         end
256
257         -- Related name
258         if query.with then
259                 where[#where+1] = "`with` = ?";
260                 args[#args+1] = query.with
261         end
262
263         -- Unique id
264         if query.key then
265                 where[#where+1] = "`key` = ?";
266                 args[#args+1] = query.key
267         end
268 end
269 local function archive_where_id_range(query, args, where)
270         local args_len = #args
271         -- Before or after specific item, exclusive
272         if query.after then  -- keys better be unique!
273                 where[#where+1] = "`sort_id` > (SELECT `sort_id` FROM `prosodyarchive` WHERE `key` = ? AND `host` = ? AND `user` = ? AND `store` = ? LIMIT 1)"
274                 args[args_len+1], args[args_len+2], args[args_len+3], args[args_len+4] = query.after, args[1], args[2], args[3];
275                 args_len = args_len + 4
276         end
277         if query.before then
278                 where[#where+1] = "`sort_id` < (SELECT `sort_id` FROM `prosodyarchive` WHERE `key` = ? AND `host` = ? AND `user` = ? AND `store` = ? LIMIT 1)"
279                 args[args_len+1], args[args_len+2], args[args_len+3], args[args_len+4] = query.before, args[1], args[2], args[3];
280         end
281 end
282
283 function archive_store:find(username, query)
284         query = query or {};
285         local user,store = username,self.store;
286         local total;
287         local ok, result = engine:transaction(function()
288                 local sql_query = "SELECT `key`, `type`, `value`, `when` FROM `prosodyarchive` WHERE %s ORDER BY `sort_id` %s%s;";
289                 local args = { host, user or "", store, };
290                 local where = { "`host` = ?", "`user` = ?", "`store` = ?", };
291
292                 archive_where(query, args, where);
293
294                 -- Total matching
295                 if query.total then
296                         local stats = engine:select("SELECT COUNT(*) FROM `prosodyarchive` WHERE " .. t_concat(where, " AND "), unpack(args));
297                         if stats then
298                                 local _total = stats()
299                                 total = _total and _total[1];
300                         end
301                         if query.limit == 0 then -- Skip the real query
302                                 return noop, total;
303                         end
304                 end
305
306                 archive_where_id_range(query, args, where);
307
308                 if query.limit then
309                         args[#args+1] = query.limit;
310                 end
311
312                 sql_query = sql_query:format(t_concat(where, " AND "), query.reverse and "DESC" or "ASC", query.limit and " LIMIT ?" or "");
313                 module:log("debug", sql_query);
314                 return engine:select(sql_query, unpack(args));
315         end);
316         if not ok then return ok, result end
317         return function()
318                 local row = result();
319                 if row ~= nil then
320                         return row[1], deserialize(row[2], row[3]), row[4];
321                 end
322         end, total;
323 end
324
325 function archive_store:delete(username, query)
326         query = query or {};
327         local user,store = username,self.store;
328         return engine:transaction(function()
329                 local sql_query = "DELETE FROM `prosodyarchive` WHERE %s;";
330                 local args = { host, user or "", store, };
331                 local where = { "`host` = ?", "`user` = ?", "`store` = ?", };
332                 if user == true then
333                         table.remove(args, 2);
334                         table.remove(where, 2);
335                 end
336                 archive_where(query, args, where);
337                 archive_where_id_range(query, args, where);
338                 sql_query = sql_query:format(t_concat(where, " AND "));
339                 module:log("debug", sql_query);
340                 return engine:delete(sql_query, unpack(args));
341         end);
342 end
343
344 local stores = {
345         keyval = keyval_store;
346         archive = archive_store;
347 };
348
349 --- Implement storage driver API
350
351 -- FIXME: Some of these operations need to operate on the archive store(s) too
352
353 local driver = {};
354
355 function driver:open(store, typ)
356         local store_mt = stores[typ or "keyval"];
357         if store_mt then
358                 return setmetatable({ store = store }, store_mt);
359         end
360         return nil, "unsupported-store";
361 end
362
363 function driver:stores(username)
364         local query = "SELECT DISTINCT `store` FROM `prosody` WHERE `host`=? AND `user`" ..
365                 (username == true and "!=?" or "=?");
366         if username == true or not username then
367                 username = "";
368         end
369         local ok, result = engine:transaction(function()
370                 return engine:select(query, host, username);
371         end);
372         if not ok then return ok, result end
373         return iterator(result);
374 end
375
376 function driver:purge(username)
377         return engine:transaction(function()
378                 local stmt,err = engine:delete("DELETE FROM `prosody` WHERE `host`=? AND `user`=?", host, username);
379                 return true, err;
380         end);
381 end
382
383 module:provides("storage", driver);
384
385