1 /* cursor.c - the cursor type
3 * Copyright (C) 2004-2006 Gerhard Häring <gh@ghaering.de>
5 * This file is part of pysqlite.
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.
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:
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.
27 #include "sqlitecompat.h"
29 /* used to decide wether to call PyInt_FromLong or PyLong_FromLongLong */
31 #define INT32_MIN (-2147483647 - 1)
34 #define INT32_MAX 2147483647
37 PyObject* cursor_iternext(Cursor *self);
39 static StatementKind detect_statement_type(char* statement)
46 /* skip over whitepace */
47 while (*src == '\r' || *src == '\n' || *src == ' ' || *src == '\t') {
52 return STATEMENT_INVALID;
56 while (isalpha(*src) && dst - buf < sizeof(buf) - 2) {
57 *dst++ = tolower(*src++);
62 if (!strcmp(buf, "select")) {
63 return STATEMENT_SELECT;
64 } else if (!strcmp(buf, "insert")) {
65 return STATEMENT_INSERT;
66 } else if (!strcmp(buf, "update")) {
67 return STATEMENT_UPDATE;
68 } else if (!strcmp(buf, "delete")) {
69 return STATEMENT_DELETE;
70 } else if (!strcmp(buf, "replace")) {
71 return STATEMENT_REPLACE;
73 return STATEMENT_OTHER;
77 int cursor_init(Cursor* self, PyObject* args, PyObject* kwargs)
79 Connection* connection;
81 if (!PyArg_ParseTuple(args, "O!", &ConnectionType, &connection))
86 Py_INCREF(connection);
87 self->connection = connection;
88 self->statement = NULL;
89 self->next_row = NULL;
91 self->row_cast_map = PyList_New(0);
92 if (!self->row_cast_map) {
97 self->description = Py_None;
100 self->lastrowid= Py_None;
104 self->rowcount = PyInt_FromLong(-1L);
105 if (!self->rowcount) {
110 self->row_factory = Py_None;
112 if (!check_thread(self->connection)) {
119 void cursor_dealloc(Cursor* self)
123 /* Reset the statement if the user has not closed the cursor */
124 if (self->statement) {
125 rc = statement_reset(self->statement);
126 Py_DECREF(self->statement);
129 Py_XDECREF(self->connection);
130 Py_XDECREF(self->row_cast_map);
131 Py_XDECREF(self->description);
132 Py_XDECREF(self->lastrowid);
133 Py_XDECREF(self->rowcount);
134 Py_XDECREF(self->row_factory);
135 Py_XDECREF(self->next_row);
137 self->ob_type->tp_free((PyObject*)self);
140 PyObject* _get_converter(PyObject* key)
142 PyObject* upcase_key;
145 upcase_key = PyObject_CallMethod(key, "upper", "");
150 retval = PyDict_GetItem(converters, upcase_key);
151 Py_DECREF(upcase_key);
156 int build_row_cast_map(Cursor* self)
159 const char* type_start = (const char*)-1;
163 const char* decltype;
164 PyObject* py_decltype;
168 if (!self->connection->detect_types) {
172 Py_XDECREF(self->row_cast_map);
173 self->row_cast_map = PyList_New(0);
175 for (i = 0; i < sqlite3_column_count(self->statement->st); i++) {
178 if (self->connection->detect_types | PARSE_COLNAMES) {
179 colname = sqlite3_column_name(self->statement->st, i);
181 for (pos = colname; *pos != 0; pos++) {
183 type_start = pos + 1;
184 } else if (*pos == ']' && type_start != (const char*)-1) {
185 key = PyString_FromStringAndSize(type_start, pos - type_start);
187 /* creating a string failed, but it is too complicated
188 * to propagate the error here, we just assume there is
189 * no converter and proceed */
193 converter = _get_converter(key);
201 if (!converter && self->connection->detect_types | PARSE_DECLTYPES) {
202 decltype = sqlite3_column_decltype(self->statement->st, i);
204 for (pos = decltype;;pos++) {
205 if (*pos == ' ' || *pos == 0) {
206 py_decltype = PyString_FromStringAndSize(decltype, pos - decltype);
214 converter = _get_converter(py_decltype);
215 Py_DECREF(py_decltype);
223 if (PyList_Append(self->row_cast_map, converter) != 0) {
224 if (converter != Py_None) {
225 Py_DECREF(converter);
227 Py_XDECREF(self->row_cast_map);
228 self->row_cast_map = NULL;
237 PyObject* _build_column_name(const char* colname)
246 for (pos = colname;; pos++) {
247 if (*pos == 0 || *pos == '[') {
248 if ((*pos == '[') && (pos > colname) && (*(pos-1) == ' ')) {
251 return PyString_FromStringAndSize(colname, pos - colname);
256 PyObject* unicode_from_string(const char* val_str, int optimize)
276 return PyString_FromString(val_str);
278 return PyUnicode_DecodeUTF8(val_str, strlen(val_str), NULL);
283 * Returns a row from the currently active SQLite statement
286 * - sqlite3_step() has been called before and it returned SQLITE_ROW.
288 PyObject* _fetch_one_row(Cursor* self)
292 PyObject* item = NULL;
304 Py_BEGIN_ALLOW_THREADS
305 numcols = sqlite3_data_count(self->statement->st);
308 row = PyTuple_New(numcols);
313 for (i = 0; i < numcols; i++) {
314 if (self->connection->detect_types) {
315 converter = PyList_GetItem(self->row_cast_map, i);
323 if (converter != Py_None) {
324 nbytes = sqlite3_column_bytes(self->statement->st, i);
325 val_str = (const char*)sqlite3_column_blob(self->statement->st, i);
330 item = PyString_FromStringAndSize(val_str, nbytes);
334 converted = PyObject_CallFunction(converter, "O", item);
341 Py_BEGIN_ALLOW_THREADS
342 coltype = sqlite3_column_type(self->statement->st, i);
344 if (coltype == SQLITE_NULL) {
347 } else if (coltype == SQLITE_INTEGER) {
348 intval = sqlite3_column_int64(self->statement->st, i);
349 if (intval < INT32_MIN || intval > INT32_MAX) {
350 converted = PyLong_FromLongLong(intval);
352 converted = PyInt_FromLong((long)intval);
354 } else if (coltype == SQLITE_FLOAT) {
355 converted = PyFloat_FromDouble(sqlite3_column_double(self->statement->st, i));
356 } else if (coltype == SQLITE_TEXT) {
357 val_str = (const char*)sqlite3_column_text(self->statement->st, i);
358 if ((self->connection->text_factory == (PyObject*)&PyUnicode_Type)
359 || (self->connection->text_factory == OptimizedUnicode)) {
361 converted = unicode_from_string(val_str,
362 self->connection->text_factory == OptimizedUnicode ? 1 : 0);
365 colname = sqlite3_column_name(self->statement->st, i);
367 colname = "<unknown column name>";
369 PyOS_snprintf(buf, sizeof(buf) - 1, "Could not decode to UTF-8 column '%s' with text '%s'",
371 PyErr_SetString(OperationalError, buf);
373 } else if (self->connection->text_factory == (PyObject*)&PyString_Type) {
374 converted = PyString_FromString(val_str);
376 converted = PyObject_CallFunction(self->connection->text_factory, "s", val_str);
379 /* coltype == SQLITE_BLOB */
380 nbytes = sqlite3_column_bytes(self->statement->st, i);
381 buffer = PyBuffer_New(nbytes);
385 if (PyObject_AsWriteBuffer(buffer, &raw_buffer, &nbytes)) {
388 memcpy(raw_buffer, sqlite3_column_blob(self->statement->st, i), nbytes);
394 PyTuple_SetItem(row, i, converted);
397 PyTuple_SetItem(row, i, Py_None);
401 if (PyErr_Occurred()) {
409 PyObject* _query_execute(Cursor* self, int multiple, PyObject* args)
412 PyObject* operation_bytestr = NULL;
413 char* operation_cstr;
414 PyObject* parameters_list = NULL;
415 PyObject* parameters_iter = NULL;
416 PyObject* parameters = NULL;
422 PY_LONG_LONG lastrowid;
424 PyObject* descriptor;
425 PyObject* second_argument = NULL;
428 if (!check_thread(self->connection) || !check_connection(self->connection)) {
432 Py_XDECREF(self->next_row);
433 self->next_row = NULL;
437 if (!PyArg_ParseTuple(args, "OO", &operation, &second_argument)) {
441 if (!PyString_Check(operation) && !PyUnicode_Check(operation)) {
442 PyErr_SetString(PyExc_ValueError, "operation parameter must be str or unicode");
446 if (PyIter_Check(second_argument)) {
448 Py_INCREF(second_argument);
449 parameters_iter = second_argument;
452 parameters_iter = PyObject_GetIter(second_argument);
453 if (!parameters_iter) {
459 if (!PyArg_ParseTuple(args, "O|O", &operation, &second_argument)) {
463 if (!PyString_Check(operation) && !PyUnicode_Check(operation)) {
464 PyErr_SetString(PyExc_ValueError, "operation parameter must be str or unicode");
468 parameters_list = PyList_New(0);
469 if (!parameters_list) {
473 if (second_argument == NULL) {
474 second_argument = PyTuple_New(0);
475 if (!second_argument) {
479 Py_INCREF(second_argument);
481 if (PyList_Append(parameters_list, second_argument) != 0) {
482 Py_DECREF(second_argument);
485 Py_DECREF(second_argument);
487 parameters_iter = PyObject_GetIter(parameters_list);
488 if (!parameters_iter) {
493 if (self->statement != NULL) {
494 /* There is an active statement */
495 rc = statement_reset(self->statement);
498 if (PyString_Check(operation)) {
499 operation_cstr = PyString_AsString(operation);
501 operation_bytestr = PyUnicode_AsUTF8String(operation);
502 if (!operation_bytestr) {
506 operation_cstr = PyString_AsString(operation_bytestr);
509 /* reset description and rowcount */
510 Py_DECREF(self->description);
512 self->description = Py_None;
514 Py_DECREF(self->rowcount);
515 self->rowcount = PyInt_FromLong(-1L);
516 if (!self->rowcount) {
520 statement_type = detect_statement_type(operation_cstr);
521 if (self->connection->begin_statement) {
522 switch (statement_type) {
523 case STATEMENT_UPDATE:
524 case STATEMENT_DELETE:
525 case STATEMENT_INSERT:
526 case STATEMENT_REPLACE:
527 if (!self->connection->inTransaction) {
528 result = _connection_begin(self->connection);
535 case STATEMENT_OTHER:
536 /* it's a DDL statement or something similar
537 - we better COMMIT first so it works for all cases */
538 if (self->connection->inTransaction) {
539 result = connection_commit(self->connection, NULL);
546 case STATEMENT_SELECT:
548 PyErr_SetString(ProgrammingError,
549 "You cannot execute SELECT statements in executemany().");
556 func_args = PyTuple_New(1);
560 Py_INCREF(operation);
561 if (PyTuple_SetItem(func_args, 0, operation) != 0) {
565 if (self->statement) {
566 (void)statement_reset(self->statement);
567 Py_DECREF(self->statement);
570 self->statement = (Statement*)cache_get(self->connection->statement_cache, func_args);
571 Py_DECREF(func_args);
573 if (!self->statement) {
577 if (self->statement->in_use) {
578 Py_DECREF(self->statement);
579 self->statement = PyObject_New(Statement, &StatementType);
580 if (!self->statement) {
583 rc = statement_create(self->statement, self->connection, operation);
584 if (rc != SQLITE_OK) {
590 statement_reset(self->statement);
591 statement_mark_dirty(self->statement);
594 parameters = PyIter_Next(parameters_iter);
599 statement_mark_dirty(self->statement);
601 statement_bind_parameters(self->statement, parameters);
602 if (PyErr_Occurred()) {
606 if (build_row_cast_map(self) != 0) {
607 PyErr_SetString(OperationalError, "Error while building row_cast_map");
611 rc = _sqlite_step_with_busyhandler(self->statement->st, self->connection);
612 if (rc != SQLITE_DONE && rc != SQLITE_ROW) {
613 rc = statement_reset(self->statement);
614 if (rc == SQLITE_SCHEMA) {
615 rc = statement_recompile(self->statement, parameters);
616 if (rc == SQLITE_OK) {
617 rc = _sqlite_step_with_busyhandler(self->statement->st, self->connection);
619 _seterror(self->connection->db);
623 if (PyErr_Occurred()) {
624 /* there was an error that occurred in a user-defined callback */
625 if (_enable_callback_tracebacks) {
631 _seterror(self->connection->db);
636 if (rc == SQLITE_ROW || (rc == SQLITE_DONE && statement_type == STATEMENT_SELECT)) {
637 Py_BEGIN_ALLOW_THREADS
638 numcols = sqlite3_column_count(self->statement->st);
641 if (self->description == Py_None) {
642 Py_DECREF(self->description);
643 self->description = PyTuple_New(numcols);
644 if (!self->description) {
647 for (i = 0; i < numcols; i++) {
648 descriptor = PyTuple_New(7);
652 PyTuple_SetItem(descriptor, 0, _build_column_name(sqlite3_column_name(self->statement->st, i)));
653 Py_INCREF(Py_None); PyTuple_SetItem(descriptor, 1, Py_None);
654 Py_INCREF(Py_None); PyTuple_SetItem(descriptor, 2, Py_None);
655 Py_INCREF(Py_None); PyTuple_SetItem(descriptor, 3, Py_None);
656 Py_INCREF(Py_None); PyTuple_SetItem(descriptor, 4, Py_None);
657 Py_INCREF(Py_None); PyTuple_SetItem(descriptor, 5, Py_None);
658 Py_INCREF(Py_None); PyTuple_SetItem(descriptor, 6, Py_None);
659 PyTuple_SetItem(self->description, i, descriptor);
664 if (rc == SQLITE_ROW) {
666 PyErr_SetString(ProgrammingError, "executemany() can only execute DML statements.");
670 self->next_row = _fetch_one_row(self);
671 } else if (rc == SQLITE_DONE && !multiple) {
672 statement_reset(self->statement);
673 Py_DECREF(self->statement);
677 switch (statement_type) {
678 case STATEMENT_UPDATE:
679 case STATEMENT_DELETE:
680 case STATEMENT_INSERT:
681 case STATEMENT_REPLACE:
682 Py_BEGIN_ALLOW_THREADS
683 rowcount += (long)sqlite3_changes(self->connection->db);
685 Py_DECREF(self->rowcount);
686 self->rowcount = PyInt_FromLong(rowcount);
689 Py_DECREF(self->lastrowid);
690 if (statement_type == STATEMENT_INSERT) {
691 Py_BEGIN_ALLOW_THREADS
692 lastrowid = sqlite3_last_insert_rowid(self->connection->db);
694 self->lastrowid = PyInt_FromLong((long)lastrowid);
697 self->lastrowid = Py_None;
701 rc = statement_reset(self->statement);
703 Py_XDECREF(parameters);
707 Py_XDECREF(operation_bytestr);
708 Py_XDECREF(parameters);
709 Py_XDECREF(parameters_iter);
710 Py_XDECREF(parameters_list);
712 if (PyErr_Occurred()) {
716 return (PyObject*)self;
720 PyObject* cursor_execute(Cursor* self, PyObject* args)
722 return _query_execute(self, 0, args);
725 PyObject* cursor_executemany(Cursor* self, PyObject* args)
727 return _query_execute(self, 1, args);
730 PyObject* cursor_executescript(Cursor* self, PyObject* args)
732 PyObject* script_obj;
733 PyObject* script_str = NULL;
734 const char* script_cstr;
735 sqlite3_stmt* statement;
738 int statement_completed = 0;
740 if (!PyArg_ParseTuple(args, "O", &script_obj)) {
744 if (!check_thread(self->connection) || !check_connection(self->connection)) {
748 if (PyString_Check(script_obj)) {
749 script_cstr = PyString_AsString(script_obj);
750 } else if (PyUnicode_Check(script_obj)) {
751 script_str = PyUnicode_AsUTF8String(script_obj);
756 script_cstr = PyString_AsString(script_str);
758 PyErr_SetString(PyExc_ValueError, "script argument must be unicode or string.");
763 result = connection_commit(self->connection, NULL);
770 if (!sqlite3_complete(script_cstr)) {
773 statement_completed = 1;
775 rc = sqlite3_prepare(self->connection->db,
780 if (rc != SQLITE_OK) {
781 _seterror(self->connection->db);
785 /* execute statement, and ignore results of SELECT statements */
787 while (rc == SQLITE_ROW) {
788 rc = _sqlite_step_with_busyhandler(statement, self->connection);
791 if (rc != SQLITE_DONE) {
792 (void)sqlite3_finalize(statement);
793 _seterror(self->connection->db);
797 rc = sqlite3_finalize(statement);
798 if (rc != SQLITE_OK) {
799 _seterror(self->connection->db);
805 Py_XDECREF(script_str);
807 if (!statement_completed) {
808 PyErr_SetString(ProgrammingError, "you did not provide a complete SQL statement");
811 if (PyErr_Occurred()) {
815 return (PyObject*)self;
819 PyObject* cursor_getiter(Cursor *self)
822 return (PyObject*)self;
825 PyObject* cursor_iternext(Cursor *self)
827 PyObject* next_row_tuple;
831 if (!check_thread(self->connection) || !check_connection(self->connection)) {
835 if (!self->next_row) {
836 if (self->statement) {
837 (void)statement_reset(self->statement);
838 Py_DECREF(self->statement);
839 self->statement = NULL;
844 next_row_tuple = self->next_row;
845 self->next_row = NULL;
847 if (self->row_factory != Py_None) {
848 next_row = PyObject_CallFunction(self->row_factory, "OO", self, next_row_tuple);
849 Py_DECREF(next_row_tuple);
851 next_row = next_row_tuple;
854 rc = _sqlite_step_with_busyhandler(self->statement->st, self->connection);
855 if (rc != SQLITE_DONE && rc != SQLITE_ROW) {
857 _seterror(self->connection->db);
861 if (rc == SQLITE_ROW) {
862 self->next_row = _fetch_one_row(self);
868 PyObject* cursor_fetchone(Cursor* self, PyObject* args)
872 row = cursor_iternext(self);
873 if (!row && !PyErr_Occurred()) {
881 PyObject* cursor_fetchmany(Cursor* self, PyObject* args)
885 int maxrows = self->arraysize;
888 if (!PyArg_ParseTuple(args, "|i", &maxrows)) {
892 list = PyList_New(0);
897 /* just make sure we enter the loop */
901 row = cursor_iternext(self);
903 PyList_Append(list, row);
909 if (++counter == maxrows) {
914 if (PyErr_Occurred()) {
922 PyObject* cursor_fetchall(Cursor* self, PyObject* args)
927 list = PyList_New(0);
932 /* just make sure we enter the loop */
933 row = (PyObject*)Py_None;
936 row = cursor_iternext(self);
938 PyList_Append(list, row);
943 if (PyErr_Occurred()) {
951 PyObject* pysqlite_noop(Connection* self, PyObject* args)
953 /* don't care, return None */
958 PyObject* cursor_close(Cursor* self, PyObject* args)
960 if (!check_thread(self->connection) || !check_connection(self->connection)) {
964 if (self->statement) {
965 (void)statement_reset(self->statement);
966 Py_DECREF(self->statement);
974 static PyMethodDef cursor_methods[] = {
975 {"execute", (PyCFunction)cursor_execute, METH_VARARGS,
976 PyDoc_STR("Executes a SQL statement.")},
977 {"executemany", (PyCFunction)cursor_executemany, METH_VARARGS,
978 PyDoc_STR("Repeatedly executes a SQL statement.")},
979 {"executescript", (PyCFunction)cursor_executescript, METH_VARARGS,
980 PyDoc_STR("Executes a multiple SQL statements at once. Non-standard.")},
981 {"fetchone", (PyCFunction)cursor_fetchone, METH_NOARGS,
982 PyDoc_STR("Fetches several rows from the resultset.")},
983 {"fetchmany", (PyCFunction)cursor_fetchmany, METH_VARARGS,
984 PyDoc_STR("Fetches all rows from the resultset.")},
985 {"fetchall", (PyCFunction)cursor_fetchall, METH_NOARGS,
986 PyDoc_STR("Fetches one row from the resultset.")},
987 {"close", (PyCFunction)cursor_close, METH_NOARGS,
988 PyDoc_STR("Closes the cursor.")},
989 {"setinputsizes", (PyCFunction)pysqlite_noop, METH_VARARGS,
990 PyDoc_STR("Required by DB-API. Does nothing in pysqlite.")},
991 {"setoutputsize", (PyCFunction)pysqlite_noop, METH_VARARGS,
992 PyDoc_STR("Required by DB-API. Does nothing in pysqlite.")},
996 static struct PyMemberDef cursor_members[] =
998 {"connection", T_OBJECT, offsetof(Cursor, connection), RO},
999 {"description", T_OBJECT, offsetof(Cursor, description), RO},
1000 {"arraysize", T_INT, offsetof(Cursor, arraysize), 0},
1001 {"lastrowid", T_OBJECT, offsetof(Cursor, lastrowid), RO},
1002 {"rowcount", T_OBJECT, offsetof(Cursor, rowcount), RO},
1003 {"row_factory", T_OBJECT, offsetof(Cursor, row_factory), 0},
1007 static char cursor_doc[] =
1008 PyDoc_STR("SQLite database cursor class.");
1010 PyTypeObject CursorType = {
1011 PyObject_HEAD_INIT(NULL)
1013 MODULE_NAME ".Cursor", /* tp_name */
1014 sizeof(Cursor), /* tp_basicsize */
1015 0, /* tp_itemsize */
1016 (destructor)cursor_dealloc, /* tp_dealloc */
1022 0, /* tp_as_number */
1023 0, /* tp_as_sequence */
1024 0, /* tp_as_mapping */
1028 0, /* tp_getattro */
1029 0, /* tp_setattro */
1030 0, /* tp_as_buffer */
1031 Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_ITER|Py_TPFLAGS_BASETYPE, /* tp_flags */
1032 cursor_doc, /* tp_doc */
1033 0, /* tp_traverse */
1035 0, /* tp_richcompare */
1036 0, /* tp_weaklistoffset */
1037 (getiterfunc)cursor_getiter, /* tp_iter */
1038 (iternextfunc)cursor_iternext, /* tp_iternext */
1039 cursor_methods, /* tp_methods */
1040 cursor_members, /* tp_members */
1044 0, /* tp_descr_get */
1045 0, /* tp_descr_set */
1046 0, /* tp_dictoffset */
1047 (initproc)cursor_init, /* tp_init */
1053 extern int cursor_setup_types(void)
1055 CursorType.tp_new = PyType_GenericNew;
1056 return PyType_Ready(&CursorType);