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