1 /* connection.c - the connection type
3 * Copyright (C) 2004-2010 Gerhard Häring <gh@ghaering.de>
5 * This file is part of pysqlite.
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.
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:
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.
26 #include "connection.h"
27 #include "statement.h"
29 #include "prepare_protocol.h"
31 #include "sqlitecompat.h"
35 #define ACTION_FINALIZE 1
36 #define ACTION_RESET 2
38 #if SQLITE_VERSION_NUMBER >= 3003008
39 #ifndef SQLITE_OMIT_LOAD_EXTENSION
40 #define HAVE_LOAD_EXTENSION
44 static int pysqlite_connection_set_isolation_level(pysqlite_Connection
* self
, PyObject
* isolation_level
);
45 static void _pysqlite_drop_unused_cursor_references(pysqlite_Connection
* self
);
48 static void _sqlite3_result_error(sqlite3_context
* ctx
, const char* errmsg
, int len
)
50 /* in older SQLite versions, calling sqlite3_result_error in callbacks
51 * triggers a bug in SQLite that leads either to irritating results or
52 * segfaults, depending on the SQLite version */
53 #if SQLITE_VERSION_NUMBER >= 3003003
54 sqlite3_result_error(ctx
, errmsg
, len
);
56 PyErr_SetString(pysqlite_OperationalError
, errmsg
);
60 int pysqlite_connection_init(pysqlite_Connection
* self
, PyObject
* args
, PyObject
* kwargs
)
62 static char *kwlist
[] = {"database", "timeout", "detect_types", "isolation_level", "check_same_thread", "factory", "cached_statements", NULL
, NULL
};
66 PyObject
* isolation_level
= NULL
;
67 PyObject
* factory
= NULL
;
68 int check_same_thread
= 1;
69 int cached_statements
= 100;
72 PyObject
* class_attr
= NULL
;
73 PyObject
* class_attr_str
= NULL
;
74 int is_apsw_connection
= 0;
75 PyObject
* database_utf8
;
77 if (!PyArg_ParseTupleAndKeywords(args
, kwargs
, "O|diOiOi", kwlist
,
78 &database
, &timeout
, &detect_types
, &isolation_level
, &check_same_thread
, &factory
, &cached_statements
))
83 self
->initialized
= 1;
85 self
->begin_statement
= NULL
;
87 self
->statement_cache
= NULL
;
88 self
->statements
= NULL
;
92 self
->row_factory
= Py_None
;
94 Py_INCREF(&PyUnicode_Type
);
95 self
->text_factory
= (PyObject
*)&PyUnicode_Type
;
97 if (PyString_Check(database
) || PyUnicode_Check(database
)) {
98 if (PyString_Check(database
)) {
99 database_utf8
= database
;
100 Py_INCREF(database_utf8
);
102 database_utf8
= PyUnicode_AsUTF8String(database
);
103 if (!database_utf8
) {
108 Py_BEGIN_ALLOW_THREADS
109 rc
= sqlite3_open(PyString_AsString(database_utf8
), &self
->db
);
112 Py_DECREF(database_utf8
);
114 if (rc
!= SQLITE_OK
) {
115 _pysqlite_seterror(self
->db
, NULL
);
119 /* Create a pysqlite connection from a APSW connection */
120 class_attr
= PyObject_GetAttrString(database
, "__class__");
122 class_attr_str
= PyObject_Str(class_attr
);
123 if (class_attr_str
) {
124 if (strcmp(PyString_AsString(class_attr_str
), "<type 'apsw.Connection'>") == 0) {
125 /* In the APSW Connection object, the first entry after
126 * PyObject_HEAD is the sqlite3* we want to get hold of.
127 * Luckily, this is the same layout as we have in our
128 * pysqlite_Connection */
129 self
->db
= ((pysqlite_Connection
*)database
)->db
;
132 self
->apsw_connection
= database
;
133 is_apsw_connection
= 1;
137 Py_XDECREF(class_attr_str
);
138 Py_XDECREF(class_attr
);
140 if (!is_apsw_connection
) {
141 PyErr_SetString(PyExc_ValueError
, "database parameter must be string or APSW Connection object");
146 if (!isolation_level
) {
147 isolation_level
= PyString_FromString("");
148 if (!isolation_level
) {
152 Py_INCREF(isolation_level
);
154 self
->isolation_level
= NULL
;
155 pysqlite_connection_set_isolation_level(self
, isolation_level
);
156 Py_DECREF(isolation_level
);
158 self
->statement_cache
= (pysqlite_Cache
*)PyObject_CallFunction((PyObject
*)&pysqlite_CacheType
, "Oi", self
, cached_statements
);
159 if (PyErr_Occurred()) {
163 self
->created_statements
= 0;
164 self
->created_cursors
= 0;
166 /* Create lists of weak references to statements/cursors */
167 self
->statements
= PyList_New(0);
168 self
->cursors
= PyList_New(0);
169 if (!self
->statements
|| !self
->cursors
) {
173 /* By default, the Cache class INCREFs the factory in its initializer, and
174 * decrefs it in its deallocator method. Since this would create a circular
175 * reference here, we're breaking it by decrementing self, and telling the
176 * cache class to not decref the factory (self) in its deallocator.
178 self
->statement_cache
->decref_factory
= 0;
181 self
->inTransaction
= 0;
182 self
->detect_types
= detect_types
;
183 self
->timeout
= timeout
;
184 (void)sqlite3_busy_timeout(self
->db
, (int)(timeout
*1000));
186 self
->thread_ident
= PyThread_get_thread_ident();
188 self
->check_same_thread
= check_same_thread
;
190 self
->function_pinboard
= PyDict_New();
191 if (!self
->function_pinboard
) {
195 self
->collations
= PyDict_New();
196 if (!self
->collations
) {
200 self
->Warning
= pysqlite_Warning
;
201 self
->Error
= pysqlite_Error
;
202 self
->InterfaceError
= pysqlite_InterfaceError
;
203 self
->DatabaseError
= pysqlite_DatabaseError
;
204 self
->DataError
= pysqlite_DataError
;
205 self
->OperationalError
= pysqlite_OperationalError
;
206 self
->IntegrityError
= pysqlite_IntegrityError
;
207 self
->InternalError
= pysqlite_InternalError
;
208 self
->ProgrammingError
= pysqlite_ProgrammingError
;
209 self
->NotSupportedError
= pysqlite_NotSupportedError
;
214 /* Empty the entire statement cache of this connection */
215 void pysqlite_flush_statement_cache(pysqlite_Connection
* self
)
218 pysqlite_Statement
* statement
;
220 node
= self
->statement_cache
->first
;
223 statement
= (pysqlite_Statement
*)(node
->data
);
224 (void)pysqlite_statement_finalize(statement
);
228 Py_DECREF(self
->statement_cache
);
229 self
->statement_cache
= (pysqlite_Cache
*)PyObject_CallFunction((PyObject
*)&pysqlite_CacheType
, "O", self
);
231 self
->statement_cache
->decref_factory
= 0;
234 /* action in (ACTION_RESET, ACTION_FINALIZE) */
235 void pysqlite_do_all_statements(pysqlite_Connection
* self
, int action
, int reset_cursors
)
240 pysqlite_Cursor
* cursor
;
242 for (i
= 0; i
< PyList_Size(self
->statements
); i
++) {
243 weakref
= PyList_GetItem(self
->statements
, i
);
244 statement
= PyWeakref_GetObject(weakref
);
245 if (statement
!= Py_None
) {
246 if (action
== ACTION_RESET
) {
247 (void)pysqlite_statement_reset((pysqlite_Statement
*)statement
);
249 (void)pysqlite_statement_finalize((pysqlite_Statement
*)statement
);
255 for (i
= 0; i
< PyList_Size(self
->cursors
); i
++) {
256 weakref
= PyList_GetItem(self
->cursors
, i
);
257 cursor
= (pysqlite_Cursor
*)PyWeakref_GetObject(weakref
);
258 if ((PyObject
*)cursor
!= Py_None
) {
265 void pysqlite_connection_dealloc(pysqlite_Connection
* self
)
267 PyObject
* ret
= NULL
;
269 Py_XDECREF(self
->statement_cache
);
271 /* Clean up if user has not called .close() explicitly. */
273 Py_BEGIN_ALLOW_THREADS
274 sqlite3_close(self
->db
);
276 } else if (self
->apsw_connection
) {
277 ret
= PyObject_CallMethod(self
->apsw_connection
, "close", "");
279 Py_XDECREF(self
->apsw_connection
);
282 if (self
->begin_statement
) {
283 PyMem_Free(self
->begin_statement
);
285 Py_XDECREF(self
->isolation_level
);
286 Py_XDECREF(self
->function_pinboard
);
287 Py_XDECREF(self
->row_factory
);
288 Py_XDECREF(self
->text_factory
);
289 Py_XDECREF(self
->collations
);
290 Py_XDECREF(self
->statements
);
291 Py_XDECREF(self
->cursors
);
293 self
->ob_type
->tp_free((PyObject
*)self
);
297 * Registers a cursor with the connection.
299 * 0 => error; 1 => ok
301 int pysqlite_connection_register_cursor(pysqlite_Connection
* connection
, PyObject
* cursor
)
305 weakref
= PyWeakref_NewRef((PyObject
*)cursor
, NULL
);
310 if (PyList_Append(connection
->cursors
, weakref
) != 0) {
322 PyObject
* pysqlite_connection_cursor(pysqlite_Connection
* self
, PyObject
* args
, PyObject
* kwargs
)
324 static char *kwlist
[] = {"factory", NULL
, NULL
};
325 PyObject
* factory
= NULL
;
328 if (!PyArg_ParseTupleAndKeywords(args
, kwargs
, "|O", kwlist
,
333 if (!pysqlite_check_thread(self
) || !pysqlite_check_connection(self
)) {
337 if (factory
== NULL
) {
338 factory
= (PyObject
*)&pysqlite_CursorType
;
341 cursor
= PyObject_CallFunction(factory
, "O", self
);
343 _pysqlite_drop_unused_cursor_references(self
);
345 if (cursor
&& self
->row_factory
!= Py_None
) {
346 Py_XDECREF(((pysqlite_Cursor
*)cursor
)->row_factory
);
347 Py_INCREF(self
->row_factory
);
348 ((pysqlite_Cursor
*)cursor
)->row_factory
= self
->row_factory
;
354 PyObject
* pysqlite_connection_close(pysqlite_Connection
* self
, PyObject
* args
)
359 if (!pysqlite_check_thread(self
)) {
363 pysqlite_do_all_statements(self
, ACTION_FINALIZE
, 1);
366 if (self
->apsw_connection
) {
367 ret
= PyObject_CallMethod(self
->apsw_connection
, "close", "");
369 Py_XDECREF(self
->apsw_connection
);
370 self
->apsw_connection
= NULL
;
373 Py_BEGIN_ALLOW_THREADS
374 rc
= sqlite3_close(self
->db
);
377 if (rc
!= SQLITE_OK
) {
378 _pysqlite_seterror(self
->db
, NULL
);
391 * Checks if a connection object is usable (i. e. not closed).
393 * 0 => error; 1 => ok
395 int pysqlite_check_connection(pysqlite_Connection
* con
)
397 if (!con
->initialized
) {
398 PyErr_SetString(pysqlite_ProgrammingError
, "Base Connection.__init__ not called.");
403 PyErr_SetString(pysqlite_ProgrammingError
, "Cannot operate on a closed database.");
410 PyObject
* _pysqlite_connection_begin(pysqlite_Connection
* self
)
414 sqlite3_stmt
* statement
;
416 Py_BEGIN_ALLOW_THREADS
417 rc
= sqlite3_prepare(self
->db
, self
->begin_statement
, -1, &statement
, &tail
);
420 if (rc
!= SQLITE_OK
) {
421 _pysqlite_seterror(self
->db
, statement
);
425 rc
= pysqlite_step(statement
, self
);
426 if (rc
== SQLITE_DONE
) {
427 self
->inTransaction
= 1;
429 _pysqlite_seterror(self
->db
, statement
);
432 Py_BEGIN_ALLOW_THREADS
433 rc
= sqlite3_finalize(statement
);
436 if (rc
!= SQLITE_OK
&& !PyErr_Occurred()) {
437 _pysqlite_seterror(self
->db
, NULL
);
441 if (PyErr_Occurred()) {
449 PyObject
* pysqlite_connection_commit(pysqlite_Connection
* self
, PyObject
* args
)
453 sqlite3_stmt
* statement
;
455 if (!pysqlite_check_thread(self
) || !pysqlite_check_connection(self
)) {
459 if (self
->inTransaction
) {
460 pysqlite_do_all_statements(self
, ACTION_RESET
, 0);
462 Py_BEGIN_ALLOW_THREADS
463 rc
= sqlite3_prepare(self
->db
, "COMMIT", -1, &statement
, &tail
);
465 if (rc
!= SQLITE_OK
) {
466 _pysqlite_seterror(self
->db
, NULL
);
470 rc
= pysqlite_step(statement
, self
);
471 if (rc
== SQLITE_DONE
) {
472 self
->inTransaction
= 0;
474 _pysqlite_seterror(self
->db
, statement
);
477 Py_BEGIN_ALLOW_THREADS
478 rc
= sqlite3_finalize(statement
);
480 if (rc
!= SQLITE_OK
&& !PyErr_Occurred()) {
481 _pysqlite_seterror(self
->db
, NULL
);
487 if (PyErr_Occurred()) {
495 PyObject
* pysqlite_connection_rollback(pysqlite_Connection
* self
, PyObject
* args
)
499 sqlite3_stmt
* statement
;
501 if (!pysqlite_check_thread(self
) || !pysqlite_check_connection(self
)) {
505 if (self
->inTransaction
) {
506 pysqlite_do_all_statements(self
, ACTION_RESET
, 1);
508 Py_BEGIN_ALLOW_THREADS
509 rc
= sqlite3_prepare(self
->db
, "ROLLBACK", -1, &statement
, &tail
);
511 if (rc
!= SQLITE_OK
) {
512 _pysqlite_seterror(self
->db
, NULL
);
516 rc
= pysqlite_step(statement
, self
);
517 if (rc
== SQLITE_DONE
) {
518 self
->inTransaction
= 0;
520 _pysqlite_seterror(self
->db
, statement
);
523 Py_BEGIN_ALLOW_THREADS
524 rc
= sqlite3_finalize(statement
);
526 if (rc
!= SQLITE_OK
&& !PyErr_Occurred()) {
527 _pysqlite_seterror(self
->db
, NULL
);
533 if (PyErr_Occurred()) {
541 void _pysqlite_set_result(sqlite3_context
* context
, PyObject
* py_val
)
548 if ((!py_val
) || PyErr_Occurred()) {
549 sqlite3_result_null(context
);
550 } else if (py_val
== Py_None
) {
551 sqlite3_result_null(context
);
552 } else if (PyInt_Check(py_val
)) {
553 longval
= PyInt_AsLong(py_val
);
554 sqlite3_result_int64(context
, (PY_LONG_LONG
)longval
);
555 } else if (PyFloat_Check(py_val
)) {
556 sqlite3_result_double(context
, PyFloat_AsDouble(py_val
));
557 } else if (PyBuffer_Check(py_val
)) {
558 if (PyObject_AsCharBuffer(py_val
, &buffer
, &buflen
) != 0) {
559 PyErr_SetString(PyExc_ValueError
, "could not convert BLOB to buffer");
561 sqlite3_result_blob(context
, buffer
, buflen
, SQLITE_TRANSIENT
);
563 } else if (PyString_Check(py_val
)) {
564 sqlite3_result_text(context
, PyString_AsString(py_val
), -1, SQLITE_TRANSIENT
);
565 } else if (PyUnicode_Check(py_val
)) {
566 stringval
= PyUnicode_AsUTF8String(py_val
);
568 sqlite3_result_text(context
, PyString_AsString(stringval
), -1, SQLITE_TRANSIENT
);
569 Py_DECREF(stringval
);
572 /* TODO: raise error */
576 PyObject
* _pysqlite_build_py_params(sqlite3_context
*context
, int argc
, sqlite3_value
** argv
)
580 sqlite3_value
* cur_value
;
581 PyObject
* cur_py_value
;
583 PY_LONG_LONG val_int
;
587 args
= PyTuple_New(argc
);
592 for (i
= 0; i
< argc
; i
++) {
594 switch (sqlite3_value_type(argv
[i
])) {
596 val_int
= sqlite3_value_int64(cur_value
);
597 cur_py_value
= PyInt_FromLong((long)val_int
);
600 cur_py_value
= PyFloat_FromDouble(sqlite3_value_double(cur_value
));
603 val_str
= (const char*)sqlite3_value_text(cur_value
);
604 cur_py_value
= PyUnicode_DecodeUTF8(val_str
, strlen(val_str
), NULL
);
605 /* TODO: have a way to show errors here */
609 cur_py_value
= Py_None
;
613 buflen
= sqlite3_value_bytes(cur_value
);
614 cur_py_value
= PyBuffer_New(buflen
);
618 if (PyObject_AsWriteBuffer(cur_py_value
, &raw_buffer
, &buflen
)) {
619 Py_DECREF(cur_py_value
);
623 memcpy(raw_buffer
, sqlite3_value_blob(cur_value
), buflen
);
628 cur_py_value
= Py_None
;
636 PyTuple_SetItem(args
, i
, cur_py_value
);
643 void _pysqlite_func_callback(sqlite3_context
* context
, int argc
, sqlite3_value
** argv
)
647 PyObject
* py_retval
= NULL
;
650 PyGILState_STATE threadstate
;
652 threadstate
= PyGILState_Ensure();
655 py_func
= (PyObject
*)sqlite3_user_data(context
);
657 args
= _pysqlite_build_py_params(context
, argc
, argv
);
659 py_retval
= PyObject_CallObject(py_func
, args
);
664 _pysqlite_set_result(context
, py_retval
);
665 Py_DECREF(py_retval
);
667 if (_enable_callback_tracebacks
) {
672 _sqlite3_result_error(context
, "user-defined function raised exception", -1);
676 PyGILState_Release(threadstate
);
680 static void _pysqlite_step_callback(sqlite3_context
*context
, int argc
, sqlite3_value
** params
)
683 PyObject
* function_result
= NULL
;
684 PyObject
* aggregate_class
;
685 PyObject
** aggregate_instance
;
686 PyObject
* stepmethod
= NULL
;
689 PyGILState_STATE threadstate
;
691 threadstate
= PyGILState_Ensure();
694 aggregate_class
= (PyObject
*)sqlite3_user_data(context
);
696 aggregate_instance
= (PyObject
**)sqlite3_aggregate_context(context
, sizeof(PyObject
*));
698 if (*aggregate_instance
== 0) {
699 *aggregate_instance
= PyObject_CallFunction(aggregate_class
, "");
701 if (PyErr_Occurred()) {
702 *aggregate_instance
= 0;
703 if (_enable_callback_tracebacks
) {
708 _sqlite3_result_error(context
, "user-defined aggregate's '__init__' method raised error", -1);
713 stepmethod
= PyObject_GetAttrString(*aggregate_instance
, "step");
718 args
= _pysqlite_build_py_params(context
, argc
, params
);
723 function_result
= PyObject_CallObject(stepmethod
, args
);
726 if (!function_result
) {
727 if (_enable_callback_tracebacks
) {
732 _sqlite3_result_error(context
, "user-defined aggregate's 'step' method raised error", -1);
736 Py_XDECREF(stepmethod
);
737 Py_XDECREF(function_result
);
740 PyGILState_Release(threadstate
);
744 void _pysqlite_final_callback(sqlite3_context
* context
)
746 PyObject
* function_result
= NULL
;
747 PyObject
** aggregate_instance
;
750 PyGILState_STATE threadstate
;
752 threadstate
= PyGILState_Ensure();
755 aggregate_instance
= (PyObject
**)sqlite3_aggregate_context(context
, sizeof(PyObject
*));
756 if (!*aggregate_instance
) {
757 /* this branch is executed if there was an exception in the aggregate's
763 function_result
= PyObject_CallMethod(*aggregate_instance
, "finalize", "");
764 if (!function_result
) {
765 if (_enable_callback_tracebacks
) {
770 _sqlite3_result_error(context
, "user-defined aggregate's 'finalize' method raised error", -1);
772 _pysqlite_set_result(context
, function_result
);
776 Py_XDECREF(*aggregate_instance
);
777 Py_XDECREF(function_result
);
780 PyGILState_Release(threadstate
);
784 static void _pysqlite_drop_unused_statement_references(pysqlite_Connection
* self
)
790 /* we only need to do this once in a while */
791 if (self
->created_statements
++ < 200) {
795 self
->created_statements
= 0;
797 new_list
= PyList_New(0);
802 for (i
= 0; i
< PyList_Size(self
->statements
); i
++) {
803 weakref
= PyList_GetItem(self
->statements
, i
);
804 if (PyWeakref_GetObject(weakref
) != Py_None
) {
805 if (PyList_Append(new_list
, weakref
) != 0) {
812 Py_DECREF(self
->statements
);
813 self
->statements
= new_list
;
816 static void _pysqlite_drop_unused_cursor_references(pysqlite_Connection
* self
)
822 /* we only need to do this once in a while */
823 if (self
->created_cursors
++ < 200) {
827 self
->created_cursors
= 0;
829 new_list
= PyList_New(0);
834 for (i
= 0; i
< PyList_Size(self
->cursors
); i
++) {
835 weakref
= PyList_GetItem(self
->cursors
, i
);
836 if (PyWeakref_GetObject(weakref
) != Py_None
) {
837 if (PyList_Append(new_list
, weakref
) != 0) {
844 Py_DECREF(self
->cursors
);
845 self
->cursors
= new_list
;
848 PyObject
* pysqlite_connection_create_function(pysqlite_Connection
* self
, PyObject
* args
, PyObject
* kwargs
)
850 static char *kwlist
[] = {"name", "narg", "func", NULL
, NULL
};
857 if (!pysqlite_check_thread(self
) || !pysqlite_check_connection(self
)) {
861 if (!PyArg_ParseTupleAndKeywords(args
, kwargs
, "siO", kwlist
,
862 &name
, &narg
, &func
))
867 rc
= sqlite3_create_function(self
->db
, name
, narg
, SQLITE_UTF8
, (void*)func
, _pysqlite_func_callback
, NULL
, NULL
);
869 if (rc
!= SQLITE_OK
) {
870 /* Workaround for SQLite bug: no error code or string is available here */
871 PyErr_SetString(pysqlite_OperationalError
, "Error creating function");
874 if (PyDict_SetItem(self
->function_pinboard
, func
, Py_None
) == -1)
882 PyObject
* pysqlite_connection_create_aggregate(pysqlite_Connection
* self
, PyObject
* args
, PyObject
* kwargs
)
884 PyObject
* aggregate_class
;
888 static char *kwlist
[] = { "name", "n_arg", "aggregate_class", NULL
};
891 if (!pysqlite_check_thread(self
) || !pysqlite_check_connection(self
)) {
895 if (!PyArg_ParseTupleAndKeywords(args
, kwargs
, "siO:create_aggregate",
896 kwlist
, &name
, &n_arg
, &aggregate_class
)) {
900 rc
= sqlite3_create_function(self
->db
, name
, n_arg
, SQLITE_UTF8
, (void*)aggregate_class
, 0, &_pysqlite_step_callback
, &_pysqlite_final_callback
);
901 if (rc
!= SQLITE_OK
) {
902 /* Workaround for SQLite bug: no error code or string is available here */
903 PyErr_SetString(pysqlite_OperationalError
, "Error creating aggregate");
906 if (PyDict_SetItem(self
->function_pinboard
, aggregate_class
, Py_None
) == -1)
914 static int _authorizer_callback(void* user_arg
, int action
, const char* arg1
, const char* arg2
, const char* dbname
, const char* access_attempt_source
)
919 PyGILState_STATE gilstate
;
921 gilstate
= PyGILState_Ensure();
923 ret
= PyObject_CallFunction((PyObject
*)user_arg
, "issss", action
, arg1
, arg2
, dbname
, access_attempt_source
);
926 if (_enable_callback_tracebacks
) {
934 if (PyInt_Check(ret
)) {
935 rc
= (int)PyInt_AsLong(ret
);
943 PyGILState_Release(gilstate
);
948 static int _progress_handler(void* user_arg
)
953 PyGILState_STATE gilstate
;
955 gilstate
= PyGILState_Ensure();
957 ret
= PyObject_CallFunction((PyObject
*)user_arg
, "");
960 if (_enable_callback_tracebacks
) {
966 /* abort query if error occurred */
969 rc
= (int)PyObject_IsTrue(ret
);
974 PyGILState_Release(gilstate
);
979 static PyObject
* pysqlite_connection_set_authorizer(pysqlite_Connection
* self
, PyObject
* args
, PyObject
* kwargs
)
981 PyObject
* authorizer_cb
;
983 static char *kwlist
[] = { "authorizer_callback", NULL
};
986 if (!pysqlite_check_thread(self
) || !pysqlite_check_connection(self
)) {
990 if (!PyArg_ParseTupleAndKeywords(args
, kwargs
, "O:set_authorizer",
991 kwlist
, &authorizer_cb
)) {
995 rc
= sqlite3_set_authorizer(self
->db
, _authorizer_callback
, (void*)authorizer_cb
);
997 if (rc
!= SQLITE_OK
) {
998 PyErr_SetString(pysqlite_OperationalError
, "Error setting authorizer callback");
1001 if (PyDict_SetItem(self
->function_pinboard
, authorizer_cb
, Py_None
) == -1)
1009 static PyObject
* pysqlite_connection_set_progress_handler(pysqlite_Connection
* self
, PyObject
* args
, PyObject
* kwargs
)
1011 PyObject
* progress_handler
;
1014 static char *kwlist
[] = { "progress_handler", "n", NULL
};
1016 if (!pysqlite_check_thread(self
) || !pysqlite_check_connection(self
)) {
1020 if (!PyArg_ParseTupleAndKeywords(args
, kwargs
, "Oi:set_progress_handler",
1021 kwlist
, &progress_handler
, &n
)) {
1025 if (progress_handler
== Py_None
) {
1026 /* None clears the progress handler previously set */
1027 sqlite3_progress_handler(self
->db
, 0, 0, (void*)0);
1029 sqlite3_progress_handler(self
->db
, n
, _progress_handler
, progress_handler
);
1030 if (PyDict_SetItem(self
->function_pinboard
, progress_handler
, Py_None
) == -1)
1038 #ifdef HAVE_LOAD_EXTENSION
1039 static PyObject
* pysqlite_enable_load_extension(pysqlite_Connection
* self
, PyObject
* args
)
1044 if (!pysqlite_check_thread(self
) || !pysqlite_check_connection(self
)) {
1048 if (!PyArg_ParseTuple(args
, "i", &onoff
)) {
1052 rc
= sqlite3_enable_load_extension(self
->db
, onoff
);
1054 if (rc
!= SQLITE_OK
) {
1055 PyErr_SetString(pysqlite_OperationalError
, "Error enabling load extension");
1063 static PyObject
* pysqlite_load_extension(pysqlite_Connection
* self
, PyObject
* args
)
1066 char* extension_name
;
1069 if (!pysqlite_check_thread(self
) || !pysqlite_check_connection(self
)) {
1073 if (!PyArg_ParseTuple(args
, "s", &extension_name
)) {
1077 rc
= sqlite3_load_extension(self
->db
, extension_name
, 0, &errmsg
);
1079 PyErr_SetString(pysqlite_OperationalError
, errmsg
);
1088 int pysqlite_check_thread(pysqlite_Connection
* self
)
1091 if (self
->check_same_thread
) {
1092 if (PyThread_get_thread_ident() != self
->thread_ident
) {
1093 PyErr_Format(pysqlite_ProgrammingError
,
1094 "SQLite objects created in a thread can only be used in that same thread."
1095 "The object was created in thread id %ld and this is thread id %ld",
1096 self
->thread_ident
, PyThread_get_thread_ident());
1105 static PyObject
* pysqlite_connection_get_isolation_level(pysqlite_Connection
* self
, void* unused
)
1107 Py_INCREF(self
->isolation_level
);
1108 return self
->isolation_level
;
1111 static PyObject
* pysqlite_connection_get_total_changes(pysqlite_Connection
* self
, void* unused
)
1113 if (!pysqlite_check_connection(self
)) {
1116 return Py_BuildValue("i", sqlite3_total_changes(self
->db
));
1120 static int pysqlite_connection_set_isolation_level(pysqlite_Connection
* self
, PyObject
* isolation_level
)
1123 PyObject
* begin_statement
;
1124 char* begin_statement_str
;
1126 Py_XDECREF(self
->isolation_level
);
1128 if (self
->begin_statement
) {
1129 PyMem_Free(self
->begin_statement
);
1130 self
->begin_statement
= NULL
;
1133 if (isolation_level
== Py_None
) {
1135 self
->isolation_level
= Py_None
;
1137 res
= pysqlite_connection_commit(self
, NULL
);
1143 self
->inTransaction
= 0;
1145 Py_INCREF(isolation_level
);
1146 self
->isolation_level
= isolation_level
;
1148 begin_statement
= PyString_FromString("BEGIN ");
1149 if (!begin_statement
) {
1152 PyString_Concat(&begin_statement
, isolation_level
);
1153 if (!begin_statement
) {
1157 begin_statement_str
= PyString_AsString(begin_statement
);
1158 if (!begin_statement_str
) {
1159 Py_DECREF(begin_statement
);
1162 self
->begin_statement
= PyMem_Malloc(strlen(begin_statement_str
) + 2);
1163 if (!self
->begin_statement
) {
1164 Py_DECREF(begin_statement
);
1168 strcpy(self
->begin_statement
, begin_statement_str
);
1169 Py_DECREF(begin_statement
);
1175 PyObject
* pysqlite_connection_call(pysqlite_Connection
* self
, PyObject
* args
, PyObject
* kwargs
)
1178 pysqlite_Statement
* statement
;
1182 if (!pysqlite_check_thread(self
) || !pysqlite_check_connection(self
)) {
1186 if (!PyArg_ParseTuple(args
, "O", &sql
)) {
1190 _pysqlite_drop_unused_statement_references(self
);
1192 statement
= PyObject_New(pysqlite_Statement
, &pysqlite_StatementType
);
1197 statement
->db
= NULL
;
1198 statement
->st
= NULL
;
1199 statement
->sql
= NULL
;
1200 statement
->in_use
= 0;
1201 statement
->in_weakreflist
= NULL
;
1203 rc
= pysqlite_statement_create(statement
, self
, sql
);
1205 if (rc
!= SQLITE_OK
) {
1206 if (rc
== PYSQLITE_TOO_MUCH_SQL
) {
1207 PyErr_SetString(pysqlite_Warning
, "You can only execute one statement at a time.");
1208 } else if (rc
== PYSQLITE_SQL_WRONG_TYPE
) {
1209 PyErr_SetString(pysqlite_Warning
, "SQL is of wrong type. Must be string or unicode.");
1211 (void)pysqlite_statement_reset(statement
);
1212 _pysqlite_seterror(self
->db
, NULL
);
1215 Py_CLEAR(statement
);
1217 weakref
= PyWeakref_NewRef((PyObject
*)statement
, NULL
);
1219 Py_CLEAR(statement
);
1223 if (PyList_Append(self
->statements
, weakref
) != 0) {
1232 return (PyObject
*)statement
;
1235 PyObject
* pysqlite_connection_execute(pysqlite_Connection
* self
, PyObject
* args
, PyObject
* kwargs
)
1237 PyObject
* cursor
= 0;
1238 PyObject
* result
= 0;
1239 PyObject
* method
= 0;
1241 cursor
= PyObject_CallMethod((PyObject
*)self
, "cursor", "");
1246 method
= PyObject_GetAttrString(cursor
, "execute");
1252 result
= PyObject_CallObject(method
, args
);
1264 PyObject
* pysqlite_connection_executemany(pysqlite_Connection
* self
, PyObject
* args
, PyObject
* kwargs
)
1266 PyObject
* cursor
= 0;
1267 PyObject
* result
= 0;
1268 PyObject
* method
= 0;
1270 cursor
= PyObject_CallMethod((PyObject
*)self
, "cursor", "");
1275 method
= PyObject_GetAttrString(cursor
, "executemany");
1281 result
= PyObject_CallObject(method
, args
);
1293 PyObject
* pysqlite_connection_executescript(pysqlite_Connection
* self
, PyObject
* args
, PyObject
* kwargs
)
1295 PyObject
* cursor
= 0;
1296 PyObject
* result
= 0;
1297 PyObject
* method
= 0;
1299 cursor
= PyObject_CallMethod((PyObject
*)self
, "cursor", "");
1304 method
= PyObject_GetAttrString(cursor
, "executescript");
1310 result
= PyObject_CallObject(method
, args
);
1322 /* ------------------------- COLLATION CODE ------------------------ */
1325 pysqlite_collation_callback(
1327 int text1_length
, const void* text1_data
,
1328 int text2_length
, const void* text2_data
)
1330 PyObject
* callback
= (PyObject
*)context
;
1331 PyObject
* string1
= 0;
1332 PyObject
* string2
= 0;
1334 PyGILState_STATE gilstate
;
1336 PyObject
* retval
= NULL
;
1339 gilstate
= PyGILState_Ensure();
1342 if (PyErr_Occurred()) {
1346 string1
= PyString_FromStringAndSize((const char*)text1_data
, text1_length
);
1347 string2
= PyString_FromStringAndSize((const char*)text2_data
, text2_length
);
1349 if (!string1
|| !string2
) {
1350 goto finally
; /* failed to allocate strings */
1353 retval
= PyObject_CallFunctionObjArgs(callback
, string1
, string2
, NULL
);
1356 /* execution failed */
1360 result
= PyInt_AsLong(retval
);
1361 if (PyErr_Occurred()) {
1366 Py_XDECREF(string1
);
1367 Py_XDECREF(string2
);
1370 PyGILState_Release(gilstate
);
1376 pysqlite_connection_interrupt(pysqlite_Connection
* self
, PyObject
* args
)
1378 PyObject
* retval
= NULL
;
1380 if (!pysqlite_check_connection(self
)) {
1384 sqlite3_interrupt(self
->db
);
1393 /* Function author: Paul Kippes <kippesp@gmail.com>
1394 * Class method of Connection to call the Python function _iterdump
1395 * of the sqlite3 module.
1398 pysqlite_connection_iterdump(pysqlite_Connection
* self
, PyObject
* args
)
1400 PyObject
* retval
= NULL
;
1401 PyObject
* module
= NULL
;
1402 PyObject
* module_dict
;
1403 PyObject
* pyfn_iterdump
;
1405 if (!pysqlite_check_connection(self
)) {
1409 module
= PyImport_ImportModule(MODULE_NAME
".dump");
1414 module_dict
= PyModule_GetDict(module
);
1419 pyfn_iterdump
= PyDict_GetItemString(module_dict
, "_iterdump");
1420 if (!pyfn_iterdump
) {
1421 PyErr_SetString(pysqlite_OperationalError
, "Failed to obtain _iterdump() reference");
1425 args
= PyTuple_New(1);
1430 PyTuple_SetItem(args
, 0, (PyObject
*)self
);
1431 retval
= PyObject_CallObject(pyfn_iterdump
, args
);
1440 pysqlite_connection_create_collation(pysqlite_Connection
* self
, PyObject
* args
)
1443 PyObject
* uppercase_name
= 0;
1449 if (!pysqlite_check_thread(self
) || !pysqlite_check_connection(self
)) {
1453 if (!PyArg_ParseTuple(args
, "O!O:create_collation(name, callback)", &PyString_Type
, &name
, &callable
)) {
1457 uppercase_name
= PyObject_CallMethod(name
, "upper", "");
1458 if (!uppercase_name
) {
1462 chk
= PyString_AsString(uppercase_name
);
1464 if ((*chk
>= '0' && *chk
<= '9')
1465 || (*chk
>= 'A' && *chk
<= 'Z')
1470 PyErr_SetString(pysqlite_ProgrammingError
, "invalid character in collation name");
1475 if (callable
!= Py_None
&& !PyCallable_Check(callable
)) {
1476 PyErr_SetString(PyExc_TypeError
, "parameter must be callable");
1480 if (callable
!= Py_None
) {
1481 if (PyDict_SetItem(self
->collations
, uppercase_name
, callable
) == -1)
1484 if (PyDict_DelItem(self
->collations
, uppercase_name
) == -1)
1488 rc
= sqlite3_create_collation(self
->db
,
1489 PyString_AsString(uppercase_name
),
1491 (callable
!= Py_None
) ? callable
: NULL
,
1492 (callable
!= Py_None
) ? pysqlite_collation_callback
: NULL
);
1493 if (rc
!= SQLITE_OK
) {
1494 PyDict_DelItem(self
->collations
, uppercase_name
);
1495 _pysqlite_seterror(self
->db
, NULL
);
1500 Py_XDECREF(uppercase_name
);
1502 if (PyErr_Occurred()) {
1512 /* Called when the connection is used as a context manager. Returns itself as a
1513 * convenience to the caller. */
1515 pysqlite_connection_enter(pysqlite_Connection
* self
, PyObject
* args
)
1518 return (PyObject
*)self
;
1521 /** Called when the connection is used as a context manager. If there was any
1522 * exception, a rollback takes place; otherwise we commit. */
1524 pysqlite_connection_exit(pysqlite_Connection
* self
, PyObject
* args
)
1526 PyObject
* exc_type
, *exc_value
, *exc_tb
;
1530 if (!PyArg_ParseTuple(args
, "OOO", &exc_type
, &exc_value
, &exc_tb
)) {
1534 if (exc_type
== Py_None
&& exc_value
== Py_None
&& exc_tb
== Py_None
) {
1535 method_name
= "commit";
1537 method_name
= "rollback";
1540 result
= PyObject_CallMethod((PyObject
*)self
, method_name
, "");
1546 Py_INCREF(Py_False
);
1550 static char connection_doc
[] =
1551 PyDoc_STR("SQLite database connection object.");
1553 static PyGetSetDef connection_getset
[] = {
1554 {"isolation_level", (getter
)pysqlite_connection_get_isolation_level
, (setter
)pysqlite_connection_set_isolation_level
},
1555 {"total_changes", (getter
)pysqlite_connection_get_total_changes
, (setter
)0},
1559 static PyMethodDef connection_methods
[] = {
1560 {"cursor", (PyCFunction
)pysqlite_connection_cursor
, METH_VARARGS
|METH_KEYWORDS
,
1561 PyDoc_STR("Return a cursor for the connection.")},
1562 {"close", (PyCFunction
)pysqlite_connection_close
, METH_NOARGS
,
1563 PyDoc_STR("Closes the connection.")},
1564 {"commit", (PyCFunction
)pysqlite_connection_commit
, METH_NOARGS
,
1565 PyDoc_STR("Commit the current transaction.")},
1566 {"rollback", (PyCFunction
)pysqlite_connection_rollback
, METH_NOARGS
,
1567 PyDoc_STR("Roll back the current transaction.")},
1568 {"create_function", (PyCFunction
)pysqlite_connection_create_function
, METH_VARARGS
|METH_KEYWORDS
,
1569 PyDoc_STR("Creates a new function. Non-standard.")},
1570 {"create_aggregate", (PyCFunction
)pysqlite_connection_create_aggregate
, METH_VARARGS
|METH_KEYWORDS
,
1571 PyDoc_STR("Creates a new aggregate. Non-standard.")},
1572 {"set_authorizer", (PyCFunction
)pysqlite_connection_set_authorizer
, METH_VARARGS
|METH_KEYWORDS
,
1573 PyDoc_STR("Sets authorizer callback. Non-standard.")},
1574 #ifdef HAVE_LOAD_EXTENSION
1575 {"enable_load_extension", (PyCFunction
)pysqlite_enable_load_extension
, METH_VARARGS
,
1576 PyDoc_STR("Enable dynamic loading of SQLite extension modules. Non-standard.")},
1577 {"load_extension", (PyCFunction
)pysqlite_load_extension
, METH_VARARGS
,
1578 PyDoc_STR("Load SQLite extension module. Non-standard.")},
1580 {"set_progress_handler", (PyCFunction
)pysqlite_connection_set_progress_handler
, METH_VARARGS
|METH_KEYWORDS
,
1581 PyDoc_STR("Sets progress handler callback. Non-standard.")},
1582 {"execute", (PyCFunction
)pysqlite_connection_execute
, METH_VARARGS
,
1583 PyDoc_STR("Executes a SQL statement. Non-standard.")},
1584 {"executemany", (PyCFunction
)pysqlite_connection_executemany
, METH_VARARGS
,
1585 PyDoc_STR("Repeatedly executes a SQL statement. Non-standard.")},
1586 {"executescript", (PyCFunction
)pysqlite_connection_executescript
, METH_VARARGS
,
1587 PyDoc_STR("Executes a multiple SQL statements at once. Non-standard.")},
1588 {"create_collation", (PyCFunction
)pysqlite_connection_create_collation
, METH_VARARGS
,
1589 PyDoc_STR("Creates a collation function. Non-standard.")},
1590 {"interrupt", (PyCFunction
)pysqlite_connection_interrupt
, METH_NOARGS
,
1591 PyDoc_STR("Abort any pending database operation. Non-standard.")},
1592 {"iterdump", (PyCFunction
)pysqlite_connection_iterdump
, METH_NOARGS
,
1593 PyDoc_STR("Returns iterator to the dump of the database in an SQL text format. Non-standard.")},
1594 {"__enter__", (PyCFunction
)pysqlite_connection_enter
, METH_NOARGS
,
1595 PyDoc_STR("For context manager. Non-standard.")},
1596 {"__exit__", (PyCFunction
)pysqlite_connection_exit
, METH_VARARGS
,
1597 PyDoc_STR("For context manager. Non-standard.")},
1601 static struct PyMemberDef connection_members
[] =
1603 {"Warning", T_OBJECT
, offsetof(pysqlite_Connection
, Warning
), RO
},
1604 {"Error", T_OBJECT
, offsetof(pysqlite_Connection
, Error
), RO
},
1605 {"InterfaceError", T_OBJECT
, offsetof(pysqlite_Connection
, InterfaceError
), RO
},
1606 {"DatabaseError", T_OBJECT
, offsetof(pysqlite_Connection
, DatabaseError
), RO
},
1607 {"DataError", T_OBJECT
, offsetof(pysqlite_Connection
, DataError
), RO
},
1608 {"OperationalError", T_OBJECT
, offsetof(pysqlite_Connection
, OperationalError
), RO
},
1609 {"IntegrityError", T_OBJECT
, offsetof(pysqlite_Connection
, IntegrityError
), RO
},
1610 {"InternalError", T_OBJECT
, offsetof(pysqlite_Connection
, InternalError
), RO
},
1611 {"ProgrammingError", T_OBJECT
, offsetof(pysqlite_Connection
, ProgrammingError
), RO
},
1612 {"NotSupportedError", T_OBJECT
, offsetof(pysqlite_Connection
, NotSupportedError
), RO
},
1613 {"row_factory", T_OBJECT
, offsetof(pysqlite_Connection
, row_factory
)},
1614 {"text_factory", T_OBJECT
, offsetof(pysqlite_Connection
, text_factory
)},
1618 PyTypeObject pysqlite_ConnectionType
= {
1619 PyVarObject_HEAD_INIT(NULL
, 0)
1620 MODULE_NAME
".Connection", /* tp_name */
1621 sizeof(pysqlite_Connection
), /* tp_basicsize */
1622 0, /* tp_itemsize */
1623 (destructor
)pysqlite_connection_dealloc
, /* tp_dealloc */
1629 0, /* tp_as_number */
1630 0, /* tp_as_sequence */
1631 0, /* tp_as_mapping */
1633 (ternaryfunc
)pysqlite_connection_call
, /* tp_call */
1635 0, /* tp_getattro */
1636 0, /* tp_setattro */
1637 0, /* tp_as_buffer */
1638 Py_TPFLAGS_DEFAULT
|Py_TPFLAGS_BASETYPE
, /* tp_flags */
1639 connection_doc
, /* tp_doc */
1640 0, /* tp_traverse */
1642 0, /* tp_richcompare */
1643 0, /* tp_weaklistoffset */
1645 0, /* tp_iternext */
1646 connection_methods
, /* tp_methods */
1647 connection_members
, /* tp_members */
1648 connection_getset
, /* tp_getset */
1651 0, /* tp_descr_get */
1652 0, /* tp_descr_set */
1653 0, /* tp_dictoffset */
1654 (initproc
)pysqlite_connection_init
, /* tp_init */
1660 extern int pysqlite_connection_setup_types(void)
1662 pysqlite_ConnectionType
.tp_new
= PyType_GenericNew
;
1663 return PyType_Ready(&pysqlite_ConnectionType
);