blob: 66adff3e517068226d2e08640d42a0446805561a [file] [log] [blame]
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001/* statement.c - the statement type
2 *
Gerhard Häringe7ea7452008-03-29 00:45:29 +00003 * Copyright (C) 2005-2007 Gerhard Häring <gh@ghaering.de>
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004 *
5 * This file is part of pysqlite.
6 *
7 * This software is provided 'as-is', without any express or implied
8 * warranty. In no event will the authors be held liable for any damages
9 * arising from the use of this software.
10 *
11 * Permission is granted to anyone to use this software for any purpose,
12 * including commercial applications, and to alter it and redistribute it
13 * freely, subject to the following restrictions:
14 *
15 * 1. The origin of this software must not be misrepresented; you must not
16 * claim that you wrote the original software. If you use this software
17 * in a product, an acknowledgment in the product documentation would be
18 * appreciated but is not required.
19 * 2. Altered source versions must be plainly marked as such, and must not be
20 * misrepresented as being the original software.
21 * 3. This notice may not be removed or altered from any source distribution.
22 */
23
24#include "statement.h"
25#include "cursor.h"
26#include "connection.h"
27#include "microprotocols.h"
28#include "prepare_protocol.h"
29#include "sqlitecompat.h"
30
31/* prototypes */
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +000032static int pysqlite_check_remaining_sql(const char* tail);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000033
34typedef enum {
35 LINECOMMENT_1,
36 IN_LINECOMMENT,
37 COMMENTSTART_1,
38 IN_COMMENT,
39 COMMENTEND_1,
40 NORMAL
41} parse_remaining_sql_state;
42
Gerhard Häringe7ea7452008-03-29 00:45:29 +000043typedef enum {
44 TYPE_LONG,
45 TYPE_FLOAT,
46 TYPE_STRING,
47 TYPE_UNICODE,
48 TYPE_BUFFER,
49 TYPE_UNKNOWN
50} parameter_type;
51
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +000052int pysqlite_statement_create(pysqlite_Statement* self, pysqlite_Connection* connection, PyObject* sql)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000053{
54 const char* tail;
55 int rc;
Guido van Rossum83857e32007-05-09 23:37:01 +000056 const char* sql_cstr;
57 Py_ssize_t sql_cstr_len;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000058
59 self->st = NULL;
60 self->in_use = 0;
61
Guido van Rossum7d1df6c2007-08-29 13:53:23 +000062 sql_cstr = PyUnicode_AsStringAndSize(sql, &sql_cstr_len);
Guido van Rossumfa9a1212007-08-29 03:34:29 +000063 if (sql_cstr == NULL) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000064 rc = PYSQLITE_SQL_WRONG_TYPE;
65 return rc;
66 }
67
Thomas Wouters477c8d52006-05-27 19:21:47 +000068 self->in_weakreflist = NULL;
Guido van Rossum83857e32007-05-09 23:37:01 +000069 Py_INCREF(sql);
70 self->sql = sql;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000071
72 rc = sqlite3_prepare(connection->db,
73 sql_cstr,
74 -1,
75 &self->st,
76 &tail);
77
78 self->db = connection->db;
79
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +000080 if (rc == SQLITE_OK && pysqlite_check_remaining_sql(tail)) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000081 (void)sqlite3_finalize(self->st);
82 self->st = NULL;
83 rc = PYSQLITE_TOO_MUCH_SQL;
84 }
85
86 return rc;
87}
88
Gerhard Häringe7ea7452008-03-29 00:45:29 +000089int pysqlite_statement_bind_parameter(pysqlite_Statement* self, int pos, PyObject* parameter, int allow_8bit_chars)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000090{
91 int rc = SQLITE_OK;
Gerhard Häringe7ea7452008-03-29 00:45:29 +000092 long longval;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000093#ifdef HAVE_LONG_LONG
94 PY_LONG_LONG longlongval;
95#endif
96 const char* buffer;
97 char* string;
98 Py_ssize_t buflen;
Gerhard Häringe7ea7452008-03-29 00:45:29 +000099 parameter_type paramtype;
100 char* c;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000101
102 if (parameter == Py_None) {
103 rc = sqlite3_bind_null(self->st, pos);
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000104 goto final;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000105 }
106
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000107 if (PyLong_CheckExact(parameter)) {
108 paramtype = TYPE_LONG;
109 } else if (PyFloat_CheckExact(parameter)) {
110 paramtype = TYPE_FLOAT;
111 } else if (PyUnicode_CheckExact(parameter)) {
112 paramtype = TYPE_UNICODE;
113 } else if (PyLong_Check(parameter)) {
114 paramtype = TYPE_LONG;
115 } else if (PyFloat_Check(parameter)) {
116 paramtype = TYPE_FLOAT;
117 } else if (PyUnicode_Check(parameter)) {
118 paramtype = TYPE_STRING;
119 } else if (PyObject_CheckBuffer(parameter)) {
120 paramtype = TYPE_BUFFER;
121 } else {
122 paramtype = TYPE_UNKNOWN;
123 }
124
125 if (paramtype == TYPE_STRING && !allow_8bit_chars) {
126 string = PyString_AS_STRING(parameter);
127 for (c = string; *c != 0; c++) {
128 if (*c & 0x80) {
129 PyErr_SetString(pysqlite_ProgrammingError, "You must not use 8-bit bytestrings unless you use a text_factory that can interpret 8-bit bytestrings (like text_factory = str). It is highly recommended that you instead just switch your application to Unicode strings.");
130 rc = -1;
131 goto final;
132 }
133 }
134 }
135
136 switch (paramtype) {
137 case TYPE_LONG:
138 /* in the overflow error case, longval/longlongval is -1, and an exception is set */
139#ifdef HAVE_LONG_LONG
140 longlongval = PyLong_AsLongLong(parameter);
141 rc = sqlite3_bind_int64(self->st, pos, (sqlite_int64)longlongval);
142#else
143 rc = sqlite3_bind_int64(self->st, pos, (sqlite_int64)longval);
144#endif
145 break;
146 case TYPE_FLOAT:
147 rc = sqlite3_bind_double(self->st, pos, PyFloat_AsDouble(parameter));
148 break;
149 case TYPE_UNICODE:
150 string = PyUnicode_AsString(parameter);
151 rc = sqlite3_bind_text(self->st, pos, string, -1, SQLITE_TRANSIENT);
152 break;
153 case TYPE_BUFFER:
154 if (PyObject_AsCharBuffer(parameter, &buffer, &buflen) == 0) {
155 rc = sqlite3_bind_blob(self->st, pos, buffer, buflen, SQLITE_TRANSIENT);
156 } else {
157 PyErr_SetString(PyExc_ValueError, "could not convert BLOB to buffer");
158 rc = -1;
159 }
160 break;
161 case TYPE_UNKNOWN:
162 rc = -1;
163 }
164
165final:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000166 return rc;
167}
168
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000169/* returns 0 if the object is one of Python's internal ones that don't need to be adapted */
170static int _need_adapt(PyObject* obj)
171{
172 if (pysqlite_BaseTypeAdapted) {
173 return 1;
174 }
175
176 if (PyLong_CheckExact(obj) || PyFloat_CheckExact(obj)
177 || PyUnicode_CheckExact(obj) || PyBytes_CheckExact(obj)) {
178 return 0;
179 } else {
180 return 1;
181 }
182}
183
184void pysqlite_statement_bind_parameters(pysqlite_Statement* self, PyObject* parameters, int allow_8bit_chars)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000185{
186 PyObject* current_param;
187 PyObject* adapted;
188 const char* binding_name;
189 int i;
190 int rc;
191 int num_params_needed;
192 int num_params;
193
194 Py_BEGIN_ALLOW_THREADS
195 num_params_needed = sqlite3_bind_parameter_count(self->st);
196 Py_END_ALLOW_THREADS
197
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000198 if (PyTuple_CheckExact(parameters) || PyList_CheckExact(parameters) || (!PyDict_Check(parameters) && PySequence_Check(parameters))) {
199 /* parameters passed as sequence */
200 if (PyTuple_CheckExact(parameters)) {
201 num_params = PyTuple_GET_SIZE(parameters);
202 } else if (PyList_CheckExact(parameters)) {
203 num_params = PyList_GET_SIZE(parameters);
204 } else {
205 num_params = PySequence_Size(parameters);
206 }
207 if (num_params != num_params_needed) {
208 PyErr_Format(pysqlite_ProgrammingError, "Incorrect number of bindings supplied. The current statement uses %d, and there are %d supplied.",
209 num_params_needed, num_params);
210 return;
211 }
212 for (i = 0; i < num_params; i++) {
213 if (PyTuple_CheckExact(parameters)) {
214 current_param = PyTuple_GET_ITEM(parameters, i);
215 Py_XINCREF(current_param);
216 } else if (PyList_CheckExact(parameters)) {
217 current_param = PyList_GET_ITEM(parameters, i);
218 Py_XINCREF(current_param);
219 } else {
220 current_param = PySequence_GetItem(parameters, i);
221 }
222 if (!current_param) {
223 return;
224 }
225
226 if (!_need_adapt(current_param)) {
227 adapted = current_param;
228 } else {
229 adapted = microprotocols_adapt(current_param, (PyObject*)&pysqlite_PrepareProtocolType, NULL);
230 if (adapted) {
231 Py_DECREF(current_param);
232 } else {
233 PyErr_Clear();
234 adapted = current_param;
235 }
236 }
237
238 rc = pysqlite_statement_bind_parameter(self, i + 1, adapted, allow_8bit_chars);
239 Py_DECREF(adapted);
240
241 if (rc != SQLITE_OK) {
242 if (!PyErr_Occurred()) {
243 PyErr_Format(pysqlite_InterfaceError, "Error binding parameter %d - probably unsupported type.", i);
244 }
245 return;
246 }
247 }
248 } else if (PyDict_Check(parameters)) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000249 /* parameters passed as dictionary */
250 for (i = 1; i <= num_params_needed; i++) {
251 Py_BEGIN_ALLOW_THREADS
252 binding_name = sqlite3_bind_parameter_name(self->st, i);
253 Py_END_ALLOW_THREADS
254 if (!binding_name) {
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000255 PyErr_Format(pysqlite_ProgrammingError, "Binding %d has no name, but you supplied a dictionary (which has only names).", i);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000256 return;
257 }
258
259 binding_name++; /* skip first char (the colon) */
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000260 if (PyDict_CheckExact(parameters)) {
261 current_param = PyDict_GetItemString(parameters, binding_name);
262 Py_XINCREF(current_param);
263 } else {
264 current_param = PyMapping_GetItemString(parameters, (char*)binding_name);
265 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000266 if (!current_param) {
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000267 PyErr_Format(pysqlite_ProgrammingError, "You did not supply a value for binding %d.", i);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000268 return;
269 }
270
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000271 if (!_need_adapt(current_param)) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000272 adapted = current_param;
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000273 } else {
274 adapted = microprotocols_adapt(current_param, (PyObject*)&pysqlite_PrepareProtocolType, NULL);
275 if (adapted) {
276 Py_DECREF(current_param);
277 } else {
278 PyErr_Clear();
279 adapted = current_param;
280 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000281 }
282
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000283 rc = pysqlite_statement_bind_parameter(self, i, adapted, allow_8bit_chars);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000284 Py_DECREF(adapted);
285
286 if (rc != SQLITE_OK) {
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000287 if (!PyErr_Occurred()) {
288 PyErr_Format(pysqlite_InterfaceError, "Error binding parameter :%s - probably unsupported type.", binding_name);
289 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000290 return;
291 }
292 }
293 } else {
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000294 PyErr_SetString(PyExc_ValueError, "parameters are of unsupported type");
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000295 }
296}
297
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000298int pysqlite_statement_recompile(pysqlite_Statement* self, PyObject* params)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000299{
300 const char* tail;
301 int rc;
Guido van Rossum83857e32007-05-09 23:37:01 +0000302 const char* sql_cstr;
303 Py_ssize_t sql_len;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000304 sqlite3_stmt* new_st;
305
Guido van Rossum7d1df6c2007-08-29 13:53:23 +0000306 sql_cstr = PyUnicode_AsStringAndSize(self->sql, &sql_len);
Guido van Rossumfa9a1212007-08-29 03:34:29 +0000307 if (sql_cstr == NULL) {
Guido van Rossum83857e32007-05-09 23:37:01 +0000308 rc = PYSQLITE_SQL_WRONG_TYPE;
309 return rc;
310 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000311
312 rc = sqlite3_prepare(self->db,
313 sql_cstr,
314 -1,
315 &new_st,
316 &tail);
317
318 if (rc == SQLITE_OK) {
319 /* The efficient sqlite3_transfer_bindings is only available in SQLite
320 * version 3.2.2 or later. For older SQLite releases, that might not
321 * even define SQLITE_VERSION_NUMBER, we do it the manual way.
322 */
323 #ifdef SQLITE_VERSION_NUMBER
324 #if SQLITE_VERSION_NUMBER >= 3002002
Christian Heimes38053212007-12-14 01:24:44 +0000325 /* The check for the number of parameters is necessary to not trigger a
326 * bug in certain SQLite versions (experienced in 3.2.8 and 3.3.4). */
327 if (sqlite3_bind_parameter_count(self->st) > 0) {
328 (void)sqlite3_transfer_bindings(self->st, new_st);
329 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000330 #endif
331 #else
332 statement_bind_parameters(self, params);
333 #endif
334
335 (void)sqlite3_finalize(self->st);
336 self->st = new_st;
337 }
338
339 return rc;
340}
341
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000342int pysqlite_statement_finalize(pysqlite_Statement* self)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000343{
344 int rc;
345
346 rc = SQLITE_OK;
347 if (self->st) {
348 Py_BEGIN_ALLOW_THREADS
349 rc = sqlite3_finalize(self->st);
350 Py_END_ALLOW_THREADS
351 self->st = NULL;
352 }
353
354 self->in_use = 0;
355
356 return rc;
357}
358
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000359int pysqlite_statement_reset(pysqlite_Statement* self)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000360{
361 int rc;
362
363 rc = SQLITE_OK;
364
365 if (self->in_use && self->st) {
366 Py_BEGIN_ALLOW_THREADS
367 rc = sqlite3_reset(self->st);
368 Py_END_ALLOW_THREADS
369
370 if (rc == SQLITE_OK) {
371 self->in_use = 0;
372 }
373 }
374
375 return rc;
376}
377
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000378void pysqlite_statement_mark_dirty(pysqlite_Statement* self)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000379{
380 self->in_use = 1;
381}
382
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000383void pysqlite_statement_dealloc(pysqlite_Statement* self)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000384{
385 int rc;
386
387 if (self->st) {
388 Py_BEGIN_ALLOW_THREADS
389 rc = sqlite3_finalize(self->st);
390 Py_END_ALLOW_THREADS
391 }
392
393 self->st = NULL;
394
395 Py_XDECREF(self->sql);
396
Thomas Wouters477c8d52006-05-27 19:21:47 +0000397 if (self->in_weakreflist != NULL) {
398 PyObject_ClearWeakRefs((PyObject*)self);
399 }
400
Christian Heimes90aa7642007-12-19 02:45:37 +0000401 Py_TYPE(self)->tp_free((PyObject*)self);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000402}
403
404/*
405 * Checks if there is anything left in an SQL string after SQLite compiled it.
406 * This is used to check if somebody tried to execute more than one SQL command
407 * with one execute()/executemany() command, which the DB-API and we don't
408 * allow.
409 *
410 * Returns 1 if there is more left than should be. 0 if ok.
411 */
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000412static int pysqlite_check_remaining_sql(const char* tail)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000413{
414 const char* pos = tail;
415
416 parse_remaining_sql_state state = NORMAL;
417
418 for (;;) {
419 switch (*pos) {
420 case 0:
421 return 0;
422 case '-':
423 if (state == NORMAL) {
424 state = LINECOMMENT_1;
425 } else if (state == LINECOMMENT_1) {
426 state = IN_LINECOMMENT;
427 }
428 break;
429 case ' ':
430 case '\t':
431 break;
432 case '\n':
433 case 13:
434 if (state == IN_LINECOMMENT) {
435 state = NORMAL;
436 }
437 break;
438 case '/':
439 if (state == NORMAL) {
440 state = COMMENTSTART_1;
441 } else if (state == COMMENTEND_1) {
442 state = NORMAL;
443 } else if (state == COMMENTSTART_1) {
444 return 1;
445 }
446 break;
447 case '*':
448 if (state == NORMAL) {
449 return 1;
450 } else if (state == LINECOMMENT_1) {
451 return 1;
452 } else if (state == COMMENTSTART_1) {
453 state = IN_COMMENT;
454 } else if (state == IN_COMMENT) {
455 state = COMMENTEND_1;
456 }
457 break;
458 default:
459 if (state == COMMENTEND_1) {
460 state = IN_COMMENT;
461 } else if (state == IN_LINECOMMENT) {
462 } else if (state == IN_COMMENT) {
463 } else {
464 return 1;
465 }
466 }
467
468 pos++;
469 }
470
471 return 0;
472}
473
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000474PyTypeObject pysqlite_StatementType = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000475 PyVarObject_HEAD_INIT(NULL, 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000476 MODULE_NAME ".Statement", /* tp_name */
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000477 sizeof(pysqlite_Statement), /* tp_basicsize */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000478 0, /* tp_itemsize */
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000479 (destructor)pysqlite_statement_dealloc, /* tp_dealloc */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000480 0, /* tp_print */
481 0, /* tp_getattr */
482 0, /* tp_setattr */
483 0, /* tp_compare */
484 0, /* tp_repr */
485 0, /* tp_as_number */
486 0, /* tp_as_sequence */
487 0, /* tp_as_mapping */
488 0, /* tp_hash */
489 0, /* tp_call */
490 0, /* tp_str */
491 0, /* tp_getattro */
492 0, /* tp_setattro */
493 0, /* tp_as_buffer */
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000494 Py_TPFLAGS_DEFAULT, /* tp_flags */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000495 0, /* tp_doc */
496 0, /* tp_traverse */
497 0, /* tp_clear */
498 0, /* tp_richcompare */
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000499 offsetof(pysqlite_Statement, in_weakreflist), /* tp_weaklistoffset */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000500 0, /* tp_iter */
501 0, /* tp_iternext */
502 0, /* tp_methods */
503 0, /* tp_members */
504 0, /* tp_getset */
505 0, /* tp_base */
506 0, /* tp_dict */
507 0, /* tp_descr_get */
508 0, /* tp_descr_set */
509 0, /* tp_dictoffset */
510 (initproc)0, /* tp_init */
511 0, /* tp_alloc */
512 0, /* tp_new */
513 0 /* tp_free */
514};
515
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000516extern int pysqlite_statement_setup_types(void)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000517{
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000518 pysqlite_StatementType.tp_new = PyType_GenericNew;
519 return PyType_Ready(&pysqlite_StatementType);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000520}