Comparison

plugins/mod_storage_sql.lua @ 6951:99de8f30d99e

storagemanager, mod_storage_sql, mod_storage_sql2: Rename mod_storage_sql2 -> mod_storage_sql, mod_storage_sql -> mod_storage_sql1 (temporarily), and emit warning for configs using sql2
author Matthew Wild <mwild1@gmail.com>
date Thu, 03 Dec 2015 14:57:49 +0000
parent 6283:7cf6d3a2c855
child 6953:b9276d677e76
comparison
equal deleted inserted replaced
6950:8ab809358922 6951:99de8f30d99e
1 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"; 2 local json = require "util.json";
30 local build_url = require"socket.url".build; 3 local sql = require "util.sql";
31 4 local xml_parse = require "util.xml".parse;
32 local DBI; 5 local uuid = require "util.uuid";
33 local connection;
34 local host,user,store = module.host;
35 local params = module:get_option("sql");
36
37 local dburi;
38 local connections = module:shared "/*/sql/connection-cache";
39
40 local function db2uri(params)
41 return build_url{
42 scheme = params.driver,
43 user = params.username,
44 password = params.password,
45 host = params.host,
46 port = params.port,
47 path = params.database,
48 };
49 end
50
51
52 local resolve_relative_path = require "util.paths".resolve_relative_path; 6 local resolve_relative_path = require "util.paths".resolve_relative_path;
53 7
54 local function test_connection() 8 local stanza_mt = require"util.stanza".stanza_mt;
55 if not connection then return nil; end 9 local getmetatable = getmetatable;
56 if connection:ping() then 10 local t_concat = table.concat;
57 return true; 11 local function is_stanza(x) return getmetatable(x) == stanza_mt; end
58 else 12
59 module:log("debug", "Database connection closed"); 13 local noop = function() end
60 connection = nil; 14 local unpack = unpack
61 connections[dburi] = nil; 15 local function iterator(result)
62 end 16 return function(result_)
63 end 17 local row = result_();
64 local function connect() 18 if row ~= nil then
65 if not test_connection() then 19 return unpack(row);
66 prosody.unlock_globals(); 20 end
67 local dbh, err = DBI.Connect( 21 end, result, nil;
68 params.driver, params.database, 22 end
69 params.username, params.password, 23
70 params.host, params.port 24 local default_params = { driver = "SQLite3" };
71 ); 25
72 prosody.lock_globals(); 26 local engine;
73 if not dbh then
74 module:log("debug", "Database connection failed: %s", tostring(err));
75 return nil, err;
76 end
77 module:log("debug", "Successfully connected to database");
78 dbh:autocommit(false); -- don't commit automatically
79 connection = dbh;
80
81 connections[dburi] = dbh;
82 end
83 return connection;
84 end
85
86 local function create_table()
87 if not module:get_option("sql_manage_tables", true) then
88 return;
89 end
90 local create_sql = "CREATE TABLE `prosody` (`host` TEXT, `user` TEXT, `store` TEXT, `key` TEXT, `type` TEXT, `value` TEXT);";
91 if params.driver == "PostgreSQL" then
92 create_sql = create_sql:gsub("`", "\"");
93 elseif params.driver == "MySQL" then
94 create_sql = create_sql:gsub("`value` TEXT", "`value` MEDIUMTEXT");
95 end
96
97 local stmt, err = connection:prepare(create_sql);
98 if stmt then
99 local ok = stmt:execute();
100 local commit_ok = connection:commit();
101 if ok and commit_ok then
102 module:log("info", "Initialized new %s database with prosody table", params.driver);
103 local index_sql = "CREATE INDEX `prosody_index` ON `prosody` (`host`, `user`, `store`, `key`)";
104 if params.driver == "PostgreSQL" then
105 index_sql = index_sql:gsub("`", "\"");
106 elseif params.driver == "MySQL" then
107 index_sql = index_sql:gsub("`([,)])", "`(20)%1");
108 end
109 local stmt, err = connection:prepare(index_sql);
110 local ok, commit_ok, commit_err;
111 if stmt then
112 ok, err = stmt:execute();
113 commit_ok, commit_err = connection:commit();
114 end
115 if not(ok and commit_ok) then
116 module:log("warn", "Failed to create index (%s), lookups may not be optimised", err or commit_err);
117 end
118 elseif params.driver == "MySQL" then -- COMPAT: Upgrade tables from 0.8.0
119 -- Failed to create, but check existing MySQL table here
120 local stmt = connection:prepare("SHOW COLUMNS FROM prosody WHERE Field='value' and Type='text'");
121 local ok = stmt:execute();
122 local commit_ok = connection:commit();
123 if ok and commit_ok then
124 if stmt:rowcount() > 0 then
125 module:log("info", "Upgrading database schema...");
126 local stmt = connection:prepare("ALTER TABLE prosody MODIFY COLUMN `value` MEDIUMTEXT");
127 local ok, err = stmt:execute();
128 local commit_ok = connection:commit();
129 if ok and commit_ok then
130 module:log("info", "Database table automatically upgraded");
131 else
132 module:log("error", "Failed to upgrade database schema (%s), please see "
133 .."http://prosody.im/doc/mysql for help",
134 err or "unknown error");
135 end
136 end
137 repeat until not stmt:fetch();
138 end
139 end
140 elseif params.driver ~= "SQLite3" then -- SQLite normally fails to prepare for existing table
141 module:log("warn", "Prosody was not able to automatically check/create the database table (%s), "
142 .."see http://prosody.im/doc/modules/mod_storage_sql#table_management for help.",
143 err or "unknown error");
144 end
145 end
146
147 do -- process options to get a db connection
148 local ok;
149 prosody.unlock_globals();
150 ok, DBI = pcall(require, "DBI");
151 if not ok then
152 package.loaded["DBI"] = {};
153 module:log("error", "Failed to load the LuaDBI library for accessing SQL databases: %s", DBI);
154 module:log("error", "More information on installing LuaDBI can be found at http://prosody.im/doc/depends#luadbi");
155 end
156 prosody.lock_globals();
157 if not ok or not DBI.Connect then
158 return; -- Halt loading of this module
159 end
160
161 params = params or { driver = "SQLite3" };
162
163 if params.driver == "SQLite3" then
164 params.database = resolve_relative_path(prosody.paths.data or ".", params.database or "prosody.sqlite");
165 end
166
167 assert(params.driver and params.database, "Both the SQL driver and the database need to be specified");
168
169 dburi = db2uri(params);
170 connection = connections[dburi];
171
172 assert(connect());
173
174 -- Automatically create table, ignore failure (table probably already exists)
175 create_table();
176 end
177 27
178 local function serialize(value) 28 local function serialize(value)
179 local t = type(value); 29 local t = type(value);
180 if t == "string" or t == "boolean" or t == "number" then 30 if t == "string" or t == "boolean" or t == "number" then
181 return t, tostring(value); 31 return t, tostring(value);
32 elseif is_stanza(value) then
33 return "xml", tostring(value);
182 elseif t == "table" then 34 elseif t == "table" then
183 local value,err = json.encode(value); 35 local value,err = json.encode(value);
184 if value then return "json", value; end 36 if value then return "json", value; end
185 return nil, err; 37 return nil, err;
186 end 38 end
192 if value == "true" then return true; 44 if value == "true" then return true;
193 elseif value == "false" then return false; end 45 elseif value == "false" then return false; end
194 elseif t == "number" then return tonumber(value); 46 elseif t == "number" then return tonumber(value);
195 elseif t == "json" then 47 elseif t == "json" then
196 return json.decode(value); 48 return json.decode(value);
197 end 49 elseif t == "xml" then
198 end 50 return xml_parse(value);
199 51 end
200 local function dosql(sql, ...) 52 end
201 if params.driver == "PostgreSQL" then 53
202 sql = sql:gsub("`", "\""); 54 local host = module.host;
203 end 55 local user, store;
204 -- do prepared statement stuff
205 local stmt, err = connection:prepare(sql);
206 if not stmt and not test_connection() then error("connection failed"); end
207 if not stmt then module:log("error", "QUERY FAILED: %s %s", err, debug.traceback()); return nil, err; end
208 -- run query
209 local ok, err = stmt:execute(...);
210 if not ok and not test_connection() then error("connection failed"); end
211 if not ok then return nil, err; end
212
213 return stmt;
214 end
215 local function getsql(sql, ...)
216 return dosql(sql, host or "", user or "", store or "", ...);
217 end
218 local function setsql(sql, ...)
219 local stmt, err = getsql(sql, ...);
220 if not stmt then return stmt, err; end
221 return stmt:affected();
222 end
223 local function transact(...)
224 -- ...
225 end
226 local function rollback(...)
227 if connection then connection:rollback(); end -- FIXME check for rollback error?
228 return ...;
229 end
230 local function commit(...)
231 local success,err = connection:commit();
232 if not success then return nil, "SQL commit failed: "..tostring(err); end
233 return ...;
234 end
235 56
236 local function keyval_store_get() 57 local function keyval_store_get()
237 local stmt, err = getsql("SELECT * FROM `prosody` WHERE `host`=? AND `user`=? AND `store`=?");
238 if not stmt then return rollback(nil, err); end
239
240 local haveany; 58 local haveany;
241 local result = {}; 59 local result = {};
242 for row in stmt:rows(true) do 60 for row in engine:select("SELECT `key`,`type`,`value` FROM `prosody` WHERE `host`=? AND `user`=? AND `store`=?", host, user or "", store) do
243 haveany = true; 61 haveany = true;
244 local k = row.key; 62 local k = row[1];
245 local v = deserialize(row.type, row.value); 63 local v = deserialize(row[2], row[3]);
246 if k and v then 64 if k and v then
247 if k ~= "" then result[k] = v; elseif type(v) == "table" then 65 if k ~= "" then result[k] = v; elseif type(v) == "table" then
248 for a,b in pairs(v) do 66 for a,b in pairs(v) do
249 result[a] = b; 67 result[a] = b;
250 end 68 end
251 end 69 end
252 end 70 end
253 end 71 end
254 return commit(haveany and result or nil); 72 if haveany then
73 return result;
74 end
255 end 75 end
256 local function keyval_store_set(data) 76 local function keyval_store_set(data)
257 local affected, err = setsql("DELETE FROM `prosody` WHERE `host`=? AND `user`=? AND `store`=?"); 77 engine:delete("DELETE FROM `prosody` WHERE `host`=? AND `user`=? AND `store`=?", host, user or "", store);
258 if not affected then return rollback(affected, err); end
259 78
260 if data and next(data) ~= nil then 79 if data and next(data) ~= nil then
261 local extradata = {}; 80 local extradata = {};
262 for key, value in pairs(data) do 81 for key, value in pairs(data) do
263 if type(key) == "string" and key ~= "" then 82 if type(key) == "string" and key ~= "" then
264 local t, value = serialize(value); 83 local t, value = serialize(value);
265 if not t then return rollback(t, value); end 84 assert(t, value);
266 local ok, err = setsql("INSERT INTO `prosody` (`host`,`user`,`store`,`key`,`type`,`value`) VALUES (?,?,?,?,?,?)", key, t, value); 85 engine:insert("INSERT INTO `prosody` (`host`,`user`,`store`,`key`,`type`,`value`) VALUES (?,?,?,?,?,?)", host, user or "", store, key, t, value);
267 if not ok then return rollback(ok, err); end
268 else 86 else
269 extradata[key] = value; 87 extradata[key] = value;
270 end 88 end
271 end 89 end
272 if next(extradata) ~= nil then 90 if next(extradata) ~= nil then
273 local t, extradata = serialize(extradata); 91 local t, extradata = serialize(extradata);
274 if not t then return rollback(t, extradata); end 92 assert(t, extradata);
275 local ok, err = setsql("INSERT INTO `prosody` (`host`,`user`,`store`,`key`,`type`,`value`) VALUES (?,?,?,?,?,?)", "", t, extradata); 93 engine:insert("INSERT INTO `prosody` (`host`,`user`,`store`,`key`,`type`,`value`) VALUES (?,?,?,?,?,?)", host, user or "", store, "", t, extradata);
276 if not ok then return rollback(ok, err); end 94 end
277 end 95 end
278 end 96 return true;
279 return commit(true); 97 end
280 end 98
99 --- Key/value store API (default store type)
281 100
282 local keyval_store = {}; 101 local keyval_store = {};
283 keyval_store.__index = keyval_store; 102 keyval_store.__index = keyval_store;
284 function keyval_store:get(username) 103 function keyval_store:get(username)
285 user,store = username,self.store; 104 user, store = username, self.store;
286 if not connection and not connect() then return nil, "Unable to connect to database"; end 105 local ok, result = engine:transaction(keyval_store_get);
287 local success, ret, err = xpcall(keyval_store_get, debug.traceback); 106 if not ok then
288 if not connection and connect() then 107 module:log("error", "Unable to read from database %s store for %s: %s", store, username or "<host>", result);
289 success, ret, err = xpcall(keyval_store_get, debug.traceback); 108 return nil, result;
290 end 109 end
291 if success then return ret, err; else return rollback(nil, ret); end 110 return result;
292 end 111 end
293 function keyval_store:set(username, data) 112 function keyval_store:set(username, data)
294 user,store = username,self.store; 113 user,store = username,self.store;
295 if not connection and not connect() then return nil, "Unable to connect to database"; end 114 return engine:transaction(function()
296 local success, ret, err = xpcall(function() return keyval_store_set(data); end, debug.traceback); 115 return keyval_store_set(data);
297 if not connection and connect() then 116 end);
298 success, ret, err = xpcall(function() return keyval_store_set(data); end, debug.traceback);
299 end
300 if success then return ret, err; else return rollback(nil, ret); end
301 end 117 end
302 function keyval_store:users() 118 function keyval_store:users()
303 local stmt, err = dosql("SELECT DISTINCT `user` FROM `prosody` WHERE `host`=? AND `store`=?", host, self.store); 119 local ok, result = engine:transaction(function()
304 if not stmt then 120 return engine:select("SELECT DISTINCT `user` FROM `prosody` WHERE `host`=? AND `store`=?", host, self.store);
305 return rollback(nil, err); 121 end);
306 end 122 if not ok then return ok, result end
307 local next = stmt:rows(); 123 return iterator(result);
308 return commit(function() 124 end
309 local row = next(); 125
310 return row and row[1]; 126 --- Archive store API
311 end); 127
312 end 128 local archive_store = {}
313 129 archive_store.caps = {
314 local function map_store_get(key) 130 total = true;
315 local stmt, err = getsql("SELECT * FROM `prosody` WHERE `host`=? AND `user`=? AND `store`=? AND `key`=?", key or ""); 131 };
316 if not stmt then return rollback(nil, err); end 132 archive_store.__index = archive_store
317 133 function archive_store:append(username, key, value, when, with)
318 local haveany; 134 if type(when) ~= "number" then
319 local result = {}; 135 when, with, value = value, when, with;
320 for row in stmt:rows(true) do 136 end
321 haveany = true; 137 local user,store = username,self.store;
322 local k = row.key; 138 return engine:transaction(function()
323 local v = deserialize(row.type, row.value); 139 if key then
324 if k and v then 140 engine:delete("DELETE FROM `prosodyarchive` WHERE `host`=? AND `user`=? AND `store`=? AND `key`=?", host, user or "", store, key);
325 if k ~= "" then result[k] = v; elseif type(v) == "table" then
326 for a,b in pairs(v) do
327 result[a] = b;
328 end
329 end
330 end
331 end
332 return commit(haveany and result[key] or nil);
333 end
334 local function map_store_set(key, data)
335 local affected, err = setsql("DELETE FROM `prosody` WHERE `host`=? AND `user`=? AND `store`=? AND `key`=?", key or "");
336 if not affected then return rollback(affected, err); end
337
338 if data and next(data) ~= nil then
339 if type(key) == "string" and key ~= "" then
340 local t, value = serialize(data);
341 if not t then return rollback(t, value); end
342 local ok, err = setsql("INSERT INTO `prosody` (`host`,`user`,`store`,`key`,`type`,`value`) VALUES (?,?,?,?,?,?)", key, t, value);
343 if not ok then return rollback(ok, err); end
344 else 141 else
345 -- TODO non-string keys 142 key = uuid.generate();
346 end 143 end
347 end 144 local t, value = serialize(value);
348 return commit(true); 145 engine:insert("INSERT INTO `prosodyarchive` (`host`, `user`, `store`, `when`, `with`, `key`, `type`, `value`) VALUES (?,?,?,?,?,?,?,?)", host, user or "", store, when, with, key, t, value);
349 end 146 return key;
350 147 end);
351 local map_store = {}; 148 end
352 map_store.__index = map_store; 149
353 function map_store:get(username, key) 150 -- Helpers for building the WHERE clause
354 user,store = username,self.store; 151 local function archive_where(query, args, where)
355 local success, ret, err = xpcall(function() return map_store_get(key); end, debug.traceback); 152 -- Time range, inclusive
356 if success then return ret, err; else return rollback(nil, ret); end 153 if query.start then
357 end 154 args[#args+1] = query.start
358 function map_store:set(username, key, data) 155 where[#where+1] = "`when` >= ?"
359 user,store = username,self.store; 156 end
360 local success, ret, err = xpcall(function() return map_store_set(key, data); end, debug.traceback); 157
361 if success then return ret, err; else return rollback(nil, ret); end 158 if query["end"] then
362 end 159 args[#args+1] = query["end"];
363 160 if query.start then
364 local list_store = {}; 161 where[#where] = "`when` BETWEEN ? AND ?" -- is this inclusive?
365 list_store.__index = list_store; 162 else
366 function list_store:scan(username, from, to, jid, typ) 163 where[#where+1] = "`when` <= ?"
367 user,store = username,self.store; 164 end
368 165 end
369 local cols = {"from", "to", "jid", "typ"}; 166
370 local vals = { from , to , jid , typ }; 167 -- Related name
371 local stmt, err; 168 if query.with then
372 local query = "SELECT * FROM `prosodyarchive` WHERE `host`=? AND `user`=? AND `store`=?"; 169 where[#where+1] = "`with` = ?";
373 170 args[#args+1] = query.with
374 query = query.." ORDER BY time"; 171 end
375 --local stmt, err = getsql("SELECT * FROM `prosody` WHERE `host`=? AND `user`=? AND `store`=? AND `key`=?", key or ""); 172
376 173 -- Unique id
377 return nil, "not-implemented" 174 if query.key then
378 end 175 where[#where+1] = "`key` = ?";
176 args[#args+1] = query.key
177 end
178 end
179 local function archive_where_id_range(query, args, where)
180 local args_len = #args
181 -- Before or after specific item, exclusive
182 if query.after then -- keys better be unique!
183 where[#where+1] = "`sort_id` > (SELECT `sort_id` FROM `prosodyarchive` WHERE `key` = ? AND `host` = ? AND `user` = ? AND `store` = ? LIMIT 1)"
184 args[args_len+1], args[args_len+2], args[args_len+3], args[args_len+4] = query.after, args[1], args[2], args[3];
185 args_len = args_len + 4
186 end
187 if query.before then
188 where[#where+1] = "`sort_id` < (SELECT `sort_id` FROM `prosodyarchive` WHERE `key` = ? AND `host` = ? AND `user` = ? AND `store` = ? LIMIT 1)"
189 args[args_len+1], args[args_len+2], args[args_len+3], args[args_len+4] = query.before, args[1], args[2], args[3];
190 end
191 end
192
193 function archive_store:find(username, query)
194 query = query or {};
195 local user,store = username,self.store;
196 local total;
197 local ok, result = engine:transaction(function()
198 local sql_query = "SELECT `key`, `type`, `value`, `when`, `with` FROM `prosodyarchive` WHERE %s ORDER BY `sort_id` %s%s;";
199 local args = { host, user or "", store, };
200 local where = { "`host` = ?", "`user` = ?", "`store` = ?", };
201
202 archive_where(query, args, where);
203
204 -- Total matching
205 if query.total then
206 local stats = engine:select("SELECT COUNT(*) FROM `prosodyarchive` WHERE " .. t_concat(where, " AND "), unpack(args));
207 if stats then
208 local _total = stats()
209 total = _total and _total[1];
210 end
211 if query.limit == 0 then -- Skip the real query
212 return noop, total;
213 end
214 end
215
216 archive_where_id_range(query, args, where);
217
218 if query.limit then
219 args[#args+1] = query.limit;
220 end
221
222 sql_query = sql_query:format(t_concat(where, " AND "), query.reverse and "DESC" or "ASC", query.limit and " LIMIT ?" or "");
223 module:log("debug", sql_query);
224 return engine:select(sql_query, unpack(args));
225 end);
226 if not ok then return ok, result end
227 return function()
228 local row = result();
229 if row ~= nil then
230 return row[1], deserialize(row[2], row[3]), row[4], row[5];
231 end
232 end, total;
233 end
234
235 function archive_store:delete(username, query)
236 query = query or {};
237 local user,store = username,self.store;
238 return engine:transaction(function()
239 local sql_query = "DELETE FROM `prosodyarchive` WHERE %s;";
240 local args = { host, user or "", store, };
241 local where = { "`host` = ?", "`user` = ?", "`store` = ?", };
242 if user == true then
243 table.remove(args, 2);
244 table.remove(where, 2);
245 end
246 archive_where(query, args, where);
247 archive_where_id_range(query, args, where);
248 sql_query = sql_query:format(t_concat(where, " AND "));
249 module:log("debug", sql_query);
250 return engine:delete(sql_query, unpack(args));
251 end);
252 end
253
254 local stores = {
255 keyval = keyval_store;
256 archive = archive_store;
257 };
258
259 --- Implement storage driver API
260
261 -- FIXME: Some of these operations need to operate on the archive store(s) too
379 262
380 local driver = {}; 263 local driver = {};
381 264
382 function driver:open(store, typ) 265 function driver:open(store, typ)
383 if typ and typ ~= "keyval" then 266 local store_mt = stores[typ or "keyval"];
384 return nil, "unsupported-store"; 267 if store_mt then
385 end 268 return setmetatable({ store = store }, store_mt);
386 return setmetatable({ store = store }, keyval_store); 269 end
270 return nil, "unsupported-store";
387 end 271 end
388 272
389 function driver:stores(username) 273 function driver:stores(username)
390 local sql = "SELECT DISTINCT `store` FROM `prosody` WHERE `host`=? AND `user`" .. 274 local query = "SELECT DISTINCT `store` FROM `prosody` WHERE `host`=? AND `user`" ..
391 (username == true and "!=?" or "=?"); 275 (username == true and "!=?" or "=?");
392 if username == true or not username then 276 if username == true or not username then
393 username = ""; 277 username = "";
394 end 278 end
395 local stmt, err = dosql(sql, host, username); 279 local ok, result = engine:transaction(function()
396 if not stmt then 280 return engine:select(query, host, username);
397 return rollback(nil, err); 281 end);
398 end 282 if not ok then return ok, result end
399 local next = stmt:rows(); 283 return iterator(result);
400 return commit(function()
401 local row = next();
402 return row and row[1];
403 end);
404 end 284 end
405 285
406 function driver:purge(username) 286 function driver:purge(username)
407 local stmt, err = dosql("DELETE FROM `prosody` WHERE `host`=? AND `user`=?", host, username); 287 return engine:transaction(function()
408 if not stmt then return rollback(stmt, err); end 288 local stmt,err = engine:delete("DELETE FROM `prosody` WHERE `host`=? AND `user`=?", host, username);
409 local changed, err = stmt:affected(); 289 return true, err;
410 if not changed then return rollback(changed, err); end 290 end);
411 return commit(true, changed); 291 end
412 end 292
413 293 --- Initialization
414 module:provides("storage", driver); 294
295
296 local function create_table(name)
297 local Table, Column, Index = sql.Table, sql.Column, sql.Index;
298
299 local ProsodyTable = Table {
300 name= name or "prosody";
301 Column { name="host", type="TEXT", nullable=false };
302 Column { name="user", type="TEXT", nullable=false };
303 Column { name="store", type="TEXT", nullable=false };
304 Column { name="key", type="TEXT", nullable=false };
305 Column { name="type", type="TEXT", nullable=false };
306 Column { name="value", type="MEDIUMTEXT", nullable=false };
307 Index { name="prosody_index", "host", "user", "store", "key" };
308 };
309 engine:transaction(function()
310 ProsodyTable:create(engine);
311 end);
312
313 local ProsodyArchiveTable = Table {
314 name="prosodyarchive";
315 Column { name="sort_id", type="INTEGER", primary_key=true, auto_increment=true };
316 Column { name="host", type="TEXT", nullable=false };
317 Column { name="user", type="TEXT", nullable=false };
318 Column { name="store", type="TEXT", nullable=false };
319 Column { name="key", type="TEXT", nullable=false }; -- item id
320 Column { name="when", type="INTEGER", nullable=false }; -- timestamp
321 Column { name="with", type="TEXT", nullable=false }; -- related id
322 Column { name="type", type="TEXT", nullable=false };
323 Column { name="value", type="MEDIUMTEXT", nullable=false };
324 Index { name="prosodyarchive_index", unique = true, "host", "user", "store", "key" };
325 };
326 engine:transaction(function()
327 ProsodyArchiveTable:create(engine);
328 end);
329 end
330
331 local function upgrade_table(params, apply_changes)
332 local changes = false;
333 if params.driver == "MySQL" then
334 local success,err = engine:transaction(function()
335 local result = engine:execute("SHOW COLUMNS FROM prosody WHERE Field='value' and Type='text'");
336 if result:rowcount() > 0 then
337 changes = true;
338 if apply_changes then
339 module:log("info", "Upgrading database schema...");
340 engine:execute("ALTER TABLE prosody MODIFY COLUMN `value` MEDIUMTEXT");
341 module:log("info", "Database table automatically upgraded");
342 end
343 end
344 return true;
345 end);
346 if not success then
347 module:log("error", "Failed to check/upgrade database schema (%s), please see "
348 .."http://prosody.im/doc/mysql for help",
349 err or "unknown error");
350 return false;
351 end
352
353 -- COMPAT w/pre-0.10: Upgrade table to UTF-8 if not already
354 local check_encoding_query = "SELECT `COLUMN_NAME`,`COLUMN_TYPE`,`TABLE_NAME` FROM `information_schema`.`columns` WHERE `TABLE_NAME` LIKE 'prosody%%' AND ( `CHARACTER_SET_NAME`!='%s' OR `COLLATION_NAME`!='%s_bin' );";
355 check_encoding_query = check_encoding_query:format(engine.charset, engine.charset);
356 success,err = engine:transaction(function()
357 local result = engine:execute(check_encoding_query);
358 local n_bad_columns = result:rowcount();
359 if n_bad_columns > 0 then
360 changes = true;
361 if apply_changes then
362 module:log("warn", "Found %d columns in prosody table requiring encoding change, updating now...", n_bad_columns);
363 local fix_column_query1 = "ALTER TABLE `%s` CHANGE `%s` `%s` BLOB;";
364 local fix_column_query2 = "ALTER TABLE `%s` CHANGE `%s` `%s` %s CHARACTER SET '%s' COLLATE '%s_bin';";
365 for row in result:rows() do
366 local column_name, column_type, table_name = unpack(row);
367 module:log("debug", "Fixing column %s in table %s", column_name, table_name);
368 engine:execute(fix_column_query1:format(table_name, column_name, column_name));
369 engine:execute(fix_column_query2:format(table_name, column_name, column_name, column_type, engine.charset, engine.charset));
370 end
371 module:log("info", "Database encoding upgrade complete!");
372 end
373 end
374 end);
375 success,err = engine:transaction(function() return engine:execute(check_encoding_query); end);
376 if not success then
377 module:log("error", "Failed to check/upgrade database encoding: %s", err or "unknown error");
378 return false;
379 end
380 end
381 return changes;
382 end
383
384 local function normalize_params(params)
385 if params.driver == "SQLite3" then
386 params.database = resolve_relative_path(prosody.paths.data or ".", params.database or "prosody.sqlite");
387 end
388 assert(params.driver and params.database, "Configuration error: Both the SQL driver and the database need to be specified");
389 return params;
390 end
391
392 function module.load()
393 if prosody.prosodyctl then return; end
394 local params = normalize_params(module:get_option("sql", default_params));
395 engine = sql:create_engine(params, function (engine)
396 if module:get_option("sql_manage_tables", true) then
397 -- Automatically create table, ignore failure (table probably already exists)
398 -- FIXME: we should check in information_schema, etc.
399 create_table();
400 -- Check whether the table needs upgrading
401 if upgrade_table(params, false) then
402 module:log("error", "Old database format detected. Please run: prosodyctl mod_%s upgrade", module.name);
403 return false, "database upgrade needed";
404 end
405 end
406 end);
407
408 module:provides("storage", driver);
409 end
410
411 function module.command(arg)
412 local config = require "core.configmanager";
413 local prosodyctl = require "util.prosodyctl";
414 local command = table.remove(arg, 1);
415 if command == "upgrade" then
416 -- We need to find every unique dburi in the config
417 local uris = {};
418 for host in pairs(prosody.hosts) do
419 local params = config.get(host, "sql") or default_params;
420 uris[sql.db2uri(params)] = params;
421 end
422 print("We will check and upgrade the following databases:\n");
423 for _, params in pairs(uris) do
424 print("", "["..params.driver.."] "..params.database..(params.host and " on "..params.host or ""));
425 end
426 print("");
427 print("Ensure you have working backups of the above databases before continuing! ");
428 if not prosodyctl.show_yesno("Continue with the database upgrade? [yN]") then
429 print("Ok, no upgrade. But you do have backups, don't you? ...don't you?? :-)");
430 return;
431 end
432 -- Upgrade each one
433 for _, params in pairs(uris) do
434 print("Checking "..params.database.."...");
435 engine = sql:create_engine(params);
436 upgrade_table(params, true);
437 end
438 print("All done!");
439 else
440 print("Unknown command: "..command);
441 end
442 end