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