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