blob: 90f1a7c915c5305d4b247bf996c7863d54d4d3dd [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
691 if (isolation_level == Py_None) {
692 Py_INCREF(Py_None);
693 self->begin_statement = NULL;
694 self->isolation_level = Py_None;
695
696 empty = PyTuple_New(0);
Anthony Baxter72289a62006-04-04 06:29:05 +0000697 if (!empty) {
698 return -1;
699 }
Anthony Baxterc51ee692006-04-01 00:57:31 +0000700 res = connection_commit(self, empty);
Anthony Baxter72289a62006-04-04 06:29:05 +0000701 if (!res) {
702 return -1;
703 }
Anthony Baxterc51ee692006-04-01 00:57:31 +0000704 Py_DECREF(empty);
705 Py_DECREF(res);
706
707 self->inTransaction = 0;
708 } else {
709 Py_INCREF(isolation_level);
710 self->isolation_level = isolation_level;
711
712 begin_statement = PyString_FromString("BEGIN ");
713 if (!begin_statement) {
714 return -1;
715 }
716 PyString_Concat(&begin_statement, isolation_level);
717 if (!begin_statement) {
718 return -1;
719 }
720
721 self->begin_statement = PyMem_Malloc(PyString_Size(begin_statement) + 2);
722 if (!self->begin_statement) {
723 return -1;
724 }
725
726 strcpy(self->begin_statement, PyString_AsString(begin_statement));
727 Py_DECREF(begin_statement);
728 }
729
730 return 0;
731}
732
733PyObject* connection_call(Connection* self, PyObject* args, PyObject* kwargs)
734{
735 PyObject* sql;
736 Statement* statement;
737 int rc;
738
739 if (!PyArg_ParseTuple(args, "O", &sql)) {
740 return NULL;
741 }
742
743 statement = PyObject_New(Statement, &StatementType);
744 if (!statement) {
745 return NULL;
746 }
747
748 rc = statement_create(statement, self, sql);
749
750 if (rc != SQLITE_OK) {
751 if (rc == PYSQLITE_TOO_MUCH_SQL) {
752 PyErr_SetString(Warning, "You can only execute one statement at a time.");
753 } else if (rc == PYSQLITE_SQL_WRONG_TYPE) {
754 PyErr_SetString(Warning, "SQL is of wrong type. Must be string or unicode.");
755 } else {
756 _seterror(self->db);
757 }
758
759 Py_DECREF(statement);
760 statement = 0;
761 }
762
763 return (PyObject*)statement;
764}
765
766PyObject* connection_execute(Connection* self, PyObject* args, PyObject* kwargs)
767{
768 PyObject* cursor = 0;
769 PyObject* result = 0;
770 PyObject* method = 0;
771
772 cursor = PyObject_CallMethod((PyObject*)self, "cursor", "");
773 if (!cursor) {
774 goto error;
775 }
776
777 method = PyObject_GetAttrString(cursor, "execute");
778 if (!method) {
779 Py_DECREF(cursor);
780 cursor = 0;
781 goto error;
782 }
783
784 result = PyObject_CallObject(method, args);
785 if (!result) {
786 Py_DECREF(cursor);
787 cursor = 0;
788 }
789
790error:
791 Py_XDECREF(result);
792 Py_XDECREF(method);
793
794 return cursor;
795}
796
797PyObject* connection_executemany(Connection* self, PyObject* args, PyObject* kwargs)
798{
799 PyObject* cursor = 0;
800 PyObject* result = 0;
801 PyObject* method = 0;
802
803 cursor = PyObject_CallMethod((PyObject*)self, "cursor", "");
804 if (!cursor) {
805 goto error;
806 }
807
808 method = PyObject_GetAttrString(cursor, "executemany");
809 if (!method) {
810 Py_DECREF(cursor);
811 cursor = 0;
812 goto error;
813 }
814
815 result = PyObject_CallObject(method, args);
816 if (!result) {
817 Py_DECREF(cursor);
818 cursor = 0;
819 }
820
821error:
822 Py_XDECREF(result);
823 Py_XDECREF(method);
824
825 return cursor;
826}
827
828PyObject* connection_executescript(Connection* self, PyObject* args, PyObject* kwargs)
829{
830 PyObject* cursor = 0;
831 PyObject* result = 0;
832 PyObject* method = 0;
833
834 cursor = PyObject_CallMethod((PyObject*)self, "cursor", "");
835 if (!cursor) {
836 goto error;
837 }
838
839 method = PyObject_GetAttrString(cursor, "executescript");
840 if (!method) {
841 Py_DECREF(cursor);
842 cursor = 0;
843 goto error;
844 }
845
846 result = PyObject_CallObject(method, args);
847 if (!result) {
848 Py_DECREF(cursor);
849 cursor = 0;
850 }
851
852error:
853 Py_XDECREF(result);
854 Py_XDECREF(method);
855
856 return cursor;
857}
858
Anthony Baxter72289a62006-04-04 06:29:05 +0000859/* ------------------------- COLLATION CODE ------------------------ */
860
861static int
862collation_callback(
863 void* context,
864 int text1_length, const void* text1_data,
865 int text2_length, const void* text2_data)
866{
867 PyObject* callback = (PyObject*)context;
868 PyObject* string1 = 0;
869 PyObject* string2 = 0;
870 PyGILState_STATE gilstate;
871
872 PyObject* retval = NULL;
873 int result = 0;
874
875 gilstate = PyGILState_Ensure();
876
877 if (PyErr_Occurred()) {
878 goto finally;
879 }
880
881 string1 = PyString_FromStringAndSize((const char*)text1_data, text1_length);
882 string2 = PyString_FromStringAndSize((const char*)text2_data, text2_length);
883
884 if (!string1 || !string2) {
885 goto finally; /* failed to allocate strings */
886 }
887
888 retval = PyObject_CallFunctionObjArgs(callback, string1, string2, NULL);
889
890 if (!retval) {
891 /* execution failed */
892 goto finally;
893 }
894
895 result = PyInt_AsLong(retval);
896 if (PyErr_Occurred()) {
897 result = 0;
898 }
899
900finally:
901 Py_XDECREF(string1);
902 Py_XDECREF(string2);
903 Py_XDECREF(retval);
904
905 PyGILState_Release(gilstate);
906
907 return result;
908}
909
910static PyObject *
911connection_create_collation(Connection* self, PyObject* args)
912{
913 PyObject* callable;
914 PyObject* uppercase_name = 0;
915 PyObject* name;
916 PyObject* retval;
917 char* chk;
918 int rc;
919
920 if (!check_thread(self) || !check_connection(self)) {
921 goto finally;
922 }
923
924 if (!PyArg_ParseTuple(args, "O!O:create_collation(name, callback)", &PyString_Type, &name, &callable)) {
925 goto finally;
926 }
927
928 uppercase_name = PyObject_CallMethod(name, "upper", "");
929 if (!uppercase_name) {
930 goto finally;
931 }
932
933 chk = PyString_AsString(uppercase_name);
934 while (*chk) {
935 if ((*chk >= '0' && *chk <= '9')
936 || (*chk >= 'A' && *chk <= 'Z')
937 || (*chk == '_'))
938 {
939 chk++;
940 } else {
941 PyErr_SetString(ProgrammingError, "invalid character in collation name");
942 goto finally;
943 }
944 }
945
946 if (callable != Py_None && !PyCallable_Check(callable)) {
947 PyErr_SetString(PyExc_TypeError, "parameter must be callable");
948 goto finally;
949 }
950
951 if (callable != Py_None) {
952 PyDict_SetItem(self->collations, uppercase_name, callable);
953 } else {
954 PyDict_DelItem(self->collations, uppercase_name);
955 }
956
957 rc = sqlite3_create_collation(self->db,
958 PyString_AsString(uppercase_name),
959 SQLITE_UTF8,
960 (callable != Py_None) ? callable : NULL,
961 (callable != Py_None) ? collation_callback : NULL);
962 if (rc != SQLITE_OK) {
963 PyDict_DelItem(self->collations, uppercase_name);
964 _seterror(self->db);
965 goto finally;
966 }
967
968finally:
969 Py_XDECREF(uppercase_name);
970
971 if (PyErr_Occurred()) {
972 retval = NULL;
973 } else {
974 Py_INCREF(Py_None);
975 retval = Py_None;
976 }
977
978 return retval;
979}
980
Anthony Baxterc51ee692006-04-01 00:57:31 +0000981static char connection_doc[] =
982PyDoc_STR("<missing docstring>");
983
984static PyGetSetDef connection_getset[] = {
985 {"isolation_level", (getter)connection_get_isolation_level, (setter)connection_set_isolation_level},
Anthony Baxter72289a62006-04-04 06:29:05 +0000986 {"total_changes", (getter)connection_get_total_changes, (setter)0},
Anthony Baxterc51ee692006-04-01 00:57:31 +0000987 {NULL}
988};
989
990static PyMethodDef connection_methods[] = {
991 {"cursor", (PyCFunction)connection_cursor, METH_VARARGS|METH_KEYWORDS,
992 PyDoc_STR("Return a cursor for the connection.")},
993 {"close", (PyCFunction)connection_close, METH_NOARGS,
994 PyDoc_STR("Closes the connection.")},
995 {"commit", (PyCFunction)connection_commit, METH_NOARGS,
996 PyDoc_STR("Commit the current transaction.")},
997 {"rollback", (PyCFunction)connection_rollback, METH_NOARGS,
998 PyDoc_STR("Roll back the current transaction.")},
999 {"create_function", (PyCFunction)connection_create_function, METH_VARARGS|METH_KEYWORDS,
1000 PyDoc_STR("Creates a new function. Non-standard.")},
1001 {"create_aggregate", (PyCFunction)connection_create_aggregate, METH_VARARGS|METH_KEYWORDS,
1002 PyDoc_STR("Creates a new aggregate. Non-standard.")},
1003 {"execute", (PyCFunction)connection_execute, METH_VARARGS,
1004 PyDoc_STR("Executes a SQL statement. Non-standard.")},
1005 {"executemany", (PyCFunction)connection_executemany, METH_VARARGS,
1006 PyDoc_STR("Repeatedly executes a SQL statement. Non-standard.")},
1007 {"executescript", (PyCFunction)connection_executescript, METH_VARARGS,
1008 PyDoc_STR("Executes a multiple SQL statements at once. Non-standard.")},
Anthony Baxter72289a62006-04-04 06:29:05 +00001009 {"create_collation", (PyCFunction)connection_create_collation, METH_VARARGS,
1010 PyDoc_STR("Creates a collation function.")},
Anthony Baxterc51ee692006-04-01 00:57:31 +00001011 {NULL, NULL}
1012};
1013
1014static struct PyMemberDef connection_members[] =
1015{
1016 {"Warning", T_OBJECT, offsetof(Connection, Warning), RO},
1017 {"Error", T_OBJECT, offsetof(Connection, Error), RO},
1018 {"InterfaceError", T_OBJECT, offsetof(Connection, InterfaceError), RO},
1019 {"DatabaseError", T_OBJECT, offsetof(Connection, DatabaseError), RO},
1020 {"DataError", T_OBJECT, offsetof(Connection, DataError), RO},
1021 {"OperationalError", T_OBJECT, offsetof(Connection, OperationalError), RO},
1022 {"IntegrityError", T_OBJECT, offsetof(Connection, IntegrityError), RO},
1023 {"InternalError", T_OBJECT, offsetof(Connection, InternalError), RO},
1024 {"ProgrammingError", T_OBJECT, offsetof(Connection, ProgrammingError), RO},
1025 {"NotSupportedError", T_OBJECT, offsetof(Connection, NotSupportedError), RO},
1026 {"row_factory", T_OBJECT, offsetof(Connection, row_factory)},
1027 {"text_factory", T_OBJECT, offsetof(Connection, text_factory)},
1028 {NULL}
1029};
1030
1031PyTypeObject ConnectionType = {
1032 PyObject_HEAD_INIT(NULL)
1033 0, /* ob_size */
Anthony Baxter8e7b4902006-04-05 18:25:33 +00001034 MODULE_NAME ".Connection", /* tp_name */
Anthony Baxterc51ee692006-04-01 00:57:31 +00001035 sizeof(Connection), /* tp_basicsize */
1036 0, /* tp_itemsize */
1037 (destructor)connection_dealloc, /* tp_dealloc */
1038 0, /* tp_print */
1039 0, /* tp_getattr */
1040 0, /* tp_setattr */
1041 0, /* tp_compare */
1042 0, /* tp_repr */
1043 0, /* tp_as_number */
1044 0, /* tp_as_sequence */
1045 0, /* tp_as_mapping */
1046 0, /* tp_hash */
1047 (ternaryfunc)connection_call, /* tp_call */
1048 0, /* tp_str */
1049 0, /* tp_getattro */
1050 0, /* tp_setattro */
1051 0, /* tp_as_buffer */
1052 Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE, /* tp_flags */
1053 connection_doc, /* tp_doc */
1054 0, /* tp_traverse */
1055 0, /* tp_clear */
1056 0, /* tp_richcompare */
1057 0, /* tp_weaklistoffset */
1058 0, /* tp_iter */
1059 0, /* tp_iternext */
1060 connection_methods, /* tp_methods */
1061 connection_members, /* tp_members */
1062 connection_getset, /* tp_getset */
1063 0, /* tp_base */
1064 0, /* tp_dict */
1065 0, /* tp_descr_get */
1066 0, /* tp_descr_set */
1067 0, /* tp_dictoffset */
1068 (initproc)connection_init, /* tp_init */
1069 0, /* tp_alloc */
1070 0, /* tp_new */
1071 0 /* tp_free */
1072};
1073
1074extern int connection_setup_types(void)
1075{
1076 ConnectionType.tp_new = PyType_GenericNew;
1077 return PyType_Ready(&ConnectionType);
1078}