blob: d8d91140c160567cb65559f5385452857c9ece93 [file] [log] [blame]
Anthony Baxterc51ee692006-04-01 00:57:31 +00001/* statement.c - the statement type
2 *
Gerhard Häring1cc60ed2008-02-29 22:08:41 +00003 * Copyright (C) 2005-2007 Gerhard Häring <gh@ghaering.de>
Anthony Baxterc51ee692006-04-01 00:57:31 +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"
Anthony Baxter07f5b352006-04-01 08:36:27 +000025#include "cursor.h"
Anthony Baxterc51ee692006-04-01 00:57:31 +000026#include "connection.h"
Anthony Baxter07f5b352006-04-01 08:36:27 +000027#include "microprotocols.h"
28#include "prepare_protocol.h"
Anthony Baxter72289a62006-04-04 06:29:05 +000029#include "sqlitecompat.h"
Anthony Baxterc51ee692006-04-01 00:57:31 +000030
31/* prototypes */
Gerhard Häring0741a602007-01-14 01:43:50 +000032static int pysqlite_check_remaining_sql(const char* tail);
Anthony Baxterc51ee692006-04-01 00:57:31 +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äring1cc60ed2008-02-29 22:08:41 +000043typedef enum {
44 TYPE_INT,
45 TYPE_LONG,
46 TYPE_FLOAT,
47 TYPE_STRING,
48 TYPE_UNICODE,
49 TYPE_BUFFER,
50 TYPE_UNKNOWN
51} parameter_type;
52
Gerhard Häring0741a602007-01-14 01:43:50 +000053int pysqlite_statement_create(pysqlite_Statement* self, pysqlite_Connection* connection, PyObject* sql)
Anthony Baxterc51ee692006-04-01 00:57:31 +000054{
55 const char* tail;
56 int rc;
57 PyObject* sql_str;
58 char* sql_cstr;
59
60 self->st = NULL;
Anthony Baxterc51ee692006-04-01 00:57:31 +000061 self->in_use = 0;
62
63 if (PyString_Check(sql)) {
64 sql_str = sql;
65 Py_INCREF(sql_str);
66 } else if (PyUnicode_Check(sql)) {
67 sql_str = PyUnicode_AsUTF8String(sql);
68 if (!sql_str) {
69 rc = PYSQLITE_SQL_WRONG_TYPE;
70 return rc;
71 }
72 } else {
73 rc = PYSQLITE_SQL_WRONG_TYPE;
74 return rc;
75 }
76
Gerhard Häring3e99c0a2006-04-23 15:24:26 +000077 self->in_weakreflist = NULL;
Anthony Baxterc51ee692006-04-01 00:57:31 +000078 self->sql = sql_str;
79
80 sql_cstr = PyString_AsString(sql_str);
81
82 rc = sqlite3_prepare(connection->db,
83 sql_cstr,
84 -1,
85 &self->st,
86 &tail);
87
88 self->db = connection->db;
89
Gerhard Häring0741a602007-01-14 01:43:50 +000090 if (rc == SQLITE_OK && pysqlite_check_remaining_sql(tail)) {
Anthony Baxterc51ee692006-04-01 00:57:31 +000091 (void)sqlite3_finalize(self->st);
Neal Norwitz195e4e62006-04-16 03:37:19 +000092 self->st = NULL;
Anthony Baxterc51ee692006-04-01 00:57:31 +000093 rc = PYSQLITE_TOO_MUCH_SQL;
94 }
95
96 return rc;
97}
98
Gerhard Häring2a11c052008-03-28 20:08:36 +000099int pysqlite_statement_bind_parameter(pysqlite_Statement* self, int pos, PyObject* parameter, int allow_8bit_chars)
Anthony Baxter07f5b352006-04-01 08:36:27 +0000100{
101 int rc = SQLITE_OK;
102 long longval;
103#ifdef HAVE_LONG_LONG
104 PY_LONG_LONG longlongval;
105#endif
106 const char* buffer;
107 char* string;
Neal Norwitz95f0e4c2006-04-01 09:08:06 +0000108 Py_ssize_t buflen;
Anthony Baxter07f5b352006-04-01 08:36:27 +0000109 PyObject* stringval;
Gerhard Häring1cc60ed2008-02-29 22:08:41 +0000110 parameter_type paramtype;
Gerhard Häring2a11c052008-03-28 20:08:36 +0000111 char* c;
Anthony Baxter07f5b352006-04-01 08:36:27 +0000112
113 if (parameter == Py_None) {
114 rc = sqlite3_bind_null(self->st, pos);
Gerhard Häring1cc60ed2008-02-29 22:08:41 +0000115 goto final;
Anthony Baxter07f5b352006-04-01 08:36:27 +0000116 }
117
Gerhard Häring1cc60ed2008-02-29 22:08:41 +0000118 if (PyInt_CheckExact(parameter)) {
119 paramtype = TYPE_INT;
120 } else if (PyLong_CheckExact(parameter)) {
121 paramtype = TYPE_LONG;
122 } else if (PyFloat_CheckExact(parameter)) {
123 paramtype = TYPE_FLOAT;
124 } else if (PyString_CheckExact(parameter)) {
125 paramtype = TYPE_STRING;
126 } else if (PyUnicode_CheckExact(parameter)) {
127 paramtype = TYPE_UNICODE;
128 } else if (PyBuffer_Check(parameter)) {
129 paramtype = TYPE_BUFFER;
130 } else if (PyInt_Check(parameter)) {
131 paramtype = TYPE_INT;
132 } else if (PyLong_Check(parameter)) {
133 paramtype = TYPE_LONG;
134 } else if (PyFloat_Check(parameter)) {
135 paramtype = TYPE_FLOAT;
136 } else if (PyString_Check(parameter)) {
137 paramtype = TYPE_STRING;
138 } else if (PyUnicode_Check(parameter)) {
139 paramtype = TYPE_UNICODE;
140 } else {
141 paramtype = TYPE_UNKNOWN;
142 }
143
Gerhard Häring2a11c052008-03-28 20:08:36 +0000144 if (paramtype == TYPE_STRING && !allow_8bit_chars) {
145 string = PyString_AS_STRING(parameter);
146 for (c = string; *c != 0; c++) {
147 if (*c & 0x80) {
148 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.");
149 rc = -1;
150 goto final;
151 }
152 }
153 }
154
Gerhard Häring1cc60ed2008-02-29 22:08:41 +0000155 switch (paramtype) {
156 case TYPE_INT:
157 longval = PyInt_AsLong(parameter);
158 rc = sqlite3_bind_int64(self->st, pos, (sqlite_int64)longval);
159 break;
160#ifdef HAVE_LONG_LONG
161 case TYPE_LONG:
162 longlongval = PyLong_AsLongLong(parameter);
163 /* in the overflow error case, longlongval is -1, and an exception is set */
164 rc = sqlite3_bind_int64(self->st, pos, (sqlite_int64)longlongval);
165 break;
166#endif
167 case TYPE_FLOAT:
168 rc = sqlite3_bind_double(self->st, pos, PyFloat_AsDouble(parameter));
169 break;
170 case TYPE_STRING:
171 string = PyString_AS_STRING(parameter);
172 rc = sqlite3_bind_text(self->st, pos, string, -1, SQLITE_TRANSIENT);
173 break;
174 case TYPE_UNICODE:
175 stringval = PyUnicode_AsUTF8String(parameter);
176 string = PyString_AsString(stringval);
177 rc = sqlite3_bind_text(self->st, pos, string, -1, SQLITE_TRANSIENT);
178 Py_DECREF(stringval);
179 break;
180 case TYPE_BUFFER:
181 if (PyObject_AsCharBuffer(parameter, &buffer, &buflen) == 0) {
182 rc = sqlite3_bind_blob(self->st, pos, buffer, buflen, SQLITE_TRANSIENT);
183 } else {
184 PyErr_SetString(PyExc_ValueError, "could not convert BLOB to buffer");
185 rc = -1;
186 }
187 break;
188 case TYPE_UNKNOWN:
189 rc = -1;
190 }
191
192final:
Anthony Baxter07f5b352006-04-01 08:36:27 +0000193 return rc;
194}
195
Gerhard Häring1cc60ed2008-02-29 22:08:41 +0000196/* returns 0 if the object is one of Python's internal ones that don't need to be adapted */
197static int _need_adapt(PyObject* obj)
198{
199 if (pysqlite_BaseTypeAdapted) {
200 return 1;
201 }
202
203 if (PyInt_CheckExact(obj) || PyLong_CheckExact(obj)
204 || PyFloat_CheckExact(obj) || PyString_CheckExact(obj)
205 || PyUnicode_CheckExact(obj) || PyBuffer_Check(obj)) {
206 return 0;
207 } else {
208 return 1;
209 }
210}
211
Gerhard Häring2a11c052008-03-28 20:08:36 +0000212void pysqlite_statement_bind_parameters(pysqlite_Statement* self, PyObject* parameters, int allow_8bit_chars)
Anthony Baxter07f5b352006-04-01 08:36:27 +0000213{
214 PyObject* current_param;
215 PyObject* adapted;
216 const char* binding_name;
217 int i;
218 int rc;
219 int num_params_needed;
220 int num_params;
221
222 Py_BEGIN_ALLOW_THREADS
223 num_params_needed = sqlite3_bind_parameter_count(self->st);
224 Py_END_ALLOW_THREADS
225
Gerhard Häring1cc60ed2008-02-29 22:08:41 +0000226 if (PyTuple_CheckExact(parameters) || PyList_CheckExact(parameters) || (!PyDict_Check(parameters) && PySequence_Check(parameters))) {
227 /* parameters passed as sequence */
228 if (PyTuple_CheckExact(parameters)) {
229 num_params = PyTuple_GET_SIZE(parameters);
230 } else if (PyList_CheckExact(parameters)) {
231 num_params = PyList_GET_SIZE(parameters);
232 } else {
233 num_params = PySequence_Size(parameters);
234 }
235 if (num_params != num_params_needed) {
236 PyErr_Format(pysqlite_ProgrammingError, "Incorrect number of bindings supplied. The current statement uses %d, and there are %d supplied.",
237 num_params_needed, num_params);
238 return;
239 }
240 for (i = 0; i < num_params; i++) {
241 if (PyTuple_CheckExact(parameters)) {
242 current_param = PyTuple_GET_ITEM(parameters, i);
243 Py_XINCREF(current_param);
244 } else if (PyList_CheckExact(parameters)) {
245 current_param = PyList_GET_ITEM(parameters, i);
246 Py_XINCREF(current_param);
247 } else {
248 current_param = PySequence_GetItem(parameters, i);
249 }
250 if (!current_param) {
251 return;
252 }
253
254 if (!_need_adapt(current_param)) {
255 adapted = current_param;
256 } else {
257 adapted = microprotocols_adapt(current_param, (PyObject*)&pysqlite_PrepareProtocolType, NULL);
258 if (adapted) {
259 Py_DECREF(current_param);
260 } else {
261 PyErr_Clear();
262 adapted = current_param;
263 }
264 }
265
Gerhard Häring2a11c052008-03-28 20:08:36 +0000266 rc = pysqlite_statement_bind_parameter(self, i + 1, adapted, allow_8bit_chars);
Gerhard Häring1cc60ed2008-02-29 22:08:41 +0000267 Py_DECREF(adapted);
268
269 if (rc != SQLITE_OK) {
Gerhard Häring2a11c052008-03-28 20:08:36 +0000270 if (!PyErr_Occurred()) {
271 PyErr_Format(pysqlite_InterfaceError, "Error binding parameter %d - probably unsupported type.", i);
272 }
Gerhard Häring1cc60ed2008-02-29 22:08:41 +0000273 return;
274 }
275 }
276 } else if (PyDict_Check(parameters)) {
Anthony Baxter07f5b352006-04-01 08:36:27 +0000277 /* parameters passed as dictionary */
278 for (i = 1; i <= num_params_needed; i++) {
279 Py_BEGIN_ALLOW_THREADS
280 binding_name = sqlite3_bind_parameter_name(self->st, i);
281 Py_END_ALLOW_THREADS
282 if (!binding_name) {
Gerhard Häring0741a602007-01-14 01:43:50 +0000283 PyErr_Format(pysqlite_ProgrammingError, "Binding %d has no name, but you supplied a dictionary (which has only names).", i);
Anthony Baxter07f5b352006-04-01 08:36:27 +0000284 return;
285 }
286
287 binding_name++; /* skip first char (the colon) */
Gerhard Häring1cc60ed2008-02-29 22:08:41 +0000288 if (PyDict_CheckExact(parameters)) {
289 current_param = PyDict_GetItemString(parameters, binding_name);
290 Py_XINCREF(current_param);
291 } else {
292 current_param = PyMapping_GetItemString(parameters, (char*)binding_name);
293 }
Anthony Baxter07f5b352006-04-01 08:36:27 +0000294 if (!current_param) {
Gerhard Häring0741a602007-01-14 01:43:50 +0000295 PyErr_Format(pysqlite_ProgrammingError, "You did not supply a value for binding %d.", i);
Anthony Baxter07f5b352006-04-01 08:36:27 +0000296 return;
297 }
298
Gerhard Häring1cc60ed2008-02-29 22:08:41 +0000299 if (!_need_adapt(current_param)) {
Anthony Baxter07f5b352006-04-01 08:36:27 +0000300 adapted = current_param;
Gerhard Häring1cc60ed2008-02-29 22:08:41 +0000301 } else {
302 adapted = microprotocols_adapt(current_param, (PyObject*)&pysqlite_PrepareProtocolType, NULL);
303 if (adapted) {
304 Py_DECREF(current_param);
305 } else {
306 PyErr_Clear();
307 adapted = current_param;
308 }
Anthony Baxter07f5b352006-04-01 08:36:27 +0000309 }
310
Gerhard Häring2a11c052008-03-28 20:08:36 +0000311 rc = pysqlite_statement_bind_parameter(self, i, adapted, allow_8bit_chars);
Anthony Baxter07f5b352006-04-01 08:36:27 +0000312 Py_DECREF(adapted);
313
314 if (rc != SQLITE_OK) {
Gerhard Häring2a11c052008-03-28 20:08:36 +0000315 if (!PyErr_Occurred()) {
316 PyErr_Format(pysqlite_InterfaceError, "Error binding parameter :%s - probably unsupported type.", binding_name);
317 }
Anthony Baxter07f5b352006-04-01 08:36:27 +0000318 return;
319 }
320 }
321 } else {
Gerhard Häring1cc60ed2008-02-29 22:08:41 +0000322 PyErr_SetString(PyExc_ValueError, "parameters are of unsupported type");
Anthony Baxter07f5b352006-04-01 08:36:27 +0000323 }
324}
325
Gerhard Häring0741a602007-01-14 01:43:50 +0000326int pysqlite_statement_recompile(pysqlite_Statement* self, PyObject* params)
Anthony Baxterc51ee692006-04-01 00:57:31 +0000327{
328 const char* tail;
329 int rc;
330 char* sql_cstr;
331 sqlite3_stmt* new_st;
332
333 sql_cstr = PyString_AsString(self->sql);
334
335 rc = sqlite3_prepare(self->db,
336 sql_cstr,
337 -1,
338 &new_st,
339 &tail);
340
341 if (rc == SQLITE_OK) {
Anthony Baxter07f5b352006-04-01 08:36:27 +0000342 /* The efficient sqlite3_transfer_bindings is only available in SQLite
343 * version 3.2.2 or later. For older SQLite releases, that might not
344 * even define SQLITE_VERSION_NUMBER, we do it the manual way.
345 */
346 #ifdef SQLITE_VERSION_NUMBER
347 #if SQLITE_VERSION_NUMBER >= 3002002
Gerhard Häring99b9df82007-12-11 21:07:40 +0000348 /* The check for the number of parameters is necessary to not trigger a
349 * bug in certain SQLite versions (experienced in 3.2.8 and 3.3.4). */
350 if (sqlite3_bind_parameter_count(self->st) > 0) {
351 (void)sqlite3_transfer_bindings(self->st, new_st);
352 }
Anthony Baxter07f5b352006-04-01 08:36:27 +0000353 #endif
354 #else
355 statement_bind_parameters(self, params);
356 #endif
Anthony Baxterc51ee692006-04-01 00:57:31 +0000357
358 (void)sqlite3_finalize(self->st);
359 self->st = new_st;
360 }
361
362 return rc;
363}
364
Gerhard Häring0741a602007-01-14 01:43:50 +0000365int pysqlite_statement_finalize(pysqlite_Statement* self)
Anthony Baxterc51ee692006-04-01 00:57:31 +0000366{
367 int rc;
368
369 rc = SQLITE_OK;
370 if (self->st) {
371 Py_BEGIN_ALLOW_THREADS
372 rc = sqlite3_finalize(self->st);
373 Py_END_ALLOW_THREADS
374 self->st = NULL;
375 }
376
377 self->in_use = 0;
378
379 return rc;
380}
381
Gerhard Häring0741a602007-01-14 01:43:50 +0000382int pysqlite_statement_reset(pysqlite_Statement* self)
Anthony Baxterc51ee692006-04-01 00:57:31 +0000383{
384 int rc;
385
386 rc = SQLITE_OK;
387
388 if (self->in_use && self->st) {
389 Py_BEGIN_ALLOW_THREADS
390 rc = sqlite3_reset(self->st);
391 Py_END_ALLOW_THREADS
392
393 if (rc == SQLITE_OK) {
394 self->in_use = 0;
395 }
396 }
397
398 return rc;
399}
400
Gerhard Häring0741a602007-01-14 01:43:50 +0000401void pysqlite_statement_mark_dirty(pysqlite_Statement* self)
Anthony Baxterc51ee692006-04-01 00:57:31 +0000402{
403 self->in_use = 1;
404}
405
Gerhard Häring0741a602007-01-14 01:43:50 +0000406void pysqlite_statement_dealloc(pysqlite_Statement* self)
Anthony Baxterc51ee692006-04-01 00:57:31 +0000407{
408 int rc;
409
410 if (self->st) {
411 Py_BEGIN_ALLOW_THREADS
412 rc = sqlite3_finalize(self->st);
413 Py_END_ALLOW_THREADS
414 }
415
416 self->st = NULL;
417
418 Py_XDECREF(self->sql);
419
Gerhard Häring3e99c0a2006-04-23 15:24:26 +0000420 if (self->in_weakreflist != NULL) {
421 PyObject_ClearWeakRefs((PyObject*)self);
422 }
423
Christian Heimese93237d2007-12-19 02:37:44 +0000424 Py_TYPE(self)->tp_free((PyObject*)self);
Anthony Baxterc51ee692006-04-01 00:57:31 +0000425}
426
427/*
428 * Checks if there is anything left in an SQL string after SQLite compiled it.
429 * This is used to check if somebody tried to execute more than one SQL command
430 * with one execute()/executemany() command, which the DB-API and we don't
431 * allow.
432 *
433 * Returns 1 if there is more left than should be. 0 if ok.
434 */
Gerhard Häring0741a602007-01-14 01:43:50 +0000435static int pysqlite_check_remaining_sql(const char* tail)
Anthony Baxterc51ee692006-04-01 00:57:31 +0000436{
437 const char* pos = tail;
438
439 parse_remaining_sql_state state = NORMAL;
440
441 for (;;) {
442 switch (*pos) {
443 case 0:
444 return 0;
445 case '-':
446 if (state == NORMAL) {
447 state = LINECOMMENT_1;
448 } else if (state == LINECOMMENT_1) {
449 state = IN_LINECOMMENT;
450 }
451 break;
452 case ' ':
453 case '\t':
454 break;
455 case '\n':
456 case 13:
457 if (state == IN_LINECOMMENT) {
458 state = NORMAL;
459 }
460 break;
461 case '/':
462 if (state == NORMAL) {
463 state = COMMENTSTART_1;
464 } else if (state == COMMENTEND_1) {
465 state = NORMAL;
466 } else if (state == COMMENTSTART_1) {
467 return 1;
468 }
469 break;
470 case '*':
471 if (state == NORMAL) {
472 return 1;
473 } else if (state == LINECOMMENT_1) {
474 return 1;
475 } else if (state == COMMENTSTART_1) {
476 state = IN_COMMENT;
477 } else if (state == IN_COMMENT) {
478 state = COMMENTEND_1;
479 }
480 break;
481 default:
482 if (state == COMMENTEND_1) {
483 state = IN_COMMENT;
484 } else if (state == IN_LINECOMMENT) {
485 } else if (state == IN_COMMENT) {
486 } else {
487 return 1;
488 }
489 }
490
491 pos++;
492 }
493
494 return 0;
495}
496
Gerhard Häring0741a602007-01-14 01:43:50 +0000497PyTypeObject pysqlite_StatementType = {
Martin v. Löwis68192102007-07-21 06:55:02 +0000498 PyVarObject_HEAD_INIT(NULL, 0)
Anthony Baxter8e7b4902006-04-05 18:25:33 +0000499 MODULE_NAME ".Statement", /* tp_name */
Gerhard Häring0741a602007-01-14 01:43:50 +0000500 sizeof(pysqlite_Statement), /* tp_basicsize */
Anthony Baxterc51ee692006-04-01 00:57:31 +0000501 0, /* tp_itemsize */
Gerhard Häring0741a602007-01-14 01:43:50 +0000502 (destructor)pysqlite_statement_dealloc, /* tp_dealloc */
Anthony Baxterc51ee692006-04-01 00:57:31 +0000503 0, /* tp_print */
504 0, /* tp_getattr */
505 0, /* tp_setattr */
506 0, /* tp_compare */
507 0, /* tp_repr */
508 0, /* tp_as_number */
509 0, /* tp_as_sequence */
510 0, /* tp_as_mapping */
511 0, /* tp_hash */
512 0, /* tp_call */
513 0, /* tp_str */
514 0, /* tp_getattro */
515 0, /* tp_setattro */
516 0, /* tp_as_buffer */
Gerhard Häring3e99c0a2006-04-23 15:24:26 +0000517 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_WEAKREFS, /* tp_flags */
Anthony Baxterc51ee692006-04-01 00:57:31 +0000518 0, /* tp_doc */
519 0, /* tp_traverse */
520 0, /* tp_clear */
521 0, /* tp_richcompare */
Gerhard Häring0741a602007-01-14 01:43:50 +0000522 offsetof(pysqlite_Statement, in_weakreflist), /* tp_weaklistoffset */
Anthony Baxterc51ee692006-04-01 00:57:31 +0000523 0, /* tp_iter */
524 0, /* tp_iternext */
525 0, /* tp_methods */
526 0, /* tp_members */
527 0, /* tp_getset */
528 0, /* tp_base */
529 0, /* tp_dict */
530 0, /* tp_descr_get */
531 0, /* tp_descr_set */
532 0, /* tp_dictoffset */
533 (initproc)0, /* tp_init */
534 0, /* tp_alloc */
535 0, /* tp_new */
536 0 /* tp_free */
537};
538
Gerhard Häring0741a602007-01-14 01:43:50 +0000539extern int pysqlite_statement_setup_types(void)
Anthony Baxterc51ee692006-04-01 00:57:31 +0000540{
Gerhard Häring0741a602007-01-14 01:43:50 +0000541 pysqlite_StatementType.tp_new = PyType_GenericNew;
542 return PyType_Ready(&pysqlite_StatementType);
Anthony Baxterc51ee692006-04-01 00:57:31 +0000543}