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(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_CallFunction(converter, "O", 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 = _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 && 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, "OO", &operation, &second_argument)) {
397 goto error;
398 }
399
400 if (!PyUnicode_Check(operation)) {
401 PyErr_SetString(PyExc_ValueError, "operation parameter must be str");
402 goto error;
403 }
404
405 if (PyIter_Check(second_argument)) {
406 /* iterator */
407 Py_INCREF(second_argument);
408 parameters_iter = second_argument;
409 } else {
410 /* sequence */
411 parameters_iter = PyObject_GetIter(second_argument);
412 if (!parameters_iter) {
413 goto error;
414 }
415 }
416 } else {
417 /* execute() */
418 if (!PyArg_ParseTuple(args, "O|O", &operation, &second_argument)) {
419 goto error;
420 }
421
422 if (!PyUnicode_Check(operation)) {
423 PyErr_SetString(PyExc_ValueError, "operation parameter must be str");
424 goto error;
425 }
426
427 parameters_list = PyList_New(0);
428 if (!parameters_list) {
429 goto error;
430 }
431
432 if (second_argument == NULL) {
433 second_argument = PyTuple_New(0);
434 if (!second_argument) {
435 goto error;
436 }
437 } else {
438 Py_INCREF(second_argument);
439 }
440 if (PyList_Append(parameters_list, second_argument) != 0) {
441 Py_DECREF(second_argument);
442 goto error;
443 }
444 Py_DECREF(second_argument);
445
446 parameters_iter = PyObject_GetIter(parameters_list);
447 if (!parameters_iter) {
448 goto error;
449 }
450 }
451
452 if (self->statement != NULL) {
453 /* There is an active statement */
454 pysqlite_statement_reset(self->statement);
455 }
456
457 /* reset description and rowcount */
458 Py_INCREF(Py_None);
459 Py_SETREF(self->description, Py_None);
460 self->rowcount = 0L;
461
462 func_args = PyTuple_New(1);
463 if (!func_args) {
464 goto error;
465 }
466 Py_INCREF(operation);
467 if (PyTuple_SetItem(func_args, 0, operation) != 0) {
468 goto error;
469 }
470
471 if (self->statement) {
472 (void)pysqlite_statement_reset(self->statement);
473 }
474
475 Py_XSETREF(self->statement,
476 (pysqlite_Statement *)pysqlite_cache_get(self->connection->statement_cache, func_args));
477 Py_DECREF(func_args);
478
479 if (!self->statement) {
480 goto error;
481 }
482
483 if (self->statement->in_use) {
484 Py_SETREF(self->statement,
485 PyObject_New(pysqlite_Statement, &pysqlite_StatementType));
486 if (!self->statement) {
487 goto error;
488 }
489 rc = pysqlite_statement_create(self->statement, self->connection, operation);
490 if (rc != SQLITE_OK) {
491 Py_CLEAR(self->statement);
492 goto error;
493 }
494 }
495
496 pysqlite_statement_reset(self->statement);
497 pysqlite_statement_mark_dirty(self->statement);
498
499 /* We start a transaction implicitly before a DML statement.
500 SELECT is the only exception. See #9924. */
501 if (self->connection->begin_statement && self->statement->is_dml) {
502 if (sqlite3_get_autocommit(self->connection->db)) {
503 result = _pysqlite_connection_begin(self->connection);
504 if (!result) {
505 goto error;
506 }
507 Py_DECREF(result);
508 }
509 }
510
511 while (1) {
512 parameters = PyIter_Next(parameters_iter);
513 if (!parameters) {
514 break;
515 }
516
517 pysqlite_statement_mark_dirty(self->statement);
518
519 pysqlite_statement_bind_parameters(self->statement, parameters);
520 if (PyErr_Occurred()) {
521 goto error;
522 }
523
524 rc = pysqlite_step(self->statement->st, self->connection);
525 if (rc != SQLITE_DONE && rc != SQLITE_ROW) {
526 if (PyErr_Occurred()) {
527 /* there was an error that occurred in a user-defined callback */
528 if (_pysqlite_enable_callback_tracebacks) {
529 PyErr_Print();
530 } else {
531 PyErr_Clear();
532 }
533 }
534 (void)pysqlite_statement_reset(self->statement);
535 _pysqlite_seterror(self->connection->db, NULL);
536 goto error;
537 }
538
539 if (pysqlite_build_row_cast_map(self) != 0) {
540 _PyErr_FormatFromCause(pysqlite_OperationalError, "Error while building row_cast_map");
541 goto error;
542 }
543
544 assert(rc == SQLITE_ROW || rc == SQLITE_DONE);
545 Py_BEGIN_ALLOW_THREADS
546 numcols = sqlite3_column_count(self->statement->st);
547 Py_END_ALLOW_THREADS
548 if (self->description == Py_None && numcols > 0) {
549 Py_SETREF(self->description, PyTuple_New(numcols));
550 if (!self->description) {
551 goto error;
552 }
553 for (i = 0; i < numcols; i++) {
554 descriptor = PyTuple_New(7);
555 if (!descriptor) {
556 goto error;
557 }
558 column_name = _pysqlite_build_column_name(self,
559 sqlite3_column_name(self->statement->st, i));
560 if (!column_name) {
561 Py_DECREF(descriptor);
562 goto error;
563 }
564 PyTuple_SetItem(descriptor, 0, column_name);
565 Py_INCREF(Py_None); PyTuple_SetItem(descriptor, 1, Py_None);
566 Py_INCREF(Py_None); PyTuple_SetItem(descriptor, 2, Py_None);
567 Py_INCREF(Py_None); PyTuple_SetItem(descriptor, 3, Py_None);
568 Py_INCREF(Py_None); PyTuple_SetItem(descriptor, 4, Py_None);
569 Py_INCREF(Py_None); PyTuple_SetItem(descriptor, 5, Py_None);
570 Py_INCREF(Py_None); PyTuple_SetItem(descriptor, 6, Py_None);
571 PyTuple_SetItem(self->description, i, descriptor);
572 }
573 }
574
575 if (self->statement->is_dml) {
576 self->rowcount += (long)sqlite3_changes(self->connection->db);
577 } else {
578 self->rowcount= -1L;
579 }
580
581 if (!multiple) {
582 Py_DECREF(self->lastrowid);
583 Py_BEGIN_ALLOW_THREADS
584 lastrowid = sqlite3_last_insert_rowid(self->connection->db);
585 Py_END_ALLOW_THREADS
586 self->lastrowid = _pysqlite_long_from_int64(lastrowid);
587 }
588
589 if (rc == SQLITE_ROW) {
590 if (multiple) {
591 PyErr_SetString(pysqlite_ProgrammingError, "executemany() can only execute DML statements.");
592 goto error;
593 }
594
595 self->next_row = _pysqlite_fetch_one_row(self);
596 if (self->next_row == NULL)
597 goto error;
598 } else if (rc == SQLITE_DONE && !multiple) {
599 pysqlite_statement_reset(self->statement);
600 Py_CLEAR(self->statement);
601 }
602
603 if (multiple) {
604 pysqlite_statement_reset(self->statement);
605 }
606 Py_XDECREF(parameters);
607 }
608
609 error:
610 Py_XDECREF(parameters);
611 Py_XDECREF(parameters_iter);
612 Py_XDECREF(parameters_list);
613
614 self->locked = 0;
615
616 if (PyErr_Occurred()) {
617 self->rowcount = -1L;
618 return NULL;
619 } else {
620 Py_INCREF(self);
621 return (PyObject*)self;
622 }
623 }
624
pysqlite_cursor_execute(pysqlite_Cursor * self,PyObject * args)625 PyObject* pysqlite_cursor_execute(pysqlite_Cursor* self, PyObject* args)
626 {
627 return _pysqlite_query_execute(self, 0, args);
628 }
629
pysqlite_cursor_executemany(pysqlite_Cursor * self,PyObject * args)630 PyObject* pysqlite_cursor_executemany(pysqlite_Cursor* self, PyObject* args)
631 {
632 return _pysqlite_query_execute(self, 1, args);
633 }
634
635 static PyObject *
pysqlite_cursor_executescript(pysqlite_Cursor * self,PyObject * args)636 pysqlite_cursor_executescript(pysqlite_Cursor* self, PyObject* args)
637 {
638 PyObject* script_obj;
639 PyObject* script_str = NULL;
640 const char* script_cstr;
641 sqlite3_stmt* statement;
642 int rc;
643 PyObject* result;
644
645 if (!PyArg_ParseTuple(args, "O", &script_obj)) {
646 return NULL;
647 }
648
649 if (!check_cursor(self)) {
650 return NULL;
651 }
652
653 self->reset = 0;
654
655 if (PyUnicode_Check(script_obj)) {
656 script_cstr = PyUnicode_AsUTF8(script_obj);
657 if (!script_cstr) {
658 return NULL;
659 }
660 } else {
661 PyErr_SetString(PyExc_ValueError, "script argument must be unicode.");
662 return NULL;
663 }
664
665 /* commit first */
666 result = pysqlite_connection_commit(self->connection, NULL);
667 if (!result) {
668 goto error;
669 }
670 Py_DECREF(result);
671
672 while (1) {
673 Py_BEGIN_ALLOW_THREADS
674 rc = sqlite3_prepare_v2(self->connection->db,
675 script_cstr,
676 -1,
677 &statement,
678 &script_cstr);
679 Py_END_ALLOW_THREADS
680 if (rc != SQLITE_OK) {
681 _pysqlite_seterror(self->connection->db, NULL);
682 goto error;
683 }
684
685 /* execute statement, and ignore results of SELECT statements */
686 rc = SQLITE_ROW;
687 while (rc == SQLITE_ROW) {
688 rc = pysqlite_step(statement, self->connection);
689 if (PyErr_Occurred()) {
690 (void)sqlite3_finalize(statement);
691 goto error;
692 }
693 }
694
695 if (rc != SQLITE_DONE) {
696 (void)sqlite3_finalize(statement);
697 _pysqlite_seterror(self->connection->db, NULL);
698 goto error;
699 }
700
701 rc = sqlite3_finalize(statement);
702 if (rc != SQLITE_OK) {
703 _pysqlite_seterror(self->connection->db, NULL);
704 goto error;
705 }
706
707 if (*script_cstr == (char)0) {
708 break;
709 }
710 }
711
712 error:
713 Py_XDECREF(script_str);
714
715 if (PyErr_Occurred()) {
716 return NULL;
717 } else {
718 Py_INCREF(self);
719 return (PyObject*)self;
720 }
721 }
722
pysqlite_cursor_iternext(pysqlite_Cursor * self)723 PyObject* pysqlite_cursor_iternext(pysqlite_Cursor *self)
724 {
725 PyObject* next_row_tuple;
726 PyObject* next_row;
727 int rc;
728
729 if (!check_cursor(self)) {
730 return NULL;
731 }
732
733 if (self->reset) {
734 PyErr_SetString(pysqlite_InterfaceError, errmsg_fetch_across_rollback);
735 return NULL;
736 }
737
738 if (!self->next_row) {
739 if (self->statement) {
740 (void)pysqlite_statement_reset(self->statement);
741 Py_CLEAR(self->statement);
742 }
743 return NULL;
744 }
745
746 next_row_tuple = self->next_row;
747 assert(next_row_tuple != NULL);
748 self->next_row = NULL;
749
750 if (self->row_factory != Py_None) {
751 next_row = PyObject_CallFunction(self->row_factory, "OO", self, next_row_tuple);
752 if (next_row == NULL) {
753 self->next_row = next_row_tuple;
754 return NULL;
755 }
756 Py_DECREF(next_row_tuple);
757 } else {
758 next_row = next_row_tuple;
759 }
760
761 if (self->statement) {
762 rc = pysqlite_step(self->statement->st, self->connection);
763 if (PyErr_Occurred()) {
764 (void)pysqlite_statement_reset(self->statement);
765 Py_DECREF(next_row);
766 return NULL;
767 }
768 if (rc != SQLITE_DONE && rc != SQLITE_ROW) {
769 (void)pysqlite_statement_reset(self->statement);
770 Py_DECREF(next_row);
771 _pysqlite_seterror(self->connection->db, NULL);
772 return NULL;
773 }
774
775 if (rc == SQLITE_ROW) {
776 self->next_row = _pysqlite_fetch_one_row(self);
777 if (self->next_row == NULL) {
778 (void)pysqlite_statement_reset(self->statement);
779 return NULL;
780 }
781 }
782 }
783
784 return next_row;
785 }
786
pysqlite_cursor_fetchone(pysqlite_Cursor * self,PyObject * args)787 PyObject* pysqlite_cursor_fetchone(pysqlite_Cursor* self, PyObject* args)
788 {
789 PyObject* row;
790
791 row = pysqlite_cursor_iternext(self);
792 if (!row && !PyErr_Occurred()) {
793 Py_RETURN_NONE;
794 }
795
796 return row;
797 }
798
pysqlite_cursor_fetchmany(pysqlite_Cursor * self,PyObject * args,PyObject * kwargs)799 PyObject* pysqlite_cursor_fetchmany(pysqlite_Cursor* self, PyObject* args, PyObject* kwargs)
800 {
801 static char *kwlist[] = {"size", NULL, NULL};
802
803 PyObject* row;
804 PyObject* list;
805 int maxrows = self->arraysize;
806 int counter = 0;
807
808 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|i:fetchmany", kwlist, &maxrows)) {
809 return NULL;
810 }
811
812 list = PyList_New(0);
813 if (!list) {
814 return NULL;
815 }
816
817 /* just make sure we enter the loop */
818 row = Py_None;
819
820 while (row) {
821 row = pysqlite_cursor_iternext(self);
822 if (row) {
823 PyList_Append(list, row);
824 Py_DECREF(row);
825 } else {
826 break;
827 }
828
829 if (++counter == maxrows) {
830 break;
831 }
832 }
833
834 if (PyErr_Occurred()) {
835 Py_DECREF(list);
836 return NULL;
837 } else {
838 return list;
839 }
840 }
841
pysqlite_cursor_fetchall(pysqlite_Cursor * self,PyObject * args)842 PyObject* pysqlite_cursor_fetchall(pysqlite_Cursor* self, PyObject* args)
843 {
844 PyObject* row;
845 PyObject* list;
846
847 list = PyList_New(0);
848 if (!list) {
849 return NULL;
850 }
851
852 /* just make sure we enter the loop */
853 row = (PyObject*)Py_None;
854
855 while (row) {
856 row = pysqlite_cursor_iternext(self);
857 if (row) {
858 PyList_Append(list, row);
859 Py_DECREF(row);
860 }
861 }
862
863 if (PyErr_Occurred()) {
864 Py_DECREF(list);
865 return NULL;
866 } else {
867 return list;
868 }
869 }
870
pysqlite_noop(pysqlite_Connection * self,PyObject * args)871 PyObject* pysqlite_noop(pysqlite_Connection* self, PyObject* args)
872 {
873 /* don't care, return None */
874 Py_RETURN_NONE;
875 }
876
pysqlite_cursor_close(pysqlite_Cursor * self,PyObject * args)877 PyObject* pysqlite_cursor_close(pysqlite_Cursor* self, PyObject* args)
878 {
879 if (!self->connection) {
880 PyErr_SetString(pysqlite_ProgrammingError,
881 "Base Cursor.__init__ not called.");
882 return NULL;
883 }
884 if (!pysqlite_check_thread(self->connection) || !pysqlite_check_connection(self->connection)) {
885 return NULL;
886 }
887
888 if (self->statement) {
889 (void)pysqlite_statement_reset(self->statement);
890 Py_CLEAR(self->statement);
891 }
892
893 self->closed = 1;
894
895 Py_RETURN_NONE;
896 }
897
898 static PyMethodDef cursor_methods[] = {
899 {"execute", (PyCFunction)pysqlite_cursor_execute, METH_VARARGS,
900 PyDoc_STR("Executes a SQL statement.")},
901 {"executemany", (PyCFunction)pysqlite_cursor_executemany, METH_VARARGS,
902 PyDoc_STR("Repeatedly executes a SQL statement.")},
903 {"executescript", (PyCFunction)pysqlite_cursor_executescript, METH_VARARGS,
904 PyDoc_STR("Executes a multiple SQL statements at once. Non-standard.")},
905 {"fetchone", (PyCFunction)pysqlite_cursor_fetchone, METH_NOARGS,
906 PyDoc_STR("Fetches one row from the resultset.")},
907 {"fetchmany", (PyCFunction)(void(*)(void))pysqlite_cursor_fetchmany, METH_VARARGS|METH_KEYWORDS,
908 PyDoc_STR("Fetches several rows from the resultset.")},
909 {"fetchall", (PyCFunction)pysqlite_cursor_fetchall, METH_NOARGS,
910 PyDoc_STR("Fetches all rows from the resultset.")},
911 {"close", (PyCFunction)pysqlite_cursor_close, METH_NOARGS,
912 PyDoc_STR("Closes the cursor.")},
913 {"setinputsizes", (PyCFunction)pysqlite_noop, METH_VARARGS,
914 PyDoc_STR("Required by DB-API. Does nothing in pysqlite.")},
915 {"setoutputsize", (PyCFunction)pysqlite_noop, METH_VARARGS,
916 PyDoc_STR("Required by DB-API. Does nothing in pysqlite.")},
917 {NULL, NULL}
918 };
919
920 static struct PyMemberDef cursor_members[] =
921 {
922 {"connection", T_OBJECT, offsetof(pysqlite_Cursor, connection), READONLY},
923 {"description", T_OBJECT, offsetof(pysqlite_Cursor, description), READONLY},
924 {"arraysize", T_INT, offsetof(pysqlite_Cursor, arraysize), 0},
925 {"lastrowid", T_OBJECT, offsetof(pysqlite_Cursor, lastrowid), READONLY},
926 {"rowcount", T_LONG, offsetof(pysqlite_Cursor, rowcount), READONLY},
927 {"row_factory", T_OBJECT, offsetof(pysqlite_Cursor, row_factory), 0},
928 {NULL}
929 };
930
931 static const char cursor_doc[] =
932 PyDoc_STR("SQLite database cursor class.");
933
934 PyTypeObject pysqlite_CursorType = {
935 PyVarObject_HEAD_INIT(NULL, 0)
936 MODULE_NAME ".Cursor", /* tp_name */
937 sizeof(pysqlite_Cursor), /* tp_basicsize */
938 0, /* tp_itemsize */
939 (destructor)pysqlite_cursor_dealloc, /* tp_dealloc */
940 0, /* tp_vectorcall_offset */
941 0, /* tp_getattr */
942 0, /* tp_setattr */
943 0, /* tp_as_async */
944 0, /* tp_repr */
945 0, /* tp_as_number */
946 0, /* tp_as_sequence */
947 0, /* tp_as_mapping */
948 0, /* tp_hash */
949 0, /* tp_call */
950 0, /* tp_str */
951 0, /* tp_getattro */
952 0, /* tp_setattro */
953 0, /* tp_as_buffer */
954 Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE, /* tp_flags */
955 cursor_doc, /* tp_doc */
956 0, /* tp_traverse */
957 0, /* tp_clear */
958 0, /* tp_richcompare */
959 offsetof(pysqlite_Cursor, in_weakreflist), /* tp_weaklistoffset */
960 PyObject_SelfIter, /* tp_iter */
961 (iternextfunc)pysqlite_cursor_iternext, /* tp_iternext */
962 cursor_methods, /* tp_methods */
963 cursor_members, /* tp_members */
964 0, /* tp_getset */
965 0, /* tp_base */
966 0, /* tp_dict */
967 0, /* tp_descr_get */
968 0, /* tp_descr_set */
969 0, /* tp_dictoffset */
970 (initproc)pysqlite_cursor_init, /* tp_init */
971 0, /* tp_alloc */
972 0, /* tp_new */
973 0 /* tp_free */
974 };
975
pysqlite_cursor_setup_types(void)976 extern int pysqlite_cursor_setup_types(void)
977 {
978 pysqlite_CursorType.tp_new = PyType_GenericNew;
979 return PyType_Ready(&pysqlite_CursorType);
980 }
981