Python-2.7.3/Modules/_sqlite/connection.c

No issues found

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