»Core Development>Code coverage>Modules/_sqlite/connection.c

Python code coverage for Modules/_sqlite/connection.c

#countcontent
1n/a/* connection.c - the connection type
2n/a *
3n/a * Copyright (C) 2004-2010 Gerhard Häring <gh@ghaering.de>
4n/a *
5n/a * This file is part of pysqlite.
6n/a *
7n/a * This software is provided 'as-is', without any express or implied
8n/a * warranty. In no event will the authors be held liable for any damages
9n/a * arising from the use of this software.
10n/a *
11n/a * Permission is granted to anyone to use this software for any purpose,
12n/a * including commercial applications, and to alter it and redistribute it
13n/a * freely, subject to the following restrictions:
14n/a *
15n/a * 1. The origin of this software must not be misrepresented; you must not
16n/a * claim that you wrote the original software. If you use this software
17n/a * in a product, an acknowledgment in the product documentation would be
18n/a * appreciated but is not required.
19n/a * 2. Altered source versions must be plainly marked as such, and must not be
20n/a * misrepresented as being the original software.
21n/a * 3. This notice may not be removed or altered from any source distribution.
22n/a */
23n/a
24n/a#include "cache.h"
25n/a#include "module.h"
26n/a#include "structmember.h"
27n/a#include "connection.h"
28n/a#include "statement.h"
29n/a#include "cursor.h"
30n/a#include "prepare_protocol.h"
31n/a#include "util.h"
32n/a
33n/a#include "pythread.h"
34n/a
35n/a#define ACTION_FINALIZE 1
36n/a#define ACTION_RESET 2
37n/a
38n/a#if SQLITE_VERSION_NUMBER >= 3003008
39n/a#ifndef SQLITE_OMIT_LOAD_EXTENSION
40n/a#define HAVE_LOAD_EXTENSION
41n/a#endif
42n/a#endif
43n/a
44n/a_Py_IDENTIFIER(cursor);
45n/a
46n/astatic const char * const begin_statements[] = {
47n/a "BEGIN ",
48n/a "BEGIN DEFERRED",
49n/a "BEGIN IMMEDIATE",
50n/a "BEGIN EXCLUSIVE",
51n/a NULL
52n/a};
53n/a
54n/astatic int pysqlite_connection_set_isolation_level(pysqlite_Connection* self, PyObject* isolation_level);
55n/astatic void _pysqlite_drop_unused_cursor_references(pysqlite_Connection* self);
56n/a
57n/a
58n/astatic void _sqlite3_result_error(sqlite3_context* ctx, const char* errmsg, int len)
59n/a{
60n/a /* in older SQLite versions, calling sqlite3_result_error in callbacks
61n/a * triggers a bug in SQLite that leads either to irritating results or
62n/a * segfaults, depending on the SQLite version */
63n/a#if SQLITE_VERSION_NUMBER >= 3003003
64n/a sqlite3_result_error(ctx, errmsg, len);
65n/a#else
66n/a PyErr_SetString(pysqlite_OperationalError, errmsg);
67n/a#endif
68n/a}
69n/a
70n/aint pysqlite_connection_init(pysqlite_Connection* self, PyObject* args, PyObject* kwargs)
71n/a{
72n/a static char *kwlist[] = {
73n/a "database", "timeout", "detect_types", "isolation_level",
74n/a "check_same_thread", "factory", "cached_statements", "uri",
75n/a NULL
76n/a };
77n/a
78n/a char* database;
79n/a int detect_types = 0;
80n/a PyObject* isolation_level = NULL;
81n/a PyObject* factory = NULL;
82n/a int check_same_thread = 1;
83n/a int cached_statements = 100;
84n/a int uri = 0;
85n/a double timeout = 5.0;
86n/a int rc;
87n/a
88n/a if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s|diOiOip", kwlist,
89n/a &database, &timeout, &detect_types,
90n/a &isolation_level, &check_same_thread,
91n/a &factory, &cached_statements, &uri))
92n/a {
93n/a return -1;
94n/a }
95n/a
96n/a self->initialized = 1;
97n/a
98n/a self->begin_statement = NULL;
99n/a
100n/a self->statement_cache = NULL;
101n/a self->statements = NULL;
102n/a self->cursors = NULL;
103n/a
104n/a Py_INCREF(Py_None);
105n/a self->row_factory = Py_None;
106n/a
107n/a Py_INCREF(&PyUnicode_Type);
108n/a self->text_factory = (PyObject*)&PyUnicode_Type;
109n/a
110n/a#ifdef SQLITE_OPEN_URI
111n/a Py_BEGIN_ALLOW_THREADS
112n/a rc = sqlite3_open_v2(database, &self->db,
113n/a SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
114n/a (uri ? SQLITE_OPEN_URI : 0), NULL);
115n/a#else
116n/a if (uri) {
117n/a PyErr_SetString(pysqlite_NotSupportedError, "URIs not supported");
118n/a return -1;
119n/a }
120n/a Py_BEGIN_ALLOW_THREADS
121n/a rc = sqlite3_open(database, &self->db);
122n/a#endif
123n/a Py_END_ALLOW_THREADS
124n/a
125n/a if (rc != SQLITE_OK) {
126n/a _pysqlite_seterror(self->db, NULL);
127n/a return -1;
128n/a }
129n/a
130n/a if (!isolation_level) {
131n/a isolation_level = PyUnicode_FromString("");
132n/a if (!isolation_level) {
133n/a return -1;
134n/a }
135n/a } else {
136n/a Py_INCREF(isolation_level);
137n/a }
138n/a self->isolation_level = NULL;
139n/a if (pysqlite_connection_set_isolation_level(self, isolation_level) < 0) {
140n/a Py_DECREF(isolation_level);
141n/a return -1;
142n/a }
143n/a Py_DECREF(isolation_level);
144n/a
145n/a self->statement_cache = (pysqlite_Cache*)PyObject_CallFunction((PyObject*)&pysqlite_CacheType, "Oi", self, cached_statements);
146n/a if (PyErr_Occurred()) {
147n/a return -1;
148n/a }
149n/a
150n/a self->created_statements = 0;
151n/a self->created_cursors = 0;
152n/a
153n/a /* Create lists of weak references to statements/cursors */
154n/a self->statements = PyList_New(0);
155n/a self->cursors = PyList_New(0);
156n/a if (!self->statements || !self->cursors) {
157n/a return -1;
158n/a }
159n/a
160n/a /* By default, the Cache class INCREFs the factory in its initializer, and
161n/a * decrefs it in its deallocator method. Since this would create a circular
162n/a * reference here, we're breaking it by decrementing self, and telling the
163n/a * cache class to not decref the factory (self) in its deallocator.
164n/a */
165n/a self->statement_cache->decref_factory = 0;
166n/a Py_DECREF(self);
167n/a
168n/a self->detect_types = detect_types;
169n/a self->timeout = timeout;
170n/a (void)sqlite3_busy_timeout(self->db, (int)(timeout*1000));
171n/a#ifdef WITH_THREAD
172n/a self->thread_ident = PyThread_get_thread_ident();
173n/a#endif
174n/a if (!check_same_thread && sqlite3_libversion_number() < 3003001) {
175n/a PyErr_SetString(pysqlite_NotSupportedError, "shared connections not available");
176n/a return -1;
177n/a }
178n/a self->check_same_thread = check_same_thread;
179n/a
180n/a self->function_pinboard = PyDict_New();
181n/a if (!self->function_pinboard) {
182n/a return -1;
183n/a }
184n/a
185n/a self->collations = PyDict_New();
186n/a if (!self->collations) {
187n/a return -1;
188n/a }
189n/a
190n/a self->Warning = pysqlite_Warning;
191n/a self->Error = pysqlite_Error;
192n/a self->InterfaceError = pysqlite_InterfaceError;
193n/a self->DatabaseError = pysqlite_DatabaseError;
194n/a self->DataError = pysqlite_DataError;
195n/a self->OperationalError = pysqlite_OperationalError;
196n/a self->IntegrityError = pysqlite_IntegrityError;
197n/a self->InternalError = pysqlite_InternalError;
198n/a self->ProgrammingError = pysqlite_ProgrammingError;
199n/a self->NotSupportedError = pysqlite_NotSupportedError;
200n/a
201n/a return 0;
202n/a}
203n/a
204n/a/* action in (ACTION_RESET, ACTION_FINALIZE) */
205n/avoid pysqlite_do_all_statements(pysqlite_Connection* self, int action, int reset_cursors)
206n/a{
207n/a int i;
208n/a PyObject* weakref;
209n/a PyObject* statement;
210n/a pysqlite_Cursor* cursor;
211n/a
212n/a for (i = 0; i < PyList_Size(self->statements); i++) {
213n/a weakref = PyList_GetItem(self->statements, i);
214n/a statement = PyWeakref_GetObject(weakref);
215n/a if (statement != Py_None) {
216n/a Py_INCREF(statement);
217n/a if (action == ACTION_RESET) {
218n/a (void)pysqlite_statement_reset((pysqlite_Statement*)statement);
219n/a } else {
220n/a (void)pysqlite_statement_finalize((pysqlite_Statement*)statement);
221n/a }
222n/a Py_DECREF(statement);
223n/a }
224n/a }
225n/a
226n/a if (reset_cursors) {
227n/a for (i = 0; i < PyList_Size(self->cursors); i++) {
228n/a weakref = PyList_GetItem(self->cursors, i);
229n/a cursor = (pysqlite_Cursor*)PyWeakref_GetObject(weakref);
230n/a if ((PyObject*)cursor != Py_None) {
231n/a cursor->reset = 1;
232n/a }
233n/a }
234n/a }
235n/a}
236n/a
237n/avoid pysqlite_connection_dealloc(pysqlite_Connection* self)
238n/a{
239n/a Py_XDECREF(self->statement_cache);
240n/a
241n/a /* Clean up if user has not called .close() explicitly. */
242n/a if (self->db) {
243n/a Py_BEGIN_ALLOW_THREADS
244n/a sqlite3_close(self->db);
245n/a Py_END_ALLOW_THREADS
246n/a }
247n/a
248n/a Py_XDECREF(self->isolation_level);
249n/a Py_XDECREF(self->function_pinboard);
250n/a Py_XDECREF(self->row_factory);
251n/a Py_XDECREF(self->text_factory);
252n/a Py_XDECREF(self->collations);
253n/a Py_XDECREF(self->statements);
254n/a Py_XDECREF(self->cursors);
255n/a
256n/a Py_TYPE(self)->tp_free((PyObject*)self);
257n/a}
258n/a
259n/a/*
260n/a * Registers a cursor with the connection.
261n/a *
262n/a * 0 => error; 1 => ok
263n/a */
264n/aint pysqlite_connection_register_cursor(pysqlite_Connection* connection, PyObject* cursor)
265n/a{
266n/a PyObject* weakref;
267n/a
268n/a weakref = PyWeakref_NewRef((PyObject*)cursor, NULL);
269n/a if (!weakref) {
270n/a goto error;
271n/a }
272n/a
273n/a if (PyList_Append(connection->cursors, weakref) != 0) {
274n/a Py_CLEAR(weakref);
275n/a goto error;
276n/a }
277n/a
278n/a Py_DECREF(weakref);
279n/a
280n/a return 1;
281n/aerror:
282n/a return 0;
283n/a}
284n/a
285n/aPyObject* pysqlite_connection_cursor(pysqlite_Connection* self, PyObject* args, PyObject* kwargs)
286n/a{
287n/a static char *kwlist[] = {"factory", NULL};
288n/a PyObject* factory = NULL;
289n/a PyObject* cursor;
290n/a
291n/a if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|O", kwlist,
292n/a &factory)) {
293n/a return NULL;
294n/a }
295n/a
296n/a if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
297n/a return NULL;
298n/a }
299n/a
300n/a if (factory == NULL) {
301n/a factory = (PyObject*)&pysqlite_CursorType;
302n/a }
303n/a
304n/a cursor = PyObject_CallFunctionObjArgs(factory, (PyObject *)self, NULL);
305n/a if (cursor == NULL)
306n/a return NULL;
307n/a if (!PyObject_TypeCheck(cursor, &pysqlite_CursorType)) {
308n/a PyErr_Format(PyExc_TypeError,
309n/a "factory must return a cursor, not %.100s",
310n/a Py_TYPE(cursor)->tp_name);
311n/a Py_DECREF(cursor);
312n/a return NULL;
313n/a }
314n/a
315n/a _pysqlite_drop_unused_cursor_references(self);
316n/a
317n/a if (cursor && self->row_factory != Py_None) {
318n/a Py_INCREF(self->row_factory);
319n/a Py_XSETREF(((pysqlite_Cursor *)cursor)->row_factory, self->row_factory);
320n/a }
321n/a
322n/a return cursor;
323n/a}
324n/a
325n/aPyObject* pysqlite_connection_close(pysqlite_Connection* self, PyObject* args)
326n/a{
327n/a int rc;
328n/a
329n/a if (!pysqlite_check_thread(self)) {
330n/a return NULL;
331n/a }
332n/a
333n/a pysqlite_do_all_statements(self, ACTION_FINALIZE, 1);
334n/a
335n/a if (self->db) {
336n/a Py_BEGIN_ALLOW_THREADS
337n/a rc = sqlite3_close(self->db);
338n/a Py_END_ALLOW_THREADS
339n/a
340n/a if (rc != SQLITE_OK) {
341n/a _pysqlite_seterror(self->db, NULL);
342n/a return NULL;
343n/a } else {
344n/a self->db = NULL;
345n/a }
346n/a }
347n/a
348n/a Py_RETURN_NONE;
349n/a}
350n/a
351n/a/*
352n/a * Checks if a connection object is usable (i. e. not closed).
353n/a *
354n/a * 0 => error; 1 => ok
355n/a */
356n/aint pysqlite_check_connection(pysqlite_Connection* con)
357n/a{
358n/a if (!con->initialized) {
359n/a PyErr_SetString(pysqlite_ProgrammingError, "Base Connection.__init__ not called.");
360n/a return 0;
361n/a }
362n/a
363n/a if (!con->db) {
364n/a PyErr_SetString(pysqlite_ProgrammingError, "Cannot operate on a closed database.");
365n/a return 0;
366n/a } else {
367n/a return 1;
368n/a }
369n/a}
370n/a
371n/aPyObject* _pysqlite_connection_begin(pysqlite_Connection* self)
372n/a{
373n/a int rc;
374n/a const char* tail;
375n/a sqlite3_stmt* statement;
376n/a
377n/a Py_BEGIN_ALLOW_THREADS
378n/a rc = sqlite3_prepare(self->db, self->begin_statement, -1, &statement, &tail);
379n/a Py_END_ALLOW_THREADS
380n/a
381n/a if (rc != SQLITE_OK) {
382n/a _pysqlite_seterror(self->db, statement);
383n/a goto error;
384n/a }
385n/a
386n/a rc = pysqlite_step(statement, self);
387n/a if (rc != SQLITE_DONE) {
388n/a _pysqlite_seterror(self->db, statement);
389n/a }
390n/a
391n/a Py_BEGIN_ALLOW_THREADS
392n/a rc = sqlite3_finalize(statement);
393n/a Py_END_ALLOW_THREADS
394n/a
395n/a if (rc != SQLITE_OK && !PyErr_Occurred()) {
396n/a _pysqlite_seterror(self->db, NULL);
397n/a }
398n/a
399n/aerror:
400n/a if (PyErr_Occurred()) {
401n/a return NULL;
402n/a } else {
403n/a Py_RETURN_NONE;
404n/a }
405n/a}
406n/a
407n/aPyObject* pysqlite_connection_commit(pysqlite_Connection* self, PyObject* args)
408n/a{
409n/a int rc;
410n/a const char* tail;
411n/a sqlite3_stmt* statement;
412n/a
413n/a if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
414n/a return NULL;
415n/a }
416n/a
417n/a if (!sqlite3_get_autocommit(self->db)) {
418n/a
419n/a Py_BEGIN_ALLOW_THREADS
420n/a rc = sqlite3_prepare(self->db, "COMMIT", -1, &statement, &tail);
421n/a Py_END_ALLOW_THREADS
422n/a if (rc != SQLITE_OK) {
423n/a _pysqlite_seterror(self->db, NULL);
424n/a goto error;
425n/a }
426n/a
427n/a rc = pysqlite_step(statement, self);
428n/a if (rc != SQLITE_DONE) {
429n/a _pysqlite_seterror(self->db, statement);
430n/a }
431n/a
432n/a Py_BEGIN_ALLOW_THREADS
433n/a rc = sqlite3_finalize(statement);
434n/a Py_END_ALLOW_THREADS
435n/a if (rc != SQLITE_OK && !PyErr_Occurred()) {
436n/a _pysqlite_seterror(self->db, NULL);
437n/a }
438n/a
439n/a }
440n/a
441n/aerror:
442n/a if (PyErr_Occurred()) {
443n/a return NULL;
444n/a } else {
445n/a Py_RETURN_NONE;
446n/a }
447n/a}
448n/a
449n/aPyObject* pysqlite_connection_rollback(pysqlite_Connection* self, PyObject* args)
450n/a{
451n/a int rc;
452n/a const char* tail;
453n/a sqlite3_stmt* statement;
454n/a
455n/a if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
456n/a return NULL;
457n/a }
458n/a
459n/a if (!sqlite3_get_autocommit(self->db)) {
460n/a pysqlite_do_all_statements(self, ACTION_RESET, 1);
461n/a
462n/a Py_BEGIN_ALLOW_THREADS
463n/a rc = sqlite3_prepare(self->db, "ROLLBACK", -1, &statement, &tail);
464n/a Py_END_ALLOW_THREADS
465n/a if (rc != SQLITE_OK) {
466n/a _pysqlite_seterror(self->db, NULL);
467n/a goto error;
468n/a }
469n/a
470n/a rc = pysqlite_step(statement, self);
471n/a if (rc != SQLITE_DONE) {
472n/a _pysqlite_seterror(self->db, statement);
473n/a }
474n/a
475n/a Py_BEGIN_ALLOW_THREADS
476n/a rc = sqlite3_finalize(statement);
477n/a Py_END_ALLOW_THREADS
478n/a if (rc != SQLITE_OK && !PyErr_Occurred()) {
479n/a _pysqlite_seterror(self->db, NULL);
480n/a }
481n/a
482n/a }
483n/a
484n/aerror:
485n/a if (PyErr_Occurred()) {
486n/a return NULL;
487n/a } else {
488n/a Py_RETURN_NONE;
489n/a }
490n/a}
491n/a
492n/astatic int
493n/a_pysqlite_set_result(sqlite3_context* context, PyObject* py_val)
494n/a{
495n/a if (py_val == Py_None) {
496n/a sqlite3_result_null(context);
497n/a } else if (PyLong_Check(py_val)) {
498n/a sqlite_int64 value = _pysqlite_long_as_int64(py_val);
499n/a if (value == -1 && PyErr_Occurred())
500n/a return -1;
501n/a sqlite3_result_int64(context, value);
502n/a } else if (PyFloat_Check(py_val)) {
503n/a sqlite3_result_double(context, PyFloat_AsDouble(py_val));
504n/a } else if (PyUnicode_Check(py_val)) {
505n/a const char *str = PyUnicode_AsUTF8(py_val);
506n/a if (str == NULL)
507n/a return -1;
508n/a sqlite3_result_text(context, str, -1, SQLITE_TRANSIENT);
509n/a } else if (PyObject_CheckBuffer(py_val)) {
510n/a Py_buffer view;
511n/a if (PyObject_GetBuffer(py_val, &view, PyBUF_SIMPLE) != 0) {
512n/a PyErr_SetString(PyExc_ValueError,
513n/a "could not convert BLOB to buffer");
514n/a return -1;
515n/a }
516n/a if (view.len > INT_MAX) {
517n/a PyErr_SetString(PyExc_OverflowError,
518n/a "BLOB longer than INT_MAX bytes");
519n/a PyBuffer_Release(&view);
520n/a return -1;
521n/a }
522n/a sqlite3_result_blob(context, view.buf, (int)view.len, SQLITE_TRANSIENT);
523n/a PyBuffer_Release(&view);
524n/a } else {
525n/a return -1;
526n/a }
527n/a return 0;
528n/a}
529n/a
530n/aPyObject* _pysqlite_build_py_params(sqlite3_context *context, int argc, sqlite3_value** argv)
531n/a{
532n/a PyObject* args;
533n/a int i;
534n/a sqlite3_value* cur_value;
535n/a PyObject* cur_py_value;
536n/a const char* val_str;
537n/a Py_ssize_t buflen;
538n/a
539n/a args = PyTuple_New(argc);
540n/a if (!args) {
541n/a return NULL;
542n/a }
543n/a
544n/a for (i = 0; i < argc; i++) {
545n/a cur_value = argv[i];
546n/a switch (sqlite3_value_type(argv[i])) {
547n/a case SQLITE_INTEGER:
548n/a cur_py_value = _pysqlite_long_from_int64(sqlite3_value_int64(cur_value));
549n/a break;
550n/a case SQLITE_FLOAT:
551n/a cur_py_value = PyFloat_FromDouble(sqlite3_value_double(cur_value));
552n/a break;
553n/a case SQLITE_TEXT:
554n/a val_str = (const char*)sqlite3_value_text(cur_value);
555n/a cur_py_value = PyUnicode_FromString(val_str);
556n/a /* TODO: have a way to show errors here */
557n/a if (!cur_py_value) {
558n/a PyErr_Clear();
559n/a Py_INCREF(Py_None);
560n/a cur_py_value = Py_None;
561n/a }
562n/a break;
563n/a case SQLITE_BLOB:
564n/a buflen = sqlite3_value_bytes(cur_value);
565n/a cur_py_value = PyBytes_FromStringAndSize(
566n/a sqlite3_value_blob(cur_value), buflen);
567n/a break;
568n/a case SQLITE_NULL:
569n/a default:
570n/a Py_INCREF(Py_None);
571n/a cur_py_value = Py_None;
572n/a }
573n/a
574n/a if (!cur_py_value) {
575n/a Py_DECREF(args);
576n/a return NULL;
577n/a }
578n/a
579n/a PyTuple_SetItem(args, i, cur_py_value);
580n/a
581n/a }
582n/a
583n/a return args;
584n/a}
585n/a
586n/avoid _pysqlite_func_callback(sqlite3_context* context, int argc, sqlite3_value** argv)
587n/a{
588n/a PyObject* args;
589n/a PyObject* py_func;
590n/a PyObject* py_retval = NULL;
591n/a int ok;
592n/a
593n/a#ifdef WITH_THREAD
594n/a PyGILState_STATE threadstate;
595n/a
596n/a threadstate = PyGILState_Ensure();
597n/a#endif
598n/a
599n/a py_func = (PyObject*)sqlite3_user_data(context);
600n/a
601n/a args = _pysqlite_build_py_params(context, argc, argv);
602n/a if (args) {
603n/a py_retval = PyObject_CallObject(py_func, args);
604n/a Py_DECREF(args);
605n/a }
606n/a
607n/a ok = 0;
608n/a if (py_retval) {
609n/a ok = _pysqlite_set_result(context, py_retval) == 0;
610n/a Py_DECREF(py_retval);
611n/a }
612n/a if (!ok) {
613n/a if (_enable_callback_tracebacks) {
614n/a PyErr_Print();
615n/a } else {
616n/a PyErr_Clear();
617n/a }
618n/a _sqlite3_result_error(context, "user-defined function raised exception", -1);
619n/a }
620n/a
621n/a#ifdef WITH_THREAD
622n/a PyGILState_Release(threadstate);
623n/a#endif
624n/a}
625n/a
626n/astatic void _pysqlite_step_callback(sqlite3_context *context, int argc, sqlite3_value** params)
627n/a{
628n/a PyObject* args;
629n/a PyObject* function_result = NULL;
630n/a PyObject* aggregate_class;
631n/a PyObject** aggregate_instance;
632n/a PyObject* stepmethod = NULL;
633n/a
634n/a#ifdef WITH_THREAD
635n/a PyGILState_STATE threadstate;
636n/a
637n/a threadstate = PyGILState_Ensure();
638n/a#endif
639n/a
640n/a aggregate_class = (PyObject*)sqlite3_user_data(context);
641n/a
642n/a aggregate_instance = (PyObject**)sqlite3_aggregate_context(context, sizeof(PyObject*));
643n/a
644n/a if (*aggregate_instance == 0) {
645n/a *aggregate_instance = _PyObject_CallNoArg(aggregate_class);
646n/a
647n/a if (PyErr_Occurred()) {
648n/a *aggregate_instance = 0;
649n/a if (_enable_callback_tracebacks) {
650n/a PyErr_Print();
651n/a } else {
652n/a PyErr_Clear();
653n/a }
654n/a _sqlite3_result_error(context, "user-defined aggregate's '__init__' method raised error", -1);
655n/a goto error;
656n/a }
657n/a }
658n/a
659n/a stepmethod = PyObject_GetAttrString(*aggregate_instance, "step");
660n/a if (!stepmethod) {
661n/a goto error;
662n/a }
663n/a
664n/a args = _pysqlite_build_py_params(context, argc, params);
665n/a if (!args) {
666n/a goto error;
667n/a }
668n/a
669n/a function_result = PyObject_CallObject(stepmethod, args);
670n/a Py_DECREF(args);
671n/a
672n/a if (!function_result) {
673n/a if (_enable_callback_tracebacks) {
674n/a PyErr_Print();
675n/a } else {
676n/a PyErr_Clear();
677n/a }
678n/a _sqlite3_result_error(context, "user-defined aggregate's 'step' method raised error", -1);
679n/a }
680n/a
681n/aerror:
682n/a Py_XDECREF(stepmethod);
683n/a Py_XDECREF(function_result);
684n/a
685n/a#ifdef WITH_THREAD
686n/a PyGILState_Release(threadstate);
687n/a#endif
688n/a}
689n/a
690n/avoid _pysqlite_final_callback(sqlite3_context* context)
691n/a{
692n/a PyObject* function_result;
693n/a PyObject** aggregate_instance;
694n/a _Py_IDENTIFIER(finalize);
695n/a int ok;
696n/a PyObject *exception, *value, *tb;
697n/a int restore;
698n/a
699n/a#ifdef WITH_THREAD
700n/a PyGILState_STATE threadstate;
701n/a
702n/a threadstate = PyGILState_Ensure();
703n/a#endif
704n/a
705n/a aggregate_instance = (PyObject**)sqlite3_aggregate_context(context, sizeof(PyObject*));
706n/a if (!*aggregate_instance) {
707n/a /* this branch is executed if there was an exception in the aggregate's
708n/a * __init__ */
709n/a
710n/a goto error;
711n/a }
712n/a
713n/a /* Keep the exception (if any) of the last call to step() */
714n/a PyErr_Fetch(&exception, &value, &tb);
715n/a restore = 1;
716n/a
717n/a function_result = _PyObject_CallMethodId(*aggregate_instance, &PyId_finalize, NULL);
718n/a
719n/a Py_DECREF(*aggregate_instance);
720n/a
721n/a ok = 0;
722n/a if (function_result) {
723n/a ok = _pysqlite_set_result(context, function_result) == 0;
724n/a Py_DECREF(function_result);
725n/a }
726n/a if (!ok) {
727n/a if (_enable_callback_tracebacks) {
728n/a PyErr_Print();
729n/a } else {
730n/a PyErr_Clear();
731n/a }
732n/a _sqlite3_result_error(context, "user-defined aggregate's 'finalize' method raised error", -1);
733n/a#if SQLITE_VERSION_NUMBER < 3003003
734n/a /* with old SQLite versions, _sqlite3_result_error() sets a new Python
735n/a exception, so don't restore the previous exception */
736n/a restore = 0;
737n/a#endif
738n/a }
739n/a
740n/a if (restore) {
741n/a /* Restore the exception (if any) of the last call to step(),
742n/a but clear also the current exception if finalize() failed */
743n/a PyErr_Restore(exception, value, tb);
744n/a }
745n/a
746n/aerror:
747n/a#ifdef WITH_THREAD
748n/a PyGILState_Release(threadstate);
749n/a#endif
750n/a /* explicit return to avoid a compilation error if WITH_THREAD
751n/a is not defined */
752n/a return;
753n/a}
754n/a
755n/astatic void _pysqlite_drop_unused_statement_references(pysqlite_Connection* self)
756n/a{
757n/a PyObject* new_list;
758n/a PyObject* weakref;
759n/a int i;
760n/a
761n/a /* we only need to do this once in a while */
762n/a if (self->created_statements++ < 200) {
763n/a return;
764n/a }
765n/a
766n/a self->created_statements = 0;
767n/a
768n/a new_list = PyList_New(0);
769n/a if (!new_list) {
770n/a return;
771n/a }
772n/a
773n/a for (i = 0; i < PyList_Size(self->statements); i++) {
774n/a weakref = PyList_GetItem(self->statements, i);
775n/a if (PyWeakref_GetObject(weakref) != Py_None) {
776n/a if (PyList_Append(new_list, weakref) != 0) {
777n/a Py_DECREF(new_list);
778n/a return;
779n/a }
780n/a }
781n/a }
782n/a
783n/a Py_SETREF(self->statements, new_list);
784n/a}
785n/a
786n/astatic void _pysqlite_drop_unused_cursor_references(pysqlite_Connection* self)
787n/a{
788n/a PyObject* new_list;
789n/a PyObject* weakref;
790n/a int i;
791n/a
792n/a /* we only need to do this once in a while */
793n/a if (self->created_cursors++ < 200) {
794n/a return;
795n/a }
796n/a
797n/a self->created_cursors = 0;
798n/a
799n/a new_list = PyList_New(0);
800n/a if (!new_list) {
801n/a return;
802n/a }
803n/a
804n/a for (i = 0; i < PyList_Size(self->cursors); i++) {
805n/a weakref = PyList_GetItem(self->cursors, i);
806n/a if (PyWeakref_GetObject(weakref) != Py_None) {
807n/a if (PyList_Append(new_list, weakref) != 0) {
808n/a Py_DECREF(new_list);
809n/a return;
810n/a }
811n/a }
812n/a }
813n/a
814n/a Py_SETREF(self->cursors, new_list);
815n/a}
816n/a
817n/aPyObject* pysqlite_connection_create_function(pysqlite_Connection* self, PyObject* args, PyObject* kwargs)
818n/a{
819n/a static char *kwlist[] = {"name", "narg", "func", NULL, NULL};
820n/a
821n/a PyObject* func;
822n/a char* name;
823n/a int narg;
824n/a int rc;
825n/a
826n/a if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
827n/a return NULL;
828n/a }
829n/a
830n/a if (!PyArg_ParseTupleAndKeywords(args, kwargs, "siO", kwlist,
831n/a &name, &narg, &func))
832n/a {
833n/a return NULL;
834n/a }
835n/a
836n/a rc = sqlite3_create_function(self->db, name, narg, SQLITE_UTF8, (void*)func, _pysqlite_func_callback, NULL, NULL);
837n/a
838n/a if (rc != SQLITE_OK) {
839n/a /* Workaround for SQLite bug: no error code or string is available here */
840n/a PyErr_SetString(pysqlite_OperationalError, "Error creating function");
841n/a return NULL;
842n/a } else {
843n/a if (PyDict_SetItem(self->function_pinboard, func, Py_None) == -1)
844n/a return NULL;
845n/a
846n/a Py_RETURN_NONE;
847n/a }
848n/a}
849n/a
850n/aPyObject* pysqlite_connection_create_aggregate(pysqlite_Connection* self, PyObject* args, PyObject* kwargs)
851n/a{
852n/a PyObject* aggregate_class;
853n/a
854n/a int n_arg;
855n/a char* name;
856n/a static char *kwlist[] = { "name", "n_arg", "aggregate_class", NULL };
857n/a int rc;
858n/a
859n/a if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
860n/a return NULL;
861n/a }
862n/a
863n/a if (!PyArg_ParseTupleAndKeywords(args, kwargs, "siO:create_aggregate",
864n/a kwlist, &name, &n_arg, &aggregate_class)) {
865n/a return NULL;
866n/a }
867n/a
868n/a rc = sqlite3_create_function(self->db, name, n_arg, SQLITE_UTF8, (void*)aggregate_class, 0, &_pysqlite_step_callback, &_pysqlite_final_callback);
869n/a if (rc != SQLITE_OK) {
870n/a /* Workaround for SQLite bug: no error code or string is available here */
871n/a PyErr_SetString(pysqlite_OperationalError, "Error creating aggregate");
872n/a return NULL;
873n/a } else {
874n/a if (PyDict_SetItem(self->function_pinboard, aggregate_class, Py_None) == -1)
875n/a return NULL;
876n/a
877n/a Py_RETURN_NONE;
878n/a }
879n/a}
880n/a
881n/astatic int _authorizer_callback(void* user_arg, int action, const char* arg1, const char* arg2 , const char* dbname, const char* access_attempt_source)
882n/a{
883n/a PyObject *ret;
884n/a int rc;
885n/a#ifdef WITH_THREAD
886n/a PyGILState_STATE gilstate;
887n/a
888n/a gilstate = PyGILState_Ensure();
889n/a#endif
890n/a
891n/a ret = PyObject_CallFunction((PyObject*)user_arg, "issss", action, arg1, arg2, dbname, access_attempt_source);
892n/a
893n/a if (ret == NULL) {
894n/a if (_enable_callback_tracebacks)
895n/a PyErr_Print();
896n/a else
897n/a PyErr_Clear();
898n/a
899n/a rc = SQLITE_DENY;
900n/a }
901n/a else {
902n/a if (PyLong_Check(ret)) {
903n/a rc = _PyLong_AsInt(ret);
904n/a if (rc == -1 && PyErr_Occurred()) {
905n/a if (_enable_callback_tracebacks)
906n/a PyErr_Print();
907n/a else
908n/a PyErr_Clear();
909n/a rc = SQLITE_DENY;
910n/a }
911n/a }
912n/a else {
913n/a rc = SQLITE_DENY;
914n/a }
915n/a Py_DECREF(ret);
916n/a }
917n/a
918n/a#ifdef WITH_THREAD
919n/a PyGILState_Release(gilstate);
920n/a#endif
921n/a return rc;
922n/a}
923n/a
924n/astatic int _progress_handler(void* user_arg)
925n/a{
926n/a int rc;
927n/a PyObject *ret;
928n/a#ifdef WITH_THREAD
929n/a PyGILState_STATE gilstate;
930n/a
931n/a gilstate = PyGILState_Ensure();
932n/a#endif
933n/a ret = _PyObject_CallNoArg((PyObject*)user_arg);
934n/a
935n/a if (!ret) {
936n/a if (_enable_callback_tracebacks) {
937n/a PyErr_Print();
938n/a } else {
939n/a PyErr_Clear();
940n/a }
941n/a
942n/a /* abort query if error occurred */
943n/a rc = 1;
944n/a } else {
945n/a rc = (int)PyObject_IsTrue(ret);
946n/a Py_DECREF(ret);
947n/a }
948n/a
949n/a#ifdef WITH_THREAD
950n/a PyGILState_Release(gilstate);
951n/a#endif
952n/a return rc;
953n/a}
954n/a
955n/astatic void _trace_callback(void* user_arg, const char* statement_string)
956n/a{
957n/a PyObject *py_statement = NULL;
958n/a PyObject *ret = NULL;
959n/a
960n/a#ifdef WITH_THREAD
961n/a PyGILState_STATE gilstate;
962n/a
963n/a gilstate = PyGILState_Ensure();
964n/a#endif
965n/a py_statement = PyUnicode_DecodeUTF8(statement_string,
966n/a strlen(statement_string), "replace");
967n/a if (py_statement) {
968n/a ret = PyObject_CallFunctionObjArgs((PyObject*)user_arg, py_statement, NULL);
969n/a Py_DECREF(py_statement);
970n/a }
971n/a
972n/a if (ret) {
973n/a Py_DECREF(ret);
974n/a } else {
975n/a if (_enable_callback_tracebacks) {
976n/a PyErr_Print();
977n/a } else {
978n/a PyErr_Clear();
979n/a }
980n/a }
981n/a
982n/a#ifdef WITH_THREAD
983n/a PyGILState_Release(gilstate);
984n/a#endif
985n/a}
986n/a
987n/astatic PyObject* pysqlite_connection_set_authorizer(pysqlite_Connection* self, PyObject* args, PyObject* kwargs)
988n/a{
989n/a PyObject* authorizer_cb;
990n/a
991n/a static char *kwlist[] = { "authorizer_callback", NULL };
992n/a int rc;
993n/a
994n/a if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
995n/a return NULL;
996n/a }
997n/a
998n/a if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O:set_authorizer",
999n/a kwlist, &authorizer_cb)) {
1000n/a return NULL;
1001n/a }
1002n/a
1003n/a rc = sqlite3_set_authorizer(self->db, _authorizer_callback, (void*)authorizer_cb);
1004n/a
1005n/a if (rc != SQLITE_OK) {
1006n/a PyErr_SetString(pysqlite_OperationalError, "Error setting authorizer callback");
1007n/a return NULL;
1008n/a } else {
1009n/a if (PyDict_SetItem(self->function_pinboard, authorizer_cb, Py_None) == -1)
1010n/a return NULL;
1011n/a
1012n/a Py_RETURN_NONE;
1013n/a }
1014n/a}
1015n/a
1016n/astatic PyObject* pysqlite_connection_set_progress_handler(pysqlite_Connection* self, PyObject* args, PyObject* kwargs)
1017n/a{
1018n/a PyObject* progress_handler;
1019n/a int n;
1020n/a
1021n/a static char *kwlist[] = { "progress_handler", "n", NULL };
1022n/a
1023n/a if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
1024n/a return NULL;
1025n/a }
1026n/a
1027n/a if (!PyArg_ParseTupleAndKeywords(args, kwargs, "Oi:set_progress_handler",
1028n/a kwlist, &progress_handler, &n)) {
1029n/a return NULL;
1030n/a }
1031n/a
1032n/a if (progress_handler == Py_None) {
1033n/a /* None clears the progress handler previously set */
1034n/a sqlite3_progress_handler(self->db, 0, 0, (void*)0);
1035n/a } else {
1036n/a sqlite3_progress_handler(self->db, n, _progress_handler, progress_handler);
1037n/a if (PyDict_SetItem(self->function_pinboard, progress_handler, Py_None) == -1)
1038n/a return NULL;
1039n/a }
1040n/a
1041n/a Py_RETURN_NONE;
1042n/a}
1043n/a
1044n/astatic PyObject* pysqlite_connection_set_trace_callback(pysqlite_Connection* self, PyObject* args, PyObject* kwargs)
1045n/a{
1046n/a PyObject* trace_callback;
1047n/a
1048n/a static char *kwlist[] = { "trace_callback", NULL };
1049n/a
1050n/a if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
1051n/a return NULL;
1052n/a }
1053n/a
1054n/a if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O:set_trace_callback",
1055n/a kwlist, &trace_callback)) {
1056n/a return NULL;
1057n/a }
1058n/a
1059n/a if (trace_callback == Py_None) {
1060n/a /* None clears the trace callback previously set */
1061n/a sqlite3_trace(self->db, 0, (void*)0);
1062n/a } else {
1063n/a if (PyDict_SetItem(self->function_pinboard, trace_callback, Py_None) == -1)
1064n/a return NULL;
1065n/a sqlite3_trace(self->db, _trace_callback, trace_callback);
1066n/a }
1067n/a
1068n/a Py_RETURN_NONE;
1069n/a}
1070n/a
1071n/a#ifdef HAVE_LOAD_EXTENSION
1072n/astatic PyObject* pysqlite_enable_load_extension(pysqlite_Connection* self, PyObject* args)
1073n/a{
1074n/a int rc;
1075n/a int onoff;
1076n/a
1077n/a if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
1078n/a return NULL;
1079n/a }
1080n/a
1081n/a if (!PyArg_ParseTuple(args, "i", &onoff)) {
1082n/a return NULL;
1083n/a }
1084n/a
1085n/a rc = sqlite3_enable_load_extension(self->db, onoff);
1086n/a
1087n/a if (rc != SQLITE_OK) {
1088n/a PyErr_SetString(pysqlite_OperationalError, "Error enabling load extension");
1089n/a return NULL;
1090n/a } else {
1091n/a Py_RETURN_NONE;
1092n/a }
1093n/a}
1094n/a
1095n/astatic PyObject* pysqlite_load_extension(pysqlite_Connection* self, PyObject* args)
1096n/a{
1097n/a int rc;
1098n/a char* extension_name;
1099n/a char* errmsg;
1100n/a
1101n/a if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
1102n/a return NULL;
1103n/a }
1104n/a
1105n/a if (!PyArg_ParseTuple(args, "s", &extension_name)) {
1106n/a return NULL;
1107n/a }
1108n/a
1109n/a rc = sqlite3_load_extension(self->db, extension_name, 0, &errmsg);
1110n/a if (rc != 0) {
1111n/a PyErr_SetString(pysqlite_OperationalError, errmsg);
1112n/a return NULL;
1113n/a } else {
1114n/a Py_RETURN_NONE;
1115n/a }
1116n/a}
1117n/a#endif
1118n/a
1119n/aint pysqlite_check_thread(pysqlite_Connection* self)
1120n/a{
1121n/a#ifdef WITH_THREAD
1122n/a if (self->check_same_thread) {
1123n/a if (PyThread_get_thread_ident() != self->thread_ident) {
1124n/a PyErr_Format(pysqlite_ProgrammingError,
1125n/a "SQLite objects created in a thread can only be used in that same thread."
1126n/a "The object was created in thread id %ld and this is thread id %ld",
1127n/a self->thread_ident, PyThread_get_thread_ident());
1128n/a return 0;
1129n/a }
1130n/a
1131n/a }
1132n/a#endif
1133n/a return 1;
1134n/a}
1135n/a
1136n/astatic PyObject* pysqlite_connection_get_isolation_level(pysqlite_Connection* self, void* unused)
1137n/a{
1138n/a Py_INCREF(self->isolation_level);
1139n/a return self->isolation_level;
1140n/a}
1141n/a
1142n/astatic PyObject* pysqlite_connection_get_total_changes(pysqlite_Connection* self, void* unused)
1143n/a{
1144n/a if (!pysqlite_check_connection(self)) {
1145n/a return NULL;
1146n/a } else {
1147n/a return Py_BuildValue("i", sqlite3_total_changes(self->db));
1148n/a }
1149n/a}
1150n/a
1151n/astatic PyObject* pysqlite_connection_get_in_transaction(pysqlite_Connection* self, void* unused)
1152n/a{
1153n/a if (!pysqlite_check_connection(self)) {
1154n/a return NULL;
1155n/a }
1156n/a if (!sqlite3_get_autocommit(self->db)) {
1157n/a Py_RETURN_TRUE;
1158n/a }
1159n/a Py_RETURN_FALSE;
1160n/a}
1161n/a
1162n/astatic int pysqlite_connection_set_isolation_level(pysqlite_Connection* self, PyObject* isolation_level)
1163n/a{
1164n/a if (isolation_level == Py_None) {
1165n/a PyObject *res = pysqlite_connection_commit(self, NULL);
1166n/a if (!res) {
1167n/a return -1;
1168n/a }
1169n/a Py_DECREF(res);
1170n/a
1171n/a self->begin_statement = NULL;
1172n/a } else {
1173n/a const char * const *candidate;
1174n/a PyObject *uppercase_level;
1175n/a _Py_IDENTIFIER(upper);
1176n/a
1177n/a if (!PyUnicode_Check(isolation_level)) {
1178n/a PyErr_Format(PyExc_TypeError,
1179n/a "isolation_level must be a string or None, not %.100s",
1180n/a Py_TYPE(isolation_level)->tp_name);
1181n/a return -1;
1182n/a }
1183n/a
1184n/a uppercase_level = _PyObject_CallMethodIdObjArgs(
1185n/a (PyObject *)&PyUnicode_Type, &PyId_upper,
1186n/a isolation_level, NULL);
1187n/a if (!uppercase_level) {
1188n/a return -1;
1189n/a }
1190n/a for (candidate = begin_statements; *candidate; candidate++) {
1191n/a if (_PyUnicode_EqualToASCIIString(uppercase_level, *candidate + 6))
1192n/a break;
1193n/a }
1194n/a Py_DECREF(uppercase_level);
1195n/a if (!*candidate) {
1196n/a PyErr_SetString(PyExc_ValueError,
1197n/a "invalid value for isolation_level");
1198n/a return -1;
1199n/a }
1200n/a self->begin_statement = *candidate;
1201n/a }
1202n/a
1203n/a Py_INCREF(isolation_level);
1204n/a Py_XSETREF(self->isolation_level, isolation_level);
1205n/a return 0;
1206n/a}
1207n/a
1208n/aPyObject* pysqlite_connection_call(pysqlite_Connection* self, PyObject* args, PyObject* kwargs)
1209n/a{
1210n/a PyObject* sql;
1211n/a pysqlite_Statement* statement;
1212n/a PyObject* weakref;
1213n/a int rc;
1214n/a
1215n/a if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
1216n/a return NULL;
1217n/a }
1218n/a
1219n/a if (!_PyArg_NoKeywords(MODULE_NAME ".Connection()", kwargs))
1220n/a return NULL;
1221n/a
1222n/a if (!PyArg_ParseTuple(args, "O", &sql))
1223n/a return NULL;
1224n/a
1225n/a _pysqlite_drop_unused_statement_references(self);
1226n/a
1227n/a statement = PyObject_New(pysqlite_Statement, &pysqlite_StatementType);
1228n/a if (!statement) {
1229n/a return NULL;
1230n/a }
1231n/a
1232n/a statement->db = NULL;
1233n/a statement->st = NULL;
1234n/a statement->sql = NULL;
1235n/a statement->in_use = 0;
1236n/a statement->in_weakreflist = NULL;
1237n/a
1238n/a rc = pysqlite_statement_create(statement, self, sql);
1239n/a if (rc != SQLITE_OK) {
1240n/a if (rc == PYSQLITE_TOO_MUCH_SQL) {
1241n/a PyErr_SetString(pysqlite_Warning, "You can only execute one statement at a time.");
1242n/a } else if (rc == PYSQLITE_SQL_WRONG_TYPE) {
1243n/a if (PyErr_ExceptionMatches(PyExc_TypeError))
1244n/a PyErr_SetString(pysqlite_Warning, "SQL is of wrong type. Must be string.");
1245n/a } else {
1246n/a (void)pysqlite_statement_reset(statement);
1247n/a _pysqlite_seterror(self->db, NULL);
1248n/a }
1249n/a goto error;
1250n/a }
1251n/a
1252n/a weakref = PyWeakref_NewRef((PyObject*)statement, NULL);
1253n/a if (weakref == NULL)
1254n/a goto error;
1255n/a if (PyList_Append(self->statements, weakref) != 0) {
1256n/a Py_DECREF(weakref);
1257n/a goto error;
1258n/a }
1259n/a Py_DECREF(weakref);
1260n/a
1261n/a return (PyObject*)statement;
1262n/a
1263n/aerror:
1264n/a Py_DECREF(statement);
1265n/a return NULL;
1266n/a}
1267n/a
1268n/aPyObject* pysqlite_connection_execute(pysqlite_Connection* self, PyObject* args)
1269n/a{
1270n/a PyObject* cursor = 0;
1271n/a PyObject* result = 0;
1272n/a PyObject* method = 0;
1273n/a
1274n/a cursor = _PyObject_CallMethodId((PyObject*)self, &PyId_cursor, NULL);
1275n/a if (!cursor) {
1276n/a goto error;
1277n/a }
1278n/a
1279n/a method = PyObject_GetAttrString(cursor, "execute");
1280n/a if (!method) {
1281n/a Py_CLEAR(cursor);
1282n/a goto error;
1283n/a }
1284n/a
1285n/a result = PyObject_CallObject(method, args);
1286n/a if (!result) {
1287n/a Py_CLEAR(cursor);
1288n/a }
1289n/a
1290n/aerror:
1291n/a Py_XDECREF(result);
1292n/a Py_XDECREF(method);
1293n/a
1294n/a return cursor;
1295n/a}
1296n/a
1297n/aPyObject* pysqlite_connection_executemany(pysqlite_Connection* self, PyObject* args)
1298n/a{
1299n/a PyObject* cursor = 0;
1300n/a PyObject* result = 0;
1301n/a PyObject* method = 0;
1302n/a
1303n/a cursor = _PyObject_CallMethodId((PyObject*)self, &PyId_cursor, NULL);
1304n/a if (!cursor) {
1305n/a goto error;
1306n/a }
1307n/a
1308n/a method = PyObject_GetAttrString(cursor, "executemany");
1309n/a if (!method) {
1310n/a Py_CLEAR(cursor);
1311n/a goto error;
1312n/a }
1313n/a
1314n/a result = PyObject_CallObject(method, args);
1315n/a if (!result) {
1316n/a Py_CLEAR(cursor);
1317n/a }
1318n/a
1319n/aerror:
1320n/a Py_XDECREF(result);
1321n/a Py_XDECREF(method);
1322n/a
1323n/a return cursor;
1324n/a}
1325n/a
1326n/aPyObject* pysqlite_connection_executescript(pysqlite_Connection* self, PyObject* args)
1327n/a{
1328n/a PyObject* cursor = 0;
1329n/a PyObject* result = 0;
1330n/a PyObject* method = 0;
1331n/a
1332n/a cursor = _PyObject_CallMethodId((PyObject*)self, &PyId_cursor, NULL);
1333n/a if (!cursor) {
1334n/a goto error;
1335n/a }
1336n/a
1337n/a method = PyObject_GetAttrString(cursor, "executescript");
1338n/a if (!method) {
1339n/a Py_CLEAR(cursor);
1340n/a goto error;
1341n/a }
1342n/a
1343n/a result = PyObject_CallObject(method, args);
1344n/a if (!result) {
1345n/a Py_CLEAR(cursor);
1346n/a }
1347n/a
1348n/aerror:
1349n/a Py_XDECREF(result);
1350n/a Py_XDECREF(method);
1351n/a
1352n/a return cursor;
1353n/a}
1354n/a
1355n/a/* ------------------------- COLLATION CODE ------------------------ */
1356n/a
1357n/astatic int
1358n/apysqlite_collation_callback(
1359n/a void* context,
1360n/a int text1_length, const void* text1_data,
1361n/a int text2_length, const void* text2_data)
1362n/a{
1363n/a PyObject* callback = (PyObject*)context;
1364n/a PyObject* string1 = 0;
1365n/a PyObject* string2 = 0;
1366n/a#ifdef WITH_THREAD
1367n/a PyGILState_STATE gilstate;
1368n/a#endif
1369n/a PyObject* retval = NULL;
1370n/a long longval;
1371n/a int result = 0;
1372n/a#ifdef WITH_THREAD
1373n/a gilstate = PyGILState_Ensure();
1374n/a#endif
1375n/a
1376n/a if (PyErr_Occurred()) {
1377n/a goto finally;
1378n/a }
1379n/a
1380n/a string1 = PyUnicode_FromStringAndSize((const char*)text1_data, text1_length);
1381n/a string2 = PyUnicode_FromStringAndSize((const char*)text2_data, text2_length);
1382n/a
1383n/a if (!string1 || !string2) {
1384n/a goto finally; /* failed to allocate strings */
1385n/a }
1386n/a
1387n/a retval = PyObject_CallFunctionObjArgs(callback, string1, string2, NULL);
1388n/a
1389n/a if (!retval) {
1390n/a /* execution failed */
1391n/a goto finally;
1392n/a }
1393n/a
1394n/a longval = PyLong_AsLongAndOverflow(retval, &result);
1395n/a if (longval == -1 && PyErr_Occurred()) {
1396n/a PyErr_Clear();
1397n/a result = 0;
1398n/a }
1399n/a else if (!result) {
1400n/a if (longval > 0)
1401n/a result = 1;
1402n/a else if (longval < 0)
1403n/a result = -1;
1404n/a }
1405n/a
1406n/afinally:
1407n/a Py_XDECREF(string1);
1408n/a Py_XDECREF(string2);
1409n/a Py_XDECREF(retval);
1410n/a#ifdef WITH_THREAD
1411n/a PyGILState_Release(gilstate);
1412n/a#endif
1413n/a return result;
1414n/a}
1415n/a
1416n/astatic PyObject *
1417n/apysqlite_connection_interrupt(pysqlite_Connection* self, PyObject* args)
1418n/a{
1419n/a PyObject* retval = NULL;
1420n/a
1421n/a if (!pysqlite_check_connection(self)) {
1422n/a goto finally;
1423n/a }
1424n/a
1425n/a sqlite3_interrupt(self->db);
1426n/a
1427n/a Py_INCREF(Py_None);
1428n/a retval = Py_None;
1429n/a
1430n/afinally:
1431n/a return retval;
1432n/a}
1433n/a
1434n/a/* Function author: Paul Kippes <kippesp@gmail.com>
1435n/a * Class method of Connection to call the Python function _iterdump
1436n/a * of the sqlite3 module.
1437n/a */
1438n/astatic PyObject *
1439n/apysqlite_connection_iterdump(pysqlite_Connection* self, PyObject* args)
1440n/a{
1441n/a PyObject* retval = NULL;
1442n/a PyObject* module = NULL;
1443n/a PyObject* module_dict;
1444n/a PyObject* pyfn_iterdump;
1445n/a
1446n/a if (!pysqlite_check_connection(self)) {
1447n/a goto finally;
1448n/a }
1449n/a
1450n/a module = PyImport_ImportModule(MODULE_NAME ".dump");
1451n/a if (!module) {
1452n/a goto finally;
1453n/a }
1454n/a
1455n/a module_dict = PyModule_GetDict(module);
1456n/a if (!module_dict) {
1457n/a goto finally;
1458n/a }
1459n/a
1460n/a pyfn_iterdump = PyDict_GetItemString(module_dict, "_iterdump");
1461n/a if (!pyfn_iterdump) {
1462n/a PyErr_SetString(pysqlite_OperationalError, "Failed to obtain _iterdump() reference");
1463n/a goto finally;
1464n/a }
1465n/a
1466n/a args = PyTuple_New(1);
1467n/a if (!args) {
1468n/a goto finally;
1469n/a }
1470n/a Py_INCREF(self);
1471n/a PyTuple_SetItem(args, 0, (PyObject*)self);
1472n/a retval = PyObject_CallObject(pyfn_iterdump, args);
1473n/a
1474n/afinally:
1475n/a Py_XDECREF(args);
1476n/a Py_XDECREF(module);
1477n/a return retval;
1478n/a}
1479n/a
1480n/astatic PyObject *
1481n/apysqlite_connection_create_collation(pysqlite_Connection* self, PyObject* args)
1482n/a{
1483n/a PyObject* callable;
1484n/a PyObject* uppercase_name = 0;
1485n/a PyObject* name;
1486n/a PyObject* retval;
1487n/a Py_ssize_t i, len;
1488n/a _Py_IDENTIFIER(upper);
1489n/a const char *uppercase_name_str;
1490n/a int rc;
1491n/a unsigned int kind;
1492n/a void *data;
1493n/a
1494n/a if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
1495n/a goto finally;
1496n/a }
1497n/a
1498n/a if (!PyArg_ParseTuple(args, "UO:create_collation(name, callback)",
1499n/a &name, &callable)) {
1500n/a goto finally;
1501n/a }
1502n/a
1503n/a uppercase_name = _PyObject_CallMethodIdObjArgs((PyObject *)&PyUnicode_Type,
1504n/a &PyId_upper, name, NULL);
1505n/a if (!uppercase_name) {
1506n/a goto finally;
1507n/a }
1508n/a
1509n/a if (PyUnicode_READY(uppercase_name))
1510n/a goto finally;
1511n/a len = PyUnicode_GET_LENGTH(uppercase_name);
1512n/a kind = PyUnicode_KIND(uppercase_name);
1513n/a data = PyUnicode_DATA(uppercase_name);
1514n/a for (i=0; i<len; i++) {
1515n/a Py_UCS4 ch = PyUnicode_READ(kind, data, i);
1516n/a if ((ch >= '0' && ch <= '9')
1517n/a || (ch >= 'A' && ch <= 'Z')
1518n/a || (ch == '_'))
1519n/a {
1520n/a continue;
1521n/a } else {
1522n/a PyErr_SetString(pysqlite_ProgrammingError, "invalid character in collation name");
1523n/a goto finally;
1524n/a }
1525n/a }
1526n/a
1527n/a uppercase_name_str = PyUnicode_AsUTF8(uppercase_name);
1528n/a if (!uppercase_name_str)
1529n/a goto finally;
1530n/a
1531n/a if (callable != Py_None && !PyCallable_Check(callable)) {
1532n/a PyErr_SetString(PyExc_TypeError, "parameter must be callable");
1533n/a goto finally;
1534n/a }
1535n/a
1536n/a if (callable != Py_None) {
1537n/a if (PyDict_SetItem(self->collations, uppercase_name, callable) == -1)
1538n/a goto finally;
1539n/a } else {
1540n/a if (PyDict_DelItem(self->collations, uppercase_name) == -1)
1541n/a goto finally;
1542n/a }
1543n/a
1544n/a rc = sqlite3_create_collation(self->db,
1545n/a uppercase_name_str,
1546n/a SQLITE_UTF8,
1547n/a (callable != Py_None) ? callable : NULL,
1548n/a (callable != Py_None) ? pysqlite_collation_callback : NULL);
1549n/a if (rc != SQLITE_OK) {
1550n/a PyDict_DelItem(self->collations, uppercase_name);
1551n/a _pysqlite_seterror(self->db, NULL);
1552n/a goto finally;
1553n/a }
1554n/a
1555n/afinally:
1556n/a Py_XDECREF(uppercase_name);
1557n/a
1558n/a if (PyErr_Occurred()) {
1559n/a retval = NULL;
1560n/a } else {
1561n/a Py_INCREF(Py_None);
1562n/a retval = Py_None;
1563n/a }
1564n/a
1565n/a return retval;
1566n/a}
1567n/a
1568n/a/* Called when the connection is used as a context manager. Returns itself as a
1569n/a * convenience to the caller. */
1570n/astatic PyObject *
1571n/apysqlite_connection_enter(pysqlite_Connection* self, PyObject* args)
1572n/a{
1573n/a Py_INCREF(self);
1574n/a return (PyObject*)self;
1575n/a}
1576n/a
1577n/a/** Called when the connection is used as a context manager. If there was any
1578n/a * exception, a rollback takes place; otherwise we commit. */
1579n/astatic PyObject *
1580n/apysqlite_connection_exit(pysqlite_Connection* self, PyObject* args)
1581n/a{
1582n/a PyObject* exc_type, *exc_value, *exc_tb;
1583n/a char* method_name;
1584n/a PyObject* result;
1585n/a
1586n/a if (!PyArg_ParseTuple(args, "OOO", &exc_type, &exc_value, &exc_tb)) {
1587n/a return NULL;
1588n/a }
1589n/a
1590n/a if (exc_type == Py_None && exc_value == Py_None && exc_tb == Py_None) {
1591n/a method_name = "commit";
1592n/a } else {
1593n/a method_name = "rollback";
1594n/a }
1595n/a
1596n/a result = PyObject_CallMethod((PyObject*)self, method_name, NULL);
1597n/a if (!result) {
1598n/a return NULL;
1599n/a }
1600n/a Py_DECREF(result);
1601n/a
1602n/a Py_RETURN_FALSE;
1603n/a}
1604n/a
1605n/astatic const char connection_doc[] =
1606n/aPyDoc_STR("SQLite database connection object.");
1607n/a
1608n/astatic PyGetSetDef connection_getset[] = {
1609n/a {"isolation_level", (getter)pysqlite_connection_get_isolation_level, (setter)pysqlite_connection_set_isolation_level},
1610n/a {"total_changes", (getter)pysqlite_connection_get_total_changes, (setter)0},
1611n/a {"in_transaction", (getter)pysqlite_connection_get_in_transaction, (setter)0},
1612n/a {NULL}
1613n/a};
1614n/a
1615n/astatic PyMethodDef connection_methods[] = {
1616n/a {"cursor", (PyCFunction)pysqlite_connection_cursor, METH_VARARGS|METH_KEYWORDS,
1617n/a PyDoc_STR("Return a cursor for the connection.")},
1618n/a {"close", (PyCFunction)pysqlite_connection_close, METH_NOARGS,
1619n/a PyDoc_STR("Closes the connection.")},
1620n/a {"commit", (PyCFunction)pysqlite_connection_commit, METH_NOARGS,
1621n/a PyDoc_STR("Commit the current transaction.")},
1622n/a {"rollback", (PyCFunction)pysqlite_connection_rollback, METH_NOARGS,
1623n/a PyDoc_STR("Roll back the current transaction.")},
1624n/a {"create_function", (PyCFunction)pysqlite_connection_create_function, METH_VARARGS|METH_KEYWORDS,
1625n/a PyDoc_STR("Creates a new function. Non-standard.")},
1626n/a {"create_aggregate", (PyCFunction)pysqlite_connection_create_aggregate, METH_VARARGS|METH_KEYWORDS,
1627n/a PyDoc_STR("Creates a new aggregate. Non-standard.")},
1628n/a {"set_authorizer", (PyCFunction)pysqlite_connection_set_authorizer, METH_VARARGS|METH_KEYWORDS,
1629n/a PyDoc_STR("Sets authorizer callback. Non-standard.")},
1630n/a #ifdef HAVE_LOAD_EXTENSION
1631n/a {"enable_load_extension", (PyCFunction)pysqlite_enable_load_extension, METH_VARARGS,
1632n/a PyDoc_STR("Enable dynamic loading of SQLite extension modules. Non-standard.")},
1633n/a {"load_extension", (PyCFunction)pysqlite_load_extension, METH_VARARGS,
1634n/a PyDoc_STR("Load SQLite extension module. Non-standard.")},
1635n/a #endif
1636n/a {"set_progress_handler", (PyCFunction)pysqlite_connection_set_progress_handler, METH_VARARGS|METH_KEYWORDS,
1637n/a PyDoc_STR("Sets progress handler callback. Non-standard.")},
1638n/a {"set_trace_callback", (PyCFunction)pysqlite_connection_set_trace_callback, METH_VARARGS|METH_KEYWORDS,
1639n/a PyDoc_STR("Sets a trace callback called for each SQL statement (passed as unicode). Non-standard.")},
1640n/a {"execute", (PyCFunction)pysqlite_connection_execute, METH_VARARGS,
1641n/a PyDoc_STR("Executes a SQL statement. Non-standard.")},
1642n/a {"executemany", (PyCFunction)pysqlite_connection_executemany, METH_VARARGS,
1643n/a PyDoc_STR("Repeatedly executes a SQL statement. Non-standard.")},
1644n/a {"executescript", (PyCFunction)pysqlite_connection_executescript, METH_VARARGS,
1645n/a PyDoc_STR("Executes a multiple SQL statements at once. Non-standard.")},
1646n/a {"create_collation", (PyCFunction)pysqlite_connection_create_collation, METH_VARARGS,
1647n/a PyDoc_STR("Creates a collation function. Non-standard.")},
1648n/a {"interrupt", (PyCFunction)pysqlite_connection_interrupt, METH_NOARGS,
1649n/a PyDoc_STR("Abort any pending database operation. Non-standard.")},
1650n/a {"iterdump", (PyCFunction)pysqlite_connection_iterdump, METH_NOARGS,
1651n/a PyDoc_STR("Returns iterator to the dump of the database in an SQL text format. Non-standard.")},
1652n/a {"__enter__", (PyCFunction)pysqlite_connection_enter, METH_NOARGS,
1653n/a PyDoc_STR("For context manager. Non-standard.")},
1654n/a {"__exit__", (PyCFunction)pysqlite_connection_exit, METH_VARARGS,
1655n/a PyDoc_STR("For context manager. Non-standard.")},
1656n/a {NULL, NULL}
1657n/a};
1658n/a
1659n/astatic struct PyMemberDef connection_members[] =
1660n/a{
1661n/a {"Warning", T_OBJECT, offsetof(pysqlite_Connection, Warning), READONLY},
1662n/a {"Error", T_OBJECT, offsetof(pysqlite_Connection, Error), READONLY},
1663n/a {"InterfaceError", T_OBJECT, offsetof(pysqlite_Connection, InterfaceError), READONLY},
1664n/a {"DatabaseError", T_OBJECT, offsetof(pysqlite_Connection, DatabaseError), READONLY},
1665n/a {"DataError", T_OBJECT, offsetof(pysqlite_Connection, DataError), READONLY},
1666n/a {"OperationalError", T_OBJECT, offsetof(pysqlite_Connection, OperationalError), READONLY},
1667n/a {"IntegrityError", T_OBJECT, offsetof(pysqlite_Connection, IntegrityError), READONLY},
1668n/a {"InternalError", T_OBJECT, offsetof(pysqlite_Connection, InternalError), READONLY},
1669n/a {"ProgrammingError", T_OBJECT, offsetof(pysqlite_Connection, ProgrammingError), READONLY},
1670n/a {"NotSupportedError", T_OBJECT, offsetof(pysqlite_Connection, NotSupportedError), READONLY},
1671n/a {"row_factory", T_OBJECT, offsetof(pysqlite_Connection, row_factory)},
1672n/a {"text_factory", T_OBJECT, offsetof(pysqlite_Connection, text_factory)},
1673n/a {NULL}
1674n/a};
1675n/a
1676n/aPyTypeObject pysqlite_ConnectionType = {
1677n/a PyVarObject_HEAD_INIT(NULL, 0)
1678n/a MODULE_NAME ".Connection", /* tp_name */
1679n/a sizeof(pysqlite_Connection), /* tp_basicsize */
1680n/a 0, /* tp_itemsize */
1681n/a (destructor)pysqlite_connection_dealloc, /* tp_dealloc */
1682n/a 0, /* tp_print */
1683n/a 0, /* tp_getattr */
1684n/a 0, /* tp_setattr */
1685n/a 0, /* tp_reserved */
1686n/a 0, /* tp_repr */
1687n/a 0, /* tp_as_number */
1688n/a 0, /* tp_as_sequence */
1689n/a 0, /* tp_as_mapping */
1690n/a 0, /* tp_hash */
1691n/a (ternaryfunc)pysqlite_connection_call, /* tp_call */
1692n/a 0, /* tp_str */
1693n/a 0, /* tp_getattro */
1694n/a 0, /* tp_setattro */
1695n/a 0, /* tp_as_buffer */
1696n/a Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE, /* tp_flags */
1697n/a connection_doc, /* tp_doc */
1698n/a 0, /* tp_traverse */
1699n/a 0, /* tp_clear */
1700n/a 0, /* tp_richcompare */
1701n/a 0, /* tp_weaklistoffset */
1702n/a 0, /* tp_iter */
1703n/a 0, /* tp_iternext */
1704n/a connection_methods, /* tp_methods */
1705n/a connection_members, /* tp_members */
1706n/a connection_getset, /* tp_getset */
1707n/a 0, /* tp_base */
1708n/a 0, /* tp_dict */
1709n/a 0, /* tp_descr_get */
1710n/a 0, /* tp_descr_set */
1711n/a 0, /* tp_dictoffset */
1712n/a (initproc)pysqlite_connection_init, /* tp_init */
1713n/a 0, /* tp_alloc */
1714n/a 0, /* tp_new */
1715n/a 0 /* tp_free */
1716n/a};
1717n/a
1718n/aextern int pysqlite_connection_setup_types(void)
1719n/a{
1720n/a pysqlite_ConnectionType.tp_new = PyType_GenericNew;
1721n/a return PyType_Ready(&pysqlite_ConnectionType);
1722n/a}