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