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