6a2d36f102b4550b599aa878b306bd9cf6a10044
[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 getsql(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(host or "", user or "", store or "", ...);
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 setsql(sql, ...)
194         local stmt, err = getsql(sql, ...);
195         if not stmt then return stmt, err; end
196         return stmt:affected();
197 end
198 local function transact(...)
199         -- ...
200 end
201 local function rollback(...)
202         if connection then connection:rollback(); end -- FIXME check for rollback error?
203         return ...;
204 end
205 local function commit(...)
206         if not connection:commit() then return nil, "SQL commit failed"; end
207         return ...;
208 end
209
210 local function keyval_store_get()
211         local stmt, err = getsql("SELECT * FROM `prosody` WHERE `host`=? AND `user`=? AND `store`=?");
212         if not stmt then return rollback(nil, err); end
213         
214         local haveany;
215         local result = {};
216         for row in stmt:rows(true) do
217                 haveany = true;
218                 local k = row.key;
219                 local v = deserialize(row.type, row.value);
220                 if k and v then
221                         if k ~= "" then result[k] = v; elseif type(v) == "table" then
222                                 for a,b in pairs(v) do
223                                         result[a] = b;
224                                 end
225                         end
226                 end
227         end
228         return commit(haveany and result or nil);
229 end
230 local function keyval_store_set(data)
231         local affected, err = setsql("DELETE FROM `prosody` WHERE `host`=? AND `user`=? AND `store`=?");
232         if not affected then return rollback(affected, err); end
233         
234         if data and next(data) ~= nil then
235                 local extradata = {};
236                 for key, value in pairs(data) do
237                         if type(key) == "string" and key ~= "" then
238                                 local t, value = serialize(value);
239                                 if not t then return rollback(t, value); end
240                                 local ok, err = setsql("INSERT INTO `prosody` (`host`,`user`,`store`,`key`,`type`,`value`) VALUES (?,?,?,?,?,?)", key, t, value);
241                                 if not ok then return rollback(ok, err); end
242                         else
243                                 extradata[key] = value;
244                         end
245                 end
246                 if next(extradata) ~= nil then
247                         local t, extradata = serialize(extradata);
248                         if not t then return rollback(t, extradata); end
249                         local ok, err = setsql("INSERT INTO `prosody` (`host`,`user`,`store`,`key`,`type`,`value`) VALUES (?,?,?,?,?,?)", "", t, extradata);
250                         if not ok then return rollback(ok, err); end
251                 end
252         end
253         return commit(true);
254 end
255
256 local keyval_store = {};
257 keyval_store.__index = keyval_store;
258 function keyval_store:get(username)
259         user,store = username,self.store;
260         if not connection and not connect() then return nil, "Unable to connect to database"; end
261         local success, ret, err = xpcall(keyval_store_get, debug.traceback);
262         if not connection and connect() then
263                 success, ret, err = xpcall(keyval_store_get, debug.traceback);
264         end
265         if success then return ret, err; else return rollback(nil, ret); end
266 end
267 function keyval_store:set(username, data)
268         user,store = username,self.store;
269         if not connection and not connect() then return nil, "Unable to connect to database"; end
270         local success, ret, err = xpcall(function() return keyval_store_set(data); end, debug.traceback);
271         if not connection and connect() then
272                 success, ret, err = xpcall(function() return keyval_store_set(data); end, debug.traceback);
273         end
274         if success then return ret, err; else return rollback(nil, ret); end
275 end
276
277 local function map_store_get(key)
278         local stmt, err = getsql("SELECT * FROM `prosody` WHERE `host`=? AND `user`=? AND `store`=? AND `key`=?", key or "");
279         if not stmt then return rollback(nil, err); end
280         
281         local haveany;
282         local result = {};
283         for row in stmt:rows(true) do
284                 haveany = true;
285                 local k = row.key;
286                 local v = deserialize(row.type, row.value);
287                 if k and v then
288                         if k ~= "" then result[k] = v; elseif type(v) == "table" then
289                                 for a,b in pairs(v) do
290                                         result[a] = b;
291                                 end
292                         end
293                 end
294         end
295         return commit(haveany and result[key] or nil);
296 end
297 local function map_store_set(key, data)
298         local affected, err = setsql("DELETE FROM `prosody` WHERE `host`=? AND `user`=? AND `store`=? AND `key`=?", key or "");
299         if not affected then return rollback(affected, err); end
300         
301         if data and next(data) ~= nil then
302                 if type(key) == "string" and key ~= "" then
303                         local t, value = serialize(data);
304                         if not t then return rollback(t, value); end
305                         local ok, err = setsql("INSERT INTO `prosody` (`host`,`user`,`store`,`key`,`type`,`value`) VALUES (?,?,?,?,?,?)", key, t, value);
306                         if not ok then return rollback(ok, err); end
307                 else
308                         -- TODO non-string keys
309                 end
310         end
311         return commit(true);
312 end
313
314 local map_store = {};
315 map_store.__index = map_store;
316 function map_store:get(username, key)
317         user,store = username,self.store;
318         local success, ret, err = xpcall(function() return map_store_get(key); end, debug.traceback);
319         if success then return ret, err; else return rollback(nil, ret); end
320 end
321 function map_store:set(username, key, data)
322         user,store = username,self.store;
323         local success, ret, err = xpcall(function() return map_store_set(key, data); end, debug.traceback);
324         if success then return ret, err; else return rollback(nil, ret); end
325 end
326
327 local list_store = {};
328 list_store.__index = list_store;
329 function list_store:scan(username, from, to, jid, typ)
330         user,store = username,self.store;
331         
332         local cols = {"from", "to", "jid", "typ"};
333         local vals = { from ,  to ,  jid ,  typ };
334         local stmt, err;
335         local query = "SELECT * FROM `prosodyarchive` WHERE `host`=? AND `user`=? AND `store`=?";
336         
337         query = query.." ORDER BY time";
338         --local stmt, err = getsql("SELECT * FROM `prosody` WHERE `host`=? AND `user`=? AND `store`=? AND `key`=?", key or "");
339         
340         return nil, "not-implemented"
341 end
342
343 local driver = { name = "sql" };
344
345 function driver:open(store, typ)
346         if not typ then -- default key-value store
347                 return setmetatable({ store = store }, keyval_store);
348         end
349         return nil, "unsupported-store";
350 end
351
352 module:add_item("data-driver", driver);