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