Line data Source code
1 : /* cursor.c - the cursor type
2 : *
3 : * Copyright (C) 2004-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 "cursor.h"
25 : #include "module.h"
26 : #include "util.h"
27 : #include "sqlitecompat.h"
28 :
29 : /* used to decide wether to call PyLong_FromLong or PyLong_FromLongLong */
30 : #ifndef INT32_MIN
31 : #define INT32_MIN (-2147483647 - 1)
32 : #endif
33 : #ifndef INT32_MAX
34 : #define INT32_MAX 2147483647
35 : #endif
36 :
37 : PyObject* pysqlite_cursor_iternext(pysqlite_Cursor* self);
38 :
39 : static char* errmsg_fetch_across_rollback = "Cursor needed to be reset because of commit/rollback and can no longer be fetched from.";
40 :
41 0 : static pysqlite_StatementKind detect_statement_type(const char* statement)
42 : {
43 : char buf[20];
44 : const char* src;
45 : char* dst;
46 :
47 0 : src = statement;
48 : /* skip over whitepace */
49 0 : while (*src == '\r' || *src == '\n' || *src == ' ' || *src == '\t') {
50 0 : src++;
51 : }
52 :
53 0 : if (*src == 0)
54 0 : return STATEMENT_INVALID;
55 :
56 0 : dst = buf;
57 0 : *dst = 0;
58 0 : while (Py_ISALPHA(*src) && dst - buf < sizeof(buf) - 2) {
59 0 : *dst++ = Py_TOLOWER(*src++);
60 : }
61 :
62 0 : *dst = 0;
63 :
64 0 : if (!strcmp(buf, "select")) {
65 0 : return STATEMENT_SELECT;
66 0 : } else if (!strcmp(buf, "insert")) {
67 0 : return STATEMENT_INSERT;
68 0 : } else if (!strcmp(buf, "update")) {
69 0 : return STATEMENT_UPDATE;
70 0 : } else if (!strcmp(buf, "delete")) {
71 0 : return STATEMENT_DELETE;
72 0 : } else if (!strcmp(buf, "replace")) {
73 0 : return STATEMENT_REPLACE;
74 : } else {
75 0 : return STATEMENT_OTHER;
76 : }
77 : }
78 :
79 0 : static int pysqlite_cursor_init(pysqlite_Cursor* self, PyObject* args, PyObject* kwargs)
80 : {
81 : pysqlite_Connection* connection;
82 :
83 0 : if (!PyArg_ParseTuple(args, "O!", &pysqlite_ConnectionType, &connection))
84 : {
85 0 : return -1;
86 : }
87 :
88 0 : Py_INCREF(connection);
89 0 : self->connection = connection;
90 0 : self->statement = NULL;
91 0 : self->next_row = NULL;
92 0 : self->in_weakreflist = NULL;
93 :
94 0 : self->row_cast_map = PyList_New(0);
95 0 : if (!self->row_cast_map) {
96 0 : return -1;
97 : }
98 :
99 0 : Py_INCREF(Py_None);
100 0 : self->description = Py_None;
101 :
102 0 : Py_INCREF(Py_None);
103 0 : self->lastrowid= Py_None;
104 :
105 0 : self->arraysize = 1;
106 0 : self->closed = 0;
107 0 : self->reset = 0;
108 :
109 0 : self->rowcount = -1L;
110 :
111 0 : Py_INCREF(Py_None);
112 0 : self->row_factory = Py_None;
113 :
114 0 : if (!pysqlite_check_thread(self->connection)) {
115 0 : return -1;
116 : }
117 :
118 0 : if (!pysqlite_connection_register_cursor(connection, (PyObject*)self)) {
119 0 : return -1;
120 : }
121 :
122 0 : self->initialized = 1;
123 :
124 0 : return 0;
125 : }
126 :
127 0 : static void pysqlite_cursor_dealloc(pysqlite_Cursor* self)
128 : {
129 : /* Reset the statement if the user has not closed the cursor */
130 0 : if (self->statement) {
131 0 : pysqlite_statement_reset(self->statement);
132 0 : Py_DECREF(self->statement);
133 : }
134 :
135 0 : Py_XDECREF(self->connection);
136 0 : Py_XDECREF(self->row_cast_map);
137 0 : Py_XDECREF(self->description);
138 0 : Py_XDECREF(self->lastrowid);
139 0 : Py_XDECREF(self->row_factory);
140 0 : Py_XDECREF(self->next_row);
141 :
142 0 : if (self->in_weakreflist != NULL) {
143 0 : PyObject_ClearWeakRefs((PyObject*)self);
144 : }
145 :
146 0 : Py_TYPE(self)->tp_free((PyObject*)self);
147 0 : }
148 :
149 0 : PyObject* _pysqlite_get_converter(PyObject* key)
150 : {
151 : PyObject* upcase_key;
152 : PyObject* retval;
153 : _Py_IDENTIFIER(upper);
154 :
155 0 : upcase_key = _PyObject_CallMethodId(key, &PyId_upper, "");
156 0 : if (!upcase_key) {
157 0 : return NULL;
158 : }
159 :
160 0 : retval = PyDict_GetItem(converters, upcase_key);
161 0 : Py_DECREF(upcase_key);
162 :
163 0 : return retval;
164 : }
165 :
166 0 : int pysqlite_build_row_cast_map(pysqlite_Cursor* self)
167 : {
168 : int i;
169 0 : const char* type_start = (const char*)-1;
170 : const char* pos;
171 :
172 : const char* colname;
173 : const char* decltype;
174 : PyObject* py_decltype;
175 : PyObject* converter;
176 : PyObject* key;
177 :
178 0 : if (!self->connection->detect_types) {
179 0 : return 0;
180 : }
181 :
182 0 : Py_XDECREF(self->row_cast_map);
183 0 : self->row_cast_map = PyList_New(0);
184 :
185 0 : for (i = 0; i < sqlite3_column_count(self->statement->st); i++) {
186 0 : converter = NULL;
187 :
188 0 : if (self->connection->detect_types & PARSE_COLNAMES) {
189 0 : colname = sqlite3_column_name(self->statement->st, i);
190 0 : if (colname) {
191 0 : for (pos = colname; *pos != 0; pos++) {
192 0 : if (*pos == '[') {
193 0 : type_start = pos + 1;
194 0 : } else if (*pos == ']' && type_start != (const char*)-1) {
195 0 : key = PyUnicode_FromStringAndSize(type_start, pos - type_start);
196 0 : if (!key) {
197 : /* creating a string failed, but it is too complicated
198 : * to propagate the error here, we just assume there is
199 : * no converter and proceed */
200 0 : break;
201 : }
202 :
203 0 : converter = _pysqlite_get_converter(key);
204 0 : Py_DECREF(key);
205 0 : break;
206 : }
207 : }
208 : }
209 : }
210 :
211 0 : if (!converter && self->connection->detect_types & PARSE_DECLTYPES) {
212 0 : decltype = sqlite3_column_decltype(self->statement->st, i);
213 0 : if (decltype) {
214 0 : for (pos = decltype;;pos++) {
215 : /* Converter names are split at '(' and blanks.
216 : * This allows 'INTEGER NOT NULL' to be treated as 'INTEGER' and
217 : * 'NUMBER(10)' to be treated as 'NUMBER', for example.
218 : * In other words, it will work as people expect it to work.*/
219 0 : if (*pos == ' ' || *pos == '(' || *pos == 0) {
220 0 : py_decltype = PyUnicode_FromStringAndSize(decltype, pos - decltype);
221 0 : if (!py_decltype) {
222 0 : return -1;
223 : }
224 0 : break;
225 : }
226 0 : }
227 :
228 0 : converter = _pysqlite_get_converter(py_decltype);
229 0 : Py_DECREF(py_decltype);
230 : }
231 : }
232 :
233 0 : if (!converter) {
234 0 : converter = Py_None;
235 : }
236 :
237 0 : if (PyList_Append(self->row_cast_map, converter) != 0) {
238 0 : if (converter != Py_None) {
239 0 : Py_DECREF(converter);
240 : }
241 0 : Py_XDECREF(self->row_cast_map);
242 0 : self->row_cast_map = NULL;
243 :
244 0 : return -1;
245 : }
246 : }
247 :
248 0 : return 0;
249 : }
250 :
251 0 : PyObject* _pysqlite_build_column_name(const char* colname)
252 : {
253 : const char* pos;
254 :
255 0 : if (!colname) {
256 0 : Py_INCREF(Py_None);
257 0 : return Py_None;
258 : }
259 :
260 0 : for (pos = colname;; pos++) {
261 0 : if (*pos == 0 || *pos == '[') {
262 0 : if ((*pos == '[') && (pos > colname) && (*(pos-1) == ' ')) {
263 0 : pos--;
264 : }
265 0 : return PyUnicode_FromStringAndSize(colname, pos - colname);
266 : }
267 0 : }
268 : }
269 :
270 : /*
271 : * Returns a row from the currently active SQLite statement
272 : *
273 : * Precondidition:
274 : * - sqlite3_step() has been called before and it returned SQLITE_ROW.
275 : */
276 0 : PyObject* _pysqlite_fetch_one_row(pysqlite_Cursor* self)
277 : {
278 : int i, numcols;
279 : PyObject* row;
280 0 : PyObject* item = NULL;
281 : int coltype;
282 : PY_LONG_LONG intval;
283 : PyObject* converter;
284 : PyObject* converted;
285 : Py_ssize_t nbytes;
286 : PyObject* buffer;
287 : const char* val_str;
288 : char buf[200];
289 : const char* colname;
290 : PyObject* buf_bytes;
291 : PyObject* error_obj;
292 :
293 0 : if (self->reset) {
294 0 : PyErr_SetString(pysqlite_InterfaceError, errmsg_fetch_across_rollback);
295 0 : return NULL;
296 : }
297 :
298 0 : Py_BEGIN_ALLOW_THREADS
299 0 : numcols = sqlite3_data_count(self->statement->st);
300 0 : Py_END_ALLOW_THREADS
301 :
302 0 : row = PyTuple_New(numcols);
303 0 : if (!row) {
304 0 : return NULL;
305 : }
306 :
307 0 : for (i = 0; i < numcols; i++) {
308 0 : if (self->connection->detect_types) {
309 0 : converter = PyList_GetItem(self->row_cast_map, i);
310 0 : if (!converter) {
311 0 : converter = Py_None;
312 : }
313 : } else {
314 0 : converter = Py_None;
315 : }
316 :
317 0 : if (converter != Py_None) {
318 0 : nbytes = sqlite3_column_bytes(self->statement->st, i);
319 0 : val_str = (const char*)sqlite3_column_blob(self->statement->st, i);
320 0 : if (!val_str) {
321 0 : Py_INCREF(Py_None);
322 0 : converted = Py_None;
323 : } else {
324 0 : item = PyBytes_FromStringAndSize(val_str, nbytes);
325 0 : if (!item) {
326 0 : return NULL;
327 : }
328 0 : converted = PyObject_CallFunction(converter, "O", item);
329 0 : Py_DECREF(item);
330 0 : if (!converted) {
331 0 : break;
332 : }
333 : }
334 : } else {
335 0 : Py_BEGIN_ALLOW_THREADS
336 0 : coltype = sqlite3_column_type(self->statement->st, i);
337 0 : Py_END_ALLOW_THREADS
338 0 : if (coltype == SQLITE_NULL) {
339 0 : Py_INCREF(Py_None);
340 0 : converted = Py_None;
341 0 : } else if (coltype == SQLITE_INTEGER) {
342 0 : intval = sqlite3_column_int64(self->statement->st, i);
343 0 : if (intval < INT32_MIN || intval > INT32_MAX) {
344 0 : converted = PyLong_FromLongLong(intval);
345 : } else {
346 0 : converted = PyLong_FromLong((long)intval);
347 : }
348 0 : } else if (coltype == SQLITE_FLOAT) {
349 0 : converted = PyFloat_FromDouble(sqlite3_column_double(self->statement->st, i));
350 0 : } else if (coltype == SQLITE_TEXT) {
351 0 : val_str = (const char*)sqlite3_column_text(self->statement->st, i);
352 0 : nbytes = sqlite3_column_bytes(self->statement->st, i);
353 0 : if (self->connection->text_factory == (PyObject*)&PyUnicode_Type) {
354 0 : converted = PyUnicode_FromStringAndSize(val_str, nbytes);
355 0 : if (!converted) {
356 0 : colname = sqlite3_column_name(self->statement->st, i);
357 0 : if (!colname) {
358 0 : colname = "<unknown column name>";
359 : }
360 0 : PyOS_snprintf(buf, sizeof(buf) - 1, "Could not decode to UTF-8 column '%s' with text '%s'",
361 : colname , val_str);
362 0 : buf_bytes = PyByteArray_FromStringAndSize(buf, strlen(buf));
363 0 : if (!buf_bytes) {
364 0 : PyErr_SetString(pysqlite_OperationalError, "Could not decode to UTF-8");
365 : } else {
366 0 : error_obj = PyUnicode_FromEncodedObject(buf_bytes, "ascii", "replace");
367 0 : if (!error_obj) {
368 0 : PyErr_SetString(pysqlite_OperationalError, "Could not decode to UTF-8");
369 : } else {
370 0 : PyErr_SetObject(pysqlite_OperationalError, error_obj);
371 0 : Py_DECREF(error_obj);
372 : }
373 0 : Py_DECREF(buf_bytes);
374 : }
375 : }
376 0 : } else if (self->connection->text_factory == (PyObject*)&PyBytes_Type) {
377 0 : converted = PyBytes_FromStringAndSize(val_str, nbytes);
378 0 : } else if (self->connection->text_factory == (PyObject*)&PyByteArray_Type) {
379 0 : converted = PyByteArray_FromStringAndSize(val_str, nbytes);
380 : } else {
381 0 : converted = PyObject_CallFunction(self->connection->text_factory, "y#", val_str, nbytes);
382 : }
383 : } else {
384 : /* coltype == SQLITE_BLOB */
385 0 : nbytes = sqlite3_column_bytes(self->statement->st, i);
386 0 : buffer = PyBytes_FromStringAndSize(
387 0 : sqlite3_column_blob(self->statement->st, i), nbytes);
388 0 : if (!buffer) {
389 0 : break;
390 : }
391 0 : converted = buffer;
392 : }
393 : }
394 :
395 0 : if (converted) {
396 0 : PyTuple_SetItem(row, i, converted);
397 : } else {
398 0 : Py_INCREF(Py_None);
399 0 : PyTuple_SetItem(row, i, Py_None);
400 : }
401 : }
402 :
403 0 : if (PyErr_Occurred()) {
404 0 : Py_DECREF(row);
405 0 : row = NULL;
406 : }
407 :
408 0 : return row;
409 : }
410 :
411 : /*
412 : * Checks if a cursor object is usable.
413 : *
414 : * 0 => error; 1 => ok
415 : */
416 0 : static int check_cursor(pysqlite_Cursor* cur)
417 : {
418 0 : if (!cur->initialized) {
419 0 : PyErr_SetString(pysqlite_ProgrammingError, "Base Cursor.__init__ not called.");
420 0 : return 0;
421 : }
422 :
423 0 : if (cur->closed) {
424 0 : PyErr_SetString(pysqlite_ProgrammingError, "Cannot operate on a closed cursor.");
425 0 : return 0;
426 : }
427 :
428 0 : if (cur->locked) {
429 0 : PyErr_SetString(pysqlite_ProgrammingError, "Recursive use of cursors not allowed.");
430 0 : return 0;
431 : }
432 :
433 0 : return pysqlite_check_thread(cur->connection) && pysqlite_check_connection(cur->connection);
434 : }
435 :
436 0 : PyObject* _pysqlite_query_execute(pysqlite_Cursor* self, int multiple, PyObject* args)
437 : {
438 : PyObject* operation;
439 : const char* operation_cstr;
440 : Py_ssize_t operation_len;
441 0 : PyObject* parameters_list = NULL;
442 0 : PyObject* parameters_iter = NULL;
443 0 : PyObject* parameters = NULL;
444 : int i;
445 : int rc;
446 : PyObject* func_args;
447 : PyObject* result;
448 : int numcols;
449 : PY_LONG_LONG lastrowid;
450 : int statement_type;
451 : PyObject* descriptor;
452 0 : PyObject* second_argument = NULL;
453 :
454 0 : if (!check_cursor(self)) {
455 0 : goto error;
456 : }
457 :
458 0 : self->locked = 1;
459 0 : self->reset = 0;
460 :
461 0 : Py_XDECREF(self->next_row);
462 0 : self->next_row = NULL;
463 :
464 0 : if (multiple) {
465 : /* executemany() */
466 0 : if (!PyArg_ParseTuple(args, "OO", &operation, &second_argument)) {
467 0 : goto error;
468 : }
469 :
470 0 : if (!PyUnicode_Check(operation)) {
471 0 : PyErr_SetString(PyExc_ValueError, "operation parameter must be str");
472 0 : goto error;
473 : }
474 :
475 0 : if (PyIter_Check(second_argument)) {
476 : /* iterator */
477 0 : Py_INCREF(second_argument);
478 0 : parameters_iter = second_argument;
479 : } else {
480 : /* sequence */
481 0 : parameters_iter = PyObject_GetIter(second_argument);
482 0 : if (!parameters_iter) {
483 0 : goto error;
484 : }
485 : }
486 : } else {
487 : /* execute() */
488 0 : if (!PyArg_ParseTuple(args, "O|O", &operation, &second_argument)) {
489 0 : goto error;
490 : }
491 :
492 0 : if (!PyUnicode_Check(operation)) {
493 0 : PyErr_SetString(PyExc_ValueError, "operation parameter must be str");
494 0 : goto error;
495 : }
496 :
497 0 : parameters_list = PyList_New(0);
498 0 : if (!parameters_list) {
499 0 : goto error;
500 : }
501 :
502 0 : if (second_argument == NULL) {
503 0 : second_argument = PyTuple_New(0);
504 0 : if (!second_argument) {
505 0 : goto error;
506 : }
507 : } else {
508 0 : Py_INCREF(second_argument);
509 : }
510 0 : if (PyList_Append(parameters_list, second_argument) != 0) {
511 0 : Py_DECREF(second_argument);
512 0 : goto error;
513 : }
514 0 : Py_DECREF(second_argument);
515 :
516 0 : parameters_iter = PyObject_GetIter(parameters_list);
517 0 : if (!parameters_iter) {
518 0 : goto error;
519 : }
520 : }
521 :
522 0 : if (self->statement != NULL) {
523 : /* There is an active statement */
524 0 : pysqlite_statement_reset(self->statement);
525 : }
526 :
527 0 : operation_cstr = _PyUnicode_AsStringAndSize(operation, &operation_len);
528 0 : if (operation_cstr == NULL)
529 0 : goto error;
530 :
531 : /* reset description and rowcount */
532 0 : Py_DECREF(self->description);
533 0 : Py_INCREF(Py_None);
534 0 : self->description = Py_None;
535 0 : self->rowcount = -1L;
536 :
537 0 : func_args = PyTuple_New(1);
538 0 : if (!func_args) {
539 0 : goto error;
540 : }
541 0 : Py_INCREF(operation);
542 0 : if (PyTuple_SetItem(func_args, 0, operation) != 0) {
543 0 : goto error;
544 : }
545 :
546 0 : if (self->statement) {
547 0 : (void)pysqlite_statement_reset(self->statement);
548 0 : Py_DECREF(self->statement);
549 : }
550 :
551 0 : self->statement = (pysqlite_Statement*)pysqlite_cache_get(self->connection->statement_cache, func_args);
552 0 : Py_DECREF(func_args);
553 :
554 0 : if (!self->statement) {
555 0 : goto error;
556 : }
557 :
558 0 : if (self->statement->in_use) {
559 0 : Py_DECREF(self->statement);
560 0 : self->statement = PyObject_New(pysqlite_Statement, &pysqlite_StatementType);
561 0 : if (!self->statement) {
562 0 : goto error;
563 : }
564 0 : rc = pysqlite_statement_create(self->statement, self->connection, operation);
565 0 : if (rc != SQLITE_OK) {
566 0 : Py_CLEAR(self->statement);
567 0 : goto error;
568 : }
569 : }
570 :
571 0 : pysqlite_statement_reset(self->statement);
572 0 : pysqlite_statement_mark_dirty(self->statement);
573 :
574 0 : statement_type = detect_statement_type(operation_cstr);
575 0 : if (self->connection->begin_statement) {
576 0 : switch (statement_type) {
577 : case STATEMENT_UPDATE:
578 : case STATEMENT_DELETE:
579 : case STATEMENT_INSERT:
580 : case STATEMENT_REPLACE:
581 0 : if (!self->connection->inTransaction) {
582 0 : result = _pysqlite_connection_begin(self->connection);
583 0 : if (!result) {
584 0 : goto error;
585 : }
586 0 : Py_DECREF(result);
587 : }
588 0 : break;
589 : case STATEMENT_OTHER:
590 : /* it's a DDL statement or something similar
591 : - we better COMMIT first so it works for all cases */
592 0 : if (self->connection->inTransaction) {
593 0 : result = pysqlite_connection_commit(self->connection, NULL);
594 0 : if (!result) {
595 0 : goto error;
596 : }
597 0 : Py_DECREF(result);
598 : }
599 0 : break;
600 : case STATEMENT_SELECT:
601 0 : if (multiple) {
602 0 : PyErr_SetString(pysqlite_ProgrammingError,
603 : "You cannot execute SELECT statements in executemany().");
604 0 : goto error;
605 : }
606 0 : break;
607 : }
608 : }
609 :
610 :
611 : while (1) {
612 0 : parameters = PyIter_Next(parameters_iter);
613 0 : if (!parameters) {
614 0 : break;
615 : }
616 :
617 0 : pysqlite_statement_mark_dirty(self->statement);
618 :
619 0 : pysqlite_statement_bind_parameters(self->statement, parameters);
620 0 : if (PyErr_Occurred()) {
621 0 : goto error;
622 : }
623 :
624 : /* Keep trying the SQL statement until the schema stops changing. */
625 : while (1) {
626 : /* Actually execute the SQL statement. */
627 0 : rc = pysqlite_step(self->statement->st, self->connection);
628 0 : if (rc == SQLITE_DONE || rc == SQLITE_ROW) {
629 : /* If it worked, let's get out of the loop */
630 : break;
631 : }
632 : /* Something went wrong. Re-set the statement and try again. */
633 0 : rc = pysqlite_statement_reset(self->statement);
634 0 : if (rc == SQLITE_SCHEMA) {
635 : /* If this was a result of the schema changing, let's try
636 : again. */
637 0 : rc = pysqlite_statement_recompile(self->statement, parameters);
638 0 : if (rc == SQLITE_OK) {
639 0 : continue;
640 : } else {
641 : /* If the database gave us an error, promote it to Python. */
642 0 : (void)pysqlite_statement_reset(self->statement);
643 0 : _pysqlite_seterror(self->connection->db, NULL);
644 0 : goto error;
645 : }
646 : } else {
647 0 : if (PyErr_Occurred()) {
648 : /* there was an error that occurred in a user-defined callback */
649 0 : if (_enable_callback_tracebacks) {
650 0 : PyErr_Print();
651 : } else {
652 0 : PyErr_Clear();
653 : }
654 : }
655 0 : (void)pysqlite_statement_reset(self->statement);
656 0 : _pysqlite_seterror(self->connection->db, NULL);
657 0 : goto error;
658 : }
659 0 : }
660 :
661 0 : if (pysqlite_build_row_cast_map(self) != 0) {
662 0 : PyErr_SetString(pysqlite_OperationalError, "Error while building row_cast_map");
663 0 : goto error;
664 : }
665 :
666 0 : if (rc == SQLITE_ROW || (rc == SQLITE_DONE && statement_type == STATEMENT_SELECT)) {
667 0 : if (self->description == Py_None) {
668 0 : Py_BEGIN_ALLOW_THREADS
669 0 : numcols = sqlite3_column_count(self->statement->st);
670 0 : Py_END_ALLOW_THREADS
671 :
672 0 : Py_DECREF(self->description);
673 0 : self->description = PyTuple_New(numcols);
674 0 : if (!self->description) {
675 0 : goto error;
676 : }
677 0 : for (i = 0; i < numcols; i++) {
678 0 : descriptor = PyTuple_New(7);
679 0 : if (!descriptor) {
680 0 : goto error;
681 : }
682 0 : PyTuple_SetItem(descriptor, 0, _pysqlite_build_column_name(sqlite3_column_name(self->statement->st, i)));
683 0 : Py_INCREF(Py_None); PyTuple_SetItem(descriptor, 1, Py_None);
684 0 : Py_INCREF(Py_None); PyTuple_SetItem(descriptor, 2, Py_None);
685 0 : Py_INCREF(Py_None); PyTuple_SetItem(descriptor, 3, Py_None);
686 0 : Py_INCREF(Py_None); PyTuple_SetItem(descriptor, 4, Py_None);
687 0 : Py_INCREF(Py_None); PyTuple_SetItem(descriptor, 5, Py_None);
688 0 : Py_INCREF(Py_None); PyTuple_SetItem(descriptor, 6, Py_None);
689 0 : PyTuple_SetItem(self->description, i, descriptor);
690 : }
691 : }
692 : }
693 :
694 0 : if (rc == SQLITE_ROW) {
695 0 : if (multiple) {
696 0 : PyErr_SetString(pysqlite_ProgrammingError, "executemany() can only execute DML statements.");
697 0 : goto error;
698 : }
699 :
700 0 : self->next_row = _pysqlite_fetch_one_row(self);
701 0 : } else if (rc == SQLITE_DONE && !multiple) {
702 0 : pysqlite_statement_reset(self->statement);
703 0 : Py_CLEAR(self->statement);
704 : }
705 :
706 0 : switch (statement_type) {
707 : case STATEMENT_UPDATE:
708 : case STATEMENT_DELETE:
709 : case STATEMENT_INSERT:
710 : case STATEMENT_REPLACE:
711 0 : if (self->rowcount == -1L) {
712 0 : self->rowcount = 0L;
713 : }
714 0 : self->rowcount += (long)sqlite3_changes(self->connection->db);
715 : }
716 :
717 0 : Py_DECREF(self->lastrowid);
718 0 : if (!multiple && statement_type == STATEMENT_INSERT) {
719 0 : Py_BEGIN_ALLOW_THREADS
720 0 : lastrowid = sqlite3_last_insert_rowid(self->connection->db);
721 0 : Py_END_ALLOW_THREADS
722 0 : self->lastrowid = PyLong_FromLong((long)lastrowid);
723 : } else {
724 0 : Py_INCREF(Py_None);
725 0 : self->lastrowid = Py_None;
726 : }
727 :
728 0 : if (multiple) {
729 0 : pysqlite_statement_reset(self->statement);
730 : }
731 0 : Py_XDECREF(parameters);
732 0 : }
733 :
734 : error:
735 : /* just to be sure (implicit ROLLBACKs with ON CONFLICT ROLLBACK/OR
736 : * ROLLBACK could have happened */
737 : #ifdef SQLITE_VERSION_NUMBER
738 : #if SQLITE_VERSION_NUMBER >= 3002002
739 0 : if (self->connection && self->connection->db)
740 0 : self->connection->inTransaction = !sqlite3_get_autocommit(self->connection->db);
741 : #endif
742 : #endif
743 :
744 0 : Py_XDECREF(parameters);
745 0 : Py_XDECREF(parameters_iter);
746 0 : Py_XDECREF(parameters_list);
747 :
748 0 : self->locked = 0;
749 :
750 0 : if (PyErr_Occurred()) {
751 0 : self->rowcount = -1L;
752 0 : return NULL;
753 : } else {
754 0 : Py_INCREF(self);
755 0 : return (PyObject*)self;
756 : }
757 : }
758 :
759 0 : PyObject* pysqlite_cursor_execute(pysqlite_Cursor* self, PyObject* args)
760 : {
761 0 : return _pysqlite_query_execute(self, 0, args);
762 : }
763 :
764 0 : PyObject* pysqlite_cursor_executemany(pysqlite_Cursor* self, PyObject* args)
765 : {
766 0 : return _pysqlite_query_execute(self, 1, args);
767 : }
768 :
769 0 : PyObject* pysqlite_cursor_executescript(pysqlite_Cursor* self, PyObject* args)
770 : {
771 : PyObject* script_obj;
772 0 : PyObject* script_str = NULL;
773 : const char* script_cstr;
774 : sqlite3_stmt* statement;
775 : int rc;
776 : PyObject* result;
777 :
778 0 : if (!PyArg_ParseTuple(args, "O", &script_obj)) {
779 0 : return NULL;
780 : }
781 :
782 0 : if (!check_cursor(self)) {
783 0 : return NULL;
784 : }
785 :
786 0 : self->reset = 0;
787 :
788 0 : if (PyUnicode_Check(script_obj)) {
789 0 : script_cstr = _PyUnicode_AsString(script_obj);
790 0 : if (!script_cstr) {
791 0 : return NULL;
792 : }
793 : } else {
794 0 : PyErr_SetString(PyExc_ValueError, "script argument must be unicode.");
795 0 : return NULL;
796 : }
797 :
798 : /* commit first */
799 0 : result = pysqlite_connection_commit(self->connection, NULL);
800 0 : if (!result) {
801 0 : goto error;
802 : }
803 0 : Py_DECREF(result);
804 :
805 : while (1) {
806 0 : Py_BEGIN_ALLOW_THREADS
807 0 : rc = sqlite3_prepare(self->connection->db,
808 : script_cstr,
809 : -1,
810 : &statement,
811 : &script_cstr);
812 0 : Py_END_ALLOW_THREADS
813 0 : if (rc != SQLITE_OK) {
814 0 : _pysqlite_seterror(self->connection->db, NULL);
815 0 : goto error;
816 : }
817 :
818 : /* execute statement, and ignore results of SELECT statements */
819 0 : rc = SQLITE_ROW;
820 0 : while (rc == SQLITE_ROW) {
821 0 : rc = pysqlite_step(statement, self->connection);
822 : /* TODO: we probably need more error handling here */
823 : }
824 :
825 0 : if (rc != SQLITE_DONE) {
826 0 : (void)sqlite3_finalize(statement);
827 0 : _pysqlite_seterror(self->connection->db, NULL);
828 0 : goto error;
829 : }
830 :
831 0 : rc = sqlite3_finalize(statement);
832 0 : if (rc != SQLITE_OK) {
833 0 : _pysqlite_seterror(self->connection->db, NULL);
834 0 : goto error;
835 : }
836 :
837 0 : if (*script_cstr == (char)0) {
838 0 : break;
839 : }
840 0 : }
841 :
842 : error:
843 0 : Py_XDECREF(script_str);
844 :
845 0 : if (PyErr_Occurred()) {
846 0 : return NULL;
847 : } else {
848 0 : Py_INCREF(self);
849 0 : return (PyObject*)self;
850 : }
851 : }
852 :
853 0 : PyObject* pysqlite_cursor_getiter(pysqlite_Cursor *self)
854 : {
855 0 : Py_INCREF(self);
856 0 : return (PyObject*)self;
857 : }
858 :
859 0 : PyObject* pysqlite_cursor_iternext(pysqlite_Cursor *self)
860 : {
861 : PyObject* next_row_tuple;
862 : PyObject* next_row;
863 : int rc;
864 :
865 0 : if (!check_cursor(self)) {
866 0 : return NULL;
867 : }
868 :
869 0 : if (self->reset) {
870 0 : PyErr_SetString(pysqlite_InterfaceError, errmsg_fetch_across_rollback);
871 0 : return NULL;
872 : }
873 :
874 0 : if (!self->next_row) {
875 0 : if (self->statement) {
876 0 : (void)pysqlite_statement_reset(self->statement);
877 0 : Py_DECREF(self->statement);
878 0 : self->statement = NULL;
879 : }
880 0 : return NULL;
881 : }
882 :
883 0 : next_row_tuple = self->next_row;
884 0 : self->next_row = NULL;
885 :
886 0 : if (self->row_factory != Py_None) {
887 0 : next_row = PyObject_CallFunction(self->row_factory, "OO", self, next_row_tuple);
888 0 : Py_DECREF(next_row_tuple);
889 : } else {
890 0 : next_row = next_row_tuple;
891 : }
892 :
893 0 : if (self->statement) {
894 0 : rc = pysqlite_step(self->statement->st, self->connection);
895 0 : if (rc != SQLITE_DONE && rc != SQLITE_ROW) {
896 0 : (void)pysqlite_statement_reset(self->statement);
897 0 : Py_DECREF(next_row);
898 0 : _pysqlite_seterror(self->connection->db, NULL);
899 0 : return NULL;
900 : }
901 :
902 0 : if (rc == SQLITE_ROW) {
903 0 : self->next_row = _pysqlite_fetch_one_row(self);
904 : }
905 : }
906 :
907 0 : return next_row;
908 : }
909 :
910 0 : PyObject* pysqlite_cursor_fetchone(pysqlite_Cursor* self, PyObject* args)
911 : {
912 : PyObject* row;
913 :
914 0 : row = pysqlite_cursor_iternext(self);
915 0 : if (!row && !PyErr_Occurred()) {
916 0 : Py_INCREF(Py_None);
917 0 : return Py_None;
918 : }
919 :
920 0 : return row;
921 : }
922 :
923 0 : PyObject* pysqlite_cursor_fetchmany(pysqlite_Cursor* self, PyObject* args, PyObject* kwargs)
924 : {
925 : static char *kwlist[] = {"size", NULL, NULL};
926 :
927 : PyObject* row;
928 : PyObject* list;
929 0 : int maxrows = self->arraysize;
930 0 : int counter = 0;
931 :
932 0 : if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|i:fetchmany", kwlist, &maxrows)) {
933 0 : return NULL;
934 : }
935 :
936 0 : list = PyList_New(0);
937 0 : if (!list) {
938 0 : return NULL;
939 : }
940 :
941 : /* just make sure we enter the loop */
942 0 : row = Py_None;
943 :
944 0 : while (row) {
945 0 : row = pysqlite_cursor_iternext(self);
946 0 : if (row) {
947 0 : PyList_Append(list, row);
948 0 : Py_DECREF(row);
949 : } else {
950 0 : break;
951 : }
952 :
953 0 : if (++counter == maxrows) {
954 0 : break;
955 : }
956 : }
957 :
958 0 : if (PyErr_Occurred()) {
959 0 : Py_DECREF(list);
960 0 : return NULL;
961 : } else {
962 0 : return list;
963 : }
964 : }
965 :
966 0 : PyObject* pysqlite_cursor_fetchall(pysqlite_Cursor* self, PyObject* args)
967 : {
968 : PyObject* row;
969 : PyObject* list;
970 :
971 0 : list = PyList_New(0);
972 0 : if (!list) {
973 0 : return NULL;
974 : }
975 :
976 : /* just make sure we enter the loop */
977 0 : row = (PyObject*)Py_None;
978 :
979 0 : while (row) {
980 0 : row = pysqlite_cursor_iternext(self);
981 0 : if (row) {
982 0 : PyList_Append(list, row);
983 0 : Py_DECREF(row);
984 : }
985 : }
986 :
987 0 : if (PyErr_Occurred()) {
988 0 : Py_DECREF(list);
989 0 : return NULL;
990 : } else {
991 0 : return list;
992 : }
993 : }
994 :
995 0 : PyObject* pysqlite_noop(pysqlite_Connection* self, PyObject* args)
996 : {
997 : /* don't care, return None */
998 0 : Py_INCREF(Py_None);
999 0 : return Py_None;
1000 : }
1001 :
1002 0 : PyObject* pysqlite_cursor_close(pysqlite_Cursor* self, PyObject* args)
1003 : {
1004 0 : if (!pysqlite_check_thread(self->connection) || !pysqlite_check_connection(self->connection)) {
1005 0 : return NULL;
1006 : }
1007 :
1008 0 : if (self->statement) {
1009 0 : (void)pysqlite_statement_reset(self->statement);
1010 0 : Py_CLEAR(self->statement);
1011 : }
1012 :
1013 0 : self->closed = 1;
1014 :
1015 0 : Py_INCREF(Py_None);
1016 0 : return Py_None;
1017 : }
1018 :
1019 : static PyMethodDef cursor_methods[] = {
1020 : {"execute", (PyCFunction)pysqlite_cursor_execute, METH_VARARGS,
1021 : PyDoc_STR("Executes a SQL statement.")},
1022 : {"executemany", (PyCFunction)pysqlite_cursor_executemany, METH_VARARGS,
1023 : PyDoc_STR("Repeatedly executes a SQL statement.")},
1024 : {"executescript", (PyCFunction)pysqlite_cursor_executescript, METH_VARARGS,
1025 : PyDoc_STR("Executes a multiple SQL statements at once. Non-standard.")},
1026 : {"fetchone", (PyCFunction)pysqlite_cursor_fetchone, METH_NOARGS,
1027 : PyDoc_STR("Fetches one row from the resultset.")},
1028 : {"fetchmany", (PyCFunction)pysqlite_cursor_fetchmany, METH_VARARGS|METH_KEYWORDS,
1029 : PyDoc_STR("Fetches several rows from the resultset.")},
1030 : {"fetchall", (PyCFunction)pysqlite_cursor_fetchall, METH_NOARGS,
1031 : PyDoc_STR("Fetches all rows from the resultset.")},
1032 : {"close", (PyCFunction)pysqlite_cursor_close, METH_NOARGS,
1033 : PyDoc_STR("Closes the cursor.")},
1034 : {"setinputsizes", (PyCFunction)pysqlite_noop, METH_VARARGS,
1035 : PyDoc_STR("Required by DB-API. Does nothing in pysqlite.")},
1036 : {"setoutputsize", (PyCFunction)pysqlite_noop, METH_VARARGS,
1037 : PyDoc_STR("Required by DB-API. Does nothing in pysqlite.")},
1038 : {NULL, NULL}
1039 : };
1040 :
1041 : static struct PyMemberDef cursor_members[] =
1042 : {
1043 : {"connection", T_OBJECT, offsetof(pysqlite_Cursor, connection), READONLY},
1044 : {"description", T_OBJECT, offsetof(pysqlite_Cursor, description), READONLY},
1045 : {"arraysize", T_INT, offsetof(pysqlite_Cursor, arraysize), 0},
1046 : {"lastrowid", T_OBJECT, offsetof(pysqlite_Cursor, lastrowid), READONLY},
1047 : {"rowcount", T_LONG, offsetof(pysqlite_Cursor, rowcount), READONLY},
1048 : {"row_factory", T_OBJECT, offsetof(pysqlite_Cursor, row_factory), 0},
1049 : {NULL}
1050 : };
1051 :
1052 : static char cursor_doc[] =
1053 : PyDoc_STR("SQLite database cursor class.");
1054 :
1055 : PyTypeObject pysqlite_CursorType = {
1056 : PyVarObject_HEAD_INIT(NULL, 0)
1057 : MODULE_NAME ".Cursor", /* tp_name */
1058 : sizeof(pysqlite_Cursor), /* tp_basicsize */
1059 : 0, /* tp_itemsize */
1060 : (destructor)pysqlite_cursor_dealloc, /* tp_dealloc */
1061 : 0, /* tp_print */
1062 : 0, /* tp_getattr */
1063 : 0, /* tp_setattr */
1064 : 0, /* tp_reserved */
1065 : 0, /* tp_repr */
1066 : 0, /* tp_as_number */
1067 : 0, /* tp_as_sequence */
1068 : 0, /* tp_as_mapping */
1069 : 0, /* tp_hash */
1070 : 0, /* tp_call */
1071 : 0, /* tp_str */
1072 : 0, /* tp_getattro */
1073 : 0, /* tp_setattro */
1074 : 0, /* tp_as_buffer */
1075 : Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE, /* tp_flags */
1076 : cursor_doc, /* tp_doc */
1077 : 0, /* tp_traverse */
1078 : 0, /* tp_clear */
1079 : 0, /* tp_richcompare */
1080 : offsetof(pysqlite_Cursor, in_weakreflist), /* tp_weaklistoffset */
1081 : (getiterfunc)pysqlite_cursor_getiter, /* tp_iter */
1082 : (iternextfunc)pysqlite_cursor_iternext, /* tp_iternext */
1083 : cursor_methods, /* tp_methods */
1084 : cursor_members, /* tp_members */
1085 : 0, /* tp_getset */
1086 : 0, /* tp_base */
1087 : 0, /* tp_dict */
1088 : 0, /* tp_descr_get */
1089 : 0, /* tp_descr_set */
1090 : 0, /* tp_dictoffset */
1091 : (initproc)pysqlite_cursor_init, /* tp_init */
1092 : 0, /* tp_alloc */
1093 : 0, /* tp_new */
1094 : 0 /* tp_free */
1095 : };
1096 :
1097 0 : extern int pysqlite_cursor_setup_types(void)
1098 : {
1099 0 : pysqlite_CursorType.tp_new = PyType_GenericNew;
1100 0 : return PyType_Ready(&pysqlite_CursorType);
1101 : }
|