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