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