Merge 0.8->trunk
[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 do -- process options to get a db connection
68         DBI = require "DBI";
69
70         params = params or { driver = "SQLite3" };
71         
72         if params.driver == "SQLite3" then
73                 params.database = resolve_relative_path(prosody.paths.data or ".", params.database or "prosody.sqlite");
74         end
75         
76         assert(params.driver and params.database, "Both the SQL driver and the database need to be specified");
77         
78         assert(connect());
79         
80         -- Automatically create table, ignore failure (table probably already exists)
81         local create_sql = "CREATE TABLE `prosody` (`host` TEXT, `user` TEXT, `store` TEXT, `key` TEXT, `type` TEXT, `value` TEXT);";
82         if params.driver == "PostgreSQL" then
83                 create_sql = create_sql:gsub("`", "\"");
84         end
85         
86         local stmt = connection:prepare(create_sql);
87         if stmt then
88                 local ok = stmt:execute();
89                 local commit_ok = connection:commit();
90                 if ok and commit_ok then
91                         module:log("info", "Initialized new %s database with prosody table", params.driver);
92                 end
93         end
94 end
95
96 local function serialize(value)
97         local t = type(value);
98         if t == "string" or t == "boolean" or t == "number" then
99                 return t, tostring(value);
100         elseif t == "table" then
101                 local value,err = json.encode(value);
102                 if value then return "json", value; end
103                 return nil, err;
104         end
105         return nil, "Unhandled value type: "..t;
106 end
107 local function deserialize(t, value)
108         if t == "string" then return value;
109         elseif t == "boolean" then
110                 if value == "true" then return true;
111                 elseif value == "false" then return false; end
112         elseif t == "number" then return tonumber(value);
113         elseif t == "json" then
114                 return json.decode(value);
115         end
116 end
117
118 local function getsql(sql, ...)
119         if params.driver == "PostgreSQL" then
120                 sql = sql:gsub("`", "\"");
121         end
122         -- do prepared statement stuff
123         local stmt, err = connection:prepare(sql);
124         if not stmt and not test_connection() then error("connection failed"); end
125         if not stmt then module:log("error", "QUERY FAILED: %s %s", err, debug.traceback()); return nil, err; end
126         -- run query
127         local ok, err = stmt:execute(host or "", user or "", store or "", ...);
128         if not ok and not test_connection() then error("connection failed"); end
129         if not ok then return nil, err; end
130         
131         return stmt;
132 end
133 local function setsql(sql, ...)
134         local stmt, err = getsql(sql, ...);
135         if not stmt then return stmt, err; end
136         return stmt:affected();
137 end
138 local function transact(...)
139         -- ...
140 end
141 local function rollback(...)
142         if connection then connection:rollback(); end -- FIXME check for rollback error?
143         return ...;
144 end
145 local function commit(...)
146         if not connection:commit() then return nil, "SQL commit failed"; end
147         return ...;
148 end
149
150 local function keyval_store_get()
151         local stmt, err = getsql("SELECT * FROM `prosody` WHERE `host`=? AND `user`=? AND `store`=?");
152         if not stmt then return rollback(nil, err); end
153         
154         local haveany;
155         local result = {};
156         for row in stmt:rows(true) do
157                 haveany = true;
158                 local k = row.key;
159                 local v = deserialize(row.type, row.value);
160                 if k and v then
161                         if k ~= "" then result[k] = v; elseif type(v) == "table" then
162                                 for a,b in pairs(v) do
163                                         result[a] = b;
164                                 end
165                         end
166                 end
167         end
168         return commit(haveany and result or nil);
169 end
170 local function keyval_store_set(data)
171         local affected, err = setsql("DELETE FROM `prosody` WHERE `host`=? AND `user`=? AND `store`=?");
172         if not affected then return rollback(affected, err); end
173         
174         if data and next(data) ~= nil then
175                 local extradata = {};
176                 for key, value in pairs(data) do
177                         if type(key) == "string" and key ~= "" then
178                                 local t, value = serialize(value);
179                                 if not t then return rollback(t, value); end
180                                 local ok, err = setsql("INSERT INTO `prosody` (`host`,`user`,`store`,`key`,`type`,`value`) VALUES (?,?,?,?,?,?)", key, t, value);
181                                 if not ok then return rollback(ok, err); end
182                         else
183                                 extradata[key] = value;
184                         end
185                 end
186                 if next(extradata) ~= nil then
187                         local t, extradata = serialize(extradata);
188                         if not t then return rollback(t, extradata); end
189                         local ok, err = setsql("INSERT INTO `prosody` (`host`,`user`,`store`,`key`,`type`,`value`) VALUES (?,?,?,?,?,?)", "", t, extradata);
190                         if not ok then return rollback(ok, err); end
191                 end
192         end
193         return commit(true);
194 end
195
196 local keyval_store = {};
197 keyval_store.__index = keyval_store;
198 function keyval_store:get(username)
199         user,store = username,self.store;
200         if not connection and not connect() then return nil, "Unable to connect to database"; end
201         local success, ret, err = xpcall(keyval_store_get, debug.traceback);
202         if not connection and connect() then
203                 success, ret, err = xpcall(keyval_store_get, debug.traceback);
204         end
205         if success then return ret, err; else return rollback(nil, ret); end
206 end
207 function keyval_store:set(username, data)
208         user,store = username,self.store;
209         if not connection and not connect() then return nil, "Unable to connect to database"; end
210         local success, ret, err = xpcall(function() return keyval_store_set(data); end, debug.traceback);
211         if not connection and connect() then
212                 success, ret, err = xpcall(function() return keyval_store_set(data); end, debug.traceback);
213         end
214         if success then return ret, err; else return rollback(nil, ret); end
215 end
216
217 local function map_store_get(key)
218         local stmt, err = getsql("SELECT * FROM `prosody` WHERE `host`=? AND `user`=? AND `store`=? AND `key`=?", key or "");
219         if not stmt then return rollback(nil, err); end
220         
221         local haveany;
222         local result = {};
223         for row in stmt:rows(true) do
224                 haveany = true;
225                 local k = row.key;
226                 local v = deserialize(row.type, row.value);
227                 if k and v then
228                         if k ~= "" then result[k] = v; elseif type(v) == "table" then
229                                 for a,b in pairs(v) do
230                                         result[a] = b;
231                                 end
232                         end
233                 end
234         end
235         return commit(haveany and result[key] or nil);
236 end
237 local function map_store_set(key, data)
238         local affected, err = setsql("DELETE FROM `prosody` WHERE `host`=? AND `user`=? AND `store`=? AND `key`=?", key or "");
239         if not affected then return rollback(affected, err); end
240         
241         if data and next(data) ~= nil then
242                 if type(key) == "string" and key ~= "" then
243                         local t, value = serialize(data);
244                         if not t then return rollback(t, value); end
245                         local ok, err = setsql("INSERT INTO `prosody` (`host`,`user`,`store`,`key`,`type`,`value`) VALUES (?,?,?,?,?,?)", key, t, value);
246                         if not ok then return rollback(ok, err); end
247                 else
248                         -- TODO non-string keys
249                 end
250         end
251         return commit(true);
252 end
253
254 local map_store = {};
255 map_store.__index = map_store;
256 function map_store:get(username, key)
257         user,store = username,self.store;
258         local success, ret, err = xpcall(function() return map_store_get(key); end, debug.traceback);
259         if success then return ret, err; else return rollback(nil, ret); end
260 end
261 function map_store:set(username, key, data)
262         user,store = username,self.store;
263         local success, ret, err = xpcall(function() return map_store_set(key, data); end, debug.traceback);
264         if success then return ret, err; else return rollback(nil, ret); end
265 end
266
267 local list_store = {};
268 list_store.__index = list_store;
269 function list_store:scan(username, from, to, jid, typ)
270         user,store = username,self.store;
271         
272         local cols = {"from", "to", "jid", "typ"};
273         local vals = { from ,  to ,  jid ,  typ };
274         local stmt, err;
275         local query = "SELECT * FROM `prosodyarchive` WHERE `host`=? AND `user`=? AND `store`=?";
276         
277         query = query.." ORDER BY time";
278         --local stmt, err = getsql("SELECT * FROM `prosody` WHERE `host`=? AND `user`=? AND `store`=? AND `key`=?", key or "");
279         
280         return nil, "not-implemented"
281 end
282
283 local driver = { name = "sql" };
284
285 function driver:open(store, typ)
286         if not typ then -- default key-value store
287                 return setmetatable({ store = store }, keyval_store);
288         end
289         return nil, "unsupported-store";
290 end
291
292 module:add_item("data-driver", driver);