blob: ebf948ba45c229717b4a61e54d17c1110392e308 [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;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000092 PY_LONG_LONG longlongval;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000093 const char* buffer;
94 char* string;
95 Py_ssize_t buflen;
Gerhard Häringe7ea7452008-03-29 00:45:29 +000096 parameter_type paramtype;
97 char* c;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000098
99 if (parameter == Py_None) {
100 rc = sqlite3_bind_null(self->st, pos);
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000101 goto final;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000102 }
103
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000104 if (PyLong_CheckExact(parameter)) {
105 paramtype = TYPE_LONG;
106 } else if (PyFloat_CheckExact(parameter)) {
107 paramtype = TYPE_FLOAT;
108 } else if (PyUnicode_CheckExact(parameter)) {
109 paramtype = TYPE_UNICODE;
110 } else if (PyLong_Check(parameter)) {
111 paramtype = TYPE_LONG;
112 } else if (PyFloat_Check(parameter)) {
113 paramtype = TYPE_FLOAT;
114 } else if (PyUnicode_Check(parameter)) {
115 paramtype = TYPE_STRING;
116 } else if (PyObject_CheckBuffer(parameter)) {
117 paramtype = TYPE_BUFFER;
118 } else {
119 paramtype = TYPE_UNKNOWN;
120 }
121
122 if (paramtype == TYPE_STRING && !allow_8bit_chars) {
123 string = PyString_AS_STRING(parameter);
124 for (c = string; *c != 0; c++) {
125 if (*c & 0x80) {
126 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.");
127 rc = -1;
128 goto final;
129 }
130 }
131 }
132
133 switch (paramtype) {
134 case TYPE_LONG:
135 /* in the overflow error case, longval/longlongval is -1, and an exception is set */
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000136 longlongval = PyLong_AsLongLong(parameter);
137 rc = sqlite3_bind_int64(self->st, pos, (sqlite_int64)longlongval);
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000138 break;
139 case TYPE_FLOAT:
140 rc = sqlite3_bind_double(self->st, pos, PyFloat_AsDouble(parameter));
141 break;
142 case TYPE_UNICODE:
143 string = PyUnicode_AsString(parameter);
144 rc = sqlite3_bind_text(self->st, pos, string, -1, SQLITE_TRANSIENT);
145 break;
146 case TYPE_BUFFER:
147 if (PyObject_AsCharBuffer(parameter, &buffer, &buflen) == 0) {
148 rc = sqlite3_bind_blob(self->st, pos, buffer, buflen, SQLITE_TRANSIENT);
149 } else {
150 PyErr_SetString(PyExc_ValueError, "could not convert BLOB to buffer");
151 rc = -1;
152 }
153 break;
154 case TYPE_UNKNOWN:
155 rc = -1;
156 }
157
158final:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000159 return rc;
160}
161
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000162/* returns 0 if the object is one of Python's internal ones that don't need to be adapted */
163static int _need_adapt(PyObject* obj)
164{
165 if (pysqlite_BaseTypeAdapted) {
166 return 1;
167 }
168
169 if (PyLong_CheckExact(obj) || PyFloat_CheckExact(obj)
170 || PyUnicode_CheckExact(obj) || PyBytes_CheckExact(obj)) {
171 return 0;
172 } else {
173 return 1;
174 }
175}
176
177void pysqlite_statement_bind_parameters(pysqlite_Statement* self, PyObject* parameters, int allow_8bit_chars)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000178{
179 PyObject* current_param;
180 PyObject* adapted;
181 const char* binding_name;
182 int i;
183 int rc;
184 int num_params_needed;
185 int num_params;
186
187 Py_BEGIN_ALLOW_THREADS
188 num_params_needed = sqlite3_bind_parameter_count(self->st);
189 Py_END_ALLOW_THREADS
190
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000191 if (PyTuple_CheckExact(parameters) || PyList_CheckExact(parameters) || (!PyDict_Check(parameters) && PySequence_Check(parameters))) {
192 /* parameters passed as sequence */
193 if (PyTuple_CheckExact(parameters)) {
194 num_params = PyTuple_GET_SIZE(parameters);
195 } else if (PyList_CheckExact(parameters)) {
196 num_params = PyList_GET_SIZE(parameters);
197 } else {
198 num_params = PySequence_Size(parameters);
199 }
200 if (num_params != num_params_needed) {
201 PyErr_Format(pysqlite_ProgrammingError, "Incorrect number of bindings supplied. The current statement uses %d, and there are %d supplied.",
202 num_params_needed, num_params);
203 return;
204 }
205 for (i = 0; i < num_params; i++) {
206 if (PyTuple_CheckExact(parameters)) {
207 current_param = PyTuple_GET_ITEM(parameters, i);
208 Py_XINCREF(current_param);
209 } else if (PyList_CheckExact(parameters)) {
210 current_param = PyList_GET_ITEM(parameters, i);
211 Py_XINCREF(current_param);
212 } else {
213 current_param = PySequence_GetItem(parameters, i);
214 }
215 if (!current_param) {
216 return;
217 }
218
219 if (!_need_adapt(current_param)) {
220 adapted = current_param;
221 } else {
222 adapted = microprotocols_adapt(current_param, (PyObject*)&pysqlite_PrepareProtocolType, NULL);
223 if (adapted) {
224 Py_DECREF(current_param);
225 } else {
226 PyErr_Clear();
227 adapted = current_param;
228 }
229 }
230
231 rc = pysqlite_statement_bind_parameter(self, i + 1, adapted, allow_8bit_chars);
232 Py_DECREF(adapted);
233
234 if (rc != SQLITE_OK) {
235 if (!PyErr_Occurred()) {
236 PyErr_Format(pysqlite_InterfaceError, "Error binding parameter %d - probably unsupported type.", i);
237 }
238 return;
239 }
240 }
241 } else if (PyDict_Check(parameters)) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000242 /* parameters passed as dictionary */
243 for (i = 1; i <= num_params_needed; i++) {
244 Py_BEGIN_ALLOW_THREADS
245 binding_name = sqlite3_bind_parameter_name(self->st, i);
246 Py_END_ALLOW_THREADS
247 if (!binding_name) {
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000248 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 +0000249 return;
250 }
251
252 binding_name++; /* skip first char (the colon) */
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000253 if (PyDict_CheckExact(parameters)) {
254 current_param = PyDict_GetItemString(parameters, binding_name);
255 Py_XINCREF(current_param);
256 } else {
257 current_param = PyMapping_GetItemString(parameters, (char*)binding_name);
258 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000259 if (!current_param) {
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000260 PyErr_Format(pysqlite_ProgrammingError, "You did not supply a value for binding %d.", i);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000261 return;
262 }
263
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000264 if (!_need_adapt(current_param)) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000265 adapted = current_param;
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000266 } else {
267 adapted = microprotocols_adapt(current_param, (PyObject*)&pysqlite_PrepareProtocolType, NULL);
268 if (adapted) {
269 Py_DECREF(current_param);
270 } else {
271 PyErr_Clear();
272 adapted = current_param;
273 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000274 }
275
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000276 rc = pysqlite_statement_bind_parameter(self, i, adapted, allow_8bit_chars);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000277 Py_DECREF(adapted);
278
279 if (rc != SQLITE_OK) {
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000280 if (!PyErr_Occurred()) {
281 PyErr_Format(pysqlite_InterfaceError, "Error binding parameter :%s - probably unsupported type.", binding_name);
282 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000283 return;
284 }
285 }
286 } else {
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000287 PyErr_SetString(PyExc_ValueError, "parameters are of unsupported type");
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000288 }
289}
290
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000291int pysqlite_statement_recompile(pysqlite_Statement* self, PyObject* params)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000292{
293 const char* tail;
294 int rc;
Guido van Rossum83857e32007-05-09 23:37:01 +0000295 const char* sql_cstr;
296 Py_ssize_t sql_len;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000297 sqlite3_stmt* new_st;
298
Guido van Rossum7d1df6c2007-08-29 13:53:23 +0000299 sql_cstr = PyUnicode_AsStringAndSize(self->sql, &sql_len);
Guido van Rossumfa9a1212007-08-29 03:34:29 +0000300 if (sql_cstr == NULL) {
Guido van Rossum83857e32007-05-09 23:37:01 +0000301 rc = PYSQLITE_SQL_WRONG_TYPE;
302 return rc;
303 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000304
305 rc = sqlite3_prepare(self->db,
306 sql_cstr,
307 -1,
308 &new_st,
309 &tail);
310
311 if (rc == SQLITE_OK) {
312 /* The efficient sqlite3_transfer_bindings is only available in SQLite
313 * version 3.2.2 or later. For older SQLite releases, that might not
314 * even define SQLITE_VERSION_NUMBER, we do it the manual way.
315 */
316 #ifdef SQLITE_VERSION_NUMBER
317 #if SQLITE_VERSION_NUMBER >= 3002002
Christian Heimes38053212007-12-14 01:24:44 +0000318 /* The check for the number of parameters is necessary to not trigger a
319 * bug in certain SQLite versions (experienced in 3.2.8 and 3.3.4). */
320 if (sqlite3_bind_parameter_count(self->st) > 0) {
321 (void)sqlite3_transfer_bindings(self->st, new_st);
322 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000323 #endif
324 #else
325 statement_bind_parameters(self, params);
326 #endif
327
328 (void)sqlite3_finalize(self->st);
329 self->st = new_st;
330 }
331
332 return rc;
333}
334
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000335int pysqlite_statement_finalize(pysqlite_Statement* self)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000336{
337 int rc;
338
339 rc = SQLITE_OK;
340 if (self->st) {
341 Py_BEGIN_ALLOW_THREADS
342 rc = sqlite3_finalize(self->st);
343 Py_END_ALLOW_THREADS
344 self->st = NULL;
345 }
346
347 self->in_use = 0;
348
349 return rc;
350}
351
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000352int pysqlite_statement_reset(pysqlite_Statement* self)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000353{
354 int rc;
355
356 rc = SQLITE_OK;
357
358 if (self->in_use && self->st) {
359 Py_BEGIN_ALLOW_THREADS
360 rc = sqlite3_reset(self->st);
361 Py_END_ALLOW_THREADS
362
363 if (rc == SQLITE_OK) {
364 self->in_use = 0;
365 }
366 }
367
368 return rc;
369}
370
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000371void pysqlite_statement_mark_dirty(pysqlite_Statement* self)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000372{
373 self->in_use = 1;
374}
375
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000376void pysqlite_statement_dealloc(pysqlite_Statement* self)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000377{
378 int rc;
379
380 if (self->st) {
381 Py_BEGIN_ALLOW_THREADS
382 rc = sqlite3_finalize(self->st);
383 Py_END_ALLOW_THREADS
384 }
385
386 self->st = NULL;
387
388 Py_XDECREF(self->sql);
389
Thomas Wouters477c8d52006-05-27 19:21:47 +0000390 if (self->in_weakreflist != NULL) {
391 PyObject_ClearWeakRefs((PyObject*)self);
392 }
393
Christian Heimes90aa7642007-12-19 02:45:37 +0000394 Py_TYPE(self)->tp_free((PyObject*)self);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000395}
396
397/*
398 * Checks if there is anything left in an SQL string after SQLite compiled it.
399 * This is used to check if somebody tried to execute more than one SQL command
400 * with one execute()/executemany() command, which the DB-API and we don't
401 * allow.
402 *
403 * Returns 1 if there is more left than should be. 0 if ok.
404 */
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000405static int pysqlite_check_remaining_sql(const char* tail)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000406{
407 const char* pos = tail;
408
409 parse_remaining_sql_state state = NORMAL;
410
411 for (;;) {
412 switch (*pos) {
413 case 0:
414 return 0;
415 case '-':
416 if (state == NORMAL) {
417 state = LINECOMMENT_1;
418 } else if (state == LINECOMMENT_1) {
419 state = IN_LINECOMMENT;
420 }
421 break;
422 case ' ':
423 case '\t':
424 break;
425 case '\n':
426 case 13:
427 if (state == IN_LINECOMMENT) {
428 state = NORMAL;
429 }
430 break;
431 case '/':
432 if (state == NORMAL) {
433 state = COMMENTSTART_1;
434 } else if (state == COMMENTEND_1) {
435 state = NORMAL;
436 } else if (state == COMMENTSTART_1) {
437 return 1;
438 }
439 break;
440 case '*':
441 if (state == NORMAL) {
442 return 1;
443 } else if (state == LINECOMMENT_1) {
444 return 1;
445 } else if (state == COMMENTSTART_1) {
446 state = IN_COMMENT;
447 } else if (state == IN_COMMENT) {
448 state = COMMENTEND_1;
449 }
450 break;
451 default:
452 if (state == COMMENTEND_1) {
453 state = IN_COMMENT;
454 } else if (state == IN_LINECOMMENT) {
455 } else if (state == IN_COMMENT) {
456 } else {
457 return 1;
458 }
459 }
460
461 pos++;
462 }
463
464 return 0;
465}
466
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000467PyTypeObject pysqlite_StatementType = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000468 PyVarObject_HEAD_INIT(NULL, 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000469 MODULE_NAME ".Statement", /* tp_name */
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000470 sizeof(pysqlite_Statement), /* tp_basicsize */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000471 0, /* tp_itemsize */
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000472 (destructor)pysqlite_statement_dealloc, /* tp_dealloc */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000473 0, /* tp_print */
474 0, /* tp_getattr */
475 0, /* tp_setattr */
476 0, /* tp_compare */
477 0, /* tp_repr */
478 0, /* tp_as_number */
479 0, /* tp_as_sequence */
480 0, /* tp_as_mapping */
481 0, /* tp_hash */
482 0, /* tp_call */
483 0, /* tp_str */
484 0, /* tp_getattro */
485 0, /* tp_setattro */
486 0, /* tp_as_buffer */
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000487 Py_TPFLAGS_DEFAULT, /* tp_flags */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000488 0, /* tp_doc */
489 0, /* tp_traverse */
490 0, /* tp_clear */
491 0, /* tp_richcompare */
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000492 offsetof(pysqlite_Statement, in_weakreflist), /* tp_weaklistoffset */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000493 0, /* tp_iter */
494 0, /* tp_iternext */
495 0, /* tp_methods */
496 0, /* tp_members */
497 0, /* tp_getset */
498 0, /* tp_base */
499 0, /* tp_dict */
500 0, /* tp_descr_get */
501 0, /* tp_descr_set */
502 0, /* tp_dictoffset */
503 (initproc)0, /* tp_init */
504 0, /* tp_alloc */
505 0, /* tp_new */
506 0 /* tp_free */
507};
508
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000509extern int pysqlite_statement_setup_types(void)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000510{
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000511 pysqlite_StatementType.tp_new = PyType_GenericNew;
512 return PyType_Ready(&pysqlite_StatementType);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000513}