blob: 78aad3799b3c42498588f117937c03fe4c787383 [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
37int connection_init(Connection* self, PyObject* args, PyObject* kwargs)
38{
39 static char *kwlist[] = {"database", "timeout", "detect_types", "isolation_level", "check_same_thread", "factory", "cached_statements", NULL, NULL};
40
41 char* database;
42 int detect_types = 0;
43 PyObject* isolation_level = NULL;
44 PyObject* factory = NULL;
45 int check_same_thread = 1;
46 int cached_statements = 100;
47 double timeout = 5.0;
48 int rc;
49
50 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s|diOiOi", kwlist,
51 &database, &timeout, &detect_types, &isolation_level, &check_same_thread, &factory, &cached_statements))
52 {
53 return -1;
54 }
55
56 self->begin_statement = NULL;
57
58 self->statement_cache = NULL;
59
60 Py_INCREF(Py_None);
61 self->row_factory = Py_None;
62
63 Py_INCREF(&PyUnicode_Type);
64 self->text_factory = (PyObject*)&PyUnicode_Type;
65
66 Py_BEGIN_ALLOW_THREADS
67 rc = sqlite3_open(database, &self->db);
68 Py_END_ALLOW_THREADS
69
70 if (rc != SQLITE_OK) {
71 _seterror(self->db);
72 return -1;
73 }
74
75 if (!isolation_level) {
76 isolation_level = PyString_FromString("");
77 } else {
78 Py_INCREF(isolation_level);
79 }
80 self->isolation_level = NULL;
81 connection_set_isolation_level(self, isolation_level);
82 Py_DECREF(isolation_level);
83
84 self->statement_cache = (Cache*)PyObject_CallFunction((PyObject*)&CacheType, "Oi", self, cached_statements);
85 if (PyErr_Occurred()) {
86 return -1;
87 }
88
89 /* By default, the Cache class INCREFs the factory in its initializer, and
90 * decrefs it in its deallocator method. Since this would create a circular
91 * reference here, we're breaking it by decrementing self, and telling the
92 * cache class to not decref the factory (self) in its deallocator.
93 */
94 self->statement_cache->decref_factory = 0;
95 Py_DECREF(self);
96
97 self->inTransaction = 0;
98 self->detect_types = detect_types;
99 self->timeout = timeout;
100 (void)sqlite3_busy_timeout(self->db, (int)(timeout*1000));
101
102 self->thread_ident = PyThread_get_thread_ident();
103 self->check_same_thread = check_same_thread;
104
105 self->function_pinboard = PyDict_New();
Anthony Baxter72289a62006-04-04 06:29:05 +0000106 if (!self->function_pinboard) {
107 return -1;
108 }
109
110 self->collations = PyDict_New();
111 if (!self->collations) {
112 return -1;
113 }
Anthony Baxterc51ee692006-04-01 00:57:31 +0000114
115 self->Warning = Warning;
116 self->Error = Error;
117 self->InterfaceError = InterfaceError;
118 self->DatabaseError = DatabaseError;
119 self->DataError = DataError;
120 self->OperationalError = OperationalError;
121 self->IntegrityError = IntegrityError;
122 self->InternalError = InternalError;
123 self->ProgrammingError = ProgrammingError;
124 self->NotSupportedError = NotSupportedError;
125
126 return 0;
127}
128
129void flush_statement_cache(Connection* self)
130{
131 Node* node;
132 Statement* statement;
133
134 node = self->statement_cache->first;
135
136 while (node) {
137 statement = (Statement*)(node->data);
138 (void)statement_finalize(statement);
139 node = node->next;
140 }
141
142 Py_DECREF(self->statement_cache);
143 self->statement_cache = (Cache*)PyObject_CallFunction((PyObject*)&CacheType, "O", self);
144 Py_DECREF(self);
145 self->statement_cache->decref_factory = 0;
146}
147
148void reset_all_statements(Connection* self)
149{
150 Node* node;
151 Statement* statement;
152
153 node = self->statement_cache->first;
154
155 while (node) {
156 statement = (Statement*)(node->data);
157 (void)statement_reset(statement);
158 node = node->next;
159 }
160}
161
162void connection_dealloc(Connection* self)
163{
164 Py_XDECREF(self->statement_cache);
165
166 /* Clean up if user has not called .close() explicitly. */
167 if (self->db) {
168 Py_BEGIN_ALLOW_THREADS
169 sqlite3_close(self->db);
170 Py_END_ALLOW_THREADS
171 }
172
173 if (self->begin_statement) {
174 PyMem_Free(self->begin_statement);
175 }
176 Py_XDECREF(self->isolation_level);
177 Py_XDECREF(self->function_pinboard);
178 Py_XDECREF(self->row_factory);
179 Py_XDECREF(self->text_factory);
Anthony Baxter72289a62006-04-04 06:29:05 +0000180 Py_XDECREF(self->collations);
Anthony Baxterc51ee692006-04-01 00:57:31 +0000181
182 self->ob_type->tp_free((PyObject*)self);
183}
184
185PyObject* connection_cursor(Connection* self, PyObject* args, PyObject* kwargs)
186{
187 static char *kwlist[] = {"factory", NULL, NULL};
188 PyObject* factory = NULL;
189 PyObject* cursor;
190
191
192 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|O", kwlist,
193 &factory)) {
194 return NULL;
195 }
196
197 if (!check_thread(self) || !check_connection(self)) {
198 return NULL;
199 }
200
201 if (factory == NULL) {
202 factory = (PyObject*)&CursorType;
203 }
204
205 cursor = PyObject_CallFunction(factory, "O", self);
206
207 if (cursor && self->row_factory != Py_None) {
208 Py_XDECREF(((Cursor*)cursor)->row_factory);
209 Py_INCREF(self->row_factory);
210 ((Cursor*)cursor)->row_factory = self->row_factory;
211 }
212
213 return cursor;
214}
215
216PyObject* connection_close(Connection* self, PyObject* args)
217{
218 int rc;
219
220 if (!check_thread(self)) {
221 return NULL;
222 }
223
224 flush_statement_cache(self);
225
226 if (self->db) {
227 Py_BEGIN_ALLOW_THREADS
228 rc = sqlite3_close(self->db);
229 Py_END_ALLOW_THREADS
230
231 if (rc != SQLITE_OK) {
232 _seterror(self->db);
233 return NULL;
234 } else {
235 self->db = NULL;
236 }
237 }
238
239 Py_INCREF(Py_None);
240 return Py_None;
241}
242
243/*
244 * Checks if a connection object is usable (i. e. not closed).
245 *
246 * 0 => error; 1 => ok
247 */
248int check_connection(Connection* con)
249{
250 if (!con->db) {
251 PyErr_SetString(ProgrammingError, "Cannot operate on a closed database.");
252 return 0;
253 } else {
254 return 1;
255 }
256}
257
258PyObject* _connection_begin(Connection* self)
259{
260 int rc;
261 const char* tail;
262 sqlite3_stmt* statement;
263
264 Py_BEGIN_ALLOW_THREADS
265 rc = sqlite3_prepare(self->db, self->begin_statement, -1, &statement, &tail);
266 Py_END_ALLOW_THREADS
267
268 if (rc != SQLITE_OK) {
269 _seterror(self->db);
270 goto error;
271 }
272
273 rc = _sqlite_step_with_busyhandler(statement, self);
274 if (rc == SQLITE_DONE) {
275 self->inTransaction = 1;
276 } else {
277 _seterror(self->db);
278 }
279
280 Py_BEGIN_ALLOW_THREADS
281 rc = sqlite3_finalize(statement);
282 Py_END_ALLOW_THREADS
283
284 if (rc != SQLITE_OK && !PyErr_Occurred()) {
285 _seterror(self->db);
286 }
287
288error:
289 if (PyErr_Occurred()) {
290 return NULL;
291 } else {
292 Py_INCREF(Py_None);
293 return Py_None;
294 }
295}
296
297PyObject* connection_commit(Connection* self, PyObject* args)
298{
299 int rc;
300 const char* tail;
301 sqlite3_stmt* statement;
302
303 if (!check_thread(self) || !check_connection(self)) {
304 return NULL;
305 }
306
307 if (self->inTransaction) {
308 Py_BEGIN_ALLOW_THREADS
309 rc = sqlite3_prepare(self->db, "COMMIT", -1, &statement, &tail);
310 Py_END_ALLOW_THREADS
311 if (rc != SQLITE_OK) {
312 _seterror(self->db);
313 goto error;
314 }
315
316 rc = _sqlite_step_with_busyhandler(statement, self);
317 if (rc == SQLITE_DONE) {
318 self->inTransaction = 0;
319 } else {
320 _seterror(self->db);
321 }
322
323 Py_BEGIN_ALLOW_THREADS
324 rc = sqlite3_finalize(statement);
325 Py_END_ALLOW_THREADS
326 if (rc != SQLITE_OK && !PyErr_Occurred()) {
327 _seterror(self->db);
328 }
329
330 }
331
332error:
333 if (PyErr_Occurred()) {
334 return NULL;
335 } else {
336 Py_INCREF(Py_None);
337 return Py_None;
338 }
339}
340
341PyObject* connection_rollback(Connection* self, PyObject* args)
342{
343 int rc;
344 const char* tail;
345 sqlite3_stmt* statement;
346
347 if (!check_thread(self) || !check_connection(self)) {
348 return NULL;
349 }
350
351 if (self->inTransaction) {
352 reset_all_statements(self);
353
354 Py_BEGIN_ALLOW_THREADS
355 rc = sqlite3_prepare(self->db, "ROLLBACK", -1, &statement, &tail);
356 Py_END_ALLOW_THREADS
357 if (rc != SQLITE_OK) {
358 _seterror(self->db);
359 goto error;
360 }
361
362 rc = _sqlite_step_with_busyhandler(statement, self);
363 if (rc == SQLITE_DONE) {
364 self->inTransaction = 0;
365 } else {
366 _seterror(self->db);
367 }
368
369 Py_BEGIN_ALLOW_THREADS
370 rc = sqlite3_finalize(statement);
371 Py_END_ALLOW_THREADS
372 if (rc != SQLITE_OK && !PyErr_Occurred()) {
373 _seterror(self->db);
374 }
375
376 }
377
378error:
379 if (PyErr_Occurred()) {
380 return NULL;
381 } else {
382 Py_INCREF(Py_None);
383 return Py_None;
384 }
385}
386
387void _set_result(sqlite3_context* context, PyObject* py_val)
388{
389 long longval;
390 const char* buffer;
Neal Norwitz95f0e4c2006-04-01 09:08:06 +0000391 Py_ssize_t buflen;
Anthony Baxterc51ee692006-04-01 00:57:31 +0000392 PyObject* stringval;
393
394 if (PyErr_Occurred()) {
395 /* Errors in callbacks are ignored, and we return NULL */
396 PyErr_Clear();
397 sqlite3_result_null(context);
398 } else if (py_val == Py_None) {
399 sqlite3_result_null(context);
400 } else if (PyInt_Check(py_val)) {
401 longval = PyInt_AsLong(py_val);
402 /* TODO: investigate what to do with range overflows - long vs. long long */
403 sqlite3_result_int64(context, (PY_LONG_LONG)longval);
404 } else if (PyFloat_Check(py_val)) {
405 sqlite3_result_double(context, PyFloat_AsDouble(py_val));
406 } else if (PyBuffer_Check(py_val)) {
407 if (PyObject_AsCharBuffer(py_val, &buffer, &buflen) != 0) {
408 PyErr_SetString(PyExc_ValueError, "could not convert BLOB to buffer");
409 }
410 sqlite3_result_blob(context, buffer, buflen, SQLITE_TRANSIENT);
411 } else if (PyString_Check(py_val)) {
412 sqlite3_result_text(context, PyString_AsString(py_val), -1, SQLITE_TRANSIENT);
413 } else if (PyUnicode_Check(py_val)) {
414 stringval = PyUnicode_AsUTF8String(py_val);
415 sqlite3_result_text(context, PyString_AsString(stringval), -1, SQLITE_TRANSIENT);
416 Py_DECREF(stringval);
417 } else {
418 /* TODO: raise error */
419 }
420}
421
422PyObject* _build_py_params(sqlite3_context *context, int argc, sqlite3_value** argv)
423{
424 PyObject* args;
425 int i;
426 sqlite3_value* cur_value;
427 PyObject* cur_py_value;
428 const char* val_str;
429 PY_LONG_LONG val_int;
Neal Norwitz95f0e4c2006-04-01 09:08:06 +0000430 Py_ssize_t buflen;
Anthony Baxterc51ee692006-04-01 00:57:31 +0000431 void* raw_buffer;
432
433 args = PyTuple_New(argc);
Anthony Baxter72289a62006-04-04 06:29:05 +0000434 if (!args) {
435 return NULL;
436 }
Anthony Baxterc51ee692006-04-01 00:57:31 +0000437
438 for (i = 0; i < argc; i++) {
439 cur_value = argv[i];
440 switch (sqlite3_value_type(argv[i])) {
441 case SQLITE_INTEGER:
442 val_int = sqlite3_value_int64(cur_value);
443 cur_py_value = PyInt_FromLong((long)val_int);
444 break;
445 case SQLITE_FLOAT:
446 cur_py_value = PyFloat_FromDouble(sqlite3_value_double(cur_value));
447 break;
448 case SQLITE_TEXT:
449 val_str = (const char*)sqlite3_value_text(cur_value);
450 cur_py_value = PyUnicode_DecodeUTF8(val_str, strlen(val_str), NULL);
451 /* TODO: have a way to show errors here */
452 if (!cur_py_value) {
453 Py_INCREF(Py_None);
454 cur_py_value = Py_None;
455 }
456 break;
457 case SQLITE_BLOB:
458 buflen = sqlite3_value_bytes(cur_value);
459 cur_py_value = PyBuffer_New(buflen);
460 if (!cur_py_value) {
461 /* TODO: error */
462 }
463 if (PyObject_AsWriteBuffer(cur_py_value, &raw_buffer, &buflen)) {
464 /* TODO: error */
465 }
466 memcpy(raw_buffer, sqlite3_value_blob(cur_value), buflen);
467 break;
468 case SQLITE_NULL:
469 default:
470 Py_INCREF(Py_None);
471 cur_py_value = Py_None;
472 }
473 PyTuple_SetItem(args, i, cur_py_value);
474
475 }
476
477 return args;
478}
479
480void _func_callback(sqlite3_context* context, int argc, sqlite3_value** argv)
481{
482 PyObject* args;
483 PyObject* py_func;
484 PyObject* py_retval;
485
486
487 PyGILState_STATE threadstate;
488
489 threadstate = PyGILState_Ensure();
490
491 py_func = (PyObject*)sqlite3_user_data(context);
492
493 args = _build_py_params(context, argc, argv);
494
495 py_retval = PyObject_CallObject(py_func, args);
496 Py_DECREF(args);
497
498 _set_result(context, py_retval);
499 Py_XDECREF(py_retval);
500
501 PyGILState_Release(threadstate);
502}
503
504static void _step_callback(sqlite3_context *context, int argc, sqlite3_value** params)
505{
506 PyObject* args;
507 PyObject* function_result;
508 PyObject* aggregate_class;
509 PyObject** aggregate_instance;
510 PyObject* stepmethod;
511
512 PyGILState_STATE threadstate;
513
514 threadstate = PyGILState_Ensure();
515
516 aggregate_class = (PyObject*)sqlite3_user_data(context);
517
518 aggregate_instance = (PyObject**)sqlite3_aggregate_context(context, sizeof(PyObject*));
519
520 if (*aggregate_instance == 0) {
521 *aggregate_instance = PyObject_CallFunction(aggregate_class, "");
522
523 if (PyErr_Occurred())
524 {
525 PyErr_Clear();
526 *aggregate_instance = 0;
527 PyGILState_Release(threadstate);
528 return;
529 }
530 }
531
532 stepmethod = PyObject_GetAttrString(*aggregate_instance, "step");
533 if (!stepmethod)
534 {
535 PyGILState_Release(threadstate);
536 return;
537 }
538
539 args = _build_py_params(context, argc, params);
540
541 function_result = PyObject_CallObject(stepmethod, args);
542 Py_DECREF(args);
543 Py_DECREF(stepmethod);
544
545 if (function_result == NULL) {
546 PyErr_Clear();
547 } else {
548 Py_DECREF(function_result);
549 }
550
551 PyGILState_Release(threadstate);
552}
553
554void _final_callback(sqlite3_context* context)
555{
556 PyObject* args;
557 PyObject* function_result;
558 PyObject** aggregate_instance;
559 PyObject* aggregate_class;
560 PyObject* finalizemethod;
561
562 PyGILState_STATE threadstate;
563
564 threadstate = PyGILState_Ensure();
565
566 aggregate_class = (PyObject*)sqlite3_user_data(context);
567
568 aggregate_instance = (PyObject**)sqlite3_aggregate_context(context, sizeof(PyObject*));
569 if (!*aggregate_instance) {
570 /* this branch is executed if there was an exception in the aggregate's
571 * __init__ */
572
573 PyGILState_Release(threadstate);
574 return;
575 }
576
577 finalizemethod = PyObject_GetAttrString(*aggregate_instance, "finalize");
578
579 if (!finalizemethod) {
580 /*
581 PyErr_SetString(ProgrammingError, "finalize method missing");
582 goto error;
583 */
584 Py_INCREF(Py_None);
585 function_result = Py_None;
586 } else {
587 args = PyTuple_New(0);
Neal Norwitzd1262002006-04-06 08:41:59 +0000588 if (!args)
589 return;
Anthony Baxterc51ee692006-04-01 00:57:31 +0000590 function_result = PyObject_CallObject(finalizemethod, args);
591 Py_DECREF(args);
592 Py_DECREF(finalizemethod);
593 }
594
595 _set_result(context, function_result);
596 Py_XDECREF(*aggregate_instance);
597 Py_XDECREF(function_result);
598
599 PyGILState_Release(threadstate);
600}
601
602
603PyObject* connection_create_function(Connection* self, PyObject* args, PyObject* kwargs)
604{
605 static char *kwlist[] = {"name", "narg", "func", NULL, NULL};
606
607 PyObject* func;
608 char* name;
609 int narg;
610 int rc;
611
612 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "siO", kwlist,
613 &name, &narg, &func))
614 {
615 return NULL;
616 }
617
618 rc = sqlite3_create_function(self->db, name, narg, SQLITE_UTF8, (void*)func, _func_callback, NULL, NULL);
619
620 PyDict_SetItem(self->function_pinboard, func, Py_None);
621
622 Py_INCREF(Py_None);
623 return Py_None;
624}
625
626PyObject* connection_create_aggregate(Connection* self, PyObject* args, PyObject* kwargs)
627{
628 PyObject* aggregate_class;
629
630 int n_arg;
631 char* name;
632 static char *kwlist[] = { "name", "n_arg", "aggregate_class", NULL };
633 int rc;
634
635 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "siO:create_aggregate",
636 kwlist, &name, &n_arg, &aggregate_class)) {
637 return NULL;
638 }
639
640 rc = sqlite3_create_function(self->db, name, n_arg, SQLITE_UTF8, (void*)aggregate_class, 0, &_step_callback, &_final_callback);
641 if (rc != SQLITE_OK) {
642 _seterror(self->db);
643 return NULL;
644 } else {
645 PyDict_SetItem(self->function_pinboard, aggregate_class, Py_None);
646
647 Py_INCREF(Py_None);
648 return Py_None;
649 }
650}
651
652int check_thread(Connection* self)
653{
654 if (self->check_same_thread) {
655 if (PyThread_get_thread_ident() != self->thread_ident) {
656 PyErr_Format(ProgrammingError,
657 "SQLite objects created in a thread can only be used in that same thread."
658 "The object was created in thread id %ld and this is thread id %ld",
659 self->thread_ident, PyThread_get_thread_ident());
660 return 0;
661 }
662
663 }
664
665 return 1;
666}
667
668static PyObject* connection_get_isolation_level(Connection* self, void* unused)
669{
670 Py_INCREF(self->isolation_level);
671 return self->isolation_level;
672}
673
Anthony Baxter72289a62006-04-04 06:29:05 +0000674static PyObject* connection_get_total_changes(Connection* self, void* unused)
675{
676 if (!check_connection(self)) {
677 return NULL;
678 } else {
679 return Py_BuildValue("i", sqlite3_total_changes(self->db));
680 }
681}
682
Anthony Baxterc51ee692006-04-01 00:57:31 +0000683static int connection_set_isolation_level(Connection* self, PyObject* isolation_level)
684{
685 PyObject* empty;
686 PyObject* res;
687 PyObject* begin_statement;
688
689 Py_XDECREF(self->isolation_level);
690
Neal Norwitz5b030652006-04-16 03:28:17 +0000691 if (self->begin_statement) {
692 PyMem_Free(self->begin_statement);
693 self->begin_statement = NULL;
694 }
695
Anthony Baxterc51ee692006-04-01 00:57:31 +0000696 if (isolation_level == Py_None) {
697 Py_INCREF(Py_None);
Anthony Baxterc51ee692006-04-01 00:57:31 +0000698 self->isolation_level = Py_None;
699
700 empty = PyTuple_New(0);
Anthony Baxter72289a62006-04-04 06:29:05 +0000701 if (!empty) {
702 return -1;
703 }
Anthony Baxterc51ee692006-04-01 00:57:31 +0000704 res = connection_commit(self, empty);
Anthony Baxter72289a62006-04-04 06:29:05 +0000705 if (!res) {
706 return -1;
707 }
Anthony Baxterc51ee692006-04-01 00:57:31 +0000708 Py_DECREF(empty);
709 Py_DECREF(res);
710
711 self->inTransaction = 0;
712 } else {
713 Py_INCREF(isolation_level);
714 self->isolation_level = isolation_level;
715
716 begin_statement = PyString_FromString("BEGIN ");
717 if (!begin_statement) {
718 return -1;
719 }
720 PyString_Concat(&begin_statement, isolation_level);
721 if (!begin_statement) {
722 return -1;
723 }
724
725 self->begin_statement = PyMem_Malloc(PyString_Size(begin_statement) + 2);
726 if (!self->begin_statement) {
727 return -1;
728 }
729
730 strcpy(self->begin_statement, PyString_AsString(begin_statement));
731 Py_DECREF(begin_statement);
732 }
733
734 return 0;
735}
736
737PyObject* connection_call(Connection* self, PyObject* args, PyObject* kwargs)
738{
739 PyObject* sql;
740 Statement* statement;
741 int rc;
742
743 if (!PyArg_ParseTuple(args, "O", &sql)) {
744 return NULL;
745 }
746
747 statement = PyObject_New(Statement, &StatementType);
748 if (!statement) {
749 return NULL;
750 }
751
752 rc = statement_create(statement, self, sql);
753
754 if (rc != SQLITE_OK) {
755 if (rc == PYSQLITE_TOO_MUCH_SQL) {
756 PyErr_SetString(Warning, "You can only execute one statement at a time.");
757 } else if (rc == PYSQLITE_SQL_WRONG_TYPE) {
758 PyErr_SetString(Warning, "SQL is of wrong type. Must be string or unicode.");
759 } else {
760 _seterror(self->db);
761 }
762
763 Py_DECREF(statement);
764 statement = 0;
765 }
766
767 return (PyObject*)statement;
768}
769
770PyObject* connection_execute(Connection* self, PyObject* args, PyObject* kwargs)
771{
772 PyObject* cursor = 0;
773 PyObject* result = 0;
774 PyObject* method = 0;
775
776 cursor = PyObject_CallMethod((PyObject*)self, "cursor", "");
777 if (!cursor) {
778 goto error;
779 }
780
781 method = PyObject_GetAttrString(cursor, "execute");
782 if (!method) {
783 Py_DECREF(cursor);
784 cursor = 0;
785 goto error;
786 }
787
788 result = PyObject_CallObject(method, args);
789 if (!result) {
790 Py_DECREF(cursor);
791 cursor = 0;
792 }
793
794error:
795 Py_XDECREF(result);
796 Py_XDECREF(method);
797
798 return cursor;
799}
800
801PyObject* connection_executemany(Connection* self, PyObject* args, PyObject* kwargs)
802{
803 PyObject* cursor = 0;
804 PyObject* result = 0;
805 PyObject* method = 0;
806
807 cursor = PyObject_CallMethod((PyObject*)self, "cursor", "");
808 if (!cursor) {
809 goto error;
810 }
811
812 method = PyObject_GetAttrString(cursor, "executemany");
813 if (!method) {
814 Py_DECREF(cursor);
815 cursor = 0;
816 goto error;
817 }
818
819 result = PyObject_CallObject(method, args);
820 if (!result) {
821 Py_DECREF(cursor);
822 cursor = 0;
823 }
824
825error:
826 Py_XDECREF(result);
827 Py_XDECREF(method);
828
829 return cursor;
830}
831
832PyObject* connection_executescript(Connection* self, PyObject* args, PyObject* kwargs)
833{
834 PyObject* cursor = 0;
835 PyObject* result = 0;
836 PyObject* method = 0;
837
838 cursor = PyObject_CallMethod((PyObject*)self, "cursor", "");
839 if (!cursor) {
840 goto error;
841 }
842
843 method = PyObject_GetAttrString(cursor, "executescript");
844 if (!method) {
845 Py_DECREF(cursor);
846 cursor = 0;
847 goto error;
848 }
849
850 result = PyObject_CallObject(method, args);
851 if (!result) {
852 Py_DECREF(cursor);
853 cursor = 0;
854 }
855
856error:
857 Py_XDECREF(result);
858 Py_XDECREF(method);
859
860 return cursor;
861}
862
Anthony Baxter72289a62006-04-04 06:29:05 +0000863/* ------------------------- COLLATION CODE ------------------------ */
864
865static int
866collation_callback(
867 void* context,
868 int text1_length, const void* text1_data,
869 int text2_length, const void* text2_data)
870{
871 PyObject* callback = (PyObject*)context;
872 PyObject* string1 = 0;
873 PyObject* string2 = 0;
874 PyGILState_STATE gilstate;
875
876 PyObject* retval = NULL;
877 int result = 0;
878
879 gilstate = PyGILState_Ensure();
880
881 if (PyErr_Occurred()) {
882 goto finally;
883 }
884
885 string1 = PyString_FromStringAndSize((const char*)text1_data, text1_length);
886 string2 = PyString_FromStringAndSize((const char*)text2_data, text2_length);
887
888 if (!string1 || !string2) {
889 goto finally; /* failed to allocate strings */
890 }
891
892 retval = PyObject_CallFunctionObjArgs(callback, string1, string2, NULL);
893
894 if (!retval) {
895 /* execution failed */
896 goto finally;
897 }
898
899 result = PyInt_AsLong(retval);
900 if (PyErr_Occurred()) {
901 result = 0;
902 }
903
904finally:
905 Py_XDECREF(string1);
906 Py_XDECREF(string2);
907 Py_XDECREF(retval);
908
909 PyGILState_Release(gilstate);
910
911 return result;
912}
913
914static PyObject *
915connection_create_collation(Connection* self, PyObject* args)
916{
917 PyObject* callable;
918 PyObject* uppercase_name = 0;
919 PyObject* name;
920 PyObject* retval;
921 char* chk;
922 int rc;
923
924 if (!check_thread(self) || !check_connection(self)) {
925 goto finally;
926 }
927
928 if (!PyArg_ParseTuple(args, "O!O:create_collation(name, callback)", &PyString_Type, &name, &callable)) {
929 goto finally;
930 }
931
932 uppercase_name = PyObject_CallMethod(name, "upper", "");
933 if (!uppercase_name) {
934 goto finally;
935 }
936
937 chk = PyString_AsString(uppercase_name);
938 while (*chk) {
939 if ((*chk >= '0' && *chk <= '9')
940 || (*chk >= 'A' && *chk <= 'Z')
941 || (*chk == '_'))
942 {
943 chk++;
944 } else {
945 PyErr_SetString(ProgrammingError, "invalid character in collation name");
946 goto finally;
947 }
948 }
949
950 if (callable != Py_None && !PyCallable_Check(callable)) {
951 PyErr_SetString(PyExc_TypeError, "parameter must be callable");
952 goto finally;
953 }
954
955 if (callable != Py_None) {
956 PyDict_SetItem(self->collations, uppercase_name, callable);
957 } else {
958 PyDict_DelItem(self->collations, uppercase_name);
959 }
960
961 rc = sqlite3_create_collation(self->db,
962 PyString_AsString(uppercase_name),
963 SQLITE_UTF8,
964 (callable != Py_None) ? callable : NULL,
965 (callable != Py_None) ? collation_callback : NULL);
966 if (rc != SQLITE_OK) {
967 PyDict_DelItem(self->collations, uppercase_name);
968 _seterror(self->db);
969 goto finally;
970 }
971
972finally:
973 Py_XDECREF(uppercase_name);
974
975 if (PyErr_Occurred()) {
976 retval = NULL;
977 } else {
978 Py_INCREF(Py_None);
979 retval = Py_None;
980 }
981
982 return retval;
983}
984
Anthony Baxterc51ee692006-04-01 00:57:31 +0000985static char connection_doc[] =
986PyDoc_STR("<missing docstring>");
987
988static PyGetSetDef connection_getset[] = {
989 {"isolation_level", (getter)connection_get_isolation_level, (setter)connection_set_isolation_level},
Anthony Baxter72289a62006-04-04 06:29:05 +0000990 {"total_changes", (getter)connection_get_total_changes, (setter)0},
Anthony Baxterc51ee692006-04-01 00:57:31 +0000991 {NULL}
992};
993
994static PyMethodDef connection_methods[] = {
995 {"cursor", (PyCFunction)connection_cursor, METH_VARARGS|METH_KEYWORDS,
996 PyDoc_STR("Return a cursor for the connection.")},
997 {"close", (PyCFunction)connection_close, METH_NOARGS,
998 PyDoc_STR("Closes the connection.")},
999 {"commit", (PyCFunction)connection_commit, METH_NOARGS,
1000 PyDoc_STR("Commit the current transaction.")},
1001 {"rollback", (PyCFunction)connection_rollback, METH_NOARGS,
1002 PyDoc_STR("Roll back the current transaction.")},
1003 {"create_function", (PyCFunction)connection_create_function, METH_VARARGS|METH_KEYWORDS,
1004 PyDoc_STR("Creates a new function. Non-standard.")},
1005 {"create_aggregate", (PyCFunction)connection_create_aggregate, METH_VARARGS|METH_KEYWORDS,
1006 PyDoc_STR("Creates a new aggregate. Non-standard.")},
1007 {"execute", (PyCFunction)connection_execute, METH_VARARGS,
1008 PyDoc_STR("Executes a SQL statement. Non-standard.")},
1009 {"executemany", (PyCFunction)connection_executemany, METH_VARARGS,
1010 PyDoc_STR("Repeatedly executes a SQL statement. Non-standard.")},
1011 {"executescript", (PyCFunction)connection_executescript, METH_VARARGS,
1012 PyDoc_STR("Executes a multiple SQL statements at once. Non-standard.")},
Anthony Baxter72289a62006-04-04 06:29:05 +00001013 {"create_collation", (PyCFunction)connection_create_collation, METH_VARARGS,
1014 PyDoc_STR("Creates a collation function.")},
Anthony Baxterc51ee692006-04-01 00:57:31 +00001015 {NULL, NULL}
1016};
1017
1018static struct PyMemberDef connection_members[] =
1019{
1020 {"Warning", T_OBJECT, offsetof(Connection, Warning), RO},
1021 {"Error", T_OBJECT, offsetof(Connection, Error), RO},
1022 {"InterfaceError", T_OBJECT, offsetof(Connection, InterfaceError), RO},
1023 {"DatabaseError", T_OBJECT, offsetof(Connection, DatabaseError), RO},
1024 {"DataError", T_OBJECT, offsetof(Connection, DataError), RO},
1025 {"OperationalError", T_OBJECT, offsetof(Connection, OperationalError), RO},
1026 {"IntegrityError", T_OBJECT, offsetof(Connection, IntegrityError), RO},
1027 {"InternalError", T_OBJECT, offsetof(Connection, InternalError), RO},
1028 {"ProgrammingError", T_OBJECT, offsetof(Connection, ProgrammingError), RO},
1029 {"NotSupportedError", T_OBJECT, offsetof(Connection, NotSupportedError), RO},
1030 {"row_factory", T_OBJECT, offsetof(Connection, row_factory)},
1031 {"text_factory", T_OBJECT, offsetof(Connection, text_factory)},
1032 {NULL}
1033};
1034
1035PyTypeObject ConnectionType = {
1036 PyObject_HEAD_INIT(NULL)
1037 0, /* ob_size */
Anthony Baxter8e7b4902006-04-05 18:25:33 +00001038 MODULE_NAME ".Connection", /* tp_name */
Anthony Baxterc51ee692006-04-01 00:57:31 +00001039 sizeof(Connection), /* tp_basicsize */
1040 0, /* tp_itemsize */
1041 (destructor)connection_dealloc, /* tp_dealloc */
1042 0, /* tp_print */
1043 0, /* tp_getattr */
1044 0, /* tp_setattr */
1045 0, /* tp_compare */
1046 0, /* tp_repr */
1047 0, /* tp_as_number */
1048 0, /* tp_as_sequence */
1049 0, /* tp_as_mapping */
1050 0, /* tp_hash */
1051 (ternaryfunc)connection_call, /* tp_call */
1052 0, /* tp_str */
1053 0, /* tp_getattro */
1054 0, /* tp_setattro */
1055 0, /* tp_as_buffer */
1056 Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE, /* tp_flags */
1057 connection_doc, /* tp_doc */
1058 0, /* tp_traverse */
1059 0, /* tp_clear */
1060 0, /* tp_richcompare */
1061 0, /* tp_weaklistoffset */
1062 0, /* tp_iter */
1063 0, /* tp_iternext */
1064 connection_methods, /* tp_methods */
1065 connection_members, /* tp_members */
1066 connection_getset, /* tp_getset */
1067 0, /* tp_base */
1068 0, /* tp_dict */
1069 0, /* tp_descr_get */
1070 0, /* tp_descr_set */
1071 0, /* tp_dictoffset */
1072 (initproc)connection_init, /* tp_init */
1073 0, /* tp_alloc */
1074 0, /* tp_new */
1075 0 /* tp_free */
1076};
1077
1078extern int connection_setup_types(void)
1079{
1080 ConnectionType.tp_new = PyType_GenericNew;
1081 return PyType_Ready(&ConnectionType);
1082}