1 /* connection.c - the connection type
3 * Copyright (C) 2004-2007 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 static int pysqlite_connection_set_isolation_level(pysqlite_Connection
* self
, PyObject
* isolation_level
);
41 static void _sqlite3_result_error(sqlite3_context
* ctx
, const char* errmsg
, int len
)
43 /* in older SQLite versions, calling sqlite3_result_error in callbacks
44 * triggers a bug in SQLite that leads either to irritating results or
45 * segfaults, depending on the SQLite version */
46 #if SQLITE_VERSION_NUMBER >= 3003003
47 sqlite3_result_error(ctx
, errmsg
, len
);
49 PyErr_SetString(pysqlite_OperationalError
, errmsg
);
53 int pysqlite_connection_init(pysqlite_Connection
* self
, PyObject
* args
, PyObject
* kwargs
)
55 static char *kwlist
[] = {"database", "timeout", "detect_types", "isolation_level", "check_same_thread", "factory", "cached_statements", NULL
, NULL
};
59 PyObject
* isolation_level
= NULL
;
60 PyObject
* factory
= NULL
;
61 int check_same_thread
= 1;
62 int cached_statements
= 100;
65 PyObject
* class_attr
= NULL
;
66 PyObject
* class_attr_str
= NULL
;
67 int is_apsw_connection
= 0;
68 PyObject
* database_utf8
;
70 if (!PyArg_ParseTupleAndKeywords(args
, kwargs
, "O|diOiOi", kwlist
,
71 &database
, &timeout
, &detect_types
, &isolation_level
, &check_same_thread
, &factory
, &cached_statements
))
76 self
->begin_statement
= NULL
;
78 self
->statement_cache
= NULL
;
79 self
->statements
= NULL
;
82 self
->row_factory
= Py_None
;
84 Py_INCREF(&PyUnicode_Type
);
85 self
->text_factory
= (PyObject
*)&PyUnicode_Type
;
87 if (PyString_Check(database
) || PyUnicode_Check(database
)) {
88 if (PyString_Check(database
)) {
89 database_utf8
= database
;
90 Py_INCREF(database_utf8
);
92 database_utf8
= PyUnicode_AsUTF8String(database
);
98 Py_BEGIN_ALLOW_THREADS
99 rc
= sqlite3_open(PyString_AsString(database_utf8
), &self
->db
);
102 Py_DECREF(database_utf8
);
104 if (rc
!= SQLITE_OK
) {
105 _pysqlite_seterror(self
->db
, NULL
);
109 /* Create a pysqlite connection from a APSW connection */
110 class_attr
= PyObject_GetAttrString(database
, "__class__");
112 class_attr_str
= PyObject_Str(class_attr
);
113 if (class_attr_str
) {
114 if (strcmp(PyString_AsString(class_attr_str
), "<type 'apsw.Connection'>") == 0) {
115 /* In the APSW Connection object, the first entry after
116 * PyObject_HEAD is the sqlite3* we want to get hold of.
117 * Luckily, this is the same layout as we have in our
118 * pysqlite_Connection */
119 self
->db
= ((pysqlite_Connection
*)database
)->db
;
122 self
->apsw_connection
= database
;
123 is_apsw_connection
= 1;
127 Py_XDECREF(class_attr_str
);
128 Py_XDECREF(class_attr
);
130 if (!is_apsw_connection
) {
131 PyErr_SetString(PyExc_ValueError
, "database parameter must be string or APSW Connection object");
136 if (!isolation_level
) {
137 isolation_level
= PyString_FromString("");
138 if (!isolation_level
) {
142 Py_INCREF(isolation_level
);
144 self
->isolation_level
= NULL
;
145 pysqlite_connection_set_isolation_level(self
, isolation_level
);
146 Py_DECREF(isolation_level
);
148 self
->statement_cache
= (pysqlite_Cache
*)PyObject_CallFunction((PyObject
*)&pysqlite_CacheType
, "Oi", self
, cached_statements
);
149 if (PyErr_Occurred()) {
153 self
->statements
= PyList_New(0);
154 if (!self
->statements
) {
157 self
->created_statements
= 0;
159 /* By default, the Cache class INCREFs the factory in its initializer, and
160 * decrefs it in its deallocator method. Since this would create a circular
161 * reference here, we're breaking it by decrementing self, and telling the
162 * cache class to not decref the factory (self) in its deallocator.
164 self
->statement_cache
->decref_factory
= 0;
167 self
->inTransaction
= 0;
168 self
->detect_types
= detect_types
;
169 self
->timeout
= timeout
;
170 (void)sqlite3_busy_timeout(self
->db
, (int)(timeout
*1000));
172 self
->thread_ident
= PyThread_get_thread_ident();
174 self
->check_same_thread
= check_same_thread
;
176 self
->function_pinboard
= PyDict_New();
177 if (!self
->function_pinboard
) {
181 self
->collations
= PyDict_New();
182 if (!self
->collations
) {
186 self
->Warning
= pysqlite_Warning
;
187 self
->Error
= pysqlite_Error
;
188 self
->InterfaceError
= pysqlite_InterfaceError
;
189 self
->DatabaseError
= pysqlite_DatabaseError
;
190 self
->DataError
= pysqlite_DataError
;
191 self
->OperationalError
= pysqlite_OperationalError
;
192 self
->IntegrityError
= pysqlite_IntegrityError
;
193 self
->InternalError
= pysqlite_InternalError
;
194 self
->ProgrammingError
= pysqlite_ProgrammingError
;
195 self
->NotSupportedError
= pysqlite_NotSupportedError
;
200 /* Empty the entire statement cache of this connection */
201 void pysqlite_flush_statement_cache(pysqlite_Connection
* self
)
204 pysqlite_Statement
* statement
;
206 node
= self
->statement_cache
->first
;
209 statement
= (pysqlite_Statement
*)(node
->data
);
210 (void)pysqlite_statement_finalize(statement
);
214 Py_DECREF(self
->statement_cache
);
215 self
->statement_cache
= (pysqlite_Cache
*)PyObject_CallFunction((PyObject
*)&pysqlite_CacheType
, "O", self
);
217 self
->statement_cache
->decref_factory
= 0;
220 /* action in (ACTION_RESET, ACTION_FINALIZE) */
221 void pysqlite_do_all_statements(pysqlite_Connection
* self
, int action
)
227 for (i
= 0; i
< PyList_Size(self
->statements
); i
++) {
228 weakref
= PyList_GetItem(self
->statements
, i
);
229 statement
= PyWeakref_GetObject(weakref
);
230 if (statement
!= Py_None
) {
231 if (action
== ACTION_RESET
) {
232 (void)pysqlite_statement_reset((pysqlite_Statement
*)statement
);
234 (void)pysqlite_statement_finalize((pysqlite_Statement
*)statement
);
240 void pysqlite_connection_dealloc(pysqlite_Connection
* self
)
242 PyObject
* ret
= NULL
;
244 Py_XDECREF(self
->statement_cache
);
246 /* Clean up if user has not called .close() explicitly. */
248 Py_BEGIN_ALLOW_THREADS
249 sqlite3_close(self
->db
);
251 } else if (self
->apsw_connection
) {
252 ret
= PyObject_CallMethod(self
->apsw_connection
, "close", "");
254 Py_XDECREF(self
->apsw_connection
);
257 if (self
->begin_statement
) {
258 PyMem_Free(self
->begin_statement
);
260 Py_XDECREF(self
->isolation_level
);
261 Py_XDECREF(self
->function_pinboard
);
262 Py_XDECREF(self
->row_factory
);
263 Py_XDECREF(self
->text_factory
);
264 Py_XDECREF(self
->collations
);
265 Py_XDECREF(self
->statements
);
267 self
->ob_type
->tp_free((PyObject
*)self
);
270 PyObject
* pysqlite_connection_cursor(pysqlite_Connection
* self
, PyObject
* args
, PyObject
* kwargs
)
272 static char *kwlist
[] = {"factory", NULL
, NULL
};
273 PyObject
* factory
= NULL
;
277 if (!PyArg_ParseTupleAndKeywords(args
, kwargs
, "|O", kwlist
,
282 if (!pysqlite_check_thread(self
) || !pysqlite_check_connection(self
)) {
286 if (factory
== NULL
) {
287 factory
= (PyObject
*)&pysqlite_CursorType
;
290 cursor
= PyObject_CallFunction(factory
, "O", self
);
292 if (cursor
&& self
->row_factory
!= Py_None
) {
293 Py_XDECREF(((pysqlite_Cursor
*)cursor
)->row_factory
);
294 Py_INCREF(self
->row_factory
);
295 ((pysqlite_Cursor
*)cursor
)->row_factory
= self
->row_factory
;
301 PyObject
* pysqlite_connection_close(pysqlite_Connection
* self
, PyObject
* args
)
306 if (!pysqlite_check_thread(self
)) {
310 pysqlite_do_all_statements(self
, ACTION_FINALIZE
);
313 if (self
->apsw_connection
) {
314 ret
= PyObject_CallMethod(self
->apsw_connection
, "close", "");
316 Py_XDECREF(self
->apsw_connection
);
317 self
->apsw_connection
= NULL
;
320 Py_BEGIN_ALLOW_THREADS
321 rc
= sqlite3_close(self
->db
);
324 if (rc
!= SQLITE_OK
) {
325 _pysqlite_seterror(self
->db
, NULL
);
338 * Checks if a connection object is usable (i. e. not closed).
340 * 0 => error; 1 => ok
342 int pysqlite_check_connection(pysqlite_Connection
* con
)
345 PyErr_SetString(pysqlite_ProgrammingError
, "Cannot operate on a closed database.");
352 PyObject
* _pysqlite_connection_begin(pysqlite_Connection
* self
)
356 sqlite3_stmt
* statement
;
358 Py_BEGIN_ALLOW_THREADS
359 rc
= sqlite3_prepare(self
->db
, self
->begin_statement
, -1, &statement
, &tail
);
362 if (rc
!= SQLITE_OK
) {
363 _pysqlite_seterror(self
->db
, statement
);
367 rc
= pysqlite_step(statement
, self
);
368 if (rc
== SQLITE_DONE
) {
369 self
->inTransaction
= 1;
371 _pysqlite_seterror(self
->db
, statement
);
374 Py_BEGIN_ALLOW_THREADS
375 rc
= sqlite3_finalize(statement
);
378 if (rc
!= SQLITE_OK
&& !PyErr_Occurred()) {
379 _pysqlite_seterror(self
->db
, NULL
);
383 if (PyErr_Occurred()) {
391 PyObject
* pysqlite_connection_commit(pysqlite_Connection
* self
, PyObject
* args
)
395 sqlite3_stmt
* statement
;
397 if (!pysqlite_check_thread(self
) || !pysqlite_check_connection(self
)) {
401 if (self
->inTransaction
) {
402 Py_BEGIN_ALLOW_THREADS
403 rc
= sqlite3_prepare(self
->db
, "COMMIT", -1, &statement
, &tail
);
405 if (rc
!= SQLITE_OK
) {
406 _pysqlite_seterror(self
->db
, NULL
);
410 rc
= pysqlite_step(statement
, self
);
411 if (rc
== SQLITE_DONE
) {
412 self
->inTransaction
= 0;
414 _pysqlite_seterror(self
->db
, statement
);
417 Py_BEGIN_ALLOW_THREADS
418 rc
= sqlite3_finalize(statement
);
420 if (rc
!= SQLITE_OK
&& !PyErr_Occurred()) {
421 _pysqlite_seterror(self
->db
, NULL
);
427 if (PyErr_Occurred()) {
435 PyObject
* pysqlite_connection_rollback(pysqlite_Connection
* self
, PyObject
* args
)
439 sqlite3_stmt
* statement
;
441 if (!pysqlite_check_thread(self
) || !pysqlite_check_connection(self
)) {
445 if (self
->inTransaction
) {
446 pysqlite_do_all_statements(self
, ACTION_RESET
);
448 Py_BEGIN_ALLOW_THREADS
449 rc
= sqlite3_prepare(self
->db
, "ROLLBACK", -1, &statement
, &tail
);
451 if (rc
!= SQLITE_OK
) {
452 _pysqlite_seterror(self
->db
, NULL
);
456 rc
= pysqlite_step(statement
, self
);
457 if (rc
== SQLITE_DONE
) {
458 self
->inTransaction
= 0;
460 _pysqlite_seterror(self
->db
, statement
);
463 Py_BEGIN_ALLOW_THREADS
464 rc
= sqlite3_finalize(statement
);
466 if (rc
!= SQLITE_OK
&& !PyErr_Occurred()) {
467 _pysqlite_seterror(self
->db
, NULL
);
473 if (PyErr_Occurred()) {
481 void _pysqlite_set_result(sqlite3_context
* context
, PyObject
* py_val
)
488 if ((!py_val
) || PyErr_Occurred()) {
489 sqlite3_result_null(context
);
490 } else if (py_val
== Py_None
) {
491 sqlite3_result_null(context
);
492 } else if (PyInt_Check(py_val
)) {
493 longval
= PyInt_AsLong(py_val
);
494 sqlite3_result_int64(context
, (PY_LONG_LONG
)longval
);
495 } else if (PyFloat_Check(py_val
)) {
496 sqlite3_result_double(context
, PyFloat_AsDouble(py_val
));
497 } else if (PyBuffer_Check(py_val
)) {
498 if (PyObject_AsCharBuffer(py_val
, &buffer
, &buflen
) != 0) {
499 PyErr_SetString(PyExc_ValueError
, "could not convert BLOB to buffer");
501 sqlite3_result_blob(context
, buffer
, buflen
, SQLITE_TRANSIENT
);
503 } else if (PyString_Check(py_val
)) {
504 sqlite3_result_text(context
, PyString_AsString(py_val
), -1, SQLITE_TRANSIENT
);
505 } else if (PyUnicode_Check(py_val
)) {
506 stringval
= PyUnicode_AsUTF8String(py_val
);
508 sqlite3_result_text(context
, PyString_AsString(stringval
), -1, SQLITE_TRANSIENT
);
509 Py_DECREF(stringval
);
512 /* TODO: raise error */
516 PyObject
* _pysqlite_build_py_params(sqlite3_context
*context
, int argc
, sqlite3_value
** argv
)
520 sqlite3_value
* cur_value
;
521 PyObject
* cur_py_value
;
523 PY_LONG_LONG val_int
;
527 args
= PyTuple_New(argc
);
532 for (i
= 0; i
< argc
; i
++) {
534 switch (sqlite3_value_type(argv
[i
])) {
536 val_int
= sqlite3_value_int64(cur_value
);
537 cur_py_value
= PyInt_FromLong((long)val_int
);
540 cur_py_value
= PyFloat_FromDouble(sqlite3_value_double(cur_value
));
543 val_str
= (const char*)sqlite3_value_text(cur_value
);
544 cur_py_value
= PyUnicode_DecodeUTF8(val_str
, strlen(val_str
), NULL
);
545 /* TODO: have a way to show errors here */
549 cur_py_value
= Py_None
;
553 buflen
= sqlite3_value_bytes(cur_value
);
554 cur_py_value
= PyBuffer_New(buflen
);
558 if (PyObject_AsWriteBuffer(cur_py_value
, &raw_buffer
, &buflen
)) {
559 Py_DECREF(cur_py_value
);
563 memcpy(raw_buffer
, sqlite3_value_blob(cur_value
), buflen
);
568 cur_py_value
= Py_None
;
576 PyTuple_SetItem(args
, i
, cur_py_value
);
583 void _pysqlite_func_callback(sqlite3_context
* context
, int argc
, sqlite3_value
** argv
)
587 PyObject
* py_retval
= NULL
;
590 PyGILState_STATE threadstate
;
592 threadstate
= PyGILState_Ensure();
595 py_func
= (PyObject
*)sqlite3_user_data(context
);
597 args
= _pysqlite_build_py_params(context
, argc
, argv
);
599 py_retval
= PyObject_CallObject(py_func
, args
);
604 _pysqlite_set_result(context
, py_retval
);
605 Py_DECREF(py_retval
);
607 if (_enable_callback_tracebacks
) {
612 _sqlite3_result_error(context
, "user-defined function raised exception", -1);
616 PyGILState_Release(threadstate
);
620 static void _pysqlite_step_callback(sqlite3_context
*context
, int argc
, sqlite3_value
** params
)
623 PyObject
* function_result
= NULL
;
624 PyObject
* aggregate_class
;
625 PyObject
** aggregate_instance
;
626 PyObject
* stepmethod
= NULL
;
629 PyGILState_STATE threadstate
;
631 threadstate
= PyGILState_Ensure();
634 aggregate_class
= (PyObject
*)sqlite3_user_data(context
);
636 aggregate_instance
= (PyObject
**)sqlite3_aggregate_context(context
, sizeof(PyObject
*));
638 if (*aggregate_instance
== 0) {
639 *aggregate_instance
= PyObject_CallFunction(aggregate_class
, "");
641 if (PyErr_Occurred()) {
642 *aggregate_instance
= 0;
643 if (_enable_callback_tracebacks
) {
648 _sqlite3_result_error(context
, "user-defined aggregate's '__init__' method raised error", -1);
653 stepmethod
= PyObject_GetAttrString(*aggregate_instance
, "step");
658 args
= _pysqlite_build_py_params(context
, argc
, params
);
663 function_result
= PyObject_CallObject(stepmethod
, args
);
666 if (!function_result
) {
667 if (_enable_callback_tracebacks
) {
672 _sqlite3_result_error(context
, "user-defined aggregate's 'step' method raised error", -1);
676 Py_XDECREF(stepmethod
);
677 Py_XDECREF(function_result
);
680 PyGILState_Release(threadstate
);
684 void _pysqlite_final_callback(sqlite3_context
* context
)
686 PyObject
* function_result
= NULL
;
687 PyObject
** aggregate_instance
;
688 PyObject
* aggregate_class
;
691 PyGILState_STATE threadstate
;
693 threadstate
= PyGILState_Ensure();
696 aggregate_class
= (PyObject
*)sqlite3_user_data(context
);
698 aggregate_instance
= (PyObject
**)sqlite3_aggregate_context(context
, sizeof(PyObject
*));
699 if (!*aggregate_instance
) {
700 /* this branch is executed if there was an exception in the aggregate's
706 function_result
= PyObject_CallMethod(*aggregate_instance
, "finalize", "");
707 if (!function_result
) {
708 if (_enable_callback_tracebacks
) {
713 _sqlite3_result_error(context
, "user-defined aggregate's 'finalize' method raised error", -1);
715 _pysqlite_set_result(context
, function_result
);
719 Py_XDECREF(*aggregate_instance
);
720 Py_XDECREF(function_result
);
723 PyGILState_Release(threadstate
);
727 void _pysqlite_drop_unused_statement_references(pysqlite_Connection
* self
)
733 /* we only need to do this once in a while */
734 if (self
->created_statements
++ < 200) {
738 self
->created_statements
= 0;
740 new_list
= PyList_New(0);
745 for (i
= 0; i
< PyList_Size(self
->statements
); i
++) {
746 weakref
= PyList_GetItem(self
->statements
, i
);
747 if (PyWeakref_GetObject(weakref
) != Py_None
) {
748 if (PyList_Append(new_list
, weakref
) != 0) {
755 Py_DECREF(self
->statements
);
756 self
->statements
= new_list
;
759 PyObject
* pysqlite_connection_create_function(pysqlite_Connection
* self
, PyObject
* args
, PyObject
* kwargs
)
761 static char *kwlist
[] = {"name", "narg", "func", NULL
, NULL
};
768 if (!PyArg_ParseTupleAndKeywords(args
, kwargs
, "siO", kwlist
,
769 &name
, &narg
, &func
))
774 rc
= sqlite3_create_function(self
->db
, name
, narg
, SQLITE_UTF8
, (void*)func
, _pysqlite_func_callback
, NULL
, NULL
);
776 if (rc
!= SQLITE_OK
) {
777 /* Workaround for SQLite bug: no error code or string is available here */
778 PyErr_SetString(pysqlite_OperationalError
, "Error creating function");
781 PyDict_SetItem(self
->function_pinboard
, func
, Py_None
);
788 PyObject
* pysqlite_connection_create_aggregate(pysqlite_Connection
* self
, PyObject
* args
, PyObject
* kwargs
)
790 PyObject
* aggregate_class
;
794 static char *kwlist
[] = { "name", "n_arg", "aggregate_class", NULL
};
797 if (!PyArg_ParseTupleAndKeywords(args
, kwargs
, "siO:create_aggregate",
798 kwlist
, &name
, &n_arg
, &aggregate_class
)) {
802 rc
= sqlite3_create_function(self
->db
, name
, n_arg
, SQLITE_UTF8
, (void*)aggregate_class
, 0, &_pysqlite_step_callback
, &_pysqlite_final_callback
);
803 if (rc
!= SQLITE_OK
) {
804 /* Workaround for SQLite bug: no error code or string is available here */
805 PyErr_SetString(pysqlite_OperationalError
, "Error creating aggregate");
808 PyDict_SetItem(self
->function_pinboard
, aggregate_class
, Py_None
);
815 static int _authorizer_callback(void* user_arg
, int action
, const char* arg1
, const char* arg2
, const char* dbname
, const char* access_attempt_source
)
820 PyGILState_STATE gilstate
;
822 gilstate
= PyGILState_Ensure();
824 ret
= PyObject_CallFunction((PyObject
*)user_arg
, "issss", action
, arg1
, arg2
, dbname
, access_attempt_source
);
827 if (_enable_callback_tracebacks
) {
835 if (PyInt_Check(ret
)) {
836 rc
= (int)PyInt_AsLong(ret
);
844 PyGILState_Release(gilstate
);
849 static int _progress_handler(void* user_arg
)
854 PyGILState_STATE gilstate
;
856 gilstate
= PyGILState_Ensure();
858 ret
= PyObject_CallFunction((PyObject
*)user_arg
, "");
861 if (_enable_callback_tracebacks
) {
867 /* abort query if error occurred */
870 rc
= (int)PyObject_IsTrue(ret
);
875 PyGILState_Release(gilstate
);
880 PyObject
* pysqlite_connection_set_authorizer(pysqlite_Connection
* self
, PyObject
* args
, PyObject
* kwargs
)
882 PyObject
* authorizer_cb
;
884 static char *kwlist
[] = { "authorizer_callback", NULL
};
887 if (!PyArg_ParseTupleAndKeywords(args
, kwargs
, "O:set_authorizer",
888 kwlist
, &authorizer_cb
)) {
892 rc
= sqlite3_set_authorizer(self
->db
, _authorizer_callback
, (void*)authorizer_cb
);
894 if (rc
!= SQLITE_OK
) {
895 PyErr_SetString(pysqlite_OperationalError
, "Error setting authorizer callback");
898 PyDict_SetItem(self
->function_pinboard
, authorizer_cb
, Py_None
);
905 PyObject
* pysqlite_connection_set_progress_handler(pysqlite_Connection
* self
, PyObject
* args
, PyObject
* kwargs
)
907 PyObject
* progress_handler
;
910 static char *kwlist
[] = { "progress_handler", "n", NULL
};
912 if (!PyArg_ParseTupleAndKeywords(args
, kwargs
, "Oi:set_progress_handler",
913 kwlist
, &progress_handler
, &n
)) {
917 if (progress_handler
== Py_None
) {
918 /* None clears the progress handler previously set */
919 sqlite3_progress_handler(self
->db
, 0, 0, (void*)0);
921 sqlite3_progress_handler(self
->db
, n
, _progress_handler
, progress_handler
);
922 PyDict_SetItem(self
->function_pinboard
, progress_handler
, Py_None
);
929 int pysqlite_check_thread(pysqlite_Connection
* self
)
932 if (self
->check_same_thread
) {
933 if (PyThread_get_thread_ident() != self
->thread_ident
) {
934 PyErr_Format(pysqlite_ProgrammingError
,
935 "SQLite objects created in a thread can only be used in that same thread."
936 "The object was created in thread id %ld and this is thread id %ld",
937 self
->thread_ident
, PyThread_get_thread_ident());
946 static PyObject
* pysqlite_connection_get_isolation_level(pysqlite_Connection
* self
, void* unused
)
948 Py_INCREF(self
->isolation_level
);
949 return self
->isolation_level
;
952 static PyObject
* pysqlite_connection_get_total_changes(pysqlite_Connection
* self
, void* unused
)
954 if (!pysqlite_check_connection(self
)) {
957 return Py_BuildValue("i", sqlite3_total_changes(self
->db
));
961 static int pysqlite_connection_set_isolation_level(pysqlite_Connection
* self
, PyObject
* isolation_level
)
964 PyObject
* begin_statement
;
965 char* begin_statement_str
;
967 Py_XDECREF(self
->isolation_level
);
969 if (self
->begin_statement
) {
970 PyMem_Free(self
->begin_statement
);
971 self
->begin_statement
= NULL
;
974 if (isolation_level
== Py_None
) {
976 self
->isolation_level
= Py_None
;
978 res
= pysqlite_connection_commit(self
, NULL
);
984 self
->inTransaction
= 0;
986 Py_INCREF(isolation_level
);
987 self
->isolation_level
= isolation_level
;
989 begin_statement
= PyString_FromString("BEGIN ");
990 if (!begin_statement
) {
993 PyString_Concat(&begin_statement
, isolation_level
);
994 if (!begin_statement
) {
998 begin_statement_str
= PyString_AsString(begin_statement
);
999 if (!begin_statement_str
) {
1000 Py_DECREF(begin_statement
);
1003 self
->begin_statement
= PyMem_Malloc(strlen(begin_statement_str
) + 2);
1004 if (!self
->begin_statement
) {
1005 Py_DECREF(begin_statement
);
1009 strcpy(self
->begin_statement
, begin_statement_str
);
1010 Py_DECREF(begin_statement
);
1016 PyObject
* pysqlite_connection_call(pysqlite_Connection
* self
, PyObject
* args
, PyObject
* kwargs
)
1019 pysqlite_Statement
* statement
;
1023 if (!PyArg_ParseTuple(args
, "O", &sql
)) {
1027 _pysqlite_drop_unused_statement_references(self
);
1029 statement
= PyObject_New(pysqlite_Statement
, &pysqlite_StatementType
);
1034 rc
= pysqlite_statement_create(statement
, self
, sql
);
1036 if (rc
!= SQLITE_OK
) {
1037 if (rc
== PYSQLITE_TOO_MUCH_SQL
) {
1038 PyErr_SetString(pysqlite_Warning
, "You can only execute one statement at a time.");
1039 } else if (rc
== PYSQLITE_SQL_WRONG_TYPE
) {
1040 PyErr_SetString(pysqlite_Warning
, "SQL is of wrong type. Must be string or unicode.");
1042 (void)pysqlite_statement_reset(statement
);
1043 _pysqlite_seterror(self
->db
, NULL
);
1046 Py_CLEAR(statement
);
1048 weakref
= PyWeakref_NewRef((PyObject
*)statement
, NULL
);
1050 Py_CLEAR(statement
);
1054 if (PyList_Append(self
->statements
, weakref
) != 0) {
1063 return (PyObject
*)statement
;
1066 PyObject
* pysqlite_connection_execute(pysqlite_Connection
* self
, PyObject
* args
, PyObject
* kwargs
)
1068 PyObject
* cursor
= 0;
1069 PyObject
* result
= 0;
1070 PyObject
* method
= 0;
1072 cursor
= PyObject_CallMethod((PyObject
*)self
, "cursor", "");
1077 method
= PyObject_GetAttrString(cursor
, "execute");
1083 result
= PyObject_CallObject(method
, args
);
1095 PyObject
* pysqlite_connection_executemany(pysqlite_Connection
* self
, PyObject
* args
, PyObject
* kwargs
)
1097 PyObject
* cursor
= 0;
1098 PyObject
* result
= 0;
1099 PyObject
* method
= 0;
1101 cursor
= PyObject_CallMethod((PyObject
*)self
, "cursor", "");
1106 method
= PyObject_GetAttrString(cursor
, "executemany");
1112 result
= PyObject_CallObject(method
, args
);
1124 PyObject
* pysqlite_connection_executescript(pysqlite_Connection
* self
, PyObject
* args
, PyObject
* kwargs
)
1126 PyObject
* cursor
= 0;
1127 PyObject
* result
= 0;
1128 PyObject
* method
= 0;
1130 cursor
= PyObject_CallMethod((PyObject
*)self
, "cursor", "");
1135 method
= PyObject_GetAttrString(cursor
, "executescript");
1141 result
= PyObject_CallObject(method
, args
);
1153 /* ------------------------- COLLATION CODE ------------------------ */
1156 pysqlite_collation_callback(
1158 int text1_length
, const void* text1_data
,
1159 int text2_length
, const void* text2_data
)
1161 PyObject
* callback
= (PyObject
*)context
;
1162 PyObject
* string1
= 0;
1163 PyObject
* string2
= 0;
1165 PyGILState_STATE gilstate
;
1167 PyObject
* retval
= NULL
;
1170 gilstate
= PyGILState_Ensure();
1173 if (PyErr_Occurred()) {
1177 string1
= PyString_FromStringAndSize((const char*)text1_data
, text1_length
);
1178 string2
= PyString_FromStringAndSize((const char*)text2_data
, text2_length
);
1180 if (!string1
|| !string2
) {
1181 goto finally
; /* failed to allocate strings */
1184 retval
= PyObject_CallFunctionObjArgs(callback
, string1
, string2
, NULL
);
1187 /* execution failed */
1191 result
= PyInt_AsLong(retval
);
1192 if (PyErr_Occurred()) {
1197 Py_XDECREF(string1
);
1198 Py_XDECREF(string2
);
1201 PyGILState_Release(gilstate
);
1207 pysqlite_connection_interrupt(pysqlite_Connection
* self
, PyObject
* args
)
1209 PyObject
* retval
= NULL
;
1211 if (!pysqlite_check_connection(self
)) {
1215 sqlite3_interrupt(self
->db
);
1224 /* Function author: Paul Kippes <kippesp@gmail.com>
1225 * Class method of Connection to call the Python function _iterdump
1226 * of the sqlite3 module.
1229 pysqlite_connection_iterdump(pysqlite_Connection
* self
, PyObject
* args
)
1231 PyObject
* retval
= NULL
;
1232 PyObject
* module
= NULL
;
1233 PyObject
* module_dict
;
1234 PyObject
* pyfn_iterdump
;
1236 if (!pysqlite_check_connection(self
)) {
1240 module
= PyImport_ImportModule(MODULE_NAME
".dump");
1245 module_dict
= PyModule_GetDict(module
);
1250 pyfn_iterdump
= PyDict_GetItemString(module_dict
, "_iterdump");
1251 if (!pyfn_iterdump
) {
1252 PyErr_SetString(pysqlite_OperationalError
, "Failed to obtain _iterdump() reference");
1256 args
= PyTuple_New(1);
1261 PyTuple_SetItem(args
, 0, (PyObject
*)self
);
1262 retval
= PyObject_CallObject(pyfn_iterdump
, args
);
1271 pysqlite_connection_create_collation(pysqlite_Connection
* self
, PyObject
* args
)
1274 PyObject
* uppercase_name
= 0;
1280 if (!pysqlite_check_thread(self
) || !pysqlite_check_connection(self
)) {
1284 if (!PyArg_ParseTuple(args
, "O!O:create_collation(name, callback)", &PyString_Type
, &name
, &callable
)) {
1288 uppercase_name
= PyObject_CallMethod(name
, "upper", "");
1289 if (!uppercase_name
) {
1293 chk
= PyString_AsString(uppercase_name
);
1295 if ((*chk
>= '0' && *chk
<= '9')
1296 || (*chk
>= 'A' && *chk
<= 'Z')
1301 PyErr_SetString(pysqlite_ProgrammingError
, "invalid character in collation name");
1306 if (callable
!= Py_None
&& !PyCallable_Check(callable
)) {
1307 PyErr_SetString(PyExc_TypeError
, "parameter must be callable");
1311 if (callable
!= Py_None
) {
1312 PyDict_SetItem(self
->collations
, uppercase_name
, callable
);
1314 PyDict_DelItem(self
->collations
, uppercase_name
);
1317 rc
= sqlite3_create_collation(self
->db
,
1318 PyString_AsString(uppercase_name
),
1320 (callable
!= Py_None
) ? callable
: NULL
,
1321 (callable
!= Py_None
) ? pysqlite_collation_callback
: NULL
);
1322 if (rc
!= SQLITE_OK
) {
1323 PyDict_DelItem(self
->collations
, uppercase_name
);
1324 _pysqlite_seterror(self
->db
, NULL
);
1329 Py_XDECREF(uppercase_name
);
1331 if (PyErr_Occurred()) {
1341 /* Called when the connection is used as a context manager. Returns itself as a
1342 * convenience to the caller. */
1344 pysqlite_connection_enter(pysqlite_Connection
* self
, PyObject
* args
)
1347 return (PyObject
*)self
;
1350 /** Called when the connection is used as a context manager. If there was any
1351 * exception, a rollback takes place; otherwise we commit. */
1353 pysqlite_connection_exit(pysqlite_Connection
* self
, PyObject
* args
)
1355 PyObject
* exc_type
, *exc_value
, *exc_tb
;
1359 if (!PyArg_ParseTuple(args
, "OOO", &exc_type
, &exc_value
, &exc_tb
)) {
1363 if (exc_type
== Py_None
&& exc_value
== Py_None
&& exc_tb
== Py_None
) {
1364 method_name
= "commit";
1366 method_name
= "rollback";
1369 result
= PyObject_CallMethod((PyObject
*)self
, method_name
, "");
1375 Py_INCREF(Py_False
);
1379 static char connection_doc
[] =
1380 PyDoc_STR("SQLite database connection object.");
1382 static PyGetSetDef connection_getset
[] = {
1383 {"isolation_level", (getter
)pysqlite_connection_get_isolation_level
, (setter
)pysqlite_connection_set_isolation_level
},
1384 {"total_changes", (getter
)pysqlite_connection_get_total_changes
, (setter
)0},
1388 static PyMethodDef connection_methods
[] = {
1389 {"cursor", (PyCFunction
)pysqlite_connection_cursor
, METH_VARARGS
|METH_KEYWORDS
,
1390 PyDoc_STR("Return a cursor for the connection.")},
1391 {"close", (PyCFunction
)pysqlite_connection_close
, METH_NOARGS
,
1392 PyDoc_STR("Closes the connection.")},
1393 {"commit", (PyCFunction
)pysqlite_connection_commit
, METH_NOARGS
,
1394 PyDoc_STR("Commit the current transaction.")},
1395 {"rollback", (PyCFunction
)pysqlite_connection_rollback
, METH_NOARGS
,
1396 PyDoc_STR("Roll back the current transaction.")},
1397 {"create_function", (PyCFunction
)pysqlite_connection_create_function
, METH_VARARGS
|METH_KEYWORDS
,
1398 PyDoc_STR("Creates a new function. Non-standard.")},
1399 {"create_aggregate", (PyCFunction
)pysqlite_connection_create_aggregate
, METH_VARARGS
|METH_KEYWORDS
,
1400 PyDoc_STR("Creates a new aggregate. Non-standard.")},
1401 {"set_authorizer", (PyCFunction
)pysqlite_connection_set_authorizer
, METH_VARARGS
|METH_KEYWORDS
,
1402 PyDoc_STR("Sets authorizer callback. Non-standard.")},
1403 {"set_progress_handler", (PyCFunction
)pysqlite_connection_set_progress_handler
, METH_VARARGS
|METH_KEYWORDS
,
1404 PyDoc_STR("Sets progress handler callback. Non-standard.")},
1405 {"execute", (PyCFunction
)pysqlite_connection_execute
, METH_VARARGS
,
1406 PyDoc_STR("Executes a SQL statement. Non-standard.")},
1407 {"executemany", (PyCFunction
)pysqlite_connection_executemany
, METH_VARARGS
,
1408 PyDoc_STR("Repeatedly executes a SQL statement. Non-standard.")},
1409 {"executescript", (PyCFunction
)pysqlite_connection_executescript
, METH_VARARGS
,
1410 PyDoc_STR("Executes a multiple SQL statements at once. Non-standard.")},
1411 {"create_collation", (PyCFunction
)pysqlite_connection_create_collation
, METH_VARARGS
,
1412 PyDoc_STR("Creates a collation function. Non-standard.")},
1413 {"interrupt", (PyCFunction
)pysqlite_connection_interrupt
, METH_NOARGS
,
1414 PyDoc_STR("Abort any pending database operation. Non-standard.")},
1415 {"iterdump", (PyCFunction
)pysqlite_connection_iterdump
, METH_NOARGS
,
1416 PyDoc_STR("Returns iterator to the dump of the database in an SQL text format. Non-standard.")},
1417 {"__enter__", (PyCFunction
)pysqlite_connection_enter
, METH_NOARGS
,
1418 PyDoc_STR("For context manager. Non-standard.")},
1419 {"__exit__", (PyCFunction
)pysqlite_connection_exit
, METH_VARARGS
,
1420 PyDoc_STR("For context manager. Non-standard.")},
1424 static struct PyMemberDef connection_members
[] =
1426 {"Warning", T_OBJECT
, offsetof(pysqlite_Connection
, Warning
), RO
},
1427 {"Error", T_OBJECT
, offsetof(pysqlite_Connection
, Error
), RO
},
1428 {"InterfaceError", T_OBJECT
, offsetof(pysqlite_Connection
, InterfaceError
), RO
},
1429 {"DatabaseError", T_OBJECT
, offsetof(pysqlite_Connection
, DatabaseError
), RO
},
1430 {"DataError", T_OBJECT
, offsetof(pysqlite_Connection
, DataError
), RO
},
1431 {"OperationalError", T_OBJECT
, offsetof(pysqlite_Connection
, OperationalError
), RO
},
1432 {"IntegrityError", T_OBJECT
, offsetof(pysqlite_Connection
, IntegrityError
), RO
},
1433 {"InternalError", T_OBJECT
, offsetof(pysqlite_Connection
, InternalError
), RO
},
1434 {"ProgrammingError", T_OBJECT
, offsetof(pysqlite_Connection
, ProgrammingError
), RO
},
1435 {"NotSupportedError", T_OBJECT
, offsetof(pysqlite_Connection
, NotSupportedError
), RO
},
1436 {"row_factory", T_OBJECT
, offsetof(pysqlite_Connection
, row_factory
)},
1437 {"text_factory", T_OBJECT
, offsetof(pysqlite_Connection
, text_factory
)},
1441 PyTypeObject pysqlite_ConnectionType
= {
1442 PyVarObject_HEAD_INIT(NULL
, 0)
1443 MODULE_NAME
".Connection", /* tp_name */
1444 sizeof(pysqlite_Connection
), /* tp_basicsize */
1445 0, /* tp_itemsize */
1446 (destructor
)pysqlite_connection_dealloc
, /* tp_dealloc */
1452 0, /* tp_as_number */
1453 0, /* tp_as_sequence */
1454 0, /* tp_as_mapping */
1456 (ternaryfunc
)pysqlite_connection_call
, /* tp_call */
1458 0, /* tp_getattro */
1459 0, /* tp_setattro */
1460 0, /* tp_as_buffer */
1461 Py_TPFLAGS_DEFAULT
|Py_TPFLAGS_BASETYPE
, /* tp_flags */
1462 connection_doc
, /* tp_doc */
1463 0, /* tp_traverse */
1465 0, /* tp_richcompare */
1466 0, /* tp_weaklistoffset */
1468 0, /* tp_iternext */
1469 connection_methods
, /* tp_methods */
1470 connection_members
, /* tp_members */
1471 connection_getset
, /* tp_getset */
1474 0, /* tp_descr_get */
1475 0, /* tp_descr_set */
1476 0, /* tp_dictoffset */
1477 (initproc
)pysqlite_connection_init
, /* tp_init */
1483 extern int pysqlite_connection_setup_types(void)
1485 pysqlite_ConnectionType
.tp_new
= PyType_GenericNew
;
1486 return PyType_Ready(&pysqlite_ConnectionType
);