Debian Codegraph @

Modules/_sqlite/cursor.c

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