Coverage Report

Created: 2022-07-08 00:21

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