6d19eee6a17de04e9ade93a9797d2927782dadeb
[prosody.git] / plugins / mod_storage_sql.lua
1
2 --[[
3
4 DB Tables:
5         Prosody - key-value, map
6                 | host | user | store | key | type | value |
7         ProsodyArchive - list
8                 | host | user | store | key | time | stanzatype | jsonvalue |
9
10 Mapping:
11         Roster - Prosody
12                 | host | user | "roster" | "contactjid" | type | value |
13                 | host | user | "roster" | NULL | "json" | roster[false] data |
14         Account - Prosody
15                 | host | user | "accounts" | "username" | type | value |
16
17         Offline - ProsodyArchive
18                 | host | user | "offline" | "contactjid" | time | "message" | json|XML |
19
20 ]]
21
22 local type = type;
23 local tostring = tostring;
24 local tonumber = tonumber;
25 local pairs = pairs;
26 local next = next;
27 local setmetatable = setmetatable;
28 local xpcall = xpcall;
29 local json = require "util.json";
30
31 local DBI;
32 local connection;
33 local host,user,store = module.host;
34 local params = module:get_option("sql");
35
36 local resolve_relative_path = require "core.configmanager".resolve_relative_path;
37
38 local function test_connection()
39         if not connection then return nil; end
40         if connection:ping() then
41                 return true;
42         else
43                 module:log("debug", "Database connection closed");
44                 connection = nil;
45         end
46 end
47 local function connect()
48         if not test_connection() then
49                 prosody.unlock_globals();
50                 local dbh, err = DBI.Connect(
51                         params.driver, params.database,
52                         params.username, params.password,
53                         params.host, params.port
54                 );
55                 prosody.lock_globals();
56                 if not dbh then
57                         module:log("debug", "Database connection failed: %s", tostring(err));
58                         return nil, err;
59                 end
60                 module:log("debug", "Successfully connected to database");
61                 dbh:autocommit(false); -- don't commit automatically
62                 connection = dbh;
63                 return connection;
64         end
65 end
66
67 local function create_table()
68         if not module:get_option("sql_manage_tables", true) then
69                 return;
70         end
71         local create_sql = "CREATE TABLE `prosody` (`host` TEXT, `user` TEXT, `store` TEXT, `key` TEXT, `type` TEXT, `value` TEXT);";
72         if params.driver == "PostgreSQL" then
73                 create_sql = create_sql:gsub("`", "\"");
74         elseif params.driver == "MySQL" then
75                 create_sql = create_sql:gsub("`value` TEXT", "`value` MEDIUMTEXT");
76         end
77         
78         local stmt, err = connection:prepare(create_sql);
79         if stmt then
80                 local ok = stmt:execute();
81                 local commit_ok = connection:commit();
82                 if ok and commit_ok then
83                         module:log("info", "Initialized new %s database with prosody table", params.driver);
84                         local index_sql = "CREATE INDEX `prosody_index` ON `prosody` (`host`, `user`, `store`, `key`)";
85                         if params.driver == "PostgreSQL" then
86                                 index_sql = index_sql:gsub("`", "\"");
87                         elseif params.driver == "MySQL" then
88                                 index_sql = index_sql:gsub("`([,)])", "`(20)%1");
89                         end
90                         local stmt, err = connection:prepare(index_sql);
91                         local ok, commit_ok, commit_err;
92                         if stmt then
93                                 ok, err = stmt:execute();
94                                 commit_ok, commit_err = connection:commit();
95                         end
96                         if not(ok and commit_ok) then
97                                 module:log("warn", "Failed to create index (%s), lookups may not be optimised", err or commit_err);
98                         end
99                 elseif params.driver == "MySQL" then  -- COMPAT: Upgrade tables from 0.8.0
100                         -- Failed to create, but check existing MySQL table here
101                         local stmt = connection:prepare("SHOW COLUMNS FROM prosody WHERE Field='value' and Type='text'");
102                         local ok = stmt:execute();
103                         local commit_ok = connection:commit();
104                         if ok and commit_ok then
105                                 if stmt:rowcount() > 0 then
106                                         module:log("info", "Upgrading database schema...");
107                                         local stmt = connection:prepare("ALTER TABLE prosody MODIFY COLUMN `value` MEDIUMTEXT");
108                                         local ok, err = stmt:execute();
109                                         local commit_ok = connection:commit();
110                                         if ok and commit_ok then
111                                                 module:log("info", "Database table automatically upgraded");
112                                         else
113                                                 module:log("error", "Failed to upgrade database schema (%s), please see "
114                                                         .."http://prosody.im/doc/mysql for help",
115                                                         err or "unknown error");
116                                         end
117                                 end
118                                 repeat until not stmt:fetch();
119                         end
120                 end
121         elseif params.driver ~= "SQLite3" then -- SQLite normally fails to prepare for existing table
122                 module:log("warn", "Prosody was not able to automatically check/create the database table (%s), "
123                         .."see http://prosody.im/doc/modules/mod_storage_sql#table_management for help.",
124                         err or "unknown error");
125         end
126 end
127
128 do -- process options to get a db connection
129         local ok;
130         prosody.unlock_globals();
131         ok, DBI = pcall(require, "DBI");
132         if not ok then
133                 package.loaded["DBI"] = {};
134                 module:log("error", "Failed to load the LuaDBI library for accessing SQL databases: %s", DBI);
135                 module:log("error", "More information on installing LuaDBI can be found at http://prosody.im/doc/depends#luadbi");
136         end
137         prosody.lock_globals();
138         if not ok or not DBI.Connect then
139                 return; -- Halt loading of this module
140         end
141
142         params = params or { driver = "SQLite3" };
143         
144         if params.driver == "SQLite3" then
145                 params.database = resolve_relative_path(prosody.paths.data or ".", params.database or "prosody.sqlite");
146         end
147         
148         assert(params.driver and params.database, "Both the SQL driver and the database need to be specified");
149         
150         assert(connect());
151         
152         -- Automatically create table, ignore failure (table probably already exists)
153         create_table();
154 end
155
156 local function serialize(value)
157         local t = type(value);
158         if t == "string" or t == "boolean" or t == "number" then
159                 return t, tostring(value);
160         elseif t == "table" then
161                 local value,err = json.encode(value);
162                 if value then return "json", value; end
163                 return nil, err;
164         end
165         return nil, "Unhandled value type: "..t;
166 end
167 local function deserialize(t, value)
168         if t == "string" then return value;
169         elseif t == "boolean" then
170                 if value == "true" then return true;
171                 elseif value == "false" then return false; end
172         elseif t == "number" then return tonumber(value);
173         elseif t == "json" then
174                 return json.decode(value);
175         end
176 end
177
178 local function dosql(sql, ...)
179         if params.driver == "PostgreSQL" then
180                 sql = sql:gsub("`", "\"");
181         end
182         -- do prepared statement stuff
183         local stmt, err = connection:prepare(sql);
184         if not stmt and not test_connection() then error("connection failed"); end
185         if not stmt then module:log("error", "QUERY FAILED: %s %s", err, debug.traceback()); return nil, err; end
186         -- run query
187         local ok, err = stmt:execute(...);
188         if not ok and not test_connection() then error("connection failed"); end
189         if not ok then return nil, err; end
190         
191         return stmt;
192 end
193 local function getsql(sql, ...)
194         return dosql(sql, host or "", user or "", store or "", ...);
195 end
196 local function setsql(sql, ...)
197         local stmt, err = getsql(sql, ...);
198         if not stmt then return stmt, err; end
199         return stmt:affected();
200 end
201 local function transact(...)
202         -- ...
203 end
204 local function rollback(...)
205         if connection then connection:rollback(); end -- FIXME check for rollback error?
206         return ...;
207 end
208 local function commit(...)
209         if not connection:commit() then return nil, "SQL commit failed"; end
210         return ...;
211 end
212
213 local function keyval_store_get()
214         local stmt, err = getsql("SELECT * FROM `prosody` WHERE `host`=? AND `user`=? AND `store`=?");
215         if not stmt then return rollback(nil, err); end
216         
217         local haveany;
218         local result = {};
219         for row in stmt:rows(true) do
220                 haveany = true;
221                 local k = row.key;
222                 local v = deserialize(row.type, row.value);
223                 if k and v then
224                         if k ~= "" then result[k] = v; elseif type(v) == "table" then
225                                 for a,b in pairs(v) do
226                                         result[a] = b;
227                                 end
228                         end
229                 end
230         end
231         return commit(haveany and result or nil);
232 end
233 local function keyval_store_set(data)
234         local affected, err = setsql("DELETE FROM `prosody` WHERE `host`=? AND `user`=? AND `store`=?");
235         if not affected then return rollback(affected, err); end
236         
237         if data and next(data) ~= nil then
238                 local extradata = {};
239                 for key, value in pairs(data) do
240                         if type(key) == "string" and key ~= "" then
241                                 local t, value = serialize(value);
242                                 if not t then return rollback(t, value); end
243                                 local ok, err = setsql("INSERT INTO `prosody` (`host`,`user`,`store`,`key`,`type`,`value`) VALUES (?,?,?,?,?,?)", key, t, value);
244                                 if not ok then return rollback(ok, err); end
245                         else
246                                 extradata[key] = value;
247                         end
248                 end
249                 if next(extradata) ~= nil then
250                         local t, extradata = serialize(extradata);
251                         if not t then return rollback(t, extradata); end
252                         local ok, err = setsql("INSERT INTO `prosody` (`host`,`user`,`store`,`key`,`type`,`value`) VALUES (?,?,?,?,?,?)", "", t, extradata);
253                         if not ok then return rollback(ok, err); end
254                 end
255         end
256         return commit(true);
257 end
258
259 local keyval_store = {};
260 keyval_store.__index = keyval_store;
261 function keyval_store:get(username)
262         user,store = username,self.store;
263         if not connection and not connect() then return nil, "Unable to connect to database"; end
264         local success, ret, err = xpcall(keyval_store_get, debug.traceback);
265         if not connection and connect() then
266                 success, ret, err = xpcall(keyval_store_get, debug.traceback);
267         end
268         if success then return ret, err; else return rollback(nil, ret); end
269 end
270 function keyval_store:set(username, data)
271         user,store = username,self.store;
272         if not connection and not connect() then return nil, "Unable to connect to database"; end
273         local success, ret, err = xpcall(function() return keyval_store_set(data); end, debug.traceback);
274         if not connection and connect() then
275                 success, ret, err = xpcall(function() return keyval_store_set(data); end, debug.traceback);
276         end
277         if success then return ret, err; else return rollback(nil, ret); end
278 end
279
280 local function map_store_get(key)
281         local stmt, err = getsql("SELECT * FROM `prosody` WHERE `host`=? AND `user`=? AND `store`=? AND `key`=?", key or "");
282         if not stmt then return rollback(nil, err); end
283         
284         local haveany;
285         local result = {};
286         for row in stmt:rows(true) do
287                 haveany = true;
288                 local k = row.key;
289                 local v = deserialize(row.type, row.value);
290                 if k and v then
291                         if k ~= "" then result[k] = v; elseif type(v) == "table" then
292                                 for a,b in pairs(v) do
293                                         result[a] = b;
294                                 end
295                         end
296                 end
297         end
298         return commit(haveany and result[key] or nil);
299 end
300 local function map_store_set(key, data)
301         local affected, err = setsql("DELETE FROM `prosody` WHERE `host`=? AND `user`=? AND `store`=? AND `key`=?", key or "");
302         if not affected then return rollback(affected, err); end
303         
304         if data and next(data) ~= nil then
305                 if type(key) == "string" and key ~= "" then
306                         local t, value = serialize(data);
307                         if not t then return rollback(t, value); end
308                         local ok, err = setsql("INSERT INTO `prosody` (`host`,`user`,`store`,`key`,`type`,`value`) VALUES (?,?,?,?,?,?)", key, t, value);
309                         if not ok then return rollback(ok, err); end
310                 else
311                         -- TODO non-string keys
312                 end
313         end
314         return commit(true);
315 end
316
317 local map_store = {};
318 map_store.__index = map_store;
319 function map_store:get(username, key)
320         user,store = username,self.store;
321         local success, ret, err = xpcall(function() return map_store_get(key); end, debug.traceback);
322         if success then return ret, err; else return rollback(nil, ret); end
323 end
324 function map_store:set(username, key, data)
325         user,store = username,self.store;
326         local success, ret, err = xpcall(function() return map_store_set(key, data); end, debug.traceback);
327         if success then return ret, err; else return rollback(nil, ret); end
328 end
329
330 local list_store = {};
331 list_store.__index = list_store;
332 function list_store:scan(username, from, to, jid, typ)
333         user,store = username,self.store;
334         
335         local cols = {"from", "to", "jid", "typ"};
336         local vals = { from ,  to ,  jid ,  typ };
337         local stmt, err;
338         local query = "SELECT * FROM `prosodyarchive` WHERE `host`=? AND `user`=? AND `store`=?";
339         
340         query = query.." ORDER BY time";
341         --local stmt, err = getsql("SELECT * FROM `prosody` WHERE `host`=? AND `user`=? AND `store`=? AND `key`=?", key or "");
342         
343         return nil, "not-implemented"
344 end
345
346 local driver = { name = "sql" };
347
348 function driver:open(store, typ)
349         if not typ then -- default key-value store
350                 return setmetatable({ store = store }, keyval_store);
351         end
352         return nil, "unsupported-store";
353 end
354
355 function driver:list_stores(username) -- Not to be confused with the list store type
356         local sql = (username == true
357                 and "SELECT DISTINCT `store` FROM `prosody` WHERE `host`=? AND `user`!=?"
358                 or  "SELECT DISTINCT `store` FROM `prosody` WHERE `host`=? AND `user`=?");
359         if username == true or not username then
360                 username = "";
361         end
362         local stmt, err = dosql(sql, host, username);
363         if not stmt then
364                 return nil, err;
365         end
366         local stores = {};
367         for row in stmt:rows() do
368                 stores[#stores+1] = row[1];
369         end
370         return stores;
371 end
372
373 function driver:purge(username)
374         local stmt, err = dosql("DELETE FROM `prosody` WHERE `host`=? AND `user`=?", host, username);
375         if not stmt then return stmt, err; end
376         local changed, err = stmt:affected();
377         if not changed then return changed, err; end
378         return true, changed;
379 end
380
381 module:add_item("data-driver", driver);