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