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;
66
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s|diOiOi", kwlist,
67
&database, &timeout, &detect_types, &isolation_level, &check_same_thread, &factory, &cached_statements))
72
self->begin_statement = NULL;
74
self->statement_cache = NULL;
75
self->statements = NULL;
78
self->row_factory = Py_None;
80
Py_INCREF(&PyUnicode_Type);
81
self->text_factory = (PyObject*)&PyUnicode_Type;
83
Py_BEGIN_ALLOW_THREADS
84
rc = sqlite3_open(database, &self->db);
87
if (rc != SQLITE_OK) {
88
_pysqlite_seterror(self->db, NULL);
92
if (!isolation_level) {
93
isolation_level = PyUnicode_FromString("");
94
if (!isolation_level) {
98
Py_INCREF(isolation_level);
100
self->isolation_level = NULL;
101
pysqlite_connection_set_isolation_level(self, isolation_level);
102
Py_DECREF(isolation_level);
104
self->statement_cache = (pysqlite_Cache*)PyObject_CallFunction((PyObject*)&pysqlite_CacheType, "Oi", self, cached_statements);
105
if (PyErr_Occurred()) {
109
self->statements = PyList_New(0);
110
if (!self->statements) {
113
self->created_statements = 0;
115
/* By default, the Cache class INCREFs the factory in its initializer, and
116
* decrefs it in its deallocator method. Since this would create a circular
117
* reference here, we're breaking it by decrementing self, and telling the
118
* cache class to not decref the factory (self) in its deallocator.
120
self->statement_cache->decref_factory = 0;
123
self->inTransaction = 0;
124
self->detect_types = detect_types;
125
self->timeout = timeout;
126
(void)sqlite3_busy_timeout(self->db, (int)(timeout*1000));
128
self->thread_ident = PyThread_get_thread_ident();
129
self->check_same_thread = check_same_thread;
131
self->function_pinboard = PyDict_New();
132
if (!self->function_pinboard) {
136
self->collations = PyDict_New();
137
if (!self->collations) {
141
self->Warning = pysqlite_Warning;
142
self->Error = pysqlite_Error;
143
self->InterfaceError = pysqlite_InterfaceError;
144
self->DatabaseError = pysqlite_DatabaseError;
145
self->DataError = pysqlite_DataError;
146
self->OperationalError = pysqlite_OperationalError;
147
self->IntegrityError = pysqlite_IntegrityError;
148
self->InternalError = pysqlite_InternalError;
149
self->ProgrammingError = pysqlite_ProgrammingError;
150
self->NotSupportedError = pysqlite_NotSupportedError;
155
/* Empty the entire statement cache of this connection */
156
void pysqlite_flush_statement_cache(pysqlite_Connection* self)
159
pysqlite_Statement* statement;
161
node = self->statement_cache->first;
164
statement = (pysqlite_Statement*)(node->data);
165
(void)pysqlite_statement_finalize(statement);
169
Py_DECREF(self->statement_cache);
170
self->statement_cache = (pysqlite_Cache*)PyObject_CallFunction((PyObject*)&pysqlite_CacheType, "O", self);
172
self->statement_cache->decref_factory = 0;
175
/* action in (ACTION_RESET, ACTION_FINALIZE) */
176
void pysqlite_do_all_statements(pysqlite_Connection* self, int action)
182
for (i = 0; i < PyList_Size(self->statements); i++) {
183
weakref = PyList_GetItem(self->statements, i);
184
statement = PyWeakref_GetObject(weakref);
185
if (statement != Py_None) {
186
if (action == ACTION_RESET) {
187
(void)pysqlite_statement_reset((pysqlite_Statement*)statement);
189
(void)pysqlite_statement_finalize((pysqlite_Statement*)statement);
195
void pysqlite_connection_dealloc(pysqlite_Connection* self)
197
Py_XDECREF(self->statement_cache);
199
/* Clean up if user has not called .close() explicitly. */
201
Py_BEGIN_ALLOW_THREADS
202
sqlite3_close(self->db);
206
if (self->begin_statement) {
207
PyMem_Free(self->begin_statement);
209
Py_XDECREF(self->isolation_level);
210
Py_XDECREF(self->function_pinboard);
211
Py_XDECREF(self->row_factory);
212
Py_XDECREF(self->text_factory);
213
Py_XDECREF(self->collations);
214
Py_XDECREF(self->statements);
216
Py_TYPE(self)->tp_free((PyObject*)self);
219
PyObject* pysqlite_connection_cursor(pysqlite_Connection* self, PyObject* args, PyObject* kwargs)
221
static char *kwlist[] = {"factory", NULL, NULL};
222
PyObject* factory = NULL;
226
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|O", kwlist,
231
if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
235
if (factory == NULL) {
236
factory = (PyObject*)&pysqlite_CursorType;
239
cursor = PyObject_CallFunction(factory, "O", self);
241
if (cursor && self->row_factory != Py_None) {
242
Py_XDECREF(((pysqlite_Cursor*)cursor)->row_factory);
243
Py_INCREF(self->row_factory);
244
((pysqlite_Cursor*)cursor)->row_factory = self->row_factory;
250
PyObject* pysqlite_connection_close(pysqlite_Connection* self, PyObject* args)
254
if (!pysqlite_check_thread(self)) {
258
pysqlite_do_all_statements(self, ACTION_FINALIZE);
261
Py_BEGIN_ALLOW_THREADS
262
rc = sqlite3_close(self->db);
265
if (rc != SQLITE_OK) {
266
_pysqlite_seterror(self->db, NULL);
278
* Checks if a connection object is usable (i. e. not closed).
280
* 0 => error; 1 => ok
282
int pysqlite_check_connection(pysqlite_Connection* con)
285
PyErr_SetString(pysqlite_ProgrammingError, "Cannot operate on a closed database.");
292
PyObject* _pysqlite_connection_begin(pysqlite_Connection* self)
296
sqlite3_stmt* statement;
298
Py_BEGIN_ALLOW_THREADS
299
rc = sqlite3_prepare(self->db, self->begin_statement, -1, &statement, &tail);
302
if (rc != SQLITE_OK) {
303
_pysqlite_seterror(self->db, statement);
307
rc = pysqlite_step(statement, self);
308
if (rc == SQLITE_DONE) {
309
self->inTransaction = 1;
311
_pysqlite_seterror(self->db, statement);
314
Py_BEGIN_ALLOW_THREADS
315
rc = sqlite3_finalize(statement);
318
if (rc != SQLITE_OK && !PyErr_Occurred()) {
319
_pysqlite_seterror(self->db, NULL);
323
if (PyErr_Occurred()) {
331
PyObject* pysqlite_connection_commit(pysqlite_Connection* self, PyObject* args)
335
sqlite3_stmt* statement;
337
if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
341
if (self->inTransaction) {
342
Py_BEGIN_ALLOW_THREADS
343
rc = sqlite3_prepare(self->db, "COMMIT", -1, &statement, &tail);
345
if (rc != SQLITE_OK) {
346
_pysqlite_seterror(self->db, NULL);
350
rc = pysqlite_step(statement, self);
351
if (rc == SQLITE_DONE) {
352
self->inTransaction = 0;
354
_pysqlite_seterror(self->db, statement);
357
Py_BEGIN_ALLOW_THREADS
358
rc = sqlite3_finalize(statement);
360
if (rc != SQLITE_OK && !PyErr_Occurred()) {
361
_pysqlite_seterror(self->db, NULL);
367
if (PyErr_Occurred()) {
375
PyObject* pysqlite_connection_rollback(pysqlite_Connection* self, PyObject* args)
379
sqlite3_stmt* statement;
381
if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
385
if (self->inTransaction) {
386
pysqlite_do_all_statements(self, ACTION_RESET);
388
Py_BEGIN_ALLOW_THREADS
389
rc = sqlite3_prepare(self->db, "ROLLBACK", -1, &statement, &tail);
391
if (rc != SQLITE_OK) {
392
_pysqlite_seterror(self->db, NULL);
396
rc = pysqlite_step(statement, self);
397
if (rc == SQLITE_DONE) {
398
self->inTransaction = 0;
400
_pysqlite_seterror(self->db, statement);
403
Py_BEGIN_ALLOW_THREADS
404
rc = sqlite3_finalize(statement);
406
if (rc != SQLITE_OK && !PyErr_Occurred()) {
407
_pysqlite_seterror(self->db, NULL);
413
if (PyErr_Occurred()) {
421
void _pysqlite_set_result(sqlite3_context* context, PyObject* py_val)
427
if ((!py_val) || PyErr_Occurred()) {
428
sqlite3_result_null(context);
429
} else if (py_val == Py_None) {
430
sqlite3_result_null(context);
431
} else if (PyLong_Check(py_val)) {
432
longval = PyLong_AsLong(py_val);
433
sqlite3_result_int64(context, (PY_LONG_LONG)longval);
434
} else if (PyFloat_Check(py_val)) {
435
sqlite3_result_double(context, PyFloat_AsDouble(py_val));
436
} else if (PyUnicode_Check(py_val)) {
437
sqlite3_result_text(context, _PyUnicode_AsString(py_val), -1, SQLITE_TRANSIENT);
438
} else if (PyObject_CheckBuffer(py_val)) {
439
if (PyObject_AsCharBuffer(py_val, &buffer, &buflen) != 0) {
440
PyErr_SetString(PyExc_ValueError, "could not convert BLOB to buffer");
442
sqlite3_result_blob(context, buffer, buflen, SQLITE_TRANSIENT);
445
/* TODO: raise error */
449
PyObject* _pysqlite_build_py_params(sqlite3_context *context, int argc, sqlite3_value** argv)
453
sqlite3_value* cur_value;
454
PyObject* cur_py_value;
456
PY_LONG_LONG val_int;
459
args = PyTuple_New(argc);
464
for (i = 0; i < argc; i++) {
466
switch (sqlite3_value_type(argv[i])) {
468
val_int = sqlite3_value_int64(cur_value);
469
cur_py_value = PyLong_FromLong((long)val_int);
472
cur_py_value = PyFloat_FromDouble(sqlite3_value_double(cur_value));
475
val_str = (const char*)sqlite3_value_text(cur_value);
476
cur_py_value = PyUnicode_FromString(val_str);
477
/* TODO: have a way to show errors here */
481
cur_py_value = Py_None;
485
buflen = sqlite3_value_bytes(cur_value);
486
cur_py_value = PyBytes_FromStringAndSize(
487
sqlite3_value_blob(cur_value), buflen);
492
cur_py_value = Py_None;
500
PyTuple_SetItem(args, i, cur_py_value);
507
void _pysqlite_func_callback(sqlite3_context* context, int argc, sqlite3_value** argv)
511
PyObject* py_retval = NULL;
513
PyGILState_STATE threadstate;
515
threadstate = PyGILState_Ensure();
517
py_func = (PyObject*)sqlite3_user_data(context);
519
args = _pysqlite_build_py_params(context, argc, argv);
521
py_retval = PyObject_CallObject(py_func, args);
526
_pysqlite_set_result(context, py_retval);
527
Py_DECREF(py_retval);
529
if (_enable_callback_tracebacks) {
534
_sqlite3_result_error(context, "user-defined function raised exception", -1);
537
PyGILState_Release(threadstate);
540
static void _pysqlite_step_callback(sqlite3_context *context, int argc, sqlite3_value** params)
543
PyObject* function_result = NULL;
544
PyObject* aggregate_class;
545
PyObject** aggregate_instance;
546
PyObject* stepmethod = NULL;
548
PyGILState_STATE threadstate;
550
threadstate = PyGILState_Ensure();
552
aggregate_class = (PyObject*)sqlite3_user_data(context);
554
aggregate_instance = (PyObject**)sqlite3_aggregate_context(context, sizeof(PyObject*));
556
if (*aggregate_instance == 0) {
557
*aggregate_instance = PyObject_CallFunction(aggregate_class, "");
559
if (PyErr_Occurred()) {
560
*aggregate_instance = 0;
561
if (_enable_callback_tracebacks) {
566
_sqlite3_result_error(context, "user-defined aggregate's '__init__' method raised error", -1);
571
stepmethod = PyObject_GetAttrString(*aggregate_instance, "step");
576
args = _pysqlite_build_py_params(context, argc, params);
581
function_result = PyObject_CallObject(stepmethod, args);
584
if (!function_result) {
585
if (_enable_callback_tracebacks) {
590
_sqlite3_result_error(context, "user-defined aggregate's 'step' method raised error", -1);
594
Py_XDECREF(stepmethod);
595
Py_XDECREF(function_result);
597
PyGILState_Release(threadstate);
600
void _pysqlite_final_callback(sqlite3_context* context)
602
PyObject* function_result = NULL;
603
PyObject** aggregate_instance;
604
PyObject* aggregate_class;
606
PyGILState_STATE threadstate;
608
threadstate = PyGILState_Ensure();
610
aggregate_class = (PyObject*)sqlite3_user_data(context);
612
aggregate_instance = (PyObject**)sqlite3_aggregate_context(context, sizeof(PyObject*));
613
if (!*aggregate_instance) {
614
/* this branch is executed if there was an exception in the aggregate's
620
function_result = PyObject_CallMethod(*aggregate_instance, "finalize", "");
621
if (!function_result) {
622
if (_enable_callback_tracebacks) {
627
_sqlite3_result_error(context, "user-defined aggregate's 'finalize' method raised error", -1);
629
_pysqlite_set_result(context, function_result);
633
Py_XDECREF(*aggregate_instance);
634
Py_XDECREF(function_result);
636
PyGILState_Release(threadstate);
639
void _pysqlite_drop_unused_statement_references(pysqlite_Connection* self)
645
/* we only need to do this once in a while */
646
if (self->created_statements++ < 200) {
650
self->created_statements = 0;
652
new_list = PyList_New(0);
657
for (i = 0; i < PyList_Size(self->statements); i++) {
658
weakref = PyList_GetItem(self->statements, i);
659
if (PyWeakref_GetObject(weakref) != Py_None) {
660
if (PyList_Append(new_list, weakref) != 0) {
667
Py_DECREF(self->statements);
668
self->statements = new_list;
671
PyObject* pysqlite_connection_create_function(pysqlite_Connection* self, PyObject* args, PyObject* kwargs)
673
static char *kwlist[] = {"name", "narg", "func", NULL, NULL};
680
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "siO", kwlist,
681
&name, &narg, &func))
686
rc = sqlite3_create_function(self->db, name, narg, SQLITE_UTF8, (void*)func, _pysqlite_func_callback, NULL, NULL);
688
if (rc != SQLITE_OK) {
689
/* Workaround for SQLite bug: no error code or string is available here */
690
PyErr_SetString(pysqlite_OperationalError, "Error creating function");
693
PyDict_SetItem(self->function_pinboard, func, Py_None);
700
PyObject* pysqlite_connection_create_aggregate(pysqlite_Connection* self, PyObject* args, PyObject* kwargs)
702
PyObject* aggregate_class;
706
static char *kwlist[] = { "name", "n_arg", "aggregate_class", NULL };
709
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "siO:create_aggregate",
710
kwlist, &name, &n_arg, &aggregate_class)) {
714
rc = sqlite3_create_function(self->db, name, n_arg, SQLITE_UTF8, (void*)aggregate_class, 0, &_pysqlite_step_callback, &_pysqlite_final_callback);
715
if (rc != SQLITE_OK) {
716
/* Workaround for SQLite bug: no error code or string is available here */
717
PyErr_SetString(pysqlite_OperationalError, "Error creating aggregate");
720
PyDict_SetItem(self->function_pinboard, aggregate_class, Py_None);
727
static int _authorizer_callback(void* user_arg, int action, const char* arg1, const char* arg2 , const char* dbname, const char* access_attempt_source)
731
PyGILState_STATE gilstate;
733
gilstate = PyGILState_Ensure();
734
ret = PyObject_CallFunction((PyObject*)user_arg, "issss", action, arg1, arg2, dbname, access_attempt_source);
737
if (_enable_callback_tracebacks) {
745
if (PyLong_Check(ret)) {
746
rc = (int)PyLong_AsLong(ret);
753
PyGILState_Release(gilstate);
757
static int _progress_handler(void* user_arg)
761
PyGILState_STATE gilstate;
763
gilstate = PyGILState_Ensure();
764
ret = PyObject_CallFunction((PyObject*)user_arg, "");
767
if (_enable_callback_tracebacks) {
773
/* abort query if error occurred */
776
rc = (int)PyObject_IsTrue(ret);
780
PyGILState_Release(gilstate);
784
PyObject* pysqlite_connection_set_authorizer(pysqlite_Connection* self, PyObject* args, PyObject* kwargs)
786
PyObject* authorizer_cb;
788
static char *kwlist[] = { "authorizer_callback", NULL };
791
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O:set_authorizer",
792
kwlist, &authorizer_cb)) {
796
rc = sqlite3_set_authorizer(self->db, _authorizer_callback, (void*)authorizer_cb);
798
if (rc != SQLITE_OK) {
799
PyErr_SetString(pysqlite_OperationalError, "Error setting authorizer callback");
802
PyDict_SetItem(self->function_pinboard, authorizer_cb, Py_None);
809
PyObject* pysqlite_connection_set_progress_handler(pysqlite_Connection* self, PyObject* args, PyObject* kwargs)
811
PyObject* progress_handler;
814
static char *kwlist[] = { "progress_handler", "n", NULL };
816
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "Oi:set_progress_handler",
817
kwlist, &progress_handler, &n)) {
821
if (progress_handler == Py_None) {
822
/* None clears the progress handler previously set */
823
sqlite3_progress_handler(self->db, 0, 0, (void*)0);
825
sqlite3_progress_handler(self->db, n, _progress_handler, progress_handler);
826
PyDict_SetItem(self->function_pinboard, progress_handler, Py_None);
833
int pysqlite_check_thread(pysqlite_Connection* self)
835
if (self->check_same_thread) {
836
if (PyThread_get_thread_ident() != self->thread_ident) {
837
PyErr_Format(pysqlite_ProgrammingError,
838
"SQLite objects created in a thread can only be used in that same thread."
839
"The object was created in thread id %ld and this is thread id %ld",
840
self->thread_ident, PyThread_get_thread_ident());
849
static PyObject* pysqlite_connection_get_isolation_level(pysqlite_Connection* self, void* unused)
851
Py_INCREF(self->isolation_level);
852
return self->isolation_level;
855
static PyObject* pysqlite_connection_get_total_changes(pysqlite_Connection* self, void* unused)
857
if (!pysqlite_check_connection(self)) {
860
return Py_BuildValue("i", sqlite3_total_changes(self->db));
864
static int pysqlite_connection_set_isolation_level(pysqlite_Connection* self, PyObject* isolation_level)
867
PyObject* begin_statement;
868
static PyObject* begin_word;
870
Py_XDECREF(self->isolation_level);
872
if (self->begin_statement) {
873
PyMem_Free(self->begin_statement);
874
self->begin_statement = NULL;
877
if (isolation_level == Py_None) {
879
self->isolation_level = Py_None;
881
res = pysqlite_connection_commit(self, NULL);
887
self->inTransaction = 0;
889
const char *statement;
892
Py_INCREF(isolation_level);
893
self->isolation_level = isolation_level;
896
begin_word = PyUnicode_FromString("BEGIN ");
897
if (!begin_word) return -1;
899
begin_statement = PyUnicode_Concat(begin_word, isolation_level);
900
if (!begin_statement) {
904
statement = _PyUnicode_AsStringAndSize(begin_statement, &size);
906
Py_DECREF(statement);
909
self->begin_statement = PyMem_Malloc(size + 2);
910
if (!self->begin_statement) {
911
Py_DECREF(begin_statement);
915
strcpy(self->begin_statement, statement);
916
Py_DECREF(begin_statement);
922
PyObject* pysqlite_connection_call(pysqlite_Connection* self, PyObject* args, PyObject* kwargs)
925
pysqlite_Statement* statement;
929
if (!PyArg_ParseTuple(args, "O", &sql)) {
933
_pysqlite_drop_unused_statement_references(self);
935
statement = PyObject_New(pysqlite_Statement, &pysqlite_StatementType);
940
rc = pysqlite_statement_create(statement, self, sql);
942
if (rc != SQLITE_OK) {
943
if (rc == PYSQLITE_TOO_MUCH_SQL) {
944
PyErr_SetString(pysqlite_Warning, "You can only execute one statement at a time.");
945
} else if (rc == PYSQLITE_SQL_WRONG_TYPE) {
946
PyErr_SetString(pysqlite_Warning, "SQL is of wrong type. Must be string or unicode.");
948
(void)pysqlite_statement_reset(statement);
949
_pysqlite_seterror(self->db, NULL);
954
weakref = PyWeakref_NewRef((PyObject*)statement, NULL);
960
if (PyList_Append(self->statements, weakref) != 0) {
969
return (PyObject*)statement;
972
PyObject* pysqlite_connection_execute(pysqlite_Connection* self, PyObject* args, PyObject* kwargs)
974
PyObject* cursor = 0;
975
PyObject* result = 0;
976
PyObject* method = 0;
978
cursor = PyObject_CallMethod((PyObject*)self, "cursor", "");
983
method = PyObject_GetAttrString(cursor, "execute");
989
result = PyObject_CallObject(method, args);
1001
PyObject* pysqlite_connection_executemany(pysqlite_Connection* self, PyObject* args, PyObject* kwargs)
1003
PyObject* cursor = 0;
1004
PyObject* result = 0;
1005
PyObject* method = 0;
1007
cursor = PyObject_CallMethod((PyObject*)self, "cursor", "");
1012
method = PyObject_GetAttrString(cursor, "executemany");
1018
result = PyObject_CallObject(method, args);
1030
PyObject* pysqlite_connection_executescript(pysqlite_Connection* self, PyObject* args, PyObject* kwargs)
1032
PyObject* cursor = 0;
1033
PyObject* result = 0;
1034
PyObject* method = 0;
1036
cursor = PyObject_CallMethod((PyObject*)self, "cursor", "");
1041
method = PyObject_GetAttrString(cursor, "executescript");
1047
result = PyObject_CallObject(method, args);
1059
/* ------------------------- COLLATION CODE ------------------------ */
1062
pysqlite_collation_callback(
1064
int text1_length, const void* text1_data,
1065
int text2_length, const void* text2_data)
1067
PyObject* callback = (PyObject*)context;
1068
PyObject* string1 = 0;
1069
PyObject* string2 = 0;
1070
PyGILState_STATE gilstate;
1072
PyObject* retval = NULL;
1075
gilstate = PyGILState_Ensure();
1077
if (PyErr_Occurred()) {
1081
string1 = PyUnicode_FromStringAndSize((const char*)text1_data, text1_length);
1082
string2 = PyUnicode_FromStringAndSize((const char*)text2_data, text2_length);
1084
if (!string1 || !string2) {
1085
goto finally; /* failed to allocate strings */
1088
retval = PyObject_CallFunctionObjArgs(callback, string1, string2, NULL);
1091
/* execution failed */
1095
result = PyLong_AsLong(retval);
1096
if (PyErr_Occurred()) {
1101
Py_XDECREF(string1);
1102
Py_XDECREF(string2);
1105
PyGILState_Release(gilstate);
1111
pysqlite_connection_interrupt(pysqlite_Connection* self, PyObject* args)
1113
PyObject* retval = NULL;
1115
if (!pysqlite_check_connection(self)) {
1119
sqlite3_interrupt(self->db);
1128
/* Function author: Paul Kippes <kippesp@gmail.com>
1129
* Class method of Connection to call the Python function _iterdump
1130
* of the sqlite3 module.
1133
pysqlite_connection_iterdump(pysqlite_Connection* self, PyObject* args)
1135
PyObject* retval = NULL;
1136
PyObject* module = NULL;
1137
PyObject* module_dict;
1138
PyObject* pyfn_iterdump;
1140
if (!pysqlite_check_connection(self)) {
1144
module = PyImport_ImportModule(MODULE_NAME ".dump");
1149
module_dict = PyModule_GetDict(module);
1154
pyfn_iterdump = PyDict_GetItemString(module_dict, "_iterdump");
1155
if (!pyfn_iterdump) {
1156
PyErr_SetString(pysqlite_OperationalError, "Failed to obtain _iterdump() reference");
1160
args = PyTuple_New(1);
1165
PyTuple_SetItem(args, 0, (PyObject*)self);
1166
retval = PyObject_CallObject(pyfn_iterdump, args);
1175
pysqlite_connection_create_collation(pysqlite_Connection* self, PyObject* args)
1178
PyObject* uppercase_name = 0;
1184
if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
1188
if (!PyArg_ParseTuple(args, "O!O:create_collation(name, callback)", &PyUnicode_Type, &name, &callable)) {
1192
uppercase_name = PyObject_CallMethod(name, "upper", "");
1193
if (!uppercase_name) {
1197
chk = _PyUnicode_AsString(uppercase_name);
1199
if ((*chk >= '0' && *chk <= '9')
1200
|| (*chk >= 'A' && *chk <= 'Z')
1205
PyErr_SetString(pysqlite_ProgrammingError, "invalid character in collation name");
1210
if (callable != Py_None && !PyCallable_Check(callable)) {
1211
PyErr_SetString(PyExc_TypeError, "parameter must be callable");
1215
if (callable != Py_None) {
1216
PyDict_SetItem(self->collations, uppercase_name, callable);
1218
PyDict_DelItem(self->collations, uppercase_name);
1221
rc = sqlite3_create_collation(self->db,
1222
_PyUnicode_AsString(uppercase_name),
1224
(callable != Py_None) ? callable : NULL,
1225
(callable != Py_None) ? pysqlite_collation_callback : NULL);
1226
if (rc != SQLITE_OK) {
1227
PyDict_DelItem(self->collations, uppercase_name);
1228
_pysqlite_seterror(self->db, NULL);
1233
Py_XDECREF(uppercase_name);
1235
if (PyErr_Occurred()) {
1245
/* Called when the connection is used as a context manager. Returns itself as a
1246
* convenience to the caller. */
1248
pysqlite_connection_enter(pysqlite_Connection* self, PyObject* args)
1251
return (PyObject*)self;
1254
/** Called when the connection is used as a context manager. If there was any
1255
* exception, a rollback takes place; otherwise we commit. */
1257
pysqlite_connection_exit(pysqlite_Connection* self, PyObject* args)
1259
PyObject* exc_type, *exc_value, *exc_tb;
1263
if (!PyArg_ParseTuple(args, "OOO", &exc_type, &exc_value, &exc_tb)) {
1267
if (exc_type == Py_None && exc_value == Py_None && exc_tb == Py_None) {
1268
method_name = "commit";
1270
method_name = "rollback";
1273
result = PyObject_CallMethod((PyObject*)self, method_name, "");
1282
static char connection_doc[] =
1283
PyDoc_STR("SQLite database connection object.");
1285
static PyGetSetDef connection_getset[] = {
1286
{"isolation_level", (getter)pysqlite_connection_get_isolation_level, (setter)pysqlite_connection_set_isolation_level},
1287
{"total_changes", (getter)pysqlite_connection_get_total_changes, (setter)0},
1291
static PyMethodDef connection_methods[] = {
1292
{"cursor", (PyCFunction)pysqlite_connection_cursor, METH_VARARGS|METH_KEYWORDS,
1293
PyDoc_STR("Return a cursor for the connection.")},
1294
{"close", (PyCFunction)pysqlite_connection_close, METH_NOARGS,
1295
PyDoc_STR("Closes the connection.")},
1296
{"commit", (PyCFunction)pysqlite_connection_commit, METH_NOARGS,
1297
PyDoc_STR("Commit the current transaction.")},
1298
{"rollback", (PyCFunction)pysqlite_connection_rollback, METH_NOARGS,
1299
PyDoc_STR("Roll back the current transaction.")},
1300
{"create_function", (PyCFunction)pysqlite_connection_create_function, METH_VARARGS|METH_KEYWORDS,
1301
PyDoc_STR("Creates a new function. Non-standard.")},
1302
{"create_aggregate", (PyCFunction)pysqlite_connection_create_aggregate, METH_VARARGS|METH_KEYWORDS,
1303
PyDoc_STR("Creates a new aggregate. Non-standard.")},
1304
{"set_authorizer", (PyCFunction)pysqlite_connection_set_authorizer, METH_VARARGS|METH_KEYWORDS,
1305
PyDoc_STR("Sets authorizer callback. Non-standard.")},
1306
{"set_progress_handler", (PyCFunction)pysqlite_connection_set_progress_handler, METH_VARARGS|METH_KEYWORDS,
1307
PyDoc_STR("Sets progress handler callback. Non-standard.")},
1308
{"execute", (PyCFunction)pysqlite_connection_execute, METH_VARARGS,
1309
PyDoc_STR("Executes a SQL statement. Non-standard.")},
1310
{"executemany", (PyCFunction)pysqlite_connection_executemany, METH_VARARGS,
1311
PyDoc_STR("Repeatedly executes a SQL statement. Non-standard.")},
1312
{"executescript", (PyCFunction)pysqlite_connection_executescript, METH_VARARGS,
1313
PyDoc_STR("Executes a multiple SQL statements at once. Non-standard.")},
1314
{"create_collation", (PyCFunction)pysqlite_connection_create_collation, METH_VARARGS,
1315
PyDoc_STR("Creates a collation function. Non-standard.")},
1316
{"interrupt", (PyCFunction)pysqlite_connection_interrupt, METH_NOARGS,
1317
PyDoc_STR("Abort any pending database operation. Non-standard.")},
1318
{"iterdump", (PyCFunction)pysqlite_connection_iterdump, METH_NOARGS,
1319
PyDoc_STR("Returns iterator to the dump of the database in an SQL text format. Non-standard.")},
1320
{"__enter__", (PyCFunction)pysqlite_connection_enter, METH_NOARGS,
1321
PyDoc_STR("For context manager. Non-standard.")},
1322
{"__exit__", (PyCFunction)pysqlite_connection_exit, METH_VARARGS,
1323
PyDoc_STR("For context manager. Non-standard.")},
1327
static struct PyMemberDef connection_members[] =
1329
{"Warning", T_OBJECT, offsetof(pysqlite_Connection, Warning), READONLY},
1330
{"Error", T_OBJECT, offsetof(pysqlite_Connection, Error), READONLY},
1331
{"InterfaceError", T_OBJECT, offsetof(pysqlite_Connection, InterfaceError), READONLY},
1332
{"DatabaseError", T_OBJECT, offsetof(pysqlite_Connection, DatabaseError), READONLY},
1333
{"DataError", T_OBJECT, offsetof(pysqlite_Connection, DataError), READONLY},
1334
{"OperationalError", T_OBJECT, offsetof(pysqlite_Connection, OperationalError), READONLY},
1335
{"IntegrityError", T_OBJECT, offsetof(pysqlite_Connection, IntegrityError), READONLY},
1336
{"InternalError", T_OBJECT, offsetof(pysqlite_Connection, InternalError), READONLY},
1337
{"ProgrammingError", T_OBJECT, offsetof(pysqlite_Connection, ProgrammingError), READONLY},
1338
{"NotSupportedError", T_OBJECT, offsetof(pysqlite_Connection, NotSupportedError), READONLY},
1339
{"row_factory", T_OBJECT, offsetof(pysqlite_Connection, row_factory)},
1340
{"text_factory", T_OBJECT, offsetof(pysqlite_Connection, text_factory)},
1344
PyTypeObject pysqlite_ConnectionType = {
1345
PyVarObject_HEAD_INIT(NULL, 0)
1346
MODULE_NAME ".Connection", /* tp_name */
1347
sizeof(pysqlite_Connection), /* tp_basicsize */
1348
0, /* tp_itemsize */
1349
(destructor)pysqlite_connection_dealloc, /* tp_dealloc */
1353
0, /* tp_reserved */
1355
0, /* tp_as_number */
1356
0, /* tp_as_sequence */
1357
0, /* tp_as_mapping */
1359
(ternaryfunc)pysqlite_connection_call, /* tp_call */
1361
0, /* tp_getattro */
1362
0, /* tp_setattro */
1363
0, /* tp_as_buffer */
1364
Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE, /* tp_flags */
1365
connection_doc, /* tp_doc */
1366
0, /* tp_traverse */
1368
0, /* tp_richcompare */
1369
0, /* tp_weaklistoffset */
1371
0, /* tp_iternext */
1372
connection_methods, /* tp_methods */
1373
connection_members, /* tp_members */
1374
connection_getset, /* tp_getset */
1377
0, /* tp_descr_get */
1378
0, /* tp_descr_set */
1379
0, /* tp_dictoffset */
1380
(initproc)pysqlite_connection_init, /* tp_init */
1386
extern int pysqlite_connection_setup_types(void)
1388
pysqlite_ConnectionType.tp_new = PyType_GenericNew;
1389
return PyType_Ready(&pysqlite_ConnectionType);