blob: 703af15fa939c2faee575b0028e2d8d7ed44c672 [file] [log] [blame]
Anthony Baxterc51ee692006-04-01 00:57:31 +00001/* connection.c - the connection type
2 *
3 * Copyright (C) 2004-2006 Gerhard Häring <gh@ghaering.de>
4 *
5 * This file is part of pysqlite.
Anthony Baxter72289a62006-04-04 06:29:05 +00006 *
Anthony Baxterc51ee692006-04-01 00:57:31 +00007 * 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 "connection.h"
27#include "statement.h"
28#include "cursor.h"
29#include "prepare_protocol.h"
30#include "util.h"
Anthony Baxter72289a62006-04-04 06:29:05 +000031#include "sqlitecompat.h"
32
Anthony Baxterc51ee692006-04-01 00:57:31 +000033#include "pythread.h"
34
35static int connection_set_isolation_level(Connection* self, PyObject* isolation_level);
36
Gerhard Häringb2e88162006-06-14 22:28:37 +000037
38void _sqlite3_result_error(sqlite3_context* ctx, const char* errmsg, int len)
39{
40 /* in older SQLite versions, calling sqlite3_result_error in callbacks
41 * triggers a bug in SQLite that leads either to irritating results or
42 * segfaults, depending on the SQLite version */
43#if SQLITE_VERSION_NUMBER >= 3003003
44 sqlite3_result_error(ctx, errmsg, len);
Neal Norwitzfe7d0c32006-06-15 04:54:29 +000045#else
46 PyErr_SetString(OperationalError, errmsg);
Gerhard Häringb2e88162006-06-14 22:28:37 +000047#endif
48}
49
Anthony Baxterc51ee692006-04-01 00:57:31 +000050int connection_init(Connection* self, PyObject* args, PyObject* kwargs)
51{
52 static char *kwlist[] = {"database", "timeout", "detect_types", "isolation_level", "check_same_thread", "factory", "cached_statements", NULL, NULL};
53
54 char* database;
55 int detect_types = 0;
56 PyObject* isolation_level = NULL;
57 PyObject* factory = NULL;
58 int check_same_thread = 1;
59 int cached_statements = 100;
60 double timeout = 5.0;
61 int rc;
62
63 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s|diOiOi", kwlist,
64 &database, &timeout, &detect_types, &isolation_level, &check_same_thread, &factory, &cached_statements))
65 {
66 return -1;
67 }
68
69 self->begin_statement = NULL;
70
71 self->statement_cache = NULL;
Gerhard Häring3e99c0a2006-04-23 15:24:26 +000072 self->statements = NULL;
Anthony Baxterc51ee692006-04-01 00:57:31 +000073
74 Py_INCREF(Py_None);
75 self->row_factory = Py_None;
76
77 Py_INCREF(&PyUnicode_Type);
78 self->text_factory = (PyObject*)&PyUnicode_Type;
79
80 Py_BEGIN_ALLOW_THREADS
81 rc = sqlite3_open(database, &self->db);
82 Py_END_ALLOW_THREADS
83
84 if (rc != SQLITE_OK) {
85 _seterror(self->db);
86 return -1;
87 }
88
89 if (!isolation_level) {
90 isolation_level = PyString_FromString("");
Gerhard Häring3e99c0a2006-04-23 15:24:26 +000091 if (!isolation_level) {
92 return -1;
93 }
Anthony Baxterc51ee692006-04-01 00:57:31 +000094 } else {
95 Py_INCREF(isolation_level);
96 }
97 self->isolation_level = NULL;
98 connection_set_isolation_level(self, isolation_level);
99 Py_DECREF(isolation_level);
100
101 self->statement_cache = (Cache*)PyObject_CallFunction((PyObject*)&CacheType, "Oi", self, cached_statements);
102 if (PyErr_Occurred()) {
103 return -1;
104 }
105
Gerhard Häring3e99c0a2006-04-23 15:24:26 +0000106 self->statements = PyList_New(0);
107 if (!self->statements) {
108 return -1;
109 }
110 self->created_statements = 0;
111
Anthony Baxterc51ee692006-04-01 00:57:31 +0000112 /* By default, the Cache class INCREFs the factory in its initializer, and
113 * decrefs it in its deallocator method. Since this would create a circular
114 * reference here, we're breaking it by decrementing self, and telling the
115 * cache class to not decref the factory (self) in its deallocator.
116 */
117 self->statement_cache->decref_factory = 0;
118 Py_DECREF(self);
119
120 self->inTransaction = 0;
121 self->detect_types = detect_types;
122 self->timeout = timeout;
123 (void)sqlite3_busy_timeout(self->db, (int)(timeout*1000));
124
125 self->thread_ident = PyThread_get_thread_ident();
126 self->check_same_thread = check_same_thread;
127
128 self->function_pinboard = PyDict_New();
Anthony Baxter72289a62006-04-04 06:29:05 +0000129 if (!self->function_pinboard) {
130 return -1;
131 }
132
133 self->collations = PyDict_New();
134 if (!self->collations) {
135 return -1;
136 }
Anthony Baxterc51ee692006-04-01 00:57:31 +0000137
138 self->Warning = Warning;
139 self->Error = Error;
140 self->InterfaceError = InterfaceError;
141 self->DatabaseError = DatabaseError;
142 self->DataError = DataError;
143 self->OperationalError = OperationalError;
144 self->IntegrityError = IntegrityError;
145 self->InternalError = InternalError;
146 self->ProgrammingError = ProgrammingError;
147 self->NotSupportedError = NotSupportedError;
148
149 return 0;
150}
151
Gerhard Häring3e99c0a2006-04-23 15:24:26 +0000152/* Empty the entire statement cache of this connection */
Anthony Baxterc51ee692006-04-01 00:57:31 +0000153void flush_statement_cache(Connection* self)
154{
155 Node* node;
156 Statement* statement;
157
158 node = self->statement_cache->first;
159
160 while (node) {
161 statement = (Statement*)(node->data);
162 (void)statement_finalize(statement);
163 node = node->next;
164 }
165
166 Py_DECREF(self->statement_cache);
167 self->statement_cache = (Cache*)PyObject_CallFunction((PyObject*)&CacheType, "O", self);
168 Py_DECREF(self);
169 self->statement_cache->decref_factory = 0;
170}
171
172void reset_all_statements(Connection* self)
173{
Gerhard Häring3e99c0a2006-04-23 15:24:26 +0000174 int i;
175 PyObject* weakref;
176 PyObject* statement;
Anthony Baxterc51ee692006-04-01 00:57:31 +0000177
Gerhard Häring3e99c0a2006-04-23 15:24:26 +0000178 for (i = 0; i < PyList_Size(self->statements); i++) {
179 weakref = PyList_GetItem(self->statements, i);
180 statement = PyWeakref_GetObject(weakref);
181 if (statement != Py_None) {
182 (void)statement_reset((Statement*)statement);
183 }
Anthony Baxterc51ee692006-04-01 00:57:31 +0000184 }
185}
186
187void connection_dealloc(Connection* self)
188{
189 Py_XDECREF(self->statement_cache);
190
191 /* Clean up if user has not called .close() explicitly. */
192 if (self->db) {
193 Py_BEGIN_ALLOW_THREADS
194 sqlite3_close(self->db);
195 Py_END_ALLOW_THREADS
196 }
197
198 if (self->begin_statement) {
199 PyMem_Free(self->begin_statement);
200 }
201 Py_XDECREF(self->isolation_level);
202 Py_XDECREF(self->function_pinboard);
203 Py_XDECREF(self->row_factory);
204 Py_XDECREF(self->text_factory);
Anthony Baxter72289a62006-04-04 06:29:05 +0000205 Py_XDECREF(self->collations);
Gerhard Häring3e99c0a2006-04-23 15:24:26 +0000206 Py_XDECREF(self->statements);
Anthony Baxterc51ee692006-04-01 00:57:31 +0000207
208 self->ob_type->tp_free((PyObject*)self);
209}
210
211PyObject* connection_cursor(Connection* self, PyObject* args, PyObject* kwargs)
212{
213 static char *kwlist[] = {"factory", NULL, NULL};
214 PyObject* factory = NULL;
215 PyObject* cursor;
216
217
218 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|O", kwlist,
219 &factory)) {
220 return NULL;
221 }
222
223 if (!check_thread(self) || !check_connection(self)) {
224 return NULL;
225 }
226
227 if (factory == NULL) {
228 factory = (PyObject*)&CursorType;
229 }
230
231 cursor = PyObject_CallFunction(factory, "O", self);
232
233 if (cursor && self->row_factory != Py_None) {
234 Py_XDECREF(((Cursor*)cursor)->row_factory);
235 Py_INCREF(self->row_factory);
236 ((Cursor*)cursor)->row_factory = self->row_factory;
237 }
238
239 return cursor;
240}
241
242PyObject* connection_close(Connection* self, PyObject* args)
243{
244 int rc;
245
246 if (!check_thread(self)) {
247 return NULL;
248 }
249
250 flush_statement_cache(self);
251
252 if (self->db) {
253 Py_BEGIN_ALLOW_THREADS
254 rc = sqlite3_close(self->db);
255 Py_END_ALLOW_THREADS
256
257 if (rc != SQLITE_OK) {
258 _seterror(self->db);
259 return NULL;
260 } else {
261 self->db = NULL;
262 }
263 }
264
265 Py_INCREF(Py_None);
266 return Py_None;
267}
268
269/*
270 * Checks if a connection object is usable (i. e. not closed).
271 *
272 * 0 => error; 1 => ok
273 */
274int check_connection(Connection* con)
275{
276 if (!con->db) {
277 PyErr_SetString(ProgrammingError, "Cannot operate on a closed database.");
278 return 0;
279 } else {
280 return 1;
281 }
282}
283
284PyObject* _connection_begin(Connection* self)
285{
286 int rc;
287 const char* tail;
288 sqlite3_stmt* statement;
289
290 Py_BEGIN_ALLOW_THREADS
291 rc = sqlite3_prepare(self->db, self->begin_statement, -1, &statement, &tail);
292 Py_END_ALLOW_THREADS
293
294 if (rc != SQLITE_OK) {
295 _seterror(self->db);
296 goto error;
297 }
298
299 rc = _sqlite_step_with_busyhandler(statement, self);
300 if (rc == SQLITE_DONE) {
301 self->inTransaction = 1;
302 } else {
303 _seterror(self->db);
304 }
305
306 Py_BEGIN_ALLOW_THREADS
307 rc = sqlite3_finalize(statement);
308 Py_END_ALLOW_THREADS
309
310 if (rc != SQLITE_OK && !PyErr_Occurred()) {
311 _seterror(self->db);
312 }
313
314error:
315 if (PyErr_Occurred()) {
316 return NULL;
317 } else {
318 Py_INCREF(Py_None);
319 return Py_None;
320 }
321}
322
323PyObject* connection_commit(Connection* self, PyObject* args)
324{
325 int rc;
326 const char* tail;
327 sqlite3_stmt* statement;
328
329 if (!check_thread(self) || !check_connection(self)) {
330 return NULL;
331 }
332
333 if (self->inTransaction) {
334 Py_BEGIN_ALLOW_THREADS
335 rc = sqlite3_prepare(self->db, "COMMIT", -1, &statement, &tail);
336 Py_END_ALLOW_THREADS
337 if (rc != SQLITE_OK) {
338 _seterror(self->db);
339 goto error;
340 }
341
342 rc = _sqlite_step_with_busyhandler(statement, self);
343 if (rc == SQLITE_DONE) {
344 self->inTransaction = 0;
345 } else {
346 _seterror(self->db);
347 }
348
349 Py_BEGIN_ALLOW_THREADS
350 rc = sqlite3_finalize(statement);
351 Py_END_ALLOW_THREADS
352 if (rc != SQLITE_OK && !PyErr_Occurred()) {
353 _seterror(self->db);
354 }
355
356 }
357
358error:
359 if (PyErr_Occurred()) {
360 return NULL;
361 } else {
362 Py_INCREF(Py_None);
363 return Py_None;
364 }
365}
366
367PyObject* connection_rollback(Connection* self, PyObject* args)
368{
369 int rc;
370 const char* tail;
371 sqlite3_stmt* statement;
372
373 if (!check_thread(self) || !check_connection(self)) {
374 return NULL;
375 }
376
377 if (self->inTransaction) {
378 reset_all_statements(self);
379
380 Py_BEGIN_ALLOW_THREADS
381 rc = sqlite3_prepare(self->db, "ROLLBACK", -1, &statement, &tail);
382 Py_END_ALLOW_THREADS
383 if (rc != SQLITE_OK) {
384 _seterror(self->db);
385 goto error;
386 }
387
388 rc = _sqlite_step_with_busyhandler(statement, self);
389 if (rc == SQLITE_DONE) {
390 self->inTransaction = 0;
391 } else {
392 _seterror(self->db);
393 }
394
395 Py_BEGIN_ALLOW_THREADS
396 rc = sqlite3_finalize(statement);
397 Py_END_ALLOW_THREADS
398 if (rc != SQLITE_OK && !PyErr_Occurred()) {
399 _seterror(self->db);
400 }
401
402 }
403
404error:
405 if (PyErr_Occurred()) {
406 return NULL;
407 } else {
408 Py_INCREF(Py_None);
409 return Py_None;
410 }
411}
412
413void _set_result(sqlite3_context* context, PyObject* py_val)
414{
415 long longval;
416 const char* buffer;
Neal Norwitz95f0e4c2006-04-01 09:08:06 +0000417 Py_ssize_t buflen;
Anthony Baxterc51ee692006-04-01 00:57:31 +0000418 PyObject* stringval;
419
Gerhard Häring3e99c0a2006-04-23 15:24:26 +0000420 if ((!py_val) || PyErr_Occurred()) {
Anthony Baxterc51ee692006-04-01 00:57:31 +0000421 sqlite3_result_null(context);
422 } else if (py_val == Py_None) {
423 sqlite3_result_null(context);
424 } else if (PyInt_Check(py_val)) {
425 longval = PyInt_AsLong(py_val);
Anthony Baxterc51ee692006-04-01 00:57:31 +0000426 sqlite3_result_int64(context, (PY_LONG_LONG)longval);
427 } else if (PyFloat_Check(py_val)) {
428 sqlite3_result_double(context, PyFloat_AsDouble(py_val));
429 } else if (PyBuffer_Check(py_val)) {
430 if (PyObject_AsCharBuffer(py_val, &buffer, &buflen) != 0) {
431 PyErr_SetString(PyExc_ValueError, "could not convert BLOB to buffer");
Gerhard Häring3e99c0a2006-04-23 15:24:26 +0000432 } else {
433 sqlite3_result_blob(context, buffer, buflen, SQLITE_TRANSIENT);
Anthony Baxterc51ee692006-04-01 00:57:31 +0000434 }
Anthony Baxterc51ee692006-04-01 00:57:31 +0000435 } else if (PyString_Check(py_val)) {
436 sqlite3_result_text(context, PyString_AsString(py_val), -1, SQLITE_TRANSIENT);
437 } else if (PyUnicode_Check(py_val)) {
438 stringval = PyUnicode_AsUTF8String(py_val);
Gerhard Häring3e99c0a2006-04-23 15:24:26 +0000439 if (stringval) {
440 sqlite3_result_text(context, PyString_AsString(stringval), -1, SQLITE_TRANSIENT);
441 Py_DECREF(stringval);
442 }
Anthony Baxterc51ee692006-04-01 00:57:31 +0000443 } else {
444 /* TODO: raise error */
445 }
446}
447
448PyObject* _build_py_params(sqlite3_context *context, int argc, sqlite3_value** argv)
449{
450 PyObject* args;
451 int i;
452 sqlite3_value* cur_value;
453 PyObject* cur_py_value;
454 const char* val_str;
455 PY_LONG_LONG val_int;
Neal Norwitz95f0e4c2006-04-01 09:08:06 +0000456 Py_ssize_t buflen;
Anthony Baxterc51ee692006-04-01 00:57:31 +0000457 void* raw_buffer;
458
459 args = PyTuple_New(argc);
Anthony Baxter72289a62006-04-04 06:29:05 +0000460 if (!args) {
461 return NULL;
462 }
Anthony Baxterc51ee692006-04-01 00:57:31 +0000463
464 for (i = 0; i < argc; i++) {
465 cur_value = argv[i];
466 switch (sqlite3_value_type(argv[i])) {
467 case SQLITE_INTEGER:
468 val_int = sqlite3_value_int64(cur_value);
469 cur_py_value = PyInt_FromLong((long)val_int);
470 break;
471 case SQLITE_FLOAT:
472 cur_py_value = PyFloat_FromDouble(sqlite3_value_double(cur_value));
473 break;
474 case SQLITE_TEXT:
475 val_str = (const char*)sqlite3_value_text(cur_value);
476 cur_py_value = PyUnicode_DecodeUTF8(val_str, strlen(val_str), NULL);
477 /* TODO: have a way to show errors here */
478 if (!cur_py_value) {
Gerhard Häring3e99c0a2006-04-23 15:24:26 +0000479 PyErr_Clear();
Anthony Baxterc51ee692006-04-01 00:57:31 +0000480 Py_INCREF(Py_None);
481 cur_py_value = Py_None;
482 }
483 break;
484 case SQLITE_BLOB:
485 buflen = sqlite3_value_bytes(cur_value);
486 cur_py_value = PyBuffer_New(buflen);
487 if (!cur_py_value) {
Gerhard Häring3e99c0a2006-04-23 15:24:26 +0000488 break;
Anthony Baxterc51ee692006-04-01 00:57:31 +0000489 }
490 if (PyObject_AsWriteBuffer(cur_py_value, &raw_buffer, &buflen)) {
Gerhard Häring3e99c0a2006-04-23 15:24:26 +0000491 Py_DECREF(cur_py_value);
492 cur_py_value = NULL;
493 break;
Anthony Baxterc51ee692006-04-01 00:57:31 +0000494 }
495 memcpy(raw_buffer, sqlite3_value_blob(cur_value), buflen);
496 break;
497 case SQLITE_NULL:
498 default:
499 Py_INCREF(Py_None);
500 cur_py_value = Py_None;
501 }
Gerhard Häring3e99c0a2006-04-23 15:24:26 +0000502
503 if (!cur_py_value) {
504 Py_DECREF(args);
505 return NULL;
506 }
507
Anthony Baxterc51ee692006-04-01 00:57:31 +0000508 PyTuple_SetItem(args, i, cur_py_value);
509
510 }
511
512 return args;
513}
514
515void _func_callback(sqlite3_context* context, int argc, sqlite3_value** argv)
516{
517 PyObject* args;
518 PyObject* py_func;
Gerhard Häring3e99c0a2006-04-23 15:24:26 +0000519 PyObject* py_retval = NULL;
Anthony Baxterc51ee692006-04-01 00:57:31 +0000520
521 PyGILState_STATE threadstate;
522
523 threadstate = PyGILState_Ensure();
524
525 py_func = (PyObject*)sqlite3_user_data(context);
526
527 args = _build_py_params(context, argc, argv);
Gerhard Häring3e99c0a2006-04-23 15:24:26 +0000528 if (args) {
529 py_retval = PyObject_CallObject(py_func, args);
530 Py_DECREF(args);
531 }
Anthony Baxterc51ee692006-04-01 00:57:31 +0000532
Gerhard Häring1541ef02006-06-13 22:24:47 +0000533 if (py_retval) {
534 _set_result(context, py_retval);
535 Py_DECREF(py_retval);
536 } else {
537 if (_enable_callback_tracebacks) {
538 PyErr_Print();
539 } else {
540 PyErr_Clear();
541 }
Gerhard Häringb2e88162006-06-14 22:28:37 +0000542 _sqlite3_result_error(context, "user-defined function raised exception", -1);
Gerhard Häring1541ef02006-06-13 22:24:47 +0000543 }
Anthony Baxterc51ee692006-04-01 00:57:31 +0000544
545 PyGILState_Release(threadstate);
546}
547
548static void _step_callback(sqlite3_context *context, int argc, sqlite3_value** params)
549{
550 PyObject* args;
Gerhard Häring3e99c0a2006-04-23 15:24:26 +0000551 PyObject* function_result = NULL;
Anthony Baxterc51ee692006-04-01 00:57:31 +0000552 PyObject* aggregate_class;
553 PyObject** aggregate_instance;
Gerhard Häring3e99c0a2006-04-23 15:24:26 +0000554 PyObject* stepmethod = NULL;
Anthony Baxterc51ee692006-04-01 00:57:31 +0000555
556 PyGILState_STATE threadstate;
557
558 threadstate = PyGILState_Ensure();
559
560 aggregate_class = (PyObject*)sqlite3_user_data(context);
561
562 aggregate_instance = (PyObject**)sqlite3_aggregate_context(context, sizeof(PyObject*));
563
564 if (*aggregate_instance == 0) {
565 *aggregate_instance = PyObject_CallFunction(aggregate_class, "");
566
Gerhard Häring3e99c0a2006-04-23 15:24:26 +0000567 if (PyErr_Occurred()) {
Anthony Baxterc51ee692006-04-01 00:57:31 +0000568 *aggregate_instance = 0;
Gerhard Häring1541ef02006-06-13 22:24:47 +0000569 if (_enable_callback_tracebacks) {
570 PyErr_Print();
571 } else {
572 PyErr_Clear();
573 }
Gerhard Häringb2e88162006-06-14 22:28:37 +0000574 _sqlite3_result_error(context, "user-defined aggregate's '__init__' method raised error", -1);
Gerhard Häring3e99c0a2006-04-23 15:24:26 +0000575 goto error;
Anthony Baxterc51ee692006-04-01 00:57:31 +0000576 }
577 }
578
579 stepmethod = PyObject_GetAttrString(*aggregate_instance, "step");
Gerhard Häring3e99c0a2006-04-23 15:24:26 +0000580 if (!stepmethod) {
581 goto error;
Anthony Baxterc51ee692006-04-01 00:57:31 +0000582 }
583
584 args = _build_py_params(context, argc, params);
Gerhard Häring3e99c0a2006-04-23 15:24:26 +0000585 if (!args) {
586 goto error;
587 }
Anthony Baxterc51ee692006-04-01 00:57:31 +0000588
589 function_result = PyObject_CallObject(stepmethod, args);
590 Py_DECREF(args);
Anthony Baxterc51ee692006-04-01 00:57:31 +0000591
Gerhard Häring3e99c0a2006-04-23 15:24:26 +0000592 if (!function_result) {
Gerhard Häring1541ef02006-06-13 22:24:47 +0000593 if (_enable_callback_tracebacks) {
594 PyErr_Print();
595 } else {
596 PyErr_Clear();
597 }
Gerhard Häringb2e88162006-06-14 22:28:37 +0000598 _sqlite3_result_error(context, "user-defined aggregate's 'step' method raised error", -1);
Anthony Baxterc51ee692006-04-01 00:57:31 +0000599 }
600
Gerhard Häring3e99c0a2006-04-23 15:24:26 +0000601error:
602 Py_XDECREF(stepmethod);
603 Py_XDECREF(function_result);
604
Anthony Baxterc51ee692006-04-01 00:57:31 +0000605 PyGILState_Release(threadstate);
606}
607
608void _final_callback(sqlite3_context* context)
609{
Gerhard Häring3e99c0a2006-04-23 15:24:26 +0000610 PyObject* function_result = NULL;
Anthony Baxterc51ee692006-04-01 00:57:31 +0000611 PyObject** aggregate_instance;
612 PyObject* aggregate_class;
Anthony Baxterc51ee692006-04-01 00:57:31 +0000613
614 PyGILState_STATE threadstate;
615
616 threadstate = PyGILState_Ensure();
617
618 aggregate_class = (PyObject*)sqlite3_user_data(context);
619
620 aggregate_instance = (PyObject**)sqlite3_aggregate_context(context, sizeof(PyObject*));
621 if (!*aggregate_instance) {
622 /* this branch is executed if there was an exception in the aggregate's
623 * __init__ */
624
Gerhard Häring3e99c0a2006-04-23 15:24:26 +0000625 goto error;
Anthony Baxterc51ee692006-04-01 00:57:31 +0000626 }
627
Gerhard Häring3e99c0a2006-04-23 15:24:26 +0000628 function_result = PyObject_CallMethod(*aggregate_instance, "finalize", "");
629 if (!function_result) {
Gerhard Häring1541ef02006-06-13 22:24:47 +0000630 if (_enable_callback_tracebacks) {
631 PyErr_Print();
632 } else {
633 PyErr_Clear();
634 }
Gerhard Häringb2e88162006-06-14 22:28:37 +0000635 _sqlite3_result_error(context, "user-defined aggregate's 'finalize' method raised error", -1);
Gerhard Häring1541ef02006-06-13 22:24:47 +0000636 } else {
637 _set_result(context, function_result);
Anthony Baxterc51ee692006-04-01 00:57:31 +0000638 }
639
Gerhard Häring3e99c0a2006-04-23 15:24:26 +0000640error:
Anthony Baxterc51ee692006-04-01 00:57:31 +0000641 Py_XDECREF(*aggregate_instance);
642 Py_XDECREF(function_result);
643
644 PyGILState_Release(threadstate);
645}
646
Gerhard Häring3e99c0a2006-04-23 15:24:26 +0000647void _drop_unused_statement_references(Connection* self)
648{
649 PyObject* new_list;
650 PyObject* weakref;
651 int i;
652
653 /* we only need to do this once in a while */
654 if (self->created_statements++ < 200) {
655 return;
656 }
657
658 self->created_statements = 0;
659
660 new_list = PyList_New(0);
661 if (!new_list) {
662 return;
663 }
664
665 for (i = 0; i < PyList_Size(self->statements); i++) {
666 weakref = PyList_GetItem(self->statements, i);
Gerhard Häringecd20102006-06-19 21:17:35 +0000667 if (PyWeakref_GetObject(weakref) != Py_None) {
Gerhard Häring3e99c0a2006-04-23 15:24:26 +0000668 if (PyList_Append(new_list, weakref) != 0) {
669 Py_DECREF(new_list);
670 return;
671 }
672 }
673 }
674
675 Py_DECREF(self->statements);
676 self->statements = new_list;
677}
Anthony Baxterc51ee692006-04-01 00:57:31 +0000678
679PyObject* connection_create_function(Connection* self, PyObject* args, PyObject* kwargs)
680{
681 static char *kwlist[] = {"name", "narg", "func", NULL, NULL};
682
683 PyObject* func;
684 char* name;
685 int narg;
686 int rc;
687
688 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "siO", kwlist,
689 &name, &narg, &func))
690 {
691 return NULL;
692 }
693
694 rc = sqlite3_create_function(self->db, name, narg, SQLITE_UTF8, (void*)func, _func_callback, NULL, NULL);
695
Gerhard Häring3e99c0a2006-04-23 15:24:26 +0000696 if (rc != SQLITE_OK) {
697 /* Workaround for SQLite bug: no error code or string is available here */
698 PyErr_SetString(OperationalError, "Error creating function");
699 return NULL;
700 } else {
701 PyDict_SetItem(self->function_pinboard, func, Py_None);
Anthony Baxterc51ee692006-04-01 00:57:31 +0000702
Gerhard Häring3e99c0a2006-04-23 15:24:26 +0000703 Py_INCREF(Py_None);
704 return Py_None;
705 }
Anthony Baxterc51ee692006-04-01 00:57:31 +0000706}
707
708PyObject* connection_create_aggregate(Connection* self, PyObject* args, PyObject* kwargs)
709{
710 PyObject* aggregate_class;
711
712 int n_arg;
713 char* name;
714 static char *kwlist[] = { "name", "n_arg", "aggregate_class", NULL };
715 int rc;
716
717 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "siO:create_aggregate",
718 kwlist, &name, &n_arg, &aggregate_class)) {
719 return NULL;
720 }
721
722 rc = sqlite3_create_function(self->db, name, n_arg, SQLITE_UTF8, (void*)aggregate_class, 0, &_step_callback, &_final_callback);
723 if (rc != SQLITE_OK) {
Gerhard Häring3e99c0a2006-04-23 15:24:26 +0000724 /* Workaround for SQLite bug: no error code or string is available here */
725 PyErr_SetString(OperationalError, "Error creating aggregate");
Anthony Baxterc51ee692006-04-01 00:57:31 +0000726 return NULL;
727 } else {
728 PyDict_SetItem(self->function_pinboard, aggregate_class, Py_None);
729
730 Py_INCREF(Py_None);
731 return Py_None;
732 }
733}
734
Gerhard Häring1541ef02006-06-13 22:24:47 +0000735int _authorizer_callback(void* user_arg, int action, const char* arg1, const char* arg2 , const char* dbname, const char* access_attempt_source)
736{
737 PyObject *ret;
738 int rc;
739 PyGILState_STATE gilstate;
740
741 gilstate = PyGILState_Ensure();
742 ret = PyObject_CallFunction((PyObject*)user_arg, "issss", action, arg1, arg2, dbname, access_attempt_source);
743
744 if (!ret) {
745 if (_enable_callback_tracebacks) {
746 PyErr_Print();
747 } else {
748 PyErr_Clear();
749 }
750
751 rc = SQLITE_DENY;
752 } else {
753 if (PyInt_Check(ret)) {
754 rc = (int)PyInt_AsLong(ret);
755 } else {
756 rc = SQLITE_DENY;
757 }
758 Py_DECREF(ret);
759 }
760
761 PyGILState_Release(gilstate);
762 return rc;
763}
764
765PyObject* connection_set_authorizer(Connection* self, PyObject* args, PyObject* kwargs)
766{
767 PyObject* authorizer_cb;
768
769 static char *kwlist[] = { "authorizer_callback", NULL };
770 int rc;
771
772 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O:set_authorizer",
773 kwlist, &authorizer_cb)) {
774 return NULL;
775 }
776
777 rc = sqlite3_set_authorizer(self->db, _authorizer_callback, (void*)authorizer_cb);
778
779 if (rc != SQLITE_OK) {
780 PyErr_SetString(OperationalError, "Error setting authorizer callback");
781 return NULL;
782 } else {
783 PyDict_SetItem(self->function_pinboard, authorizer_cb, Py_None);
784
785 Py_INCREF(Py_None);
786 return Py_None;
787 }
788}
789
Anthony Baxterc51ee692006-04-01 00:57:31 +0000790int check_thread(Connection* self)
791{
792 if (self->check_same_thread) {
793 if (PyThread_get_thread_ident() != self->thread_ident) {
794 PyErr_Format(ProgrammingError,
795 "SQLite objects created in a thread can only be used in that same thread."
796 "The object was created in thread id %ld and this is thread id %ld",
797 self->thread_ident, PyThread_get_thread_ident());
798 return 0;
799 }
800
801 }
802
803 return 1;
804}
805
806static PyObject* connection_get_isolation_level(Connection* self, void* unused)
807{
808 Py_INCREF(self->isolation_level);
809 return self->isolation_level;
810}
811
Anthony Baxter72289a62006-04-04 06:29:05 +0000812static PyObject* connection_get_total_changes(Connection* self, void* unused)
813{
814 if (!check_connection(self)) {
815 return NULL;
816 } else {
817 return Py_BuildValue("i", sqlite3_total_changes(self->db));
818 }
819}
820
Anthony Baxterc51ee692006-04-01 00:57:31 +0000821static int connection_set_isolation_level(Connection* self, PyObject* isolation_level)
822{
Anthony Baxterc51ee692006-04-01 00:57:31 +0000823 PyObject* res;
824 PyObject* begin_statement;
825
826 Py_XDECREF(self->isolation_level);
827
Neal Norwitz5b030652006-04-16 03:28:17 +0000828 if (self->begin_statement) {
829 PyMem_Free(self->begin_statement);
830 self->begin_statement = NULL;
831 }
832
Anthony Baxterc51ee692006-04-01 00:57:31 +0000833 if (isolation_level == Py_None) {
834 Py_INCREF(Py_None);
Anthony Baxterc51ee692006-04-01 00:57:31 +0000835 self->isolation_level = Py_None;
836
Gerhard Häring3e99c0a2006-04-23 15:24:26 +0000837 res = connection_commit(self, NULL);
Anthony Baxter72289a62006-04-04 06:29:05 +0000838 if (!res) {
839 return -1;
840 }
Anthony Baxterc51ee692006-04-01 00:57:31 +0000841 Py_DECREF(res);
842
843 self->inTransaction = 0;
844 } else {
845 Py_INCREF(isolation_level);
846 self->isolation_level = isolation_level;
847
848 begin_statement = PyString_FromString("BEGIN ");
849 if (!begin_statement) {
850 return -1;
851 }
852 PyString_Concat(&begin_statement, isolation_level);
853 if (!begin_statement) {
854 return -1;
855 }
856
857 self->begin_statement = PyMem_Malloc(PyString_Size(begin_statement) + 2);
858 if (!self->begin_statement) {
859 return -1;
860 }
861
862 strcpy(self->begin_statement, PyString_AsString(begin_statement));
863 Py_DECREF(begin_statement);
864 }
865
866 return 0;
867}
868
869PyObject* connection_call(Connection* self, PyObject* args, PyObject* kwargs)
870{
871 PyObject* sql;
872 Statement* statement;
Gerhard Häring3e99c0a2006-04-23 15:24:26 +0000873 PyObject* weakref;
Anthony Baxterc51ee692006-04-01 00:57:31 +0000874 int rc;
875
876 if (!PyArg_ParseTuple(args, "O", &sql)) {
877 return NULL;
878 }
879
Gerhard Häring3e99c0a2006-04-23 15:24:26 +0000880 _drop_unused_statement_references(self);
881
Anthony Baxterc51ee692006-04-01 00:57:31 +0000882 statement = PyObject_New(Statement, &StatementType);
883 if (!statement) {
884 return NULL;
885 }
886
887 rc = statement_create(statement, self, sql);
888
889 if (rc != SQLITE_OK) {
890 if (rc == PYSQLITE_TOO_MUCH_SQL) {
891 PyErr_SetString(Warning, "You can only execute one statement at a time.");
892 } else if (rc == PYSQLITE_SQL_WRONG_TYPE) {
893 PyErr_SetString(Warning, "SQL is of wrong type. Must be string or unicode.");
894 } else {
895 _seterror(self->db);
896 }
897
898 Py_DECREF(statement);
899 statement = 0;
Gerhard Häring3e99c0a2006-04-23 15:24:26 +0000900 } else {
901 weakref = PyWeakref_NewRef((PyObject*)statement, NULL);
902 if (!weakref) {
903 Py_DECREF(statement);
904 statement = 0;
905 goto error;
906 }
907
908 if (PyList_Append(self->statements, weakref) != 0) {
909 Py_DECREF(weakref);
910 statement = 0;
911 goto error;
912 }
913
914 Py_DECREF(weakref);
Anthony Baxterc51ee692006-04-01 00:57:31 +0000915 }
916
Gerhard Häring3e99c0a2006-04-23 15:24:26 +0000917error:
Anthony Baxterc51ee692006-04-01 00:57:31 +0000918 return (PyObject*)statement;
919}
920
921PyObject* connection_execute(Connection* self, PyObject* args, PyObject* kwargs)
922{
923 PyObject* cursor = 0;
924 PyObject* result = 0;
925 PyObject* method = 0;
926
927 cursor = PyObject_CallMethod((PyObject*)self, "cursor", "");
928 if (!cursor) {
929 goto error;
930 }
931
932 method = PyObject_GetAttrString(cursor, "execute");
933 if (!method) {
934 Py_DECREF(cursor);
935 cursor = 0;
936 goto error;
937 }
938
939 result = PyObject_CallObject(method, args);
940 if (!result) {
941 Py_DECREF(cursor);
942 cursor = 0;
943 }
944
945error:
946 Py_XDECREF(result);
947 Py_XDECREF(method);
948
949 return cursor;
950}
951
952PyObject* connection_executemany(Connection* self, PyObject* args, PyObject* kwargs)
953{
954 PyObject* cursor = 0;
955 PyObject* result = 0;
956 PyObject* method = 0;
957
958 cursor = PyObject_CallMethod((PyObject*)self, "cursor", "");
959 if (!cursor) {
960 goto error;
961 }
962
963 method = PyObject_GetAttrString(cursor, "executemany");
964 if (!method) {
965 Py_DECREF(cursor);
966 cursor = 0;
967 goto error;
968 }
969
970 result = PyObject_CallObject(method, args);
971 if (!result) {
972 Py_DECREF(cursor);
973 cursor = 0;
974 }
975
976error:
977 Py_XDECREF(result);
978 Py_XDECREF(method);
979
980 return cursor;
981}
982
983PyObject* connection_executescript(Connection* self, PyObject* args, PyObject* kwargs)
984{
985 PyObject* cursor = 0;
986 PyObject* result = 0;
987 PyObject* method = 0;
988
989 cursor = PyObject_CallMethod((PyObject*)self, "cursor", "");
990 if (!cursor) {
991 goto error;
992 }
993
994 method = PyObject_GetAttrString(cursor, "executescript");
995 if (!method) {
996 Py_DECREF(cursor);
997 cursor = 0;
998 goto error;
999 }
1000
1001 result = PyObject_CallObject(method, args);
1002 if (!result) {
1003 Py_DECREF(cursor);
1004 cursor = 0;
1005 }
1006
1007error:
1008 Py_XDECREF(result);
1009 Py_XDECREF(method);
1010
1011 return cursor;
1012}
1013
Anthony Baxter72289a62006-04-04 06:29:05 +00001014/* ------------------------- COLLATION CODE ------------------------ */
1015
1016static int
1017collation_callback(
1018 void* context,
1019 int text1_length, const void* text1_data,
1020 int text2_length, const void* text2_data)
1021{
1022 PyObject* callback = (PyObject*)context;
1023 PyObject* string1 = 0;
1024 PyObject* string2 = 0;
1025 PyGILState_STATE gilstate;
1026
1027 PyObject* retval = NULL;
1028 int result = 0;
1029
1030 gilstate = PyGILState_Ensure();
1031
1032 if (PyErr_Occurred()) {
1033 goto finally;
1034 }
1035
1036 string1 = PyString_FromStringAndSize((const char*)text1_data, text1_length);
1037 string2 = PyString_FromStringAndSize((const char*)text2_data, text2_length);
1038
1039 if (!string1 || !string2) {
1040 goto finally; /* failed to allocate strings */
1041 }
1042
1043 retval = PyObject_CallFunctionObjArgs(callback, string1, string2, NULL);
1044
1045 if (!retval) {
1046 /* execution failed */
1047 goto finally;
1048 }
1049
1050 result = PyInt_AsLong(retval);
1051 if (PyErr_Occurred()) {
1052 result = 0;
1053 }
1054
1055finally:
1056 Py_XDECREF(string1);
1057 Py_XDECREF(string2);
1058 Py_XDECREF(retval);
1059
1060 PyGILState_Release(gilstate);
1061
1062 return result;
1063}
1064
1065static PyObject *
Gerhard Häring1541ef02006-06-13 22:24:47 +00001066connection_interrupt(Connection* self, PyObject* args)
1067{
1068 PyObject* retval = NULL;
1069
1070 if (!check_connection(self)) {
1071 goto finally;
1072 }
1073
1074 sqlite3_interrupt(self->db);
1075
1076 Py_INCREF(Py_None);
1077 retval = Py_None;
1078
1079finally:
1080 return retval;
1081}
1082
1083static PyObject *
Anthony Baxter72289a62006-04-04 06:29:05 +00001084connection_create_collation(Connection* self, PyObject* args)
1085{
1086 PyObject* callable;
1087 PyObject* uppercase_name = 0;
1088 PyObject* name;
1089 PyObject* retval;
1090 char* chk;
1091 int rc;
1092
1093 if (!check_thread(self) || !check_connection(self)) {
1094 goto finally;
1095 }
1096
1097 if (!PyArg_ParseTuple(args, "O!O:create_collation(name, callback)", &PyString_Type, &name, &callable)) {
1098 goto finally;
1099 }
1100
1101 uppercase_name = PyObject_CallMethod(name, "upper", "");
1102 if (!uppercase_name) {
1103 goto finally;
1104 }
1105
1106 chk = PyString_AsString(uppercase_name);
1107 while (*chk) {
1108 if ((*chk >= '0' && *chk <= '9')
1109 || (*chk >= 'A' && *chk <= 'Z')
1110 || (*chk == '_'))
1111 {
1112 chk++;
1113 } else {
1114 PyErr_SetString(ProgrammingError, "invalid character in collation name");
1115 goto finally;
1116 }
1117 }
1118
1119 if (callable != Py_None && !PyCallable_Check(callable)) {
1120 PyErr_SetString(PyExc_TypeError, "parameter must be callable");
1121 goto finally;
1122 }
1123
1124 if (callable != Py_None) {
1125 PyDict_SetItem(self->collations, uppercase_name, callable);
1126 } else {
1127 PyDict_DelItem(self->collations, uppercase_name);
1128 }
1129
1130 rc = sqlite3_create_collation(self->db,
1131 PyString_AsString(uppercase_name),
1132 SQLITE_UTF8,
1133 (callable != Py_None) ? callable : NULL,
1134 (callable != Py_None) ? collation_callback : NULL);
1135 if (rc != SQLITE_OK) {
1136 PyDict_DelItem(self->collations, uppercase_name);
1137 _seterror(self->db);
1138 goto finally;
1139 }
1140
1141finally:
1142 Py_XDECREF(uppercase_name);
1143
1144 if (PyErr_Occurred()) {
1145 retval = NULL;
1146 } else {
1147 Py_INCREF(Py_None);
1148 retval = Py_None;
1149 }
1150
1151 return retval;
1152}
1153
Anthony Baxterc51ee692006-04-01 00:57:31 +00001154static char connection_doc[] =
Gerhard Häring3e99c0a2006-04-23 15:24:26 +00001155PyDoc_STR("SQLite database connection object.");
Anthony Baxterc51ee692006-04-01 00:57:31 +00001156
1157static PyGetSetDef connection_getset[] = {
1158 {"isolation_level", (getter)connection_get_isolation_level, (setter)connection_set_isolation_level},
Anthony Baxter72289a62006-04-04 06:29:05 +00001159 {"total_changes", (getter)connection_get_total_changes, (setter)0},
Anthony Baxterc51ee692006-04-01 00:57:31 +00001160 {NULL}
1161};
1162
1163static PyMethodDef connection_methods[] = {
1164 {"cursor", (PyCFunction)connection_cursor, METH_VARARGS|METH_KEYWORDS,
1165 PyDoc_STR("Return a cursor for the connection.")},
1166 {"close", (PyCFunction)connection_close, METH_NOARGS,
1167 PyDoc_STR("Closes the connection.")},
1168 {"commit", (PyCFunction)connection_commit, METH_NOARGS,
1169 PyDoc_STR("Commit the current transaction.")},
1170 {"rollback", (PyCFunction)connection_rollback, METH_NOARGS,
1171 PyDoc_STR("Roll back the current transaction.")},
1172 {"create_function", (PyCFunction)connection_create_function, METH_VARARGS|METH_KEYWORDS,
1173 PyDoc_STR("Creates a new function. Non-standard.")},
1174 {"create_aggregate", (PyCFunction)connection_create_aggregate, METH_VARARGS|METH_KEYWORDS,
1175 PyDoc_STR("Creates a new aggregate. Non-standard.")},
Gerhard Häring1541ef02006-06-13 22:24:47 +00001176 {"set_authorizer", (PyCFunction)connection_set_authorizer, METH_VARARGS|METH_KEYWORDS,
1177 PyDoc_STR("Sets authorizer callback. Non-standard.")},
Anthony Baxterc51ee692006-04-01 00:57:31 +00001178 {"execute", (PyCFunction)connection_execute, METH_VARARGS,
1179 PyDoc_STR("Executes a SQL statement. Non-standard.")},
1180 {"executemany", (PyCFunction)connection_executemany, METH_VARARGS,
1181 PyDoc_STR("Repeatedly executes a SQL statement. Non-standard.")},
1182 {"executescript", (PyCFunction)connection_executescript, METH_VARARGS,
1183 PyDoc_STR("Executes a multiple SQL statements at once. Non-standard.")},
Anthony Baxter72289a62006-04-04 06:29:05 +00001184 {"create_collation", (PyCFunction)connection_create_collation, METH_VARARGS,
Gerhard Häring3e99c0a2006-04-23 15:24:26 +00001185 PyDoc_STR("Creates a collation function. Non-standard.")},
Gerhard Häring1541ef02006-06-13 22:24:47 +00001186 {"interrupt", (PyCFunction)connection_interrupt, METH_NOARGS,
1187 PyDoc_STR("Abort any pending database operation. Non-standard.")},
Anthony Baxterc51ee692006-04-01 00:57:31 +00001188 {NULL, NULL}
1189};
1190
1191static struct PyMemberDef connection_members[] =
1192{
1193 {"Warning", T_OBJECT, offsetof(Connection, Warning), RO},
1194 {"Error", T_OBJECT, offsetof(Connection, Error), RO},
1195 {"InterfaceError", T_OBJECT, offsetof(Connection, InterfaceError), RO},
1196 {"DatabaseError", T_OBJECT, offsetof(Connection, DatabaseError), RO},
1197 {"DataError", T_OBJECT, offsetof(Connection, DataError), RO},
1198 {"OperationalError", T_OBJECT, offsetof(Connection, OperationalError), RO},
1199 {"IntegrityError", T_OBJECT, offsetof(Connection, IntegrityError), RO},
1200 {"InternalError", T_OBJECT, offsetof(Connection, InternalError), RO},
1201 {"ProgrammingError", T_OBJECT, offsetof(Connection, ProgrammingError), RO},
1202 {"NotSupportedError", T_OBJECT, offsetof(Connection, NotSupportedError), RO},
1203 {"row_factory", T_OBJECT, offsetof(Connection, row_factory)},
1204 {"text_factory", T_OBJECT, offsetof(Connection, text_factory)},
1205 {NULL}
1206};
1207
1208PyTypeObject ConnectionType = {
1209 PyObject_HEAD_INIT(NULL)
1210 0, /* ob_size */
Anthony Baxter8e7b4902006-04-05 18:25:33 +00001211 MODULE_NAME ".Connection", /* tp_name */
Anthony Baxterc51ee692006-04-01 00:57:31 +00001212 sizeof(Connection), /* tp_basicsize */
1213 0, /* tp_itemsize */
1214 (destructor)connection_dealloc, /* tp_dealloc */
1215 0, /* tp_print */
1216 0, /* tp_getattr */
1217 0, /* tp_setattr */
1218 0, /* tp_compare */
1219 0, /* tp_repr */
1220 0, /* tp_as_number */
1221 0, /* tp_as_sequence */
1222 0, /* tp_as_mapping */
1223 0, /* tp_hash */
1224 (ternaryfunc)connection_call, /* tp_call */
1225 0, /* tp_str */
1226 0, /* tp_getattro */
1227 0, /* tp_setattro */
1228 0, /* tp_as_buffer */
1229 Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE, /* tp_flags */
1230 connection_doc, /* tp_doc */
1231 0, /* tp_traverse */
1232 0, /* tp_clear */
1233 0, /* tp_richcompare */
1234 0, /* tp_weaklistoffset */
1235 0, /* tp_iter */
1236 0, /* tp_iternext */
1237 connection_methods, /* tp_methods */
1238 connection_members, /* tp_members */
1239 connection_getset, /* tp_getset */
1240 0, /* tp_base */
1241 0, /* tp_dict */
1242 0, /* tp_descr_get */
1243 0, /* tp_descr_set */
1244 0, /* tp_dictoffset */
1245 (initproc)connection_init, /* tp_init */
1246 0, /* tp_alloc */
1247 0, /* tp_new */
1248 0 /* tp_free */
1249};
1250
1251extern int connection_setup_types(void)
1252{
1253 ConnectionType.tp_new = PyType_GenericNew;
1254 return PyType_Ready(&ConnectionType);
1255}