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