1 /* cursor.c - the cursor type
2 *
3 * Copyright (C) 2004-2010 Gerhard Häring <[email protected]>
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 "microprotocols.h"
26 #include "module.h"
27 #include "util.h"
28
29 typedef enum {
30 TYPE_LONG,
31 TYPE_FLOAT,
32 TYPE_UNICODE,
33 TYPE_BUFFER,
34 TYPE_UNKNOWN
35 } parameter_type;
36
37 #define clinic_state() (pysqlite_get_state_by_type(Py_TYPE(self)))
38 #include "clinic/cursor.c.h"
39 #undef clinic_state
40
41 static inline int
check_cursor_locked(pysqlite_Cursor * cur)42 check_cursor_locked(pysqlite_Cursor *cur)
43 {
44 if (cur->locked) {
45 PyErr_SetString(cur->connection->ProgrammingError,
46 "Recursive use of cursors not allowed.");
47 return 0;
48 }
49 return 1;
50 }
51
52 /*[clinic input]
53 module _sqlite3
54 class _sqlite3.Cursor "pysqlite_Cursor *" "clinic_state()->CursorType"
55 [clinic start generated code]*/
56 /*[clinic end generated code: output=da39a3ee5e6b4b0d input=3c5b8115c5cf30f1]*/
57
58 /*
59 * Registers a cursor with the connection.
60 *
61 * 0 => error; 1 => ok
62 */
63 static int
register_cursor(pysqlite_Connection * connection,PyObject * cursor)64 register_cursor(pysqlite_Connection *connection, PyObject *cursor)
65 {
66 PyObject *weakref = PyWeakref_NewRef((PyObject *)cursor, NULL);
67 if (weakref == NULL) {
68 return 0;
69 }
70
71 if (PyList_Append(connection->cursors, weakref) < 0) {
72 Py_CLEAR(weakref);
73 return 0;
74 }
75
76 Py_DECREF(weakref);
77 return 1;
78 }
79
80 /*[clinic input]
81 _sqlite3.Cursor.__init__ as pysqlite_cursor_init
82
83 connection: object(type='pysqlite_Connection *', subclass_of='clinic_state()->ConnectionType')
84 /
85
86 [clinic start generated code]*/
87
88 static int
pysqlite_cursor_init_impl(pysqlite_Cursor * self,pysqlite_Connection * connection)89 pysqlite_cursor_init_impl(pysqlite_Cursor *self,
90 pysqlite_Connection *connection)
91 /*[clinic end generated code: output=ac59dce49a809ca8 input=23d4265b534989fb]*/
92 {
93 if (!check_cursor_locked(self)) {
94 return -1;
95 }
96
97 Py_INCREF(connection);
98 Py_XSETREF(self->connection, connection);
99 Py_CLEAR(self->statement);
100 Py_CLEAR(self->row_cast_map);
101
102 Py_INCREF(Py_None);
103 Py_XSETREF(self->description, Py_None);
104
105 Py_INCREF(Py_None);
106 Py_XSETREF(self->lastrowid, Py_None);
107
108 self->arraysize = 1;
109 self->closed = 0;
110 self->rowcount = -1L;
111
112 Py_INCREF(Py_None);
113 Py_XSETREF(self->row_factory, Py_None);
114
115 if (!pysqlite_check_thread(self->connection)) {
116 return -1;
117 }
118
119 if (!register_cursor(connection, (PyObject *)self)) {
120 return -1;
121 }
122
123 self->initialized = 1;
124
125 return 0;
126 }
127
128 static inline int
stmt_reset(pysqlite_Statement * self)129 stmt_reset(pysqlite_Statement *self)
130 {
131 int rc = SQLITE_OK;
132
133 if (self->in_use && self->st) {
134 Py_BEGIN_ALLOW_THREADS
135 rc = sqlite3_reset(self->st);
136 Py_END_ALLOW_THREADS
137
138 if (rc == SQLITE_OK) {
139 self->in_use = 0;
140 }
141 }
142
143 return rc;
144 }
145
146 static int
cursor_traverse(pysqlite_Cursor * self,visitproc visit,void * arg)147 cursor_traverse(pysqlite_Cursor *self, visitproc visit, void *arg)
148 {
149 Py_VISIT(Py_TYPE(self));
150 Py_VISIT(self->connection);
151 Py_VISIT(self->description);
152 Py_VISIT(self->row_cast_map);
153 Py_VISIT(self->lastrowid);
154 Py_VISIT(self->row_factory);
155 Py_VISIT(self->statement);
156 return 0;
157 }
158
159 static int
cursor_clear(pysqlite_Cursor * self)160 cursor_clear(pysqlite_Cursor *self)
161 {
162 Py_CLEAR(self->connection);
163 Py_CLEAR(self->description);
164 Py_CLEAR(self->row_cast_map);
165 Py_CLEAR(self->lastrowid);
166 Py_CLEAR(self->row_factory);
167 if (self->statement) {
168 /* Reset the statement if the user has not closed the cursor */
169 stmt_reset(self->statement);
170 Py_CLEAR(self->statement);
171 }
172
173 return 0;
174 }
175
176 static void
cursor_dealloc(pysqlite_Cursor * self)177 cursor_dealloc(pysqlite_Cursor *self)
178 {
179 PyTypeObject *tp = Py_TYPE(self);
180 PyObject_GC_UnTrack(self);
181 if (self->in_weakreflist != NULL) {
182 PyObject_ClearWeakRefs((PyObject*)self);
183 }
184 tp->tp_clear((PyObject *)self);
185 tp->tp_free(self);
186 Py_DECREF(tp);
187 }
188
189 static PyObject *
_pysqlite_get_converter(pysqlite_state * state,const char * keystr,Py_ssize_t keylen)190 _pysqlite_get_converter(pysqlite_state *state, const char *keystr,
191 Py_ssize_t keylen)
192 {
193 PyObject *key;
194 PyObject *upcase_key;
195 PyObject *retval;
196
197 key = PyUnicode_FromStringAndSize(keystr, keylen);
198 if (!key) {
199 return NULL;
200 }
201 upcase_key = PyObject_CallMethodNoArgs(key, state->str_upper);
202 Py_DECREF(key);
203 if (!upcase_key) {
204 return NULL;
205 }
206
207 retval = PyDict_GetItemWithError(state->converters, upcase_key);
208 Py_DECREF(upcase_key);
209
210 return retval;
211 }
212
213 static int
pysqlite_build_row_cast_map(pysqlite_Cursor * self)214 pysqlite_build_row_cast_map(pysqlite_Cursor* self)
215 {
216 int i;
217 const char* pos;
218 const char* decltype;
219 PyObject* converter;
220
221 if (!self->connection->detect_types) {
222 return 0;
223 }
224
225 Py_XSETREF(self->row_cast_map, PyList_New(0));
226 if (!self->row_cast_map) {
227 return -1;
228 }
229
230 for (i = 0; i < sqlite3_column_count(self->statement->st); i++) {
231 converter = NULL;
232
233 if (self->connection->detect_types & PARSE_COLNAMES) {
234 const char *colname = sqlite3_column_name(self->statement->st, i);
235 if (colname == NULL) {
236 PyErr_NoMemory();
237 Py_CLEAR(self->row_cast_map);
238 return -1;
239 }
240 const char *type_start = NULL;
241 for (pos = colname; *pos != 0; pos++) {
242 if (*pos == '[') {
243 type_start = pos + 1;
244 }
245 else if (*pos == ']' && type_start != NULL) {
246 pysqlite_state *state = self->connection->state;
247 converter = _pysqlite_get_converter(state, type_start,
248 pos - type_start);
249 if (!converter && PyErr_Occurred()) {
250 Py_CLEAR(self->row_cast_map);
251 return -1;
252 }
253 break;
254 }
255 }
256 }
257
258 if (!converter && self->connection->detect_types & PARSE_DECLTYPES) {
259 decltype = sqlite3_column_decltype(self->statement->st, i);
260 if (decltype) {
261 for (pos = decltype;;pos++) {
262 /* Converter names are split at '(' and blanks.
263 * This allows 'INTEGER NOT NULL' to be treated as 'INTEGER' and
264 * 'NUMBER(10)' to be treated as 'NUMBER', for example.
265 * In other words, it will work as people expect it to work.*/
266 if (*pos == ' ' || *pos == '(' || *pos == 0) {
267 pysqlite_state *state = self->connection->state;
268 converter = _pysqlite_get_converter(state, decltype,
269 pos - decltype);
270 if (!converter && PyErr_Occurred()) {
271 Py_CLEAR(self->row_cast_map);
272 return -1;
273 }
274 break;
275 }
276 }
277 }
278 }
279
280 if (!converter) {
281 converter = Py_None;
282 }
283
284 if (PyList_Append(self->row_cast_map, converter) != 0) {
285 Py_CLEAR(self->row_cast_map);
286 return -1;
287 }
288 }
289
290 return 0;
291 }
292
293 static PyObject *
_pysqlite_build_column_name(pysqlite_Cursor * self,const char * colname)294 _pysqlite_build_column_name(pysqlite_Cursor *self, const char *colname)
295 {
296 const char* pos;
297 Py_ssize_t len;
298
299 if (self->connection->detect_types & PARSE_COLNAMES) {
300 for (pos = colname; *pos; pos++) {
301 if (*pos == '[') {
302 if ((pos != colname) && (*(pos-1) == ' ')) {
303 pos--;
304 }
305 break;
306 }
307 }
308 len = pos - colname;
309 }
310 else {
311 len = strlen(colname);
312 }
313 return PyUnicode_FromStringAndSize(colname, len);
314 }
315
316 /*
317 * Returns a row from the currently active SQLite statement
318 *
319 * Precondidition:
320 * - sqlite3_step() has been called before and it returned SQLITE_ROW.
321 */
322 static PyObject *
_pysqlite_fetch_one_row(pysqlite_Cursor * self)323 _pysqlite_fetch_one_row(pysqlite_Cursor* self)
324 {
325 int i, numcols;
326 PyObject* row;
327 int coltype;
328 PyObject* converter;
329 PyObject* converted;
330 Py_ssize_t nbytes;
331 char buf[200];
332 const char* colname;
333 PyObject* error_msg;
334
335 Py_BEGIN_ALLOW_THREADS
336 numcols = sqlite3_data_count(self->statement->st);
337 Py_END_ALLOW_THREADS
338
339 row = PyTuple_New(numcols);
340 if (!row)
341 return NULL;
342
343 sqlite3 *db = self->connection->db;
344 for (i = 0; i < numcols; i++) {
345 if (self->connection->detect_types
346 && self->row_cast_map != NULL
347 && i < PyList_GET_SIZE(self->row_cast_map))
348 {
349 converter = PyList_GET_ITEM(self->row_cast_map, i);
350 }
351 else {
352 converter = Py_None;
353 }
354
355 /*
356 * Note, sqlite3_column_bytes() must come after sqlite3_column_blob()
357 * or sqlite3_column_text().
358 *
359 * See https://sqlite.org/c3ref/column_blob.html for details.
360 */
361 if (converter != Py_None) {
362 const void *blob = sqlite3_column_blob(self->statement->st, i);
363 if (blob == NULL) {
364 if (sqlite3_errcode(db) == SQLITE_NOMEM) {
365 PyErr_NoMemory();
366 goto error;
367 }
368 converted = Py_NewRef(Py_None);
369 }
370 else {
371 nbytes = sqlite3_column_bytes(self->statement->st, i);
372 PyObject *item = PyBytes_FromStringAndSize(blob, nbytes);
373 if (item == NULL) {
374 goto error;
375 }
376 converted = PyObject_CallOneArg(converter, item);
377 Py_DECREF(item);
378 }
379 } else {
380 Py_BEGIN_ALLOW_THREADS
381 coltype = sqlite3_column_type(self->statement->st, i);
382 Py_END_ALLOW_THREADS
383 if (coltype == SQLITE_NULL) {
384 converted = Py_NewRef(Py_None);
385 } else if (coltype == SQLITE_INTEGER) {
386 converted = PyLong_FromLongLong(sqlite3_column_int64(self->statement->st, i));
387 } else if (coltype == SQLITE_FLOAT) {
388 converted = PyFloat_FromDouble(sqlite3_column_double(self->statement->st, i));
389 } else if (coltype == SQLITE_TEXT) {
390 const char *text = (const char*)sqlite3_column_text(self->statement->st, i);
391 if (text == NULL && sqlite3_errcode(db) == SQLITE_NOMEM) {
392 PyErr_NoMemory();
393 goto error;
394 }
395
396 nbytes = sqlite3_column_bytes(self->statement->st, i);
397 if (self->connection->text_factory == (PyObject*)&PyUnicode_Type) {
398 converted = PyUnicode_FromStringAndSize(text, nbytes);
399 if (!converted && PyErr_ExceptionMatches(PyExc_UnicodeDecodeError)) {
400 PyErr_Clear();
401 colname = sqlite3_column_name(self->statement->st, i);
402 if (colname == NULL) {
403 PyErr_NoMemory();
404 goto error;
405 }
406 PyOS_snprintf(buf, sizeof(buf) - 1, "Could not decode to UTF-8 column '%s' with text '%s'",
407 colname , text);
408 error_msg = PyUnicode_Decode(buf, strlen(buf), "ascii", "replace");
409
410 PyObject *exc = self->connection->OperationalError;
411 if (!error_msg) {
412 PyErr_SetString(exc, "Could not decode to UTF-8");
413 } else {
414 PyErr_SetObject(exc, error_msg);
415 Py_DECREF(error_msg);
416 }
417 }
418 } else if (self->connection->text_factory == (PyObject*)&PyBytes_Type) {
419 converted = PyBytes_FromStringAndSize(text, nbytes);
420 } else if (self->connection->text_factory == (PyObject*)&PyByteArray_Type) {
421 converted = PyByteArray_FromStringAndSize(text, nbytes);
422 } else {
423 converted = PyObject_CallFunction(self->connection->text_factory, "y#", text, nbytes);
424 }
425 } else {
426 /* coltype == SQLITE_BLOB */
427 const void *blob = sqlite3_column_blob(self->statement->st, i);
428 if (blob == NULL && sqlite3_errcode(db) == SQLITE_NOMEM) {
429 PyErr_NoMemory();
430 goto error;
431 }
432
433 nbytes = sqlite3_column_bytes(self->statement->st, i);
434 converted = PyBytes_FromStringAndSize(blob, nbytes);
435 }
436 }
437
438 if (!converted) {
439 goto error;
440 }
441 PyTuple_SET_ITEM(row, i, converted);
442 }
443
444 if (PyErr_Occurred())
445 goto error;
446
447 return row;
448
449 error:
450 Py_DECREF(row);
451 return NULL;
452 }
453
454 /*
455 * Checks if a cursor object is usable.
456 *
457 * 0 => error; 1 => ok
458 */
check_cursor(pysqlite_Cursor * cur)459 static int check_cursor(pysqlite_Cursor* cur)
460 {
461 if (!cur->initialized) {
462 pysqlite_state *state = pysqlite_get_state_by_type(Py_TYPE(cur));
463 PyErr_SetString(state->ProgrammingError,
464 "Base Cursor.__init__ not called.");
465 return 0;
466 }
467
468 if (cur->closed) {
469 PyErr_SetString(cur->connection->state->ProgrammingError,
470 "Cannot operate on a closed cursor.");
471 return 0;
472 }
473
474 return (pysqlite_check_thread(cur->connection)
475 && pysqlite_check_connection(cur->connection)
476 && check_cursor_locked(cur));
477 }
478
479 static int
begin_transaction(pysqlite_Connection * self)480 begin_transaction(pysqlite_Connection *self)
481 {
482 assert(self->isolation_level != NULL);
483 int rc;
484
485 Py_BEGIN_ALLOW_THREADS
486 sqlite3_stmt *statement;
487 char begin_stmt[16] = "BEGIN ";
488 #ifdef Py_DEBUG
489 size_t len = strlen(self->isolation_level);
490 assert(len <= 9);
491 #endif
492 (void)strcat(begin_stmt, self->isolation_level);
493 rc = sqlite3_prepare_v2(self->db, begin_stmt, -1, &statement, NULL);
494 if (rc == SQLITE_OK) {
495 (void)sqlite3_step(statement);
496 rc = sqlite3_finalize(statement);
497 }
498 Py_END_ALLOW_THREADS
499
500 if (rc != SQLITE_OK) {
501 (void)_pysqlite_seterror(self->state, self->db);
502 return -1;
503 }
504
505 return 0;
506 }
507
508 static PyObject *
get_statement_from_cache(pysqlite_Cursor * self,PyObject * operation)509 get_statement_from_cache(pysqlite_Cursor *self, PyObject *operation)
510 {
511 PyObject *args[] = { NULL, operation, }; // Borrowed ref.
512 PyObject *cache = self->connection->statement_cache;
513 size_t nargsf = 1 | PY_VECTORCALL_ARGUMENTS_OFFSET;
514 return PyObject_Vectorcall(cache, args + 1, nargsf, NULL);
515 }
516
517 static inline int
stmt_step(sqlite3_stmt * statement)518 stmt_step(sqlite3_stmt *statement)
519 {
520 int rc;
521
522 Py_BEGIN_ALLOW_THREADS
523 rc = sqlite3_step(statement);
524 Py_END_ALLOW_THREADS
525
526 return rc;
527 }
528
529 static int
bind_param(pysqlite_state * state,pysqlite_Statement * self,int pos,PyObject * parameter)530 bind_param(pysqlite_state *state, pysqlite_Statement *self, int pos,
531 PyObject *parameter)
532 {
533 int rc = SQLITE_OK;
534 const char *string;
535 Py_ssize_t buflen;
536 parameter_type paramtype;
537
538 if (parameter == Py_None) {
539 rc = sqlite3_bind_null(self->st, pos);
540 goto final;
541 }
542
543 if (PyLong_CheckExact(parameter)) {
544 paramtype = TYPE_LONG;
545 } else if (PyFloat_CheckExact(parameter)) {
546 paramtype = TYPE_FLOAT;
547 } else if (PyUnicode_CheckExact(parameter)) {
548 paramtype = TYPE_UNICODE;
549 } else if (PyLong_Check(parameter)) {
550 paramtype = TYPE_LONG;
551 } else if (PyFloat_Check(parameter)) {
552 paramtype = TYPE_FLOAT;
553 } else if (PyUnicode_Check(parameter)) {
554 paramtype = TYPE_UNICODE;
555 } else if (PyObject_CheckBuffer(parameter)) {
556 paramtype = TYPE_BUFFER;
557 } else {
558 paramtype = TYPE_UNKNOWN;
559 }
560
561 switch (paramtype) {
562 case TYPE_LONG: {
563 sqlite_int64 value = _pysqlite_long_as_int64(parameter);
564 if (value == -1 && PyErr_Occurred())
565 rc = -1;
566 else
567 rc = sqlite3_bind_int64(self->st, pos, value);
568 break;
569 }
570 case TYPE_FLOAT: {
571 double value = PyFloat_AsDouble(parameter);
572 if (value == -1 && PyErr_Occurred()) {
573 rc = -1;
574 }
575 else {
576 rc = sqlite3_bind_double(self->st, pos, value);
577 }
578 break;
579 }
580 case TYPE_UNICODE:
581 string = PyUnicode_AsUTF8AndSize(parameter, &buflen);
582 if (string == NULL)
583 return -1;
584 if (buflen > INT_MAX) {
585 PyErr_SetString(PyExc_OverflowError,
586 "string longer than INT_MAX bytes");
587 return -1;
588 }
589 rc = sqlite3_bind_text(self->st, pos, string, (int)buflen, SQLITE_TRANSIENT);
590 break;
591 case TYPE_BUFFER: {
592 Py_buffer view;
593 if (PyObject_GetBuffer(parameter, &view, PyBUF_SIMPLE) != 0) {
594 return -1;
595 }
596 if (view.len > INT_MAX) {
597 PyErr_SetString(PyExc_OverflowError,
598 "BLOB longer than INT_MAX bytes");
599 PyBuffer_Release(&view);
600 return -1;
601 }
602 rc = sqlite3_bind_blob(self->st, pos, view.buf, (int)view.len, SQLITE_TRANSIENT);
603 PyBuffer_Release(&view);
604 break;
605 }
606 case TYPE_UNKNOWN:
607 PyErr_Format(state->ProgrammingError,
608 "Error binding parameter %d: type '%s' is not supported",
609 pos, Py_TYPE(parameter)->tp_name);
610 rc = -1;
611 }
612
613 final:
614 return rc;
615 }
616
617 /* returns 0 if the object is one of Python's internal ones that don't need to be adapted */
618 static inline int
need_adapt(pysqlite_state * state,PyObject * obj)619 need_adapt(pysqlite_state *state, PyObject *obj)
620 {
621 if (state->BaseTypeAdapted) {
622 return 1;
623 }
624
625 if (PyLong_CheckExact(obj) || PyFloat_CheckExact(obj)
626 || PyUnicode_CheckExact(obj) || PyByteArray_CheckExact(obj)) {
627 return 0;
628 } else {
629 return 1;
630 }
631 }
632
633 static void
bind_parameters(pysqlite_state * state,pysqlite_Statement * self,PyObject * parameters)634 bind_parameters(pysqlite_state *state, pysqlite_Statement *self,
635 PyObject *parameters)
636 {
637 PyObject* current_param;
638 PyObject* adapted;
639 const char* binding_name;
640 int i;
641 int rc;
642 int num_params_needed;
643 Py_ssize_t num_params;
644
645 Py_BEGIN_ALLOW_THREADS
646 num_params_needed = sqlite3_bind_parameter_count(self->st);
647 Py_END_ALLOW_THREADS
648
649 if (PyTuple_CheckExact(parameters) || PyList_CheckExact(parameters) || (!PyDict_Check(parameters) && PySequence_Check(parameters))) {
650 /* parameters passed as sequence */
651 if (PyTuple_CheckExact(parameters)) {
652 num_params = PyTuple_GET_SIZE(parameters);
653 } else if (PyList_CheckExact(parameters)) {
654 num_params = PyList_GET_SIZE(parameters);
655 } else {
656 num_params = PySequence_Size(parameters);
657 if (num_params == -1) {
658 return;
659 }
660 }
661 if (num_params != num_params_needed) {
662 PyErr_Format(state->ProgrammingError,
663 "Incorrect number of bindings supplied. The current "
664 "statement uses %d, and there are %zd supplied.",
665 num_params_needed, num_params);
666 return;
667 }
668 for (i = 0; i < num_params; i++) {
669 if (PyTuple_CheckExact(parameters)) {
670 PyObject *item = PyTuple_GET_ITEM(parameters, i);
671 current_param = Py_NewRef(item);
672 } else if (PyList_CheckExact(parameters)) {
673 PyObject *item = PyList_GetItem(parameters, i);
674 current_param = Py_XNewRef(item);
675 } else {
676 current_param = PySequence_GetItem(parameters, i);
677 }
678 if (!current_param) {
679 return;
680 }
681
682 if (!need_adapt(state, current_param)) {
683 adapted = current_param;
684 } else {
685 PyObject *protocol = (PyObject *)state->PrepareProtocolType;
686 adapted = pysqlite_microprotocols_adapt(state, current_param,
687 protocol,
688 current_param);
689 Py_DECREF(current_param);
690 if (!adapted) {
691 return;
692 }
693 }
694
695 rc = bind_param(state, self, i + 1, adapted);
696 Py_DECREF(adapted);
697
698 if (rc != SQLITE_OK) {
699 PyObject *exc, *val, *tb;
700 PyErr_Fetch(&exc, &val, &tb);
701 sqlite3 *db = sqlite3_db_handle(self->st);
702 _pysqlite_seterror(state, db);
703 _PyErr_ChainExceptions(exc, val, tb);
704 return;
705 }
706 }
707 } else if (PyDict_Check(parameters)) {
708 /* parameters passed as dictionary */
709 for (i = 1; i <= num_params_needed; i++) {
710 PyObject *binding_name_obj;
711 Py_BEGIN_ALLOW_THREADS
712 binding_name = sqlite3_bind_parameter_name(self->st, i);
713 Py_END_ALLOW_THREADS
714 if (!binding_name) {
715 PyErr_Format(state->ProgrammingError,
716 "Binding %d has no name, but you supplied a "
717 "dictionary (which has only names).", i);
718 return;
719 }
720
721 binding_name++; /* skip first char (the colon) */
722 binding_name_obj = PyUnicode_FromString(binding_name);
723 if (!binding_name_obj) {
724 return;
725 }
726 if (PyDict_CheckExact(parameters)) {
727 PyObject *item = PyDict_GetItemWithError(parameters, binding_name_obj);
728 current_param = Py_XNewRef(item);
729 } else {
730 current_param = PyObject_GetItem(parameters, binding_name_obj);
731 }
732 Py_DECREF(binding_name_obj);
733 if (!current_param) {
734 if (!PyErr_Occurred() || PyErr_ExceptionMatches(PyExc_LookupError)) {
735 PyErr_Format(state->ProgrammingError,
736 "You did not supply a value for binding "
737 "parameter :%s.", binding_name);
738 }
739 return;
740 }
741
742 if (!need_adapt(state, current_param)) {
743 adapted = current_param;
744 } else {
745 PyObject *protocol = (PyObject *)state->PrepareProtocolType;
746 adapted = pysqlite_microprotocols_adapt(state, current_param,
747 protocol,
748 current_param);
749 Py_DECREF(current_param);
750 if (!adapted) {
751 return;
752 }
753 }
754
755 rc = bind_param(state, self, i, adapted);
756 Py_DECREF(adapted);
757
758 if (rc != SQLITE_OK) {
759 PyObject *exc, *val, *tb;
760 PyErr_Fetch(&exc, &val, &tb);
761 sqlite3 *db = sqlite3_db_handle(self->st);
762 _pysqlite_seterror(state, db);
763 _PyErr_ChainExceptions(exc, val, tb);
764 return;
765 }
766 }
767 } else {
768 PyErr_SetString(state->ProgrammingError,
769 "parameters are of unsupported type");
770 }
771 }
772
773 static inline void
stmt_mark_dirty(pysqlite_Statement * self)774 stmt_mark_dirty(pysqlite_Statement *self)
775 {
776 self->in_use = 1;
777 }
778
779 PyObject *
_pysqlite_query_execute(pysqlite_Cursor * self,int multiple,PyObject * operation,PyObject * second_argument)780 _pysqlite_query_execute(pysqlite_Cursor* self, int multiple, PyObject* operation, PyObject* second_argument)
781 {
782 PyObject* parameters_list = NULL;
783 PyObject* parameters_iter = NULL;
784 PyObject* parameters = NULL;
785 int i;
786 int rc;
787 int numcols;
788 PyObject* column_name;
789
790 if (!check_cursor(self)) {
791 goto error;
792 }
793
794 self->locked = 1;
795
796 if (multiple) {
797 if (PyIter_Check(second_argument)) {
798 /* iterator */
799 parameters_iter = Py_NewRef(second_argument);
800 } else {
801 /* sequence */
802 parameters_iter = PyObject_GetIter(second_argument);
803 if (!parameters_iter) {
804 goto error;
805 }
806 }
807 } else {
808 parameters_list = PyList_New(0);
809 if (!parameters_list) {
810 goto error;
811 }
812
813 if (second_argument == NULL) {
814 second_argument = PyTuple_New(0);
815 if (!second_argument) {
816 goto error;
817 }
818 } else {
819 Py_INCREF(second_argument);
820 }
821 if (PyList_Append(parameters_list, second_argument) != 0) {
822 Py_DECREF(second_argument);
823 goto error;
824 }
825 Py_DECREF(second_argument);
826
827 parameters_iter = PyObject_GetIter(parameters_list);
828 if (!parameters_iter) {
829 goto error;
830 }
831 }
832
833 if (self->statement != NULL) {
834 /* There is an active statement */
835 stmt_reset(self->statement);
836 }
837
838 /* reset description */
839 Py_INCREF(Py_None);
840 Py_SETREF(self->description, Py_None);
841
842 if (self->statement) {
843 (void)stmt_reset(self->statement);
844 }
845
846 PyObject *stmt = get_statement_from_cache(self, operation);
847 Py_XSETREF(self->statement, (pysqlite_Statement *)stmt);
848 if (!self->statement) {
849 goto error;
850 }
851
852 pysqlite_state *state = self->connection->state;
853 if (multiple && sqlite3_stmt_readonly(self->statement->st)) {
854 PyErr_SetString(state->ProgrammingError,
855 "executemany() can only execute DML statements.");
856 goto error;
857 }
858
859 if (self->statement->in_use) {
860 Py_SETREF(self->statement,
861 pysqlite_statement_create(self->connection, operation));
862 if (self->statement == NULL) {
863 goto error;
864 }
865 }
866
867 stmt_reset(self->statement);
868 stmt_mark_dirty(self->statement);
869 self->rowcount = self->statement->is_dml ? 0L : -1L;
870
871 /* We start a transaction implicitly before a DML statement.
872 SELECT is the only exception. See #9924. */
873 if (self->connection->isolation_level
874 && self->statement->is_dml
875 && sqlite3_get_autocommit(self->connection->db))
876 {
877 if (begin_transaction(self->connection) < 0) {
878 goto error;
879 }
880 }
881
882 while (1) {
883 parameters = PyIter_Next(parameters_iter);
884 if (!parameters) {
885 break;
886 }
887
888 stmt_mark_dirty(self->statement);
889
890 bind_parameters(state, self->statement, parameters);
891 if (PyErr_Occurred()) {
892 goto error;
893 }
894
895 rc = stmt_step(self->statement->st);
896 if (rc != SQLITE_DONE && rc != SQLITE_ROW) {
897 if (PyErr_Occurred()) {
898 /* there was an error that occurred in a user-defined callback */
899 if (state->enable_callback_tracebacks) {
900 PyErr_Print();
901 } else {
902 PyErr_Clear();
903 }
904 }
905 (void)stmt_reset(self->statement);
906 _pysqlite_seterror(state, self->connection->db);
907 goto error;
908 }
909
910 if (pysqlite_build_row_cast_map(self) != 0) {
911 _PyErr_FormatFromCause(state->OperationalError,
912 "Error while building row_cast_map");
913 goto error;
914 }
915
916 assert(rc == SQLITE_ROW || rc == SQLITE_DONE);
917 Py_BEGIN_ALLOW_THREADS
918 numcols = sqlite3_column_count(self->statement->st);
919 Py_END_ALLOW_THREADS
920 if (self->description == Py_None && numcols > 0) {
921 Py_SETREF(self->description, PyTuple_New(numcols));
922 if (!self->description) {
923 goto error;
924 }
925 for (i = 0; i < numcols; i++) {
926 const char *colname;
927 colname = sqlite3_column_name(self->statement->st, i);
928 if (colname == NULL) {
929 PyErr_NoMemory();
930 goto error;
931 }
932 column_name = _pysqlite_build_column_name(self, colname);
933 if (column_name == NULL) {
934 goto error;
935 }
936 PyObject *descriptor = PyTuple_Pack(7, column_name,
937 Py_None, Py_None, Py_None,
938 Py_None, Py_None, Py_None);
939 Py_DECREF(column_name);
940 if (descriptor == NULL) {
941 goto error;
942 }
943 PyTuple_SET_ITEM(self->description, i, descriptor);
944 }
945 }
946
947 if (rc == SQLITE_DONE && !multiple) {
948 if (self->statement->is_dml) {
949 self->rowcount = (long)sqlite3_changes(self->connection->db);
950 }
951 stmt_reset(self->statement);
952 Py_CLEAR(self->statement);
953 }
954
955 if (multiple) {
956 if (self->statement->is_dml && rc == SQLITE_DONE) {
957 self->rowcount += (long)sqlite3_changes(self->connection->db);
958 }
959 stmt_reset(self->statement);
960 }
961 Py_XDECREF(parameters);
962 }
963
964 if (!multiple) {
965 sqlite_int64 lastrowid;
966
967 Py_BEGIN_ALLOW_THREADS
968 lastrowid = sqlite3_last_insert_rowid(self->connection->db);
969 Py_END_ALLOW_THREADS
970
971 Py_SETREF(self->lastrowid, PyLong_FromLongLong(lastrowid));
972 // Fall through on error.
973 }
974
975 error:
976 Py_XDECREF(parameters);
977 Py_XDECREF(parameters_iter);
978 Py_XDECREF(parameters_list);
979
980 self->locked = 0;
981
982 if (PyErr_Occurred()) {
983 self->rowcount = -1L;
984 return NULL;
985 } else {
986 return Py_NewRef((PyObject *)self);
987 }
988 }
989
990 /*[clinic input]
991 _sqlite3.Cursor.execute as pysqlite_cursor_execute
992
993 sql: unicode
994 parameters: object(c_default = 'NULL') = ()
995 /
996
997 Executes an SQL statement.
998 [clinic start generated code]*/
999
1000 static PyObject *
pysqlite_cursor_execute_impl(pysqlite_Cursor * self,PyObject * sql,PyObject * parameters)1001 pysqlite_cursor_execute_impl(pysqlite_Cursor *self, PyObject *sql,
1002 PyObject *parameters)
1003 /*[clinic end generated code: output=d81b4655c7c0bbad input=a8e0200a11627f94]*/
1004 {
1005 return _pysqlite_query_execute(self, 0, sql, parameters);
1006 }
1007
1008 /*[clinic input]
1009 _sqlite3.Cursor.executemany as pysqlite_cursor_executemany
1010
1011 sql: unicode
1012 seq_of_parameters: object
1013 /
1014
1015 Repeatedly executes an SQL statement.
1016 [clinic start generated code]*/
1017
1018 static PyObject *
pysqlite_cursor_executemany_impl(pysqlite_Cursor * self,PyObject * sql,PyObject * seq_of_parameters)1019 pysqlite_cursor_executemany_impl(pysqlite_Cursor *self, PyObject *sql,
1020 PyObject *seq_of_parameters)
1021 /*[clinic end generated code: output=2c65a3c4733fb5d8 input=0d0a52e5eb7ccd35]*/
1022 {
1023 return _pysqlite_query_execute(self, 1, sql, seq_of_parameters);
1024 }
1025
1026 /*[clinic input]
1027 _sqlite3.Cursor.executescript as pysqlite_cursor_executescript
1028
1029 sql_script: str
1030 /
1031
1032 Executes multiple SQL statements at once.
1033 [clinic start generated code]*/
1034
1035 static PyObject *
pysqlite_cursor_executescript_impl(pysqlite_Cursor * self,const char * sql_script)1036 pysqlite_cursor_executescript_impl(pysqlite_Cursor *self,
1037 const char *sql_script)
1038 /*[clinic end generated code: output=8fd726dde1c65164 input=78f093be415a8a2c]*/
1039 {
1040 if (!check_cursor(self)) {
1041 return NULL;
1042 }
1043
1044 size_t sql_len = strlen(sql_script);
1045 int max_length = sqlite3_limit(self->connection->db,
1046 SQLITE_LIMIT_SQL_LENGTH, -1);
1047 if (sql_len > (unsigned)max_length) {
1048 PyErr_SetString(self->connection->DataError,
1049 "query string is too large");
1050 return NULL;
1051 }
1052
1053 // Commit if needed
1054 sqlite3 *db = self->connection->db;
1055 if (!sqlite3_get_autocommit(db)) {
1056 int rc = SQLITE_OK;
1057
1058 Py_BEGIN_ALLOW_THREADS
1059 rc = sqlite3_exec(db, "COMMIT", NULL, NULL, NULL);
1060 Py_END_ALLOW_THREADS
1061
1062 if (rc != SQLITE_OK) {
1063 goto error;
1064 }
1065 }
1066
1067 while (1) {
1068 int rc;
1069 const char *tail;
1070
1071 Py_BEGIN_ALLOW_THREADS
1072 sqlite3_stmt *stmt;
1073 rc = sqlite3_prepare_v2(db, sql_script, (int)sql_len + 1, &stmt,
1074 &tail);
1075 if (rc == SQLITE_OK) {
1076 do {
1077 rc = sqlite3_step(stmt);
1078 } while (rc == SQLITE_ROW);
1079 rc = sqlite3_finalize(stmt);
1080 }
1081 Py_END_ALLOW_THREADS
1082
1083 if (rc != SQLITE_OK) {
1084 goto error;
1085 }
1086
1087 if (*tail == (char)0) {
1088 break;
1089 }
1090 sql_len -= (tail - sql_script);
1091 sql_script = tail;
1092 }
1093
1094 return Py_NewRef((PyObject *)self);
1095
1096 error:
1097 _pysqlite_seterror(self->connection->state, db);
1098 return NULL;
1099 }
1100
1101 static PyObject *
pysqlite_cursor_iternext(pysqlite_Cursor * self)1102 pysqlite_cursor_iternext(pysqlite_Cursor *self)
1103 {
1104 if (!check_cursor(self)) {
1105 return NULL;
1106 }
1107
1108 if (self->statement == NULL) {
1109 return NULL;
1110 }
1111
1112 sqlite3_stmt *stmt = self->statement->st;
1113 assert(stmt != NULL);
1114 if (sqlite3_data_count(stmt) == 0) {
1115 (void)stmt_reset(self->statement);
1116 Py_CLEAR(self->statement);
1117 return NULL;
1118 }
1119
1120 self->locked = 1; // GH-80254: Prevent recursive use of cursors.
1121 PyObject *row = _pysqlite_fetch_one_row(self);
1122 self->locked = 0;
1123 if (row == NULL) {
1124 return NULL;
1125 }
1126 int rc = stmt_step(stmt);
1127 if (rc == SQLITE_DONE) {
1128 if (self->statement->is_dml) {
1129 self->rowcount = (long)sqlite3_changes(self->connection->db);
1130 }
1131 (void)stmt_reset(self->statement);
1132 Py_CLEAR(self->statement);
1133 }
1134 else if (rc != SQLITE_ROW) {
1135 (void)_pysqlite_seterror(self->connection->state,
1136 self->connection->db);
1137 (void)stmt_reset(self->statement);
1138 Py_CLEAR(self->statement);
1139 Py_DECREF(row);
1140 return NULL;
1141 }
1142 if (!Py_IsNone(self->row_factory)) {
1143 PyObject *factory = self->row_factory;
1144 PyObject *args[] = { (PyObject *)self, row, };
1145 PyObject *new_row = PyObject_Vectorcall(factory, args, 2, NULL);
1146 Py_DECREF(row);
1147 row = new_row;
1148 }
1149 return row;
1150 }
1151
1152 /*[clinic input]
1153 _sqlite3.Cursor.fetchone as pysqlite_cursor_fetchone
1154
1155 Fetches one row from the resultset.
1156 [clinic start generated code]*/
1157
1158 static PyObject *
pysqlite_cursor_fetchone_impl(pysqlite_Cursor * self)1159 pysqlite_cursor_fetchone_impl(pysqlite_Cursor *self)
1160 /*[clinic end generated code: output=4bd2eabf5baaddb0 input=e78294ec5980fdba]*/
1161 {
1162 PyObject* row;
1163
1164 row = pysqlite_cursor_iternext(self);
1165 if (!row && !PyErr_Occurred()) {
1166 Py_RETURN_NONE;
1167 }
1168
1169 return row;
1170 }
1171
1172 /*[clinic input]
1173 _sqlite3.Cursor.fetchmany as pysqlite_cursor_fetchmany
1174
1175 size as maxrows: int(c_default='self->arraysize') = 1
1176 The default value is set by the Cursor.arraysize attribute.
1177
1178 Fetches several rows from the resultset.
1179 [clinic start generated code]*/
1180
1181 static PyObject *
pysqlite_cursor_fetchmany_impl(pysqlite_Cursor * self,int maxrows)1182 pysqlite_cursor_fetchmany_impl(pysqlite_Cursor *self, int maxrows)
1183 /*[clinic end generated code: output=a8ef31fea64d0906 input=c26e6ca3f34debd0]*/
1184 {
1185 PyObject* row;
1186 PyObject* list;
1187 int counter = 0;
1188
1189 list = PyList_New(0);
1190 if (!list) {
1191 return NULL;
1192 }
1193
1194 while ((row = pysqlite_cursor_iternext(self))) {
1195 if (PyList_Append(list, row) < 0) {
1196 Py_DECREF(row);
1197 break;
1198 }
1199 Py_DECREF(row);
1200
1201 if (++counter == maxrows) {
1202 break;
1203 }
1204 }
1205
1206 if (PyErr_Occurred()) {
1207 Py_DECREF(list);
1208 return NULL;
1209 } else {
1210 return list;
1211 }
1212 }
1213
1214 /*[clinic input]
1215 _sqlite3.Cursor.fetchall as pysqlite_cursor_fetchall
1216
1217 Fetches all rows from the resultset.
1218 [clinic start generated code]*/
1219
1220 static PyObject *
pysqlite_cursor_fetchall_impl(pysqlite_Cursor * self)1221 pysqlite_cursor_fetchall_impl(pysqlite_Cursor *self)
1222 /*[clinic end generated code: output=d5da12aca2da4b27 input=f5d401086a8df25a]*/
1223 {
1224 PyObject* row;
1225 PyObject* list;
1226
1227 list = PyList_New(0);
1228 if (!list) {
1229 return NULL;
1230 }
1231
1232 while ((row = pysqlite_cursor_iternext(self))) {
1233 if (PyList_Append(list, row) < 0) {
1234 Py_DECREF(row);
1235 break;
1236 }
1237 Py_DECREF(row);
1238 }
1239
1240 if (PyErr_Occurred()) {
1241 Py_DECREF(list);
1242 return NULL;
1243 } else {
1244 return list;
1245 }
1246 }
1247
1248 /*[clinic input]
1249 _sqlite3.Cursor.setinputsizes as pysqlite_cursor_setinputsizes
1250
1251 sizes: object
1252 /
1253
1254 Required by DB-API. Does nothing in sqlite3.
1255 [clinic start generated code]*/
1256
1257 static PyObject *
pysqlite_cursor_setinputsizes(pysqlite_Cursor * self,PyObject * sizes)1258 pysqlite_cursor_setinputsizes(pysqlite_Cursor *self, PyObject *sizes)
1259 /*[clinic end generated code: output=893c817afe9d08ad input=de7950a3aec79bdf]*/
1260 {
1261 Py_RETURN_NONE;
1262 }
1263
1264 /*[clinic input]
1265 _sqlite3.Cursor.setoutputsize as pysqlite_cursor_setoutputsize
1266
1267 size: object
1268 column: object = None
1269 /
1270
1271 Required by DB-API. Does nothing in sqlite3.
1272 [clinic start generated code]*/
1273
1274 static PyObject *
pysqlite_cursor_setoutputsize_impl(pysqlite_Cursor * self,PyObject * size,PyObject * column)1275 pysqlite_cursor_setoutputsize_impl(pysqlite_Cursor *self, PyObject *size,
1276 PyObject *column)
1277 /*[clinic end generated code: output=018d7e9129d45efe input=607a6bece8bbb273]*/
1278 {
1279 Py_RETURN_NONE;
1280 }
1281
1282 /*[clinic input]
1283 _sqlite3.Cursor.close as pysqlite_cursor_close
1284
1285 Closes the cursor.
1286 [clinic start generated code]*/
1287
1288 static PyObject *
pysqlite_cursor_close_impl(pysqlite_Cursor * self)1289 pysqlite_cursor_close_impl(pysqlite_Cursor *self)
1290 /*[clinic end generated code: output=b6055e4ec6fe63b6 input=08b36552dbb9a986]*/
1291 {
1292 if (!check_cursor_locked(self)) {
1293 return NULL;
1294 }
1295
1296 if (!self->connection) {
1297 PyTypeObject *tp = Py_TYPE(self);
1298 pysqlite_state *state = pysqlite_get_state_by_type(tp);
1299 PyErr_SetString(state->ProgrammingError,
1300 "Base Cursor.__init__ not called.");
1301 return NULL;
1302 }
1303 if (!pysqlite_check_thread(self->connection) || !pysqlite_check_connection(self->connection)) {
1304 return NULL;
1305 }
1306
1307 if (self->statement) {
1308 (void)stmt_reset(self->statement);
1309 Py_CLEAR(self->statement);
1310 }
1311
1312 self->closed = 1;
1313
1314 Py_RETURN_NONE;
1315 }
1316
1317 static PyMethodDef cursor_methods[] = {
1318 PYSQLITE_CURSOR_CLOSE_METHODDEF
1319 PYSQLITE_CURSOR_EXECUTEMANY_METHODDEF
1320 PYSQLITE_CURSOR_EXECUTESCRIPT_METHODDEF
1321 PYSQLITE_CURSOR_EXECUTE_METHODDEF
1322 PYSQLITE_CURSOR_FETCHALL_METHODDEF
1323 PYSQLITE_CURSOR_FETCHMANY_METHODDEF
1324 PYSQLITE_CURSOR_FETCHONE_METHODDEF
1325 PYSQLITE_CURSOR_SETINPUTSIZES_METHODDEF
1326 PYSQLITE_CURSOR_SETOUTPUTSIZE_METHODDEF
1327 {NULL, NULL}
1328 };
1329
1330 static struct PyMemberDef cursor_members[] =
1331 {
1332 {"connection", T_OBJECT, offsetof(pysqlite_Cursor, connection), READONLY},
1333 {"description", T_OBJECT, offsetof(pysqlite_Cursor, description), READONLY},
1334 {"arraysize", T_INT, offsetof(pysqlite_Cursor, arraysize), 0},
1335 {"lastrowid", T_OBJECT, offsetof(pysqlite_Cursor, lastrowid), READONLY},
1336 {"rowcount", T_LONG, offsetof(pysqlite_Cursor, rowcount), READONLY},
1337 {"row_factory", T_OBJECT, offsetof(pysqlite_Cursor, row_factory), 0},
1338 {"__weaklistoffset__", T_PYSSIZET, offsetof(pysqlite_Cursor, in_weakreflist), READONLY},
1339 {NULL}
1340 };
1341
1342 static const char cursor_doc[] =
1343 PyDoc_STR("SQLite database cursor class.");
1344
1345 static PyType_Slot cursor_slots[] = {
1346 {Py_tp_dealloc, cursor_dealloc},
1347 {Py_tp_doc, (void *)cursor_doc},
1348 {Py_tp_iter, PyObject_SelfIter},
1349 {Py_tp_iternext, pysqlite_cursor_iternext},
1350 {Py_tp_methods, cursor_methods},
1351 {Py_tp_members, cursor_members},
1352 {Py_tp_init, pysqlite_cursor_init},
1353 {Py_tp_traverse, cursor_traverse},
1354 {Py_tp_clear, cursor_clear},
1355 {0, NULL},
1356 };
1357
1358 static PyType_Spec cursor_spec = {
1359 .name = MODULE_NAME ".Cursor",
1360 .basicsize = sizeof(pysqlite_Cursor),
1361 .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
1362 Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_IMMUTABLETYPE),
1363 .slots = cursor_slots,
1364 };
1365
1366 int
pysqlite_cursor_setup_types(PyObject * module)1367 pysqlite_cursor_setup_types(PyObject *module)
1368 {
1369 PyObject *type = PyType_FromModuleAndSpec(module, &cursor_spec, NULL);
1370 if (type == NULL) {
1371 return -1;
1372 }
1373 pysqlite_state *state = pysqlite_get_state(module);
1374 state->CursorType = (PyTypeObject *)type;
1375 return 0;
1376 }
1377