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