util.sql: Make set_encoding() return failure of SET NAMES
[prosody.git] / util / sql.lua
1
2 local setmetatable, getmetatable = setmetatable, getmetatable;
3 local ipairs, unpack, select = ipairs, unpack, select;
4 local tonumber, tostring = tonumber, tostring;
5 local assert, xpcall, debug_traceback = assert, xpcall, debug.traceback;
6 local t_concat = table.concat;
7 local s_char = string.char;
8 local log = require "util.logger".init("sql");
9
10 local DBI = require "DBI";
11 -- This loads all available drivers while globals are unlocked
12 -- LuaDBI should be fixed to not set globals.
13 DBI.Drivers();
14 local build_url = require "socket.url".build;
15
16 module("sql")
17
18 local column_mt = {};
19 local table_mt = {};
20 local query_mt = {};
21 --local op_mt = {};
22 local index_mt = {};
23
24 function is_column(x) return getmetatable(x)==column_mt; end
25 function is_index(x) return getmetatable(x)==index_mt; end
26 function is_table(x) return getmetatable(x)==table_mt; end
27 function is_query(x) return getmetatable(x)==query_mt; end
28 function Integer(n) return "Integer()" end
29 function String(n) return "String()" end
30
31 function Column(definition)
32         return setmetatable(definition, column_mt);
33 end
34 function Table(definition)
35         local c = {}
36         for i,col in ipairs(definition) do
37                 if is_column(col) then
38                         c[i], c[col.name] = col, col;
39                 elseif is_index(col) then
40                         col.table = definition.name;
41                 end
42         end
43         return setmetatable({ __table__ = definition, c = c, name = definition.name }, table_mt);
44 end
45 function Index(definition)
46         return setmetatable(definition, index_mt);
47 end
48
49 function table_mt:__tostring()
50         local s = { 'name="'..self.__table__.name..'"' }
51         for i,col in ipairs(self.__table__) do
52                 s[#s+1] = tostring(col);
53         end
54         return 'Table{ '..t_concat(s, ", ")..' }'
55 end
56 table_mt.__index = {};
57 function table_mt.__index:create(engine)
58         return engine:_create_table(self);
59 end
60 function table_mt:__call(...)
61         -- TODO
62 end
63 function column_mt:__tostring()
64         return 'Column{ name="'..self.name..'", type="'..self.type..'" }'
65 end
66 function index_mt:__tostring()
67         local s = 'Index{ name="'..self.name..'"';
68         for i=1,#self do s = s..', "'..self[i]:gsub("[\\\"]", "\\%1")..'"'; end
69         return s..' }';
70 --      return 'Index{ name="'..self.name..'", type="'..self.type..'" }'
71 end
72
73 local function urldecode(s) return s and (s:gsub("%%(%x%x)", function (c) return s_char(tonumber(c,16)); end)); end
74 local function parse_url(url)
75         local scheme, secondpart, database = url:match("^([%w%+]+)://([^/]*)/?(.*)");
76         assert(scheme, "Invalid URL format");
77         local username, password, host, port;
78         local authpart, hostpart = secondpart:match("([^@]+)@([^@+])");
79         if not authpart then hostpart = secondpart; end
80         if authpart then
81                 username, password = authpart:match("([^:]*):(.*)");
82                 username = username or authpart;
83                 password = password and urldecode(password);
84         end
85         if hostpart then
86                 host, port = hostpart:match("([^:]*):(.*)");
87                 host = host or hostpart;
88                 port = port and assert(tonumber(port), "Invalid URL format");
89         end
90         return {
91                 scheme = scheme:lower();
92                 username = username; password = password;
93                 host = host; port = port;
94                 database = #database > 0 and database or nil;
95         };
96 end
97
98 local engine = {};
99 function engine:connect()
100         if self.conn then return true; end
101
102         local params = self.params;
103         assert(params.driver, "no driver")
104         local dbh, err = DBI.Connect(
105                 params.driver, params.database,
106                 params.username, params.password,
107                 params.host, params.port
108         );
109         if not dbh then return nil, err; end
110         dbh:autocommit(false); -- don't commit automatically
111         self.conn = dbh;
112         self.prepared = {};
113         local ok, err = self:set_encoding();
114         if not ok then
115                 return ok, err;
116         end
117         local ok, err = self:onconnect();
118         if ok == false then
119                 return ok, err;
120         end
121         return true;
122 end
123 function engine:onconnect()
124         -- Override from create_engine()
125 end
126 function engine:execute(sql, ...)
127         local success, err = self:connect();
128         if not success then return success, err; end
129         local prepared = self.prepared;
130
131         local stmt = prepared[sql];
132         if not stmt then
133                 local err;
134                 stmt, err = self.conn:prepare(sql);
135                 if not stmt then return stmt, err; end
136                 prepared[sql] = stmt;
137         end
138
139         local success, err = stmt:execute(...);
140         if not success then return success, err; end
141         return stmt;
142 end
143
144 local result_mt = { __index = {
145         affected = function(self) return self.__stmt:affected(); end;
146         rowcount = function(self) return self.__stmt:rowcount(); end;
147 } };
148
149 function engine:execute_query(sql, ...)
150         if self.params.driver == "PostgreSQL" then
151                 sql = sql:gsub("`", "\"");
152         end
153         local stmt = assert(self.conn:prepare(sql));
154         assert(stmt:execute(...));
155         return stmt:rows();
156 end
157 function engine:execute_update(sql, ...)
158         if self.params.driver == "PostgreSQL" then
159                 sql = sql:gsub("`", "\"");
160         end
161         local prepared = self.prepared;
162         local stmt = prepared[sql];
163         if not stmt then
164                 stmt = assert(self.conn:prepare(sql));
165                 prepared[sql] = stmt;
166         end
167         assert(stmt:execute(...));
168         return setmetatable({ __stmt = stmt }, result_mt);
169 end
170 engine.insert = engine.execute_update;
171 engine.select = engine.execute_query;
172 engine.delete = engine.execute_update;
173 engine.update = engine.execute_update;
174 function engine:_transaction(func, ...)
175         if not self.conn then
176                 local ok, err = self:connect();
177                 if not ok then return ok, err; end
178         end
179         --assert(not self.__transaction, "Recursive transactions not allowed");
180         local args, n_args = {...}, select("#", ...);
181         local function f() return func(unpack(args, 1, n_args)); end
182         self.__transaction = true;
183         local success, a, b, c = xpcall(f, debug_traceback);
184         self.__transaction = nil;
185         if success then
186                 log("debug", "SQL transaction success [%s]", tostring(func));
187                 local ok, err = self.conn:commit();
188                 if not ok then return ok, err; end -- commit failed
189                 return success, a, b, c;
190         else
191                 log("debug", "SQL transaction failure [%s]: %s", tostring(func), a);
192                 if self.conn then self.conn:rollback(); end
193                 return success, a;
194         end
195 end
196 function engine:transaction(...)
197         local ok, ret = self:_transaction(...);
198         if not ok then
199                 local conn = self.conn;
200                 if not conn or not conn:ping() then
201                         self.conn = nil;
202                         ok, ret = self:_transaction(...);
203                 end
204         end
205         return ok, ret;
206 end
207 function engine:_create_index(index)
208         local sql = "CREATE INDEX `"..index.name.."` ON `"..index.table.."` (";
209         for i=1,#index do
210                 sql = sql.."`"..index[i].."`";
211                 if i ~= #index then sql = sql..", "; end
212         end
213         sql = sql..");"
214         if self.params.driver == "PostgreSQL" then
215                 sql = sql:gsub("`", "\"");
216         elseif self.params.driver == "MySQL" then
217                 sql = sql:gsub("`([,)])", "`(20)%1");
218         end
219         if index.unique then
220                 sql = sql:gsub("^CREATE", "CREATE UNIQUE");
221         end
222         --print(sql);
223         return self:execute(sql);
224 end
225 function engine:_create_table(table)
226         local sql = "CREATE TABLE `"..table.name.."` (";
227         for i,col in ipairs(table.c) do
228                 local col_type = col.type;
229                 if col_type == "MEDIUMTEXT" and self.params.driver ~= "MySQL" then
230                         col_type = "TEXT"; -- MEDIUMTEXT is MySQL-specific
231                 end
232                 if col.auto_increment == true and self.params.driver == "PostgreSQL" then
233                         col_type = "BIGSERIAL";
234                 end
235                 sql = sql.."`"..col.name.."` "..col_type;
236                 if col.nullable == false then sql = sql.." NOT NULL"; end
237                 if col.primary_key == true then sql = sql.." PRIMARY KEY"; end
238                 if col.auto_increment == true then
239                         if self.params.driver == "MySQL" then
240                                 sql = sql.." AUTO_INCREMENT";
241                         elseif self.params.driver == "SQLite3" then
242                                 sql = sql.." AUTOINCREMENT";
243                         end
244                 end
245                 if i ~= #table.c then sql = sql..", "; end
246         end
247         sql = sql.. ");"
248         if self.params.driver == "PostgreSQL" then
249                 sql = sql:gsub("`", "\"");
250         elseif self.params.driver == "MySQL" then
251                 sql = sql:gsub(";$", (" CHARACTER SET '%s' COLLATE '%s_bin';"):format(self.charset, self.charset));
252         end
253         local success,err = self:execute(sql);
254         if not success then return success,err; end
255         for i,v in ipairs(table.__table__) do
256                 if is_index(v) then
257                         self:_create_index(v);
258                 end
259         end
260         return success;
261 end
262 function engine:set_encoding() -- to UTF-8
263         local driver = self.params.driver;
264         if driver == "SQLite3" then
265                 return self:transaction(function()
266                         if self:select"PRAGMA encoding;"()[1] == "UTF-8" then
267                                 self.charset = "utf8";
268                         end
269                 end);
270         end
271         local set_names_query = "SET NAMES '%s';"
272         local charset = "utf8";
273         if driver == "MySQL" then
274                 local ok, charsets = self:transaction(function()
275                         return self:select"SELECT `CHARACTER_SET_NAME` FROM `information_schema`.`CHARACTER_SETS` WHERE `CHARACTER_SET_NAME` LIKE 'utf8%' ORDER BY MAXLEN DESC LIMIT 1;";
276                 end);
277                 local row = ok and charsets();
278                 charset = row and row[1] or charset;
279                 set_names_query = set_names_query:gsub(";$", (" COLLATE '%s';"):format(charset.."_bin"));
280         end
281         self.charset = charset;
282         log("debug", "Using encoding '%s' for database connection", charset);
283         local ok, err = self:transaction(function() return self:execute(set_names_query:format(charset)); end);
284         if not ok then
285                 return ok, err;
286         end
287         
288         return true;
289 end
290 local engine_mt = { __index = engine };
291
292 function db2uri(params)
293         return build_url{
294                 scheme = params.driver,
295                 user = params.username,
296                 password = params.password,
297                 host = params.host,
298                 port = params.port,
299                 path = params.database,
300         };
301 end
302
303 function create_engine(self, params, onconnect)
304         return setmetatable({ url = db2uri(params), params = params, onconnect = onconnect }, engine_mt);
305 end
306
307 return _M;