59583def2bf4ef82e77e72f28809af32fe4d656f
[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 = 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                                         local stmt = connection:prepare("ALTER TABLE prosody MODIFY COLUMN `value` MEDIUMTEXT");
107                                         local ok = stmt:execute();
108                                         local commit_ok = connection:commit();
109                                         if ok and commit_ok then
110                                                 module:log("info", "Database table automatically upgraded");
111                                         end
112                                 end
113                                 repeat until not stmt:fetch();
114                         else
115                                 module:log("error", "Failed to upgrade database schema, please see http://prosody.im/doc/mysql for help");
116                         end
117                 end
118         end
119 end
120
121 do -- process options to get a db connection
122         local ok;
123         prosody.unlock_globals();
124         ok, DBI = pcall(require, "DBI");
125         if not ok then
126                 package.loaded["DBI"] = {};
127                 module:log("error", "Failed to load the LuaDBI library for accessing SQL databases: %s", DBI);
128                 module:log("error", "More information on installing LuaDBI can be found at http://prosody.im/doc/depends#luadbi");
129         end
130         prosody.lock_globals();
131         if not ok or not DBI.Connect then
132                 return; -- Halt loading of this module
133         end
134
135         params = params or { driver = "SQLite3" };
136         
137         if params.driver == "SQLite3" then
138                 params.database = resolve_relative_path(prosody.paths.data or ".", params.database or "prosody.sqlite");
139         end
140         
141         assert(params.driver and params.database, "Both the SQL driver and the database need to be specified");
142         
143         assert(connect());
144         
145         -- Automatically create table, ignore failure (table probably already exists)
146         create_table();
147 end
148
149 local function serialize(value)
150         local t = type(value);
151         if t == "string" or t == "boolean" or t == "number" then
152                 return t, tostring(value);
153         elseif t == "table" then
154                 local value,err = json.encode(value);
155                 if value then return "json", value; end
156                 return nil, err;
157         end
158         return nil, "Unhandled value type: "..t;
159 end
160 local function deserialize(t, value)
161         if t == "string" then return value;
162         elseif t == "boolean" then
163                 if value == "true" then return true;
164                 elseif value == "false" then return false; end
165         elseif t == "number" then return tonumber(value);
166         elseif t == "json" then
167                 return json.decode(value);
168         end
169 end
170
171 local function getsql(sql, ...)
172         if params.driver == "PostgreSQL" then
173                 sql = sql:gsub("`", "\"");
174         end
175         -- do prepared statement stuff
176         local stmt, err = connection:prepare(sql);
177         if not stmt and not test_connection() then error("connection failed"); end
178         if not stmt then module:log("error", "QUERY FAILED: %s %s", err, debug.traceback()); return nil, err; end
179         -- run query
180         local ok, err = stmt:execute(host or "", user or "", store or "", ...);
181         if not ok and not test_connection() then error("connection failed"); end
182         if not ok then return nil, err; end
183         
184         return stmt;
185 end
186 local function setsql(sql, ...)
187         local stmt, err = getsql(sql, ...);
188         if not stmt then return stmt, err; end
189         return stmt:affected();
190 end
191 local function transact(...)
192         -- ...
193 end
194 local function rollback(...)
195         if connection then connection:rollback(); end -- FIXME check for rollback error?
196         return ...;
197 end
198 local function commit(...)
199         if not connection:commit() then return nil, "SQL commit failed"; end
200         return ...;
201 end
202
203 local function keyval_store_get()
204         local stmt, err = getsql("SELECT * FROM `prosody` WHERE `host`=? AND `user`=? AND `store`=?");
205         if not stmt then return rollback(nil, err); end
206         
207         local haveany;
208         local result = {};
209         for row in stmt:rows(true) do
210                 haveany = true;
211                 local k = row.key;
212                 local v = deserialize(row.type, row.value);
213                 if k and v then
214                         if k ~= "" then result[k] = v; elseif type(v) == "table" then
215                                 for a,b in pairs(v) do
216                                         result[a] = b;
217                                 end
218                         end
219                 end
220         end
221         return commit(haveany and result or nil);
222 end
223 local function keyval_store_set(data)
224         local affected, err = setsql("DELETE FROM `prosody` WHERE `host`=? AND `user`=? AND `store`=?");
225         if not affected then return rollback(affected, err); end
226         
227         if data and next(data) ~= nil then
228                 local extradata = {};
229                 for key, value in pairs(data) do
230                         if type(key) == "string" and key ~= "" then
231                                 local t, value = serialize(value);
232                                 if not t then return rollback(t, value); end
233                                 local ok, err = setsql("INSERT INTO `prosody` (`host`,`user`,`store`,`key`,`type`,`value`) VALUES (?,?,?,?,?,?)", key, t, value);
234                                 if not ok then return rollback(ok, err); end
235                         else
236                                 extradata[key] = value;
237                         end
238                 end
239                 if next(extradata) ~= nil then
240                         local t, extradata = serialize(extradata);
241                         if not t then return rollback(t, extradata); end
242                         local ok, err = setsql("INSERT INTO `prosody` (`host`,`user`,`store`,`key`,`type`,`value`) VALUES (?,?,?,?,?,?)", "", t, extradata);
243                         if not ok then return rollback(ok, err); end
244                 end
245         end
246         return commit(true);
247 end
248
249 local keyval_store = {};
250 keyval_store.__index = keyval_store;
251 function keyval_store:get(username)
252         user,store = username,self.store;
253         if not connection and not connect() then return nil, "Unable to connect to database"; end
254         local success, ret, err = xpcall(keyval_store_get, debug.traceback);
255         if not connection and connect() then
256                 success, ret, err = xpcall(keyval_store_get, debug.traceback);
257         end
258         if success then return ret, err; else return rollback(nil, ret); end
259 end
260 function keyval_store:set(username, data)
261         user,store = username,self.store;
262         if not connection and not connect() then return nil, "Unable to connect to database"; end
263         local success, ret, err = xpcall(function() return keyval_store_set(data); end, debug.traceback);
264         if not connection and connect() then
265                 success, ret, err = xpcall(function() return keyval_store_set(data); end, debug.traceback);
266         end
267         if success then return ret, err; else return rollback(nil, ret); end
268 end
269
270 local function map_store_get(key)
271         local stmt, err = getsql("SELECT * FROM `prosody` WHERE `host`=? AND `user`=? AND `store`=? AND `key`=?", key or "");
272         if not stmt then return rollback(nil, err); end
273         
274         local haveany;
275         local result = {};
276         for row in stmt:rows(true) do
277                 haveany = true;
278                 local k = row.key;
279                 local v = deserialize(row.type, row.value);
280                 if k and v then
281                         if k ~= "" then result[k] = v; elseif type(v) == "table" then
282                                 for a,b in pairs(v) do
283                                         result[a] = b;
284                                 end
285                         end
286                 end
287         end
288         return commit(haveany and result[key] or nil);
289 end
290 local function map_store_set(key, data)
291         local affected, err = setsql("DELETE FROM `prosody` WHERE `host`=? AND `user`=? AND `store`=? AND `key`=?", key or "");
292         if not affected then return rollback(affected, err); end
293         
294         if data and next(data) ~= nil then
295                 if type(key) == "string" and key ~= "" then
296                         local t, value = serialize(data);
297                         if not t then return rollback(t, value); end
298                         local ok, err = setsql("INSERT INTO `prosody` (`host`,`user`,`store`,`key`,`type`,`value`) VALUES (?,?,?,?,?,?)", key, t, value);
299                         if not ok then return rollback(ok, err); end
300                 else
301                         -- TODO non-string keys
302                 end
303         end
304         return commit(true);
305 end
306
307 local map_store = {};
308 map_store.__index = map_store;
309 function map_store:get(username, key)
310         user,store = username,self.store;
311         local success, ret, err = xpcall(function() return map_store_get(key); end, debug.traceback);
312         if success then return ret, err; else return rollback(nil, ret); end
313 end
314 function map_store:set(username, key, data)
315         user,store = username,self.store;
316         local success, ret, err = xpcall(function() return map_store_set(key, data); end, debug.traceback);
317         if success then return ret, err; else return rollback(nil, ret); end
318 end
319
320 local list_store = {};
321 list_store.__index = list_store;
322 function list_store:scan(username, from, to, jid, typ)
323         user,store = username,self.store;
324         
325         local cols = {"from", "to", "jid", "typ"};
326         local vals = { from ,  to ,  jid ,  typ };
327         local stmt, err;
328         local query = "SELECT * FROM `prosodyarchive` WHERE `host`=? AND `user`=? AND `store`=?";
329         
330         query = query.." ORDER BY time";
331         --local stmt, err = getsql("SELECT * FROM `prosody` WHERE `host`=? AND `user`=? AND `store`=? AND `key`=?", key or "");
332         
333         return nil, "not-implemented"
334 end
335
336 local driver = { name = "sql" };
337
338 function driver:open(store, typ)
339         if not typ then -- default key-value store
340                 return setmetatable({ store = store }, keyval_store);
341         end
342         return nil, "unsupported-store";
343 end
344
345 module:add_item("data-driver", driver);