~ubuntu-branches/ubuntu/maverick/python3.1/maverick

« back to all changes in this revision

Viewing changes to Modules/_sqlite/connection.c

  • Committer: Bazaar Package Importer
  • Author(s): Matthias Klose
  • Date: 2009-03-23 00:01:27 UTC
  • Revision ID: james.westby@ubuntu.com-20090323000127-5fstfxju4ufrhthq
Tags: upstream-3.1~a1+20090322
ImportĀ upstreamĀ versionĀ 3.1~a1+20090322

Show diffs side-by-side

added added

removed removed

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