Comparison

util/sql.lua @ 7272:a23ca90d1984

util.sql: Move per-driver (currenly only PostgreSQL) query transform into its own method
author Kim Alvefur <zash@zash.se>
date Sun, 13 Mar 2016 17:38:49 +0100
parent 7180:0d7f80263813
child 7275:187ba2e9c012
comparison
equal deleted inserted replaced
7271:dae47cd774ac 7272:a23ca90d1984
122 return true; 122 return true;
123 end 123 end
124 function engine:onconnect() 124 function engine:onconnect()
125 -- Override from create_engine() 125 -- Override from create_engine()
126 end 126 end
127
128 function engine:prepquery(sql)
129 if self.params.driver == "PostgreSQL" then
130 sql = sql:gsub("`", "\"");
131 end
132 return sql;
133 end
134
127 function engine:execute(sql, ...) 135 function engine:execute(sql, ...)
128 local success, err = self:connect(); 136 local success, err = self:connect();
129 if not success then return success, err; end 137 if not success then return success, err; end
130 local prepared = self.prepared; 138 local prepared = self.prepared;
131 139
151 local i = 0; local a = {...} 159 local i = 0; local a = {...}
152 log("debug", "[%s] %s", where, sql:gsub("%?", function () i = i + 1; local v = a[i]; if type(v) == "string" then v = ("%q"):format(v); end return tostring(v); end)); 160 log("debug", "[%s] %s", where, sql:gsub("%?", function () i = i + 1; local v = a[i]; if type(v) == "string" then v = ("%q"):format(v); end return tostring(v); end));
153 end 161 end
154 162
155 function engine:execute_query(sql, ...) 163 function engine:execute_query(sql, ...)
156 if self.params.driver == "PostgreSQL" then 164 sql = self:prepquery(sql);
157 sql = sql:gsub("`", "\"");
158 end
159 local stmt = assert(self.conn:prepare(sql)); 165 local stmt = assert(self.conn:prepare(sql));
160 assert(stmt:execute(...)); 166 assert(stmt:execute(...));
161 return stmt:rows(); 167 return stmt:rows();
162 end 168 end
163 function engine:execute_update(sql, ...) 169 function engine:execute_update(sql, ...)
164 if self.params.driver == "PostgreSQL" then 170 sql = self:prepquery(sql);
165 sql = sql:gsub("`", "\"");
166 end
167 local prepared = self.prepared; 171 local prepared = self.prepared;
168 local stmt = prepared[sql]; 172 local stmt = prepared[sql];
169 if not stmt then 173 if not stmt then
170 stmt = assert(self.conn:prepare(sql)); 174 stmt = assert(self.conn:prepare(sql));
171 prepared[sql] = stmt; 175 prepared[sql] = stmt;