• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* statement.c - the statement type
2  *
3  * Copyright (C) 2005-2010 Gerhard Häring <gh@ghaering.de>
4  *
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 "util.h"
30 
31 /* prototypes */
32 static int pysqlite_check_remaining_sql(const char* tail);
33 
34 typedef enum {
35     LINECOMMENT_1,
36     IN_LINECOMMENT,
37     COMMENTSTART_1,
38     IN_COMMENT,
39     COMMENTEND_1,
40     NORMAL
41 } parse_remaining_sql_state;
42 
43 typedef enum {
44     TYPE_LONG,
45     TYPE_FLOAT,
46     TYPE_UNICODE,
47     TYPE_BUFFER,
48     TYPE_UNKNOWN
49 } parameter_type;
50 
51 pysqlite_Statement *
pysqlite_statement_create(pysqlite_Connection * connection,PyObject * sql)52 pysqlite_statement_create(pysqlite_Connection *connection, PyObject *sql)
53 {
54     const char* tail;
55     int rc;
56     const char* sql_cstr;
57     Py_ssize_t sql_cstr_len;
58     const char* p;
59 
60     assert(PyUnicode_Check(sql));
61 
62     sql_cstr = PyUnicode_AsUTF8AndSize(sql, &sql_cstr_len);
63     if (sql_cstr == NULL) {
64         PyErr_Format(pysqlite_Warning,
65                      "SQL is of wrong type ('%s'). Must be string.",
66                      Py_TYPE(sql)->tp_name);
67         return NULL;
68     }
69     if (strlen(sql_cstr) != (size_t)sql_cstr_len) {
70         PyErr_SetString(PyExc_ValueError,
71                         "the query contains a null character");
72         return NULL;
73     }
74 
75     pysqlite_Statement *self = PyObject_GC_New(pysqlite_Statement,
76                                                pysqlite_StatementType);
77     if (self == NULL) {
78         return NULL;
79     }
80 
81     self->db = connection->db;
82     self->st = NULL;
83     self->sql = Py_NewRef(sql);
84     self->in_use = 0;
85     self->is_dml = 0;
86     self->in_weakreflist = NULL;
87 
88     /* Determine if the statement is a DML statement.
89        SELECT is the only exception. See #9924. */
90     for (p = sql_cstr; *p != 0; p++) {
91         switch (*p) {
92             case ' ':
93             case '\r':
94             case '\n':
95             case '\t':
96                 continue;
97         }
98 
99         self->is_dml = (PyOS_strnicmp(p, "insert", 6) == 0)
100                     || (PyOS_strnicmp(p, "update", 6) == 0)
101                     || (PyOS_strnicmp(p, "delete", 6) == 0)
102                     || (PyOS_strnicmp(p, "replace", 7) == 0);
103         break;
104     }
105 
106     Py_BEGIN_ALLOW_THREADS
107     rc = sqlite3_prepare_v2(self->db,
108                             sql_cstr,
109                             -1,
110                             &self->st,
111                             &tail);
112     Py_END_ALLOW_THREADS
113 
114     PyObject_GC_Track(self);
115 
116     if (rc != SQLITE_OK) {
117         _pysqlite_seterror(self->db, NULL);
118         goto error;
119     }
120 
121     if (rc == SQLITE_OK && pysqlite_check_remaining_sql(tail)) {
122         (void)sqlite3_finalize(self->st);
123         self->st = NULL;
124         PyErr_SetString(pysqlite_Warning,
125                         "You can only execute one statement at a time.");
126         goto error;
127     }
128 
129     return self;
130 
131 error:
132     Py_DECREF(self);
133     return NULL;
134 }
135 
pysqlite_statement_bind_parameter(pysqlite_Statement * self,int pos,PyObject * parameter)136 int pysqlite_statement_bind_parameter(pysqlite_Statement* self, int pos, PyObject* parameter)
137 {
138     int rc = SQLITE_OK;
139     const char *string;
140     Py_ssize_t buflen;
141     parameter_type paramtype;
142 
143     if (parameter == Py_None) {
144         rc = sqlite3_bind_null(self->st, pos);
145         goto final;
146     }
147 
148     if (PyLong_CheckExact(parameter)) {
149         paramtype = TYPE_LONG;
150     } else if (PyFloat_CheckExact(parameter)) {
151         paramtype = TYPE_FLOAT;
152     } else if (PyUnicode_CheckExact(parameter)) {
153         paramtype = TYPE_UNICODE;
154     } else if (PyLong_Check(parameter)) {
155         paramtype = TYPE_LONG;
156     } else if (PyFloat_Check(parameter)) {
157         paramtype = TYPE_FLOAT;
158     } else if (PyUnicode_Check(parameter)) {
159         paramtype = TYPE_UNICODE;
160     } else if (PyObject_CheckBuffer(parameter)) {
161         paramtype = TYPE_BUFFER;
162     } else {
163         paramtype = TYPE_UNKNOWN;
164     }
165 
166     switch (paramtype) {
167         case TYPE_LONG: {
168             sqlite_int64 value = _pysqlite_long_as_int64(parameter);
169             if (value == -1 && PyErr_Occurred())
170                 rc = -1;
171             else
172                 rc = sqlite3_bind_int64(self->st, pos, value);
173             break;
174         }
175         case TYPE_FLOAT:
176             rc = sqlite3_bind_double(self->st, pos, PyFloat_AsDouble(parameter));
177             break;
178         case TYPE_UNICODE:
179             string = PyUnicode_AsUTF8AndSize(parameter, &buflen);
180             if (string == NULL)
181                 return -1;
182             if (buflen > INT_MAX) {
183                 PyErr_SetString(PyExc_OverflowError,
184                                 "string longer than INT_MAX bytes");
185                 return -1;
186             }
187             rc = sqlite3_bind_text(self->st, pos, string, (int)buflen, SQLITE_TRANSIENT);
188             break;
189         case TYPE_BUFFER: {
190             Py_buffer view;
191             if (PyObject_GetBuffer(parameter, &view, PyBUF_SIMPLE) != 0) {
192                 PyErr_SetString(PyExc_ValueError, "could not convert BLOB to buffer");
193                 return -1;
194             }
195             if (view.len > INT_MAX) {
196                 PyErr_SetString(PyExc_OverflowError,
197                                 "BLOB longer than INT_MAX bytes");
198                 PyBuffer_Release(&view);
199                 return -1;
200             }
201             rc = sqlite3_bind_blob(self->st, pos, view.buf, (int)view.len, SQLITE_TRANSIENT);
202             PyBuffer_Release(&view);
203             break;
204         }
205         case TYPE_UNKNOWN:
206             rc = -1;
207     }
208 
209 final:
210     return rc;
211 }
212 
213 /* returns 0 if the object is one of Python's internal ones that don't need to be adapted */
_need_adapt(PyObject * obj)214 static int _need_adapt(PyObject* obj)
215 {
216     if (pysqlite_BaseTypeAdapted) {
217         return 1;
218     }
219 
220     if (PyLong_CheckExact(obj) || PyFloat_CheckExact(obj)
221           || PyUnicode_CheckExact(obj) || PyByteArray_CheckExact(obj)) {
222         return 0;
223     } else {
224         return 1;
225     }
226 }
227 
pysqlite_statement_bind_parameters(pysqlite_Statement * self,PyObject * parameters)228 void pysqlite_statement_bind_parameters(pysqlite_Statement* self, PyObject* parameters)
229 {
230     PyObject* current_param;
231     PyObject* adapted;
232     const char* binding_name;
233     int i;
234     int rc;
235     int num_params_needed;
236     Py_ssize_t num_params;
237 
238     Py_BEGIN_ALLOW_THREADS
239     num_params_needed = sqlite3_bind_parameter_count(self->st);
240     Py_END_ALLOW_THREADS
241 
242     if (PyTuple_CheckExact(parameters) || PyList_CheckExact(parameters) || (!PyDict_Check(parameters) && PySequence_Check(parameters))) {
243         /* parameters passed as sequence */
244         if (PyTuple_CheckExact(parameters)) {
245             num_params = PyTuple_GET_SIZE(parameters);
246         } else if (PyList_CheckExact(parameters)) {
247             num_params = PyList_GET_SIZE(parameters);
248         } else {
249             num_params = PySequence_Size(parameters);
250             if (num_params == -1) {
251                 return;
252             }
253         }
254         if (num_params != num_params_needed) {
255             PyErr_Format(pysqlite_ProgrammingError,
256                          "Incorrect number of bindings supplied. The current "
257                          "statement uses %d, and there are %zd supplied.",
258                          num_params_needed, num_params);
259             return;
260         }
261         for (i = 0; i < num_params; i++) {
262             if (PyTuple_CheckExact(parameters)) {
263                 PyObject *item = PyTuple_GET_ITEM(parameters, i);
264                 current_param = Py_NewRef(item);
265             } else if (PyList_CheckExact(parameters)) {
266                 PyObject *item = PyList_GetItem(parameters, i);
267                 current_param = Py_XNewRef(item);
268             } else {
269                 current_param = PySequence_GetItem(parameters, i);
270             }
271             if (!current_param) {
272                 return;
273             }
274 
275             if (!_need_adapt(current_param)) {
276                 adapted = current_param;
277             } else {
278                 adapted = pysqlite_microprotocols_adapt(current_param, (PyObject*)pysqlite_PrepareProtocolType, current_param);
279                 Py_DECREF(current_param);
280                 if (!adapted) {
281                     return;
282                 }
283             }
284 
285             rc = pysqlite_statement_bind_parameter(self, i + 1, adapted);
286             Py_DECREF(adapted);
287 
288             if (rc != SQLITE_OK) {
289                 if (!PyErr_Occurred()) {
290                     PyErr_Format(pysqlite_InterfaceError, "Error binding parameter %d - probably unsupported type.", i);
291                 }
292                 return;
293             }
294         }
295     } else if (PyDict_Check(parameters)) {
296         /* parameters passed as dictionary */
297         for (i = 1; i <= num_params_needed; i++) {
298             PyObject *binding_name_obj;
299             Py_BEGIN_ALLOW_THREADS
300             binding_name = sqlite3_bind_parameter_name(self->st, i);
301             Py_END_ALLOW_THREADS
302             if (!binding_name) {
303                 PyErr_Format(pysqlite_ProgrammingError, "Binding %d has no name, but you supplied a dictionary (which has only names).", i);
304                 return;
305             }
306 
307             binding_name++; /* skip first char (the colon) */
308             binding_name_obj = PyUnicode_FromString(binding_name);
309             if (!binding_name_obj) {
310                 return;
311             }
312             if (PyDict_CheckExact(parameters)) {
313                 PyObject *item = PyDict_GetItemWithError(parameters, binding_name_obj);
314                 current_param = Py_XNewRef(item);
315             } else {
316                 current_param = PyObject_GetItem(parameters, binding_name_obj);
317             }
318             Py_DECREF(binding_name_obj);
319             if (!current_param) {
320                 if (!PyErr_Occurred() || PyErr_ExceptionMatches(PyExc_LookupError)) {
321                     PyErr_Format(pysqlite_ProgrammingError, "You did not supply a value for binding parameter :%s.", binding_name);
322                 }
323                 return;
324             }
325 
326             if (!_need_adapt(current_param)) {
327                 adapted = current_param;
328             } else {
329                 adapted = pysqlite_microprotocols_adapt(current_param, (PyObject*)pysqlite_PrepareProtocolType, current_param);
330                 Py_DECREF(current_param);
331                 if (!adapted) {
332                     return;
333                 }
334             }
335 
336             rc = pysqlite_statement_bind_parameter(self, i, adapted);
337             Py_DECREF(adapted);
338 
339             if (rc != SQLITE_OK) {
340                 if (!PyErr_Occurred()) {
341                     PyErr_Format(pysqlite_InterfaceError, "Error binding parameter :%s - probably unsupported type.", binding_name);
342                 }
343                 return;
344            }
345         }
346     } else {
347         PyErr_SetString(PyExc_ValueError, "parameters are of unsupported type");
348     }
349 }
350 
pysqlite_statement_finalize(pysqlite_Statement * self)351 int pysqlite_statement_finalize(pysqlite_Statement* self)
352 {
353     int rc;
354 
355     rc = SQLITE_OK;
356     if (self->st) {
357         Py_BEGIN_ALLOW_THREADS
358         rc = sqlite3_finalize(self->st);
359         Py_END_ALLOW_THREADS
360         self->st = NULL;
361     }
362 
363     self->in_use = 0;
364 
365     return rc;
366 }
367 
pysqlite_statement_reset(pysqlite_Statement * self)368 int pysqlite_statement_reset(pysqlite_Statement* self)
369 {
370     int rc;
371 
372     rc = SQLITE_OK;
373 
374     if (self->in_use && self->st) {
375         Py_BEGIN_ALLOW_THREADS
376         rc = sqlite3_reset(self->st);
377         Py_END_ALLOW_THREADS
378 
379         if (rc == SQLITE_OK) {
380             self->in_use = 0;
381         }
382     }
383 
384     return rc;
385 }
386 
pysqlite_statement_mark_dirty(pysqlite_Statement * self)387 void pysqlite_statement_mark_dirty(pysqlite_Statement* self)
388 {
389     self->in_use = 1;
390 }
391 
392 static void
stmt_dealloc(pysqlite_Statement * self)393 stmt_dealloc(pysqlite_Statement *self)
394 {
395     PyTypeObject *tp = Py_TYPE(self);
396     PyObject_GC_UnTrack(self);
397     if (self->in_weakreflist != NULL) {
398         PyObject_ClearWeakRefs((PyObject*)self);
399     }
400     if (self->st) {
401         Py_BEGIN_ALLOW_THREADS
402         sqlite3_finalize(self->st);
403         Py_END_ALLOW_THREADS
404         self->st = 0;
405     }
406     tp->tp_clear((PyObject *)self);
407     tp->tp_free(self);
408     Py_DECREF(tp);
409 }
410 
411 static int
stmt_clear(pysqlite_Statement * self)412 stmt_clear(pysqlite_Statement *self)
413 {
414     Py_CLEAR(self->sql);
415     return 0;
416 }
417 
418 static int
stmt_traverse(pysqlite_Statement * self,visitproc visit,void * arg)419 stmt_traverse(pysqlite_Statement *self, visitproc visit, void *arg)
420 {
421     Py_VISIT(Py_TYPE(self));
422     Py_VISIT(self->sql);
423     return 0;
424 }
425 
426 /*
427  * Checks if there is anything left in an SQL string after SQLite compiled it.
428  * This is used to check if somebody tried to execute more than one SQL command
429  * with one execute()/executemany() command, which the DB-API and we don't
430  * allow.
431  *
432  * Returns 1 if there is more left than should be. 0 if ok.
433  */
pysqlite_check_remaining_sql(const char * tail)434 static int pysqlite_check_remaining_sql(const char* tail)
435 {
436     const char* pos = tail;
437 
438     parse_remaining_sql_state state = NORMAL;
439 
440     for (;;) {
441         switch (*pos) {
442             case 0:
443                 return 0;
444             case '-':
445                 if (state == NORMAL) {
446                     state  = LINECOMMENT_1;
447                 } else if (state == LINECOMMENT_1) {
448                     state = IN_LINECOMMENT;
449                 }
450                 break;
451             case ' ':
452             case '\t':
453                 break;
454             case '\n':
455             case 13:
456                 if (state == IN_LINECOMMENT) {
457                     state = NORMAL;
458                 }
459                 break;
460             case '/':
461                 if (state == NORMAL) {
462                     state = COMMENTSTART_1;
463                 } else if (state == COMMENTEND_1) {
464                     state = NORMAL;
465                 } else if (state == COMMENTSTART_1) {
466                     return 1;
467                 }
468                 break;
469             case '*':
470                 if (state == NORMAL) {
471                     return 1;
472                 } else if (state == LINECOMMENT_1) {
473                     return 1;
474                 } else if (state == COMMENTSTART_1) {
475                     state = IN_COMMENT;
476                 } else if (state == IN_COMMENT) {
477                     state = COMMENTEND_1;
478                 }
479                 break;
480             default:
481                 if (state == COMMENTEND_1) {
482                     state = IN_COMMENT;
483                 } else if (state == IN_LINECOMMENT) {
484                 } else if (state == IN_COMMENT) {
485                 } else {
486                     return 1;
487                 }
488         }
489 
490         pos++;
491     }
492 
493     return 0;
494 }
495 
496 static PyMemberDef stmt_members[] = {
497     {"__weaklistoffset__", T_PYSSIZET, offsetof(pysqlite_Statement, in_weakreflist), READONLY},
498     {NULL},
499 };
500 static PyType_Slot stmt_slots[] = {
501     {Py_tp_members, stmt_members},
502     {Py_tp_dealloc, stmt_dealloc},
503     {Py_tp_traverse, stmt_traverse},
504     {Py_tp_clear, stmt_clear},
505     {0, NULL},
506 };
507 
508 static PyType_Spec stmt_spec = {
509     .name = MODULE_NAME ".Statement",
510     .basicsize = sizeof(pysqlite_Statement),
511     .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
512               Py_TPFLAGS_IMMUTABLETYPE | Py_TPFLAGS_DISALLOW_INSTANTIATION),
513     .slots = stmt_slots,
514 };
515 PyTypeObject *pysqlite_StatementType = NULL;
516 
517 int
pysqlite_statement_setup_types(PyObject * module)518 pysqlite_statement_setup_types(PyObject *module)
519 {
520     pysqlite_StatementType = (PyTypeObject *)PyType_FromModuleAndSpec(module, &stmt_spec, NULL);
521     if (pysqlite_StatementType == NULL) {
522         return -1;
523     }
524     return 0;
525 }
526