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