2
Another Python Sqlite Wrapper
4
This wrapper aims to be the minimum necessary layer over SQLite 3
7
It assumes we are running as 32 bit int with a 64 bit long long type
10
Copyright (C) 2004-2006 Roger Binns <rogerb@rogerbinns.com>
12
This software is provided 'as-is', without any express or implied
13
warranty. In no event will the authors be held liable for any
14
damages arising from the use of this software.
16
Permission is granted to anyone to use this software for any
17
purpose, including commercial applications, and to alter it and
18
redistribute it freely, subject to the following restrictions:
20
1. The origin of this software must not be misrepresented; you must
21
not claim that you wrote the original software. If you use this
22
software in a product, an acknowledgment in the product
23
documentation would be appreciated but is not required.
25
2. Altered source versions must be plainly marked as such, and must
26
not be misrepresented as being the original software.
28
3. This notice may not be removed or altered from any source
33
/* Get the version number */
34
#include "apswversion.h"
39
#include "structmember.h"
41
/* Python 2.5 compatibility when size_t types become 64 bit.
42
SQLite3 is limited to 32 bit sizes even on a 64 bit machine. */
43
#if PY_VERSION_HEX < 0x02050000
44
typedef int Py_ssize_t;
47
/* SQLite 3 headers */
53
/* used to decide if we will use int or long long */
54
#define INT32_MIN (-2147483647 - 1)
55
#define INT32_MAX 2147483647
57
/* The encoding we use with SQLite. SQLite supports either utf8 or 16
58
bit unicode (host byte order). If the latter is used then all
59
functions have "16" appended to their name. The encoding used also
60
affects how strings are stored in the database. We use utf8 since
61
it is more space efficient, and Python can't make its mind up about
62
Unicode (it uses 16 or 32 bit unichars and often likes to use Byte
64
#define STRENCODING "utf_8"
66
/* Some macros used for frequent operations */
68
#define CHECK_THREAD(x,e) \
69
{ if(x->thread_ident!=PyThread_get_thread_ident()) \
70
{ /* raise exception if we aren't already in one */ \
71
if (!PyErr_Occurred()) \
72
PyErr_Format(ExcThreadingViolation, "All SQLite objects created in a thread can only be used in that same thread. " \
73
"The object was created in thread id %d and this is %d", \
74
(int)(x->thread_ident), (int)(PyThread_get_thread_ident())); \
83
static PyObject *APSWException; /* root exception class */
84
static PyObject *ExcThreadingViolation; /* thread misuse */
85
static PyObject *ExcIncomplete; /* didn't finish previous query */
86
static PyObject *ExcBindings; /* wrong number of bindings */
87
static PyObject *ExcComplete; /* query is finished */
88
static PyObject *ExcTraceAbort; /* aborted by exectrace */
89
static PyObject *ExcTooBig; /* object is too large for SQLite */
91
static struct { int code; const char *name; PyObject *cls;}
95
{SQLITE_ERROR, "SQL"},
96
{SQLITE_MISMATCH, "Mismatch"},
99
{SQLITE_INTERNAL, "Internal"}, /* NOT USED */
100
{SQLITE_PROTOCOL, "Protocol"},
101
{SQLITE_MISUSE, "Misuse"},
102
{SQLITE_RANGE, "Range"},
104
/* permissions etc */
105
{SQLITE_PERM, "Permissions"},
106
{SQLITE_READONLY, "ReadOnly"},
107
{SQLITE_CANTOPEN, "CantOpen"},
108
{SQLITE_AUTH, "Auth"},
111
{SQLITE_ABORT, "Abort"},
112
{SQLITE_BUSY, "Busy"},
113
{SQLITE_LOCKED, "Locked"},
114
{SQLITE_INTERRUPT,"Interrupt"},
115
{SQLITE_SCHEMA, "SchemaChange"},
116
{SQLITE_CONSTRAINT, "Constraint"},
118
/* memory/disk/corrupt etc */
119
{SQLITE_NOMEM, "NoMem"},
120
{SQLITE_IOERR, "IO"},
121
{SQLITE_CORRUPT, "Corrupt"},
122
{SQLITE_FULL, "Full"},
123
{SQLITE_TOOBIG, "TooBig"}, /* NOT USED */
124
{SQLITE_NOLFS, "NoLFS"},
125
{SQLITE_EMPTY, "Empty"},
126
{SQLITE_FORMAT, "Format"},
127
{SQLITE_NOTADB, "NotADB"},
135
static int init_exceptions(PyObject *m)
137
char buffy[100]; /* more than enough for anyone :-) */
141
/* PyModule_AddObject uses borrowed reference so we incref whatever
142
we give to it, so we still have a copy to use */
144
/* custom ones first */
146
APSWException=PyErr_NewException("apsw.Error", NULL, NULL);
147
if(!APSWException) return -1;
148
Py_INCREF(APSWException);
149
if(PyModule_AddObject(m, "Error", (PyObject *)APSWException))
152
#define EXC(varname,name) \
153
varname=PyErr_NewException("apsw." name, APSWException, NULL); \
154
if(!varname) return -1; \
155
Py_INCREF(varname); \
156
if(PyModule_AddObject(m, name, (PyObject *)varname)) \
159
EXC(ExcThreadingViolation, "ThreadingViolationError");
160
EXC(ExcIncomplete, "IncompleteExecutionError");
161
EXC(ExcBindings, "BindingsError");
162
EXC(ExcComplete, "ExecutionCompleteError");
163
EXC(ExcTraceAbort, "ExecTraceAbort");
164
EXC(ExcTooBig, "TooBigError");
168
/* all the ones corresponding to SQLITE error codes */
169
for(i=0;exc_descriptors[i].name;i++)
171
sprintf(buffy, "apsw.%sError", exc_descriptors[i].name);
172
obj=PyErr_NewException(buffy, APSWException, NULL);
175
exc_descriptors[i].cls=obj;
176
sprintf(buffy, "%sError", exc_descriptors[i].name);
177
if(PyModule_AddObject(m, buffy, obj))
184
static void make_exception(int res, sqlite3 *db)
188
for(i=0;exc_descriptors[i].name;i++)
189
if (exc_descriptors[i].code==res)
191
assert(exc_descriptors[i].cls);
192
PyErr_Format(exc_descriptors[i].cls, "%sError: %s", exc_descriptors[i].name, db?(sqlite3_errmsg(db)):"error");
193
assert(PyErr_Occurred());
197
PyErr_Format(APSWException, "Error %d: %s", res, db?(sqlite3_errmsg(db)):"error");
200
/* If res indicates an SQLite error then do all the exception creation
201
work. We don't overwrite earlier exceptions hence the PyErr_Occurred
203
#define SET_EXC(db,res) { if(res != SQLITE_OK && !PyErr_Occurred()) make_exception(res,db); }
207
/* details of a registered function passed as user data to sqlite3_create_function */
208
typedef struct _funccbinfo
210
struct _funccbinfo *next; /* we use a linked list */
211
char *name; /* ascii function name which we uppercased */
212
PyObject *scalarfunc; /* the function to call for stepping */
213
PyObject *aggregatefactory; /* factory for aggregate functions */
216
/* a particular aggregate function instance used as sqlite3_aggregate_context */
217
typedef struct _aggregatefunctioncontext
219
PyObject *aggvalue; /* the aggregation value passed as first parameter */
220
PyObject *stepfunc; /* step function */
221
PyObject *finalfunc; /* final function */
222
} aggregatefunctioncontext;
224
static funccbinfo *freefunccbinfo(funccbinfo *);
226
typedef struct _collationcbinfo
228
struct _collationcbinfo *next; /* we use a linked list */
229
char *name; /* ascii collation name which we uppercased */
230
PyObject *func; /* the actual function to call */
233
static collationcbinfo *freecollationcbinfo(collationcbinfo *);
236
/* CONNECTION TYPE */
240
sqlite3 *db; /* the actual database connection */
241
long thread_ident; /* which thread we were made in */
242
funccbinfo *functions; /* linked list of registered functions */
243
collationcbinfo *collations; /* linked list of registered collations */
245
/* registered hooks/handlers (NULL or callable) */
246
PyObject *busyhandler;
247
PyObject *rollbackhook;
249
PyObject *updatehook;
250
PyObject *commithook;
251
PyObject *progresshandler;
252
PyObject *authorizer;
255
static PyTypeObject ConnectionType;
261
Connection *connection; /* pointer to parent connection */
262
sqlite3_stmt *statement; /* current compiled statement */
264
/* see sqlite3_prepare for the origin of these */
265
const char *zsql; /* current sqlstatement (which may include multiple statements) */
266
const char *zsqlnextpos; /* the next statement to execute (or NULL if no more) */
268
/* what state we are in */
269
enum { C_BEGIN, C_ROW, C_DONE } status;
271
/* bindings for query */
272
PyObject *bindings; /* dict or sequence */
273
Py_ssize_t bindingsoffset; /* for sequence tracks how far along we are when dealing with multiple statements */
275
/* iterator for executemany */
278
/* tracing functions */
284
static PyTypeObject CursorType;
287
/* CONVENIENCE FUNCTIONS */
289
/* Convert a NULL terminated UTF-8 string into a Python object. None
290
is returned if NULL is passed in. */
292
convertutf8string(const char *str)
302
for(chk=str;*chk && !((*chk)&0x80); chk++) ;
304
return PyUnicode_DecodeUTF8(str, strlen(str), NULL);
306
return PyString_FromString(str);
309
/* Convert a pointer and size UTF-8 string into a Python object.
310
Pointer must be non-NULL. */
312
convertutf8stringsize(const char *str, Py_ssize_t size)
320
for(i=0;i<size && !(chk[i]&0x80);i++);
323
return PyUnicode_DecodeUTF8(str, size, NULL);
325
return PyString_FromStringAndSize(str, size);
329
Python's handling of Unicode is horrible. It can use 2 or 4 byte
330
unicode chars and the conversion routines like to put out BOMs
331
which makes life even harder. These macros are used in pairs to do
332
the right form of conversion and tell us whether to use the plain
333
or -16 version of the SQLite function that is about to be called.
336
#if Py_UNICODE_SIZE==2
337
#define UNIDATABEGIN(obj) \
340
size_t strbytes=2*PyUnicode_GET_SIZE(obj); \
341
const void *strdata=PyUnicode_AS_DATA(obj);
343
#define UNIDATAEND(obj) \
346
#else /* Py_UNICODE_SIZE!=2 */
348
#define UNIDATABEGIN(obj) \
351
Py_ssize_t strbytes=0; \
352
const char *strdata=NULL; \
353
PyObject *_utf8=NULL; \
355
_utf8=PyUnicode_AsUTF8String(obj); \
358
strbytes=PyString_GET_SIZE(_utf8); \
359
strdata=PyString_AsString(_utf8); \
362
#define UNIDATAEND(obj) \
366
#endif /* Py_UNICODE_SIZE */
368
/* CONNECTION CODE */
371
Connection_dealloc(Connection* self)
373
/* thread check - we can't use macro as that returns */
375
if(self->thread_ident!=PyThread_get_thread_ident())
377
PyObject *err_type, *err_value, *err_traceback;
378
int have_error=PyErr_Occurred()?1:0;
380
PyErr_Fetch(&err_type, &err_value, &err_traceback);
381
PyErr_Format(ExcThreadingViolation, "The destructor for Connection is called in a different thread than it"
382
"was created in. All calls must be in the same thread. It was created in thread %d"
383
"and this is %d. This SQLite database is not being closed as a result.",
384
(int)(self->thread_ident), (int)(PyThread_get_thread_ident()));
385
PyErr_WriteUnraisable((PyObject*)self);
387
PyErr_Restore(err_type, err_value, err_traceback);
395
Py_BEGIN_ALLOW_THREADS
396
res=sqlite3_close(self->db);
397
Py_END_ALLOW_THREADS;
401
PyObject *err_type, *err_value, *err_traceback;
402
int have_error=PyErr_Occurred()?1:0;
404
PyErr_Fetch(&err_type, &err_value, &err_traceback);
405
make_exception(res,self->db);
408
PyErr_WriteUnraisable((PyObject*)self);
409
PyErr_Restore(err_type, err_value, err_traceback);
418
funccbinfo *func=self->functions;
419
while((func=freefunccbinfo(func)));
422
/* free collations */
424
collationcbinfo *coll=self->collations;
425
while((coll=freecollationcbinfo(coll)));
428
Py_XDECREF(self->busyhandler);
431
Py_XDECREF(self->rollbackhook);
432
self->rollbackhook=0;
434
Py_XDECREF(self->profile);
437
Py_XDECREF(self->commithook);
440
Py_XDECREF(self->progresshandler);
441
self->progresshandler=0;
443
Py_XDECREF(self->authorizer);
446
self->thread_ident=-1;
447
self->ob_type->tp_free((PyObject*)self);
451
Connection_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
455
self = (Connection *)type->tp_alloc(type, 0);
457
/* Strictly speaking the memory was already zeroed. This is
458
just defensive coding. */
460
self->thread_ident=PyThread_get_thread_ident();
464
self->rollbackhook=0;
468
self->progresshandler=0;
472
return (PyObject *)self;
476
Connection_init(Connection *self, PyObject *args, PyObject *kwds)
481
CHECK_THREAD(self,-1);
483
if(kwds && kwds!=Py_None)
485
if(!PyDict_Check(kwds))
487
PyErr_Format(PyExc_TypeError, "Bad type for keyword args");
490
if(PyDict_Size(kwds))
492
PyErr_Format(PyExc_TypeError, "Connection constructor does not take keyword arguments");
497
if(!PyArg_ParseTuple(args, "es:Connection(filename)", STRENCODING, &filename))
500
Py_BEGIN_ALLOW_THREADS
501
res=sqlite3_open(filename, &self->db);
502
Py_END_ALLOW_THREADS;
503
SET_EXC(self->db, res); /* nb sqlite3_open always allocates the db even on error */
505
PyMem_Free(filename);
507
return (res==SQLITE_OK)?0:-1;
511
Connection_cursor(Connection *self)
513
Cursor* cursor = NULL;
515
CHECK_THREAD(self,NULL);
517
/* there is absolutely no documentation on how to allocate a new
518
object in the Python C API. Actually there is documentation of 5
519
different methods, all of which take various parameters we don't
520
have. This appears to be yet another (and undocumented) way of
522
cursor = (Cursor*) (CursorType.tp_alloc(&CursorType, 0));
526
/* incref me since cursor holds a pointer */
527
Py_INCREF((PyObject*)self);
528
cursor->connection=self;
530
return (PyObject*)cursor;
535
Connection_setbusytimeout(Connection *self, PyObject *args)
540
CHECK_THREAD(self,NULL);
542
if(!PyArg_ParseTuple(args, "i:setbusytimeout(millseconds)", &ms))
545
res=sqlite3_busy_timeout(self->db, ms);
546
SET_EXC(self->db, res);
550
/* free any explicit busyhandler we may have had */
551
Py_XDECREF(self->busyhandler);
554
return Py_BuildValue("");
558
Connection_changes(Connection *self)
560
CHECK_THREAD(self,NULL);
561
return Py_BuildValue("i", sqlite3_changes(self->db));
565
Connection_totalchanges(Connection *self)
567
CHECK_THREAD(self,NULL);
568
return Py_BuildValue("i", sqlite3_total_changes(self->db));
572
Connection_getautocommit(Connection *self)
575
CHECK_THREAD(self,NULL);
576
res=(sqlite3_get_autocommit(self->db))?(Py_True):(Py_False);
582
Connection_last_insert_rowid(Connection *self)
586
CHECK_THREAD(self,NULL);
588
vint=sqlite3_last_insert_rowid(self->db);
590
if(vint<INT32_MIN || vint>INT32_MAX)
591
return PyLong_FromLongLong(vint);
593
return PyInt_FromLong((long)vint);
597
Connection_complete(Connection *self, PyObject *args)
599
char *statements=NULL;
602
CHECK_THREAD(self,NULL);
604
if(!PyArg_ParseTuple(args, "es:complete(statement)", STRENCODING, &statements))
607
res=sqlite3_complete(statements);
609
PyMem_Free(statements);
621
Connection_interrupt(Connection *self)
623
CHECK_THREAD(self, NULL);
625
sqlite3_interrupt(self->db); /* no return value */
626
return Py_BuildValue("");
630
updatecb(void *context, int updatetype, char const *databasename, char const *tablename, sqlite_int64 rowid)
632
/* The hook returns void. That makes it impossible for us to
633
abort immediately due to an error in the callback */
635
PyGILState_STATE gilstate;
636
PyObject *retval=NULL, *args=NULL;
637
Connection *self=(Connection *)context;
638
PyObject *pupdatetype=NULL, *pdatabasename=NULL, *ptablename=NULL, *prowid=NULL;
641
assert(self->updatehook);
642
assert(self->updatehook!=Py_None);
644
/* defensive coding */
645
if(!self->updatehook)
648
gilstate=PyGILState_Ensure();
651
goto finally; /* abort hook due to outstanding exception */
654
pupdatetype=Py_BuildValue("i", updatetype);
655
pdatabasename=convertutf8string(databasename);
656
ptablename=convertutf8string(tablename);
657
prowid=PyLong_FromLongLong(rowid);
659
if (!pupdatetype || !pdatabasename || !ptablename || !prowid)
664
goto finally; /* abort hook on failure to allocate args */
666
PyTuple_SET_ITEM(args, 0, pupdatetype);
667
PyTuple_SET_ITEM(args, 1, pdatabasename);
668
PyTuple_SET_ITEM(args, 2, ptablename);
669
PyTuple_SET_ITEM(args, 3, prowid);
671
pupdatetype=pdatabasename=ptablename=prowid=NULL; /* owned by args now */
673
retval=PyEval_CallObject(self->updatehook, args);
678
Py_XDECREF(pupdatetype);
679
Py_XDECREF(pdatabasename);
680
Py_XDECREF(ptablename);
682
PyGILState_Release(gilstate);
686
Connection_setupdatehook(Connection *self, PyObject *callable)
688
/* sqlite3_update_hook doesn't return an error code */
690
CHECK_THREAD(self,NULL);
692
if(callable==Py_None)
694
sqlite3_update_hook(self->db, NULL, NULL);
699
if(!PyCallable_Check(callable))
701
PyErr_Format(PyExc_TypeError, "update hook must be callable");
705
sqlite3_update_hook(self->db, updatecb, self);
711
Py_XDECREF(self->updatehook);
712
self->updatehook=callable;
714
return Py_BuildValue("");
718
rollbackhookcb(void *context)
720
/* The hook returns void. That makes it impossible for us to
721
abort immediately due to an error in the callback */
723
PyGILState_STATE gilstate;
724
PyObject *retval=NULL, *args=NULL;
725
Connection *self=(Connection *)context;
728
assert(self->rollbackhook);
729
assert(self->rollbackhook!=Py_None);
731
/* defensive coding */
732
if(!self->rollbackhook)
735
gilstate=PyGILState_Ensure();
738
goto finally; /* abort hook due to outstanding exception */
742
goto finally; /* abort hook on failure to allocate args */
744
retval=PyEval_CallObject(self->rollbackhook, args);
749
PyGILState_Release(gilstate);
753
Connection_setrollbackhook(Connection *self, PyObject *callable)
755
/* sqlite3_rollback_hook doesn't return an error code */
757
CHECK_THREAD(self,NULL);
759
if(callable==Py_None)
761
sqlite3_rollback_hook(self->db, NULL, NULL);
766
if(!PyCallable_Check(callable))
768
PyErr_Format(PyExc_TypeError, "rollback hook must be callable");
772
sqlite3_rollback_hook(self->db, rollbackhookcb, self);
778
Py_XDECREF(self->rollbackhook);
779
self->rollbackhook=callable;
781
return Py_BuildValue("");
784
#ifdef EXPERIMENTAL /* sqlite3_profile */
786
profilecb(void *context, const char *statement, sqlite_uint64 runtime)
788
/* The hook returns void. That makes it impossible for us to
789
abort immediately due to an error in the callback */
791
PyGILState_STATE gilstate;
792
PyObject *retval=NULL, *args=NULL;
793
Connection *self=(Connection *)context;
794
PyObject *pstatement=NULL, *pruntime=NULL;
797
assert(self->profile);
798
assert(self->profile!=Py_None);
800
/* defensive coding */
804
gilstate=PyGILState_Ensure();
807
goto finally; /* abort hook due to outstanding exception */
809
pstatement=convertutf8string(statement);
810
pruntime=PyLong_FromUnsignedLongLong(runtime);
812
if (!pstatement || !pruntime)
817
goto finally; /* abort hook on failure to allocate args */
819
PyTuple_SET_ITEM(args, 0, pstatement);
820
PyTuple_SET_ITEM(args, 1, pruntime);
822
pstatement=pruntime=NULL; /* owned by args now */
824
retval=PyEval_CallObject(self->profile, args);
829
Py_XDECREF(pstatement);
830
Py_XDECREF(pruntime);
831
PyGILState_Release(gilstate);
835
Connection_setprofile(Connection *self, PyObject *callable)
837
/* sqlite3_profile doesn't return an error code */
839
CHECK_THREAD(self,NULL);
841
if(callable==Py_None)
843
sqlite3_profile(self->db, NULL, NULL);
848
if(!PyCallable_Check(callable))
850
PyErr_Format(PyExc_TypeError, "profile function must be callable");
854
sqlite3_profile(self->db, profilecb, self);
860
Py_XDECREF(self->profile);
861
self->profile=callable;
863
return Py_BuildValue("");
865
#endif /* EXPERIMENTAL - sqlite3_profile */
868
#ifdef EXPERIMENTAL /* commit hook */
869
int commithookcb(void *context)
871
/* The hook returns 0 for commit to go ahead and non-zero to abort
872
commit (turn into a rollback). We return non-zero for errors */
874
PyGILState_STATE gilstate;
875
PyObject *retval=NULL, *args=NULL;
876
int ok=1; /* error state */
877
Connection *self=(Connection *)context;
880
assert(self->commithook);
881
assert(self->commithook!=Py_None);
883
/* defensive coding */
884
if(!self->commithook)
887
gilstate=PyGILState_Ensure();
890
goto finally; /* abort hook due to outstanding exception */
894
goto finally; /* abort hook on failure to allocate args */
896
retval=PyEval_CallObject(self->commithook, args);
899
goto finally; /* abort hook due to exeception */
901
ok=PyObject_IsTrue(retval);
902
assert(ok==-1 || ok==0 || ok==1);
907
goto finally; /* abort due to exception in return value */
913
PyGILState_Release(gilstate);
918
Connection_setcommithook(Connection *self, PyObject *callable)
920
/* sqlite3_commit_hook doesn't return an error code */
922
CHECK_THREAD(self,NULL);
924
if(callable==Py_None)
926
sqlite3_commit_hook(self->db, NULL, NULL);
931
if(!PyCallable_Check(callable))
933
PyErr_Format(PyExc_TypeError, "commit hook must be callable");
937
sqlite3_commit_hook(self->db, commithookcb, self);
943
Py_XDECREF(self->commithook);
944
self->commithook=callable;
946
return Py_BuildValue("");
948
#endif /* EXPERIMENTAL sqlite3_commit_hook */
950
#ifdef EXPERIMENTAL /* sqlite3_progress_handler */
951
int progresshandlercb(void *context)
953
/* The hook returns 0 for continue and non-zero to abort (rollback).
954
We return non-zero for errors */
956
PyGILState_STATE gilstate;
957
PyObject *retval=NULL, *args=NULL;
958
int ok=1; /* error state */
959
Connection *self=(Connection *)context;
962
assert(self->progresshandler);
964
/* defensive coding */
965
if(!self->progresshandler)
968
gilstate=PyGILState_Ensure();
972
goto finally; /* abort handler due to failure to allocate args */
974
retval=PyEval_CallObject(self->progresshandler, args);
977
goto finally; /* abort due to exeception */
979
ok=PyObject_IsTrue(retval);
981
assert(ok==-1 || ok==0 || ok==1);
986
goto finally; /* abort due to exception in result */
993
PyGILState_Release(gilstate);
998
Connection_setprogresshandler(Connection *self, PyObject *args)
1000
/* sqlite3_progress_handler doesn't return an error code */
1002
PyObject *callable=NULL;
1004
CHECK_THREAD(self,NULL);
1006
if(!PyArg_ParseTuple(args, "O|i:setprogresshandler(callable, nsteps=20)", &callable, &nsteps))
1009
if(callable==Py_None)
1011
sqlite3_progress_handler(self->db, 0, NULL, NULL);
1016
if(!PyCallable_Check(callable))
1018
PyErr_Format(PyExc_TypeError, "progress handler must be callable");
1022
sqlite3_progress_handler(self->db, nsteps, progresshandlercb, self);
1023
Py_INCREF(callable);
1027
Py_XDECREF(self->progresshandler);
1028
self->progresshandler=callable;
1030
return Py_BuildValue("");
1032
#endif /* EXPERIMENTAL sqlite3_progress_handler */
1034
int authorizercb(void *context, int operation, const char *paramone, const char *paramtwo, const char *databasename, const char *triggerview)
1036
/* should return one of SQLITE_OK, SQLITE_DENY, or
1037
SQLITE_IGNORE. (0, 1 or 2 respectively) */
1039
PyGILState_STATE gilstate;
1040
PyObject *args=NULL, *retval=NULL;
1041
int result=SQLITE_DENY; /* default to deny */
1042
Connection *self=(Connection *)context;
1044
PyObject *poperation=NULL, *pone=NULL, *ptwo=NULL, *pdatabasename=NULL, *ptriggerview=NULL;
1047
assert(self->authorizer);
1048
assert(self->authorizer!=Py_None);
1050
/* defensive coding */
1051
if(!self->authorizer)
1054
gilstate=PyGILState_Ensure();
1056
if(PyErr_Occurred())
1057
goto finally; /* abort due to earlier exception */
1059
poperation=Py_BuildValue("i", operation);
1060
pone=convertutf8string(paramone);
1061
ptwo=convertutf8string(paramtwo);
1062
pdatabasename=convertutf8string(databasename);
1063
ptriggerview=convertutf8string(triggerview);
1064
args=PyTuple_New(5);
1066
if(!poperation || !pone || !ptwo || !pdatabasename || !ptriggerview || !args)
1069
PyTuple_SET_ITEM(args, 0, poperation);
1070
PyTuple_SET_ITEM(args, 1, pone);
1071
PyTuple_SET_ITEM(args, 2, ptwo);
1072
PyTuple_SET_ITEM(args, 3, pdatabasename);
1073
PyTuple_SET_ITEM(args, 4, ptriggerview);
1075
poperation=pone=ptwo=pdatabasename=ptriggerview=NULL; /* owned by args now */
1077
retval=PyEval_CallObject(self->authorizer, args);
1080
goto finally; /* abort due to exeception */
1082
result=PyInt_AsLong(retval);
1083
if (PyErr_Occurred())
1087
Py_XDECREF(poperation);
1090
Py_XDECREF(pdatabasename);
1091
Py_XDECREF(ptriggerview);
1095
PyGILState_Release(gilstate);
1100
Connection_setauthorizer(Connection *self, PyObject *callable)
1104
CHECK_THREAD(self,NULL);
1106
if(callable==Py_None)
1108
res=sqlite3_set_authorizer(self->db, NULL, NULL);
1113
if(!PyCallable_Check(callable))
1115
PyErr_Format(PyExc_TypeError, "authorizer must be callable");
1119
res=sqlite3_set_authorizer(self->db, authorizercb, self);
1120
SET_EXC(self->db, res);
1122
Py_INCREF(callable);
1125
Py_XDECREF(self->authorizer);
1126
self->authorizer=callable;
1128
return (res==SQLITE_OK)?Py_BuildValue(""):NULL;
1131
int busyhandlercb(void *context, int ncall)
1133
/* Return zero for caller to get SQLITE_BUSY error. We default to
1134
zero in case of error. */
1136
PyGILState_STATE gilstate;
1137
PyObject *args, *retval;
1138
int result=0; /* default to fail with SQLITE_BUSY */
1139
Connection *self=(Connection *)context;
1142
assert(self->busyhandler);
1144
/* defensive coding */
1145
if(!self->busyhandler)
1148
gilstate=PyGILState_Ensure();
1150
args=Py_BuildValue("(i)", ncall);
1152
goto finally; /* abort busy due to memory allocation failure */
1154
retval=PyEval_CallObject(self->busyhandler, args);
1158
goto finally; /* abort due to exeception */
1160
result=PyObject_IsTrue(retval);
1161
assert(result==-1 || result==0 || result==1);
1167
goto finally; /* abort due to exception converting retval */
1171
PyGILState_Release(gilstate);
1176
Connection_setbusyhandler(Connection *self, PyObject *callable)
1180
CHECK_THREAD(self,NULL);
1182
if(callable==Py_None)
1184
res=sqlite3_busy_handler(self->db, NULL, NULL);
1189
if(!PyCallable_Check(callable))
1191
PyErr_Format(PyExc_TypeError, "busyhandler must be callable");
1195
res=sqlite3_busy_handler(self->db, busyhandlercb, self);
1196
SET_EXC(self->db, res);
1198
Py_INCREF(callable);
1201
Py_XDECREF(self->busyhandler);
1202
self->busyhandler=callable;
1204
return (res==SQLITE_OK)?Py_BuildValue(""):NULL;
1208
/* USER DEFINED FUNCTION CODE.*/
1210
/* We store the registered functions in a linked list hooked into the
1211
connection object so we can free them. There is probably a better
1212
data structure to use but this was most convenient. */
1215
freefunccbinfo(funccbinfo *func)
1218
if(!func) return NULL;
1221
PyMem_Free(func->name);
1222
Py_XDECREF(func->scalarfunc);
1223
Py_XDECREF(func->aggregatefactory);
1230
allocfunccbinfo(void)
1232
funccbinfo *res=PyMem_Malloc(sizeof(funccbinfo));
1234
memset(res, 0, sizeof(funccbinfo));
1238
/* Converts sqlite3_value to PyObject. Returns a new reference. */
1240
convert_value_to_pyobject(sqlite3_value *value)
1242
/* DUPLICATE(ish) code: this is substantially similar to the code in
1243
Cursor_next. If you fix anything here then do it there as
1245
const int coltype=sqlite3_value_type(value);
1249
case SQLITE_INTEGER:
1251
long long vint=sqlite3_value_int64(value);
1252
if(vint<INT32_MIN || vint>INT32_MAX)
1253
return PyLong_FromLongLong(vint);
1255
return PyInt_FromLong((long)vint);
1259
return PyFloat_FromDouble(sqlite3_value_double(value));
1262
return convertutf8string(sqlite3_value_text(value));
1271
Py_ssize_t sz=sqlite3_value_bytes(value);
1272
item=PyBuffer_New(sz);
1277
if(!PyObject_AsWriteBuffer(item, &buffy, &sz2))
1278
memcpy(buffy, sqlite3_value_blob(value), sz);
1289
PyErr_Format(APSWException, "Unknown sqlite column type %d!", coltype);
1292
/* can't get here */
1298
set_context_result(sqlite3_context *context, PyObject *obj)
1302
assert(PyErr_Occurred());
1303
/* TODO: possibly examine exception and return appropriate error
1304
code eg for BusyError set error to SQLITE_BUSY */
1305
sqlite3_result_error(context, "executing scalarcallback failed", SQLITE_ERROR);
1309
/* DUPLICATE(ish) code: this is substantially similar to the code in
1310
Cursor_dobinding. If you fix anything here then do it there as
1315
sqlite3_result_null(context);
1318
if(PyInt_Check(obj))
1320
sqlite3_result_int64(context, PyInt_AS_LONG(obj));
1323
if (PyLong_Check(obj))
1325
sqlite3_result_int64(context, PyLong_AsLongLong(obj));
1328
if (PyFloat_CheckExact(obj))
1330
sqlite3_result_double(context, PyFloat_AS_DOUBLE(obj));
1333
if (PyUnicode_Check(obj))
1338
if(strbytes>INT32_MAX)
1340
PyErr_Format(ExcTooBig, "Unicode object is too large - SQLite only supports up to 2GB");
1345
sqlite3_result_text16(context, strdata, (int)strbytes, SQLITE_TRANSIENT);
1347
sqlite3_result_text(context, strdata, (int)strbytes, SQLITE_TRANSIENT);
1351
sqlite3_result_error(context, "Unicode conversions failed", SQLITE_ERROR);
1355
if (PyString_Check(obj))
1357
const char *val=PyString_AS_STRING(obj);
1358
const char *chk=val;
1359
for(;*chk && !((*chk)&0x80); chk++);
1362
PyObject *str2=PyUnicode_FromObject(obj);
1365
sqlite3_result_error(context, "PyUnicode_FromObject failed", SQLITE_ERROR);
1371
if(strbytes>INT32_MAX)
1373
PyErr_Format(ExcTooBig, "Unicode object is too large - SQLite only supports up to 2GB");
1378
sqlite3_result_text16(context, strdata, (int)strbytes, SQLITE_TRANSIENT);
1380
sqlite3_result_text(context, strdata, (int)strbytes, SQLITE_TRANSIENT);
1384
sqlite3_result_error(context, "Unicode conversions failed", SQLITE_ERROR);
1390
Py_ssize_t lenval=PyString_GET_SIZE(obj);
1391
if(lenval>INT32_MAX)
1393
PyErr_Format(ExcTooBig, "String object is too large - SQLite only supports up to 2GB");
1396
sqlite3_result_text(context, val, (int)lenval, SQLITE_TRANSIENT);
1400
if (PyBuffer_Check(obj))
1404
if(PyObject_AsCharBuffer(obj, &buffer, &buflen))
1406
sqlite3_result_error(context, "PyObject_AsCharBuffer failed", SQLITE_ERROR);
1409
if (buflen>INT32_MAX)
1410
sqlite3_result_error(context, "Buffer object is too large for SQLite - only up to 2GB is supported", SQLITE_ERROR);
1412
sqlite3_result_blob(context, buffer, (int)buflen, SQLITE_TRANSIENT);
1416
PyErr_Format(PyExc_TypeError, "Bad return type from function callback");
1417
sqlite3_result_error(context, "Bad return type from function callback", SQLITE_ERROR);
1421
/* Returns a new reference to a tuple formed from function parameters */
1423
getfunctionargs(sqlite3_context *context, PyObject *firstelement, int argc, sqlite3_value **argv)
1425
PyObject *pyargs=NULL;
1429
/* extra first item */
1433
pyargs=PyTuple_New((long)argc+extra);
1436
sqlite3_result_error(context, "PyTuple_New failed", SQLITE_ERROR);
1442
Py_INCREF(firstelement);
1443
PyTuple_SET_ITEM(pyargs, 0, firstelement);
1448
PyObject *item=convert_value_to_pyobject(argv[i]);
1452
sqlite3_result_error(context, "convert_value_to_pyobject failed", SQLITE_ERROR);
1455
PyTuple_SET_ITEM(pyargs, i+extra, item);
1466
/* dispatches scalar function */
1468
cbdispatch_func(sqlite3_context *context, int argc, sqlite3_value **argv)
1470
PyGILState_STATE gilstate;
1473
funccbinfo *cbinfo=(funccbinfo*)sqlite3_user_data(context);
1476
gilstate=PyGILState_Ensure();
1478
assert(cbinfo->scalarfunc);
1480
if(PyErr_Occurred())
1482
sqlite3_result_error(context, "Prior Python Error", SQLITE_ERROR);
1486
pyargs=getfunctionargs(context, NULL, argc, argv);
1490
assert(!PyErr_Occurred());
1491
retval=PyEval_CallObject(cbinfo->scalarfunc, pyargs);
1493
set_context_result(context, retval);
1497
PyGILState_Release(gilstate);
1500
static aggregatefunctioncontext *
1501
getaggregatefunctioncontext(sqlite3_context *context)
1503
aggregatefunctioncontext *aggfc=sqlite3_aggregate_context(context, sizeof(aggregatefunctioncontext));
1507
/* have we seen it before? */
1508
if(aggfc->aggvalue) return aggfc;
1510
/* fill in with Py_None so we know it is valid */
1511
aggfc->aggvalue=Py_None;
1514
cbinfo=(funccbinfo*)sqlite3_user_data(context);
1516
assert(cbinfo->aggregatefactory);
1518
/* call the aggregatefactory to get our working objects */
1519
args=PyTuple_New(0);
1522
retval=PyEval_CallObject(cbinfo->aggregatefactory, args);
1526
/* it should have returned a tuple of 3 items: object, stepfunction and finalfunction */
1527
if(!PyTuple_Check(retval))
1529
PyErr_Format(PyExc_TypeError, "Aggregate factory should return tuple of (object, stepfunction, finalfunction)");
1532
if(PyTuple_GET_SIZE(retval)!=3)
1534
PyErr_Format(PyExc_TypeError, "Aggregate factory should return 3 item tuple of (object, stepfunction, finalfunction)");
1537
/* we don't care about the type of the zeroth item (object) ... */
1540
if (!PyCallable_Check(PyTuple_GET_ITEM(retval,1)))
1542
PyErr_Format(PyExc_TypeError, "stepfunction must be callable");
1547
if (!PyCallable_Check(PyTuple_GET_ITEM(retval,2)))
1549
PyErr_Format(PyExc_TypeError, "final function must be callable");
1553
aggfc->aggvalue=PyTuple_GET_ITEM(retval,0);
1554
aggfc->stepfunc=PyTuple_GET_ITEM(retval,1);
1555
aggfc->finalfunc=PyTuple_GET_ITEM(retval,2);
1557
Py_INCREF(aggfc->aggvalue);
1558
Py_INCREF(aggfc->stepfunc);
1559
Py_INCREF(aggfc->finalfunc);
1561
Py_DECREF(Py_None); /* we used this earlier as a sentinel */
1571
Note that we can't call sqlite3_result_error in the step function as
1572
SQLite doesn't want to you to do that (and core dumps!)
1573
Consequently if an error is returned, we will still be repeatedly
1578
cbdispatch_step(sqlite3_context *context, int argc, sqlite3_value **argv)
1580
PyGILState_STATE gilstate;
1583
aggregatefunctioncontext *aggfc=NULL;
1585
gilstate=PyGILState_Ensure();
1587
if (PyErr_Occurred())
1590
aggfc=getaggregatefunctioncontext(context);
1592
if (PyErr_Occurred())
1597
pyargs=getfunctionargs(context, aggfc->aggvalue, argc, argv);
1601
assert(!PyErr_Occurred());
1602
retval=PyEval_CallObject(aggfc->stepfunc, pyargs);
1608
assert(PyErr_Occurred());
1612
PyGILState_Release(gilstate);
1615
/* this is somewhat similar to cbdispatch_step, except we also have to
1616
do some cleanup of the aggregatefunctioncontext */
1618
cbdispatch_final(sqlite3_context *context)
1620
PyGILState_STATE gilstate;
1621
PyObject *pyargs=NULL;
1622
PyObject *retval=NULL;
1623
aggregatefunctioncontext *aggfc=NULL;
1624
PyObject *err_type=NULL, *err_value=NULL, *err_traceback=NULL;
1626
gilstate=PyGILState_Ensure();
1628
PyErr_Fetch(&err_type, &err_value, &err_traceback);
1631
aggfc=getaggregatefunctioncontext(context);
1635
if((err_type||err_value||err_traceback) || PyErr_Occurred() || !aggfc->finalfunc)
1637
sqlite3_result_error(context, "Prior Python Error in step function", SQLITE_ERROR);
1641
pyargs=PyTuple_New(1);
1645
Py_INCREF(aggfc->aggvalue);
1646
PyTuple_SET_ITEM(pyargs, 0, aggfc->aggvalue);
1648
retval=PyEval_CallObject(aggfc->finalfunc, pyargs);
1650
set_context_result(context, retval);
1654
/* we also free the aggregatefunctioncontext here */
1655
assert(aggfc->aggvalue); /* should always be set, perhaps to Py_None */
1656
Py_XDECREF(aggfc->aggvalue);
1657
Py_XDECREF(aggfc->stepfunc);
1658
Py_XDECREF(aggfc->finalfunc);
1660
if(PyErr_Occurred() && (err_type||err_value||err_traceback))
1662
PyErr_Format(PyExc_StandardError, "An exception happened during cleanup of an aggregate function, but there was already error in the step function so only that can be returned");
1663
PyErr_WriteUnraisable(Py_None); /* there is no object to give, and NULL causes some versions to core dump */
1666
if(err_type||err_value||err_traceback)
1667
PyErr_Restore(err_type, err_value, err_traceback);
1669
/* sqlite3 frees the actual underlying memory we used (aggfc itself) */
1671
PyGILState_Release(gilstate);
1676
Connection_createscalarfunction(Connection *self, PyObject *args)
1685
CHECK_THREAD(self,NULL);
1687
if(!PyArg_ParseTuple(args, "esO|i:createscalarfunction(name,callback, numargs=-1)", STRENCODING, &name, &callable, &numargs))
1693
/* there isn't a C api to get a (potentially unicode) string and
1694
make it uppercase so we hack around */
1696
/* validate the name */
1697
for(chk=name;*chk && !((*chk)&0x80);chk++);
1701
PyErr_SetString(PyExc_TypeError, "function name must be ascii characters only");
1705
/* convert name to upper case */
1706
for(chk=name;*chk;chk++)
1707
if(*chk>='a' && *chk<='z')
1710
/* ::TODO:: check if name points to already defined function and free relevant funccbinfo */
1712
if(callable!=Py_None && !PyCallable_Check(callable))
1715
PyErr_SetString(PyExc_TypeError, "parameter must be callable");
1719
Py_INCREF(callable);
1721
cbinfo=allocfunccbinfo();
1723
cbinfo->scalarfunc=callable;
1725
res=sqlite3_create_function(self->db,
1728
SQLITE_UTF8, /* it isn't very clear what this parameter does */
1729
(callable!=Py_None)?cbinfo:NULL,
1730
(callable!=Py_None)?cbdispatch_func:NULL,
1736
freefunccbinfo(cbinfo);
1737
SET_EXC(self->db, res);
1741
if(callable!=Py_None)
1743
/* put cbinfo into the linked list */
1744
cbinfo->next=self->functions;
1745
self->functions=cbinfo;
1749
/* free it since we cancelled the function */
1750
freefunccbinfo(cbinfo);
1753
return Py_BuildValue("");
1757
Connection_createaggregatefunction(Connection *self, PyObject *args)
1766
CHECK_THREAD(self,NULL);
1768
if(!PyArg_ParseTuple(args, "esO|i:createaggregatefunction(name, factorycallback, numargs=-1)", STRENCODING, &name, &callable, &numargs))
1774
/* there isn't a C api to get a (potentially unicode) string and make it uppercase so we hack around */
1776
/* validate the name */
1777
for(chk=name;*chk && !((*chk)&0x80);chk++);
1781
PyErr_SetString(PyExc_TypeError, "function name must be ascii characters only");
1785
/* convert name to upper case */
1786
for(chk=name;*chk;chk++)
1787
if(*chk>='a' && *chk<='z')
1790
/* ::TODO:: check if name points to already defined function and free relevant funccbinfo */
1792
if(callable!=Py_None && !PyCallable_Check(callable))
1795
PyErr_SetString(PyExc_TypeError, "parameter must be callable");
1799
Py_INCREF(callable);
1801
cbinfo=allocfunccbinfo();
1803
cbinfo->aggregatefactory=callable;
1805
res=sqlite3_create_function(self->db,
1808
SQLITE_UTF8, /* it isn't very clear what this parameter does */
1809
(callable!=Py_None)?cbinfo:NULL,
1811
(callable!=Py_None)?cbdispatch_step:NULL,
1812
(callable!=Py_None)?cbdispatch_final:NULL);
1816
freefunccbinfo(cbinfo);
1817
SET_EXC(self->db, res);
1821
if(callable!=Py_None)
1823
/* put cbinfo into the linked list */
1824
cbinfo->next=self->functions;
1825
self->functions=cbinfo;
1829
/* free things up */
1830
freefunccbinfo(cbinfo);
1833
return Py_BuildValue("");
1836
/* USER DEFINED COLLATION CODE.*/
1838
/* We store the registered collations in a linked list hooked into
1839
the connection object so we can free them. There is probably a
1840
better data structure to use but this was most convenient. */
1842
static collationcbinfo *
1843
freecollationcbinfo(collationcbinfo *collation)
1845
collationcbinfo *cnext;
1846
if(!collation) return NULL;
1849
PyMem_Free(collation->name);
1850
Py_XDECREF(collation->func);
1851
cnext=collation->next;
1852
PyMem_Free(collation);
1856
static collationcbinfo *
1857
alloccollationcbinfo(void)
1859
collationcbinfo *res=PyMem_Malloc(sizeof(collationcbinfo));
1860
memset(res, 0, sizeof(collationcbinfo));
1864
int collation_cb(void *context,
1865
int stringonelen, const void *stringonedata,
1866
int stringtwolen, const void *stringtwodata)
1868
PyGILState_STATE gilstate;
1869
collationcbinfo *cbinfo=(collationcbinfo*)context;
1870
PyObject *pys1=NULL, *pys2=NULL, *retval=NULL, *pyargs=NULL;
1875
gilstate=PyGILState_Ensure();
1877
if(PyErr_Occurred()) goto finally; /* outstanding error */
1879
pys1=convertutf8stringsize(stringonedata, stringonelen);
1880
pys2=convertutf8stringsize(stringtwodata, stringtwolen);
1883
goto finally; /* failed to allocate strings */
1885
pyargs=PyTuple_New(2);
1887
goto finally; /* failed to allocate arg tuple */
1889
PyTuple_SET_ITEM(pyargs, 0, pys1);
1890
PyTuple_SET_ITEM(pyargs, 1, pys2);
1892
pys1=pys2=NULL; /* pyargs owns them now */
1894
assert(!PyErr_Occurred());
1896
retval=PyEval_CallObject(cbinfo->func, pyargs);
1898
if(!retval) goto finally; /* execution failed */
1900
result=PyInt_AsLong(retval);
1901
if(PyErr_Occurred())
1910
PyGILState_Release(gilstate);
1916
Connection_createcollation(Connection *self, PyObject *args)
1921
collationcbinfo *cbinfo;
1924
CHECK_THREAD(self,NULL);
1926
if(!PyArg_ParseTuple(args, "esO:createcollation(name,callback)", STRENCODING, &name, &callable))
1932
/* there isn't a C api to get a (potentially unicode) string and make it uppercase so we hack around */
1934
/* validate the name */
1935
for(chk=name;*chk && !((*chk)&0x80);chk++);
1939
PyErr_SetString(PyExc_TypeError, "function name must be ascii characters only");
1943
/* convert name to upper case */
1944
for(chk=name;*chk;chk++)
1945
if(*chk>='a' && *chk<='z')
1948
/* ::TODO:: check if name points to already defined collation and free relevant collationcbinfo */
1950
if(callable!=Py_None && !PyCallable_Check(callable))
1953
PyErr_SetString(PyExc_TypeError, "parameter must be callable");
1957
Py_INCREF(callable);
1959
cbinfo=alloccollationcbinfo();
1961
cbinfo->func=callable;
1963
res=sqlite3_create_collation(self->db,
1966
(callable!=Py_None)?cbinfo:NULL,
1967
(callable!=Py_None)?collation_cb:NULL);
1970
freecollationcbinfo(cbinfo);
1971
SET_EXC(self->db, res);
1975
if (callable!=Py_None)
1977
/* put cbinfo into the linked list */
1978
cbinfo->next=self->collations;
1979
self->collations=cbinfo;
1984
freecollationcbinfo(cbinfo);
1987
return Py_BuildValue("");
1991
static PyMethodDef Connection_methods[] = {
1992
{"cursor", (PyCFunction)Connection_cursor, METH_NOARGS,
1993
"Create a new cursor" },
1994
{"setbusytimeout", (PyCFunction)Connection_setbusytimeout, METH_VARARGS,
1995
"Sets the sqlite busy timeout in milliseconds. Use zero to disable the timeout"},
1996
{"interrupt", (PyCFunction)Connection_interrupt, METH_NOARGS,
1997
"Causes any pending database operations to abort at the earliest opportunity"},
1998
{"createscalarfunction", (PyCFunction)Connection_createscalarfunction, METH_VARARGS,
1999
"Creates a scalar function"},
2000
{"createaggregatefunction", (PyCFunction)Connection_createaggregatefunction, METH_VARARGS,
2001
"Creates an aggregate function"},
2002
{"setbusyhandler", (PyCFunction)Connection_setbusyhandler, METH_O,
2003
"Sets the busy handler"},
2004
{"changes", (PyCFunction)Connection_changes, METH_NOARGS,
2005
"Returns the number of rows changed by last query"},
2006
{"totalchanges", (PyCFunction)Connection_totalchanges, METH_NOARGS,
2007
"Returns the total number of changes to database since it was opened"},
2008
{"getautocommit", (PyCFunction)Connection_getautocommit, METH_NOARGS,
2009
"Returns if the database is in auto-commit mode"},
2010
{"createcollation", (PyCFunction)Connection_createcollation, METH_VARARGS,
2011
"Creates a collation function"},
2012
{"last_insert_rowid", (PyCFunction)Connection_last_insert_rowid, METH_NOARGS,
2013
"Returns rowid for last insert"},
2014
{"complete", (PyCFunction)Connection_complete, METH_VARARGS,
2015
"Checks if a SQL statement is complete"},
2016
{"setauthorizer", (PyCFunction)Connection_setauthorizer, METH_O,
2017
"Sets an authorizer function"},
2018
{"setupdatehook", (PyCFunction)Connection_setupdatehook, METH_O,
2019
"Sets an update hook"},
2020
{"setrollbackhook", (PyCFunction)Connection_setrollbackhook, METH_O,
2021
"Sets a callable invoked before each rollback"},
2023
{"setprofile", (PyCFunction)Connection_setprofile, METH_O,
2024
"Sets a callable invoked with profile information after each statement"},
2025
{"setcommithook", (PyCFunction)Connection_setcommithook, METH_O,
2026
"Sets a callable invoked before each commit"},
2027
{"setprogresshandler", (PyCFunction)Connection_setprogresshandler, METH_VARARGS,
2028
"Sets a callback invoked periodically during long running calls"},
2030
{NULL} /* Sentinel */
2034
static PyTypeObject ConnectionType = {
2035
PyObject_HEAD_INIT(NULL)
2037
"apsw.Connection", /*tp_name*/
2038
sizeof(Connection), /*tp_basicsize*/
2040
(destructor)Connection_dealloc, /*tp_dealloc*/
2047
0, /*tp_as_sequence*/
2048
0, /*tp_as_mapping*/
2055
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/
2056
"Connection object", /* tp_doc */
2057
0, /* tp_traverse */
2059
0, /* tp_richcompare */
2060
0, /* tp_weaklistoffset */
2062
0, /* tp_iternext */
2063
Connection_methods, /* tp_methods */
2068
0, /* tp_descr_get */
2069
0, /* tp_descr_set */
2070
0, /* tp_dictoffset */
2071
(initproc)Connection_init, /* tp_init */
2073
Connection_new, /* tp_new */
2079
/* Do finalization and free resources. Returns the SQLITE error code */
2081
resetcursor(Cursor *self)
2085
Py_XDECREF(self->bindings);
2086
self->bindings=NULL;
2087
self->bindingsoffset=-1;
2091
res=sqlite3_finalize(self->statement);
2092
SET_EXC(self->connection->db, res);
2096
if(self->status!=C_DONE && self->zsqlnextpos)
2098
if (*self->zsqlnextpos && res==SQLITE_OK)
2100
/* We still have more, so this is actually an abort. */
2102
if(!PyErr_Occurred())
2103
PyErr_Format(ExcIncomplete, "Error: there are still remaining sql statements to execute");
2106
self->zsqlnextpos=NULL;
2108
if(self->status!=C_DONE && self->emiter)
2110
PyObject *next=PyIter_Next(self->emiter);
2115
if (!PyErr_Occurred())
2116
PyErr_Format(ExcIncomplete, "Error: there are still many remaining sql statements to execute");
2120
Py_XDECREF(self->emiter);
2125
PyMem_Free((void*)self->zsql);
2129
self->status=C_DONE;
2135
Cursor_dealloc(Cursor * self)
2137
/* thread check - we can't use macro as it returns*/
2138
PyObject *err_type, *err_value, *err_traceback;
2139
int have_error=PyErr_Occurred()?1:0;
2141
if(self->connection->thread_ident!=PyThread_get_thread_ident())
2144
PyErr_Fetch(&err_type, &err_value, &err_traceback);
2145
PyErr_Format(PyExc_RuntimeError, "The destructor for Cursor is called in a different thread than it"
2146
"was created in. All calls must be in the same thread. It was created in thread %d"
2147
"and this is %d. SQLite is not being closed as a result.",
2148
(int)(self->connection->thread_ident), (int)(PyThread_get_thread_ident()));
2149
PyErr_WriteUnraisable((PyObject*)self);
2151
PyErr_Restore(err_type, err_value, err_traceback);
2156
/* do our finalisation ... */
2160
/* remember the existing error so that resetcursor won't immediately return */
2161
PyErr_Fetch(&err_type, &err_value, &err_traceback);
2166
if(PyErr_Occurred())
2167
PyErr_Clear(); /* clear out any exceptions from resetcursor since we don't care */
2170
/* restore earlier error if there was one */
2171
PyErr_Restore(err_type, err_value, err_traceback);
2173
/* we no longer need connection */
2174
if(self->connection)
2176
Py_DECREF(self->connection);
2180
/* executemany iterator */
2181
Py_XDECREF(self->emiter);
2184
/* no need for tracing */
2185
Py_XDECREF(self->exectrace);
2186
Py_XDECREF(self->rowtrace);
2187
self->exectrace=self->rowtrace=0;
2189
self->ob_type->tp_free((PyObject*)self);
2193
Cursor_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2197
self = (Cursor *)type->tp_alloc(type, 0);
2202
self->zsqlnextpos=0;
2203
self->status=C_DONE;
2205
self->bindingsoffset=0;
2211
return (PyObject *)self;
2215
Cursor_init(Cursor *self, PyObject *args, PyObject *kwds)
2217
CHECK_THREAD(self->connection,-1);
2219
if(!PyArg_ParseTupleAndKeywords(args, kwds, "", NULL))
2226
Cursor_getdescription(Cursor *self)
2229
PyObject *result=NULL;
2230
PyObject *pair=NULL;
2231
PyObject *first=NULL;
2232
PyObject *second=NULL;
2235
CHECK_THREAD(self->connection,NULL);
2237
if(!self->statement)
2239
PyErr_Format(ExcComplete, "Can't get description for statements that have completed execution");
2243
ncols=sqlite3_column_count(self->statement);
2244
result=PyTuple_New(ncols);
2245
if(!result) goto error;
2247
for(i=0;i<ncols;i++)
2249
pair=PyTuple_New(2);
2250
if(!pair) goto error;
2252
str=sqlite3_column_name(self->statement, i);
2253
first=convertutf8string(str);
2255
str=sqlite3_column_decltype(self->statement, i);
2256
second=convertutf8string(str);
2258
if(!first || !second) goto error;
2260
PyTuple_SET_ITEM(pair, 0, first);
2261
PyTuple_SET_ITEM(pair, 1, second);
2263
/* owned by pair now */
2266
PyTuple_SET_ITEM(result, i, pair);
2267
/* owned by result now */
2281
/* internal function - returns SQLite error code (ie SQLITE_OK if all is well) */
2283
Cursor_dobinding(Cursor *self, int arg, PyObject *obj)
2286
/* DUPLICATE(ish) code: this is substantially similar to the code in
2287
set_context_result. If you fix anything here then do it there as
2292
if(PyErr_Occurred()) return -1;
2295
res=sqlite3_bind_null(self->statement, arg);
2296
/* Python uses a 'long' for storage of PyInt. This could
2297
be a 32bit or 64bit quantity depending on the platform. */
2298
else if(PyInt_Check(obj))
2299
res=sqlite3_bind_int64(self->statement, arg, PyInt_AS_LONG(obj));
2300
else if (PyLong_Check(obj))
2301
/* nb: PyLong_AsLongLong can cause Python level error */
2302
res=sqlite3_bind_int64(self->statement, arg, PyLong_AsLongLong(obj));
2303
else if (PyFloat_Check(obj))
2304
res=sqlite3_bind_double(self->statement, arg, PyFloat_AS_DOUBLE(obj));
2305
else if (PyUnicode_Check(obj))
2307
const void *badptr=NULL;
2312
if(strbytes>INT32_MAX)
2314
PyErr_Format(ExcTooBig, "Unicode object is too large - SQLite only supports up to 2GB");
2319
res=sqlite3_bind_text16(self->statement, arg, strdata, (int)strbytes, SQLITE_TRANSIENT);
2321
res=sqlite3_bind_text(self->statement, arg, strdata, (int)strbytes, SQLITE_TRANSIENT);
2327
assert(PyErr_Occurred());
2331
else if (PyString_Check(obj))
2333
const char *val=PyString_AS_STRING(obj);
2334
const char *chk=val;
2335
for(;*chk && !((*chk)&0x80); chk++);
2338
const void *badptr=NULL;
2339
PyObject *str2=PyUnicode_FromObject(obj);
2346
if(strbytes>INT32_MAX)
2348
PyErr_Format(ExcTooBig, "Unicode object is too large - SQLite only supports up to 2GB");
2353
res=sqlite3_bind_text16(self->statement, arg, strdata, (int)strbytes, SQLITE_TRANSIENT);
2355
res=sqlite3_bind_text(self->statement, arg, strdata, (int)strbytes, SQLITE_TRANSIENT);
2362
assert(PyErr_Occurred());
2368
size_t lenval=strlen(val);
2369
if(lenval>INT32_MAX)
2371
PyErr_Format(ExcTooBig, "String object is too large - SQLite only supports up to 2GB");
2374
res=sqlite3_bind_text(self->statement, arg, val, (int)lenval, SQLITE_TRANSIENT);
2377
else if (PyBuffer_Check(obj))
2381
if(PyObject_AsCharBuffer(obj, &buffer, &buflen))
2383
if (buflen>INT32_MAX)
2385
PyErr_Format(ExcTooBig, "Binding object is too large - SQLite only supports up to 2GB");
2388
res=sqlite3_bind_blob(self->statement, arg, buffer, (int)buflen, SQLITE_TRANSIENT);
2392
PyObject *strrep=PyObject_Str(obj);
2393
PyErr_Format(PyExc_TypeError, "Bad binding argument type supplied - argument #%d: %s", (int)(arg+self->bindingsoffset), strrep?PyString_AsString(strrep):"<str failed>");
2399
SET_EXC(self->connection->db, res);
2402
if(PyErr_Occurred())
2407
/* internal function */
2409
Cursor_dobindings(Cursor *self)
2411
int nargs, arg, res, sz=0;
2414
if(PyErr_Occurred()) return -1;
2416
assert(self->bindingsoffset>=0);
2418
nargs=sqlite3_bind_parameter_count(self->statement);
2421
if (self->bindings && PyDict_Check(self->bindings))
2423
for(arg=1;arg<=nargs;arg++)
2425
const char *key=sqlite3_bind_parameter_name(self->statement, arg);
2430
PyErr_Format(ExcBindings, "Binding %d has no name, but you supplied a dict (which only has names).", arg-1);
2434
assert(*key==':' || *key=='$');
2435
key++; /* first char is a colon or dollar which we skip */
2437
for(chk=key;*chk && !((*chk)&0x80); chk++);
2440
PyObject *keyo=PyUnicode_DecodeUTF8(key, strlen(key), NULL);
2441
if(!keyo) return -1;
2443
obj=PyDict_GetItem(self->bindings, keyo);
2447
obj=PyDict_GetItemString(self->bindings, key);
2450
/* this is where we could error on missing keys */
2452
if(Cursor_dobinding(self,arg,obj))
2454
assert(PyErr_Occurred());
2462
/* it must be a fast sequence */
2463
/* verify the number of args supplied */
2465
sz=PySequence_Fast_GET_SIZE(self->bindings);
2466
/* there is another statement after this one ... */
2467
if(*self->zsqlnextpos && sz-self->bindingsoffset<nargs)
2469
PyErr_Format(ExcBindings, "Incorrect number of bindings supplied. The current statement uses %d and there are only %d left. Current offset is %d",
2470
nargs, (self->bindings)?sz:0, (int)(self->bindingsoffset));
2473
/* no more statements */
2474
if(!*self->zsqlnextpos && sz-self->bindingsoffset!=nargs)
2476
PyErr_Format(ExcBindings, "Incorrect number of bindings supplied. The current statement uses %d and there are %d supplied. Current offset is %d",
2477
nargs, (self->bindings)?sz:0, (int)(self->bindingsoffset));
2483
/* nb sqlite starts bind args at one not zero */
2484
for(arg=1;arg<=nargs;arg++)
2486
obj=PySequence_Fast_GET_ITEM(self->bindings, arg-1+self->bindingsoffset);
2487
if(Cursor_dobinding(self, arg, obj))
2489
assert(PyErr_Occurred());
2494
self->bindingsoffset+=nargs;
2500
const char *previouszsqlpos; /* where the begining of the statement was */
2501
Py_ssize_t savedbindingsoffset; /* where the bindings began */
2502
} exectrace_oldstate;
2505
Cursor_doexectrace(Cursor *self, exectrace_oldstate *etos)
2507
PyObject *retval=NULL;
2508
PyObject *args=NULL;
2509
PyObject *sqlcmd=NULL;
2510
PyObject *bindings=NULL;
2513
assert(self->exectrace);
2515
/* make a string of the command */
2516
sqlcmd=convertutf8stringsize(etos->previouszsqlpos, self->zsqlnextpos-etos->previouszsqlpos);
2518
if(!sqlcmd) return -1;
2519
/* now deal with the bindings */
2522
if(PyDict_Check(self->bindings))
2524
bindings=self->bindings;
2525
Py_INCREF(self->bindings);
2529
bindings=PySequence_GetSlice(self->bindings, etos->savedbindingsoffset, self->bindingsoffset);
2540
Py_INCREF(bindings);
2542
args=PyTuple_New(2);
2546
Py_DECREF(bindings);
2549
PyTuple_SET_ITEM(args, 0, sqlcmd);
2550
PyTuple_SET_ITEM(args, 1, bindings);
2552
retval=PyEval_CallObject(self->exectrace, args);
2556
assert(PyErr_Occurred());
2559
result=PyObject_IsTrue(retval);
2561
assert (result==-1 || result==0 || result ==1);
2564
assert(PyErr_Occurred());
2570
/* callback didn't want us to continue */
2571
PyErr_Format(ExcTraceAbort, "Aborted by false/null return value of exec tracer");
2576
Cursor_dorowtrace(Cursor *self, PyObject *retval)
2578
assert(self->rowtrace);
2580
retval=PyEval_CallObject(self->rowtrace, retval);
2581
if(!retval) return NULL;
2586
/* Returns a borrowed reference to self if all is ok, else NULL on error */
2588
Cursor_step(Cursor *self)
2591
exectrace_oldstate etos;
2593
if(self->status==C_DONE)
2595
PyErr_Format(ExcComplete, "The statement(s) have finished or errored, so you can't keep running them");
2601
assert(!PyErr_Occurred());
2602
Py_BEGIN_ALLOW_THREADS
2603
res=sqlite3_step(self->statement);
2604
Py_END_ALLOW_THREADS;
2610
return (PyErr_Occurred())?(NULL):((PyObject*)self);
2612
self->status=C_BEGIN;
2613
SET_EXC(self->connection->db,res);
2616
default: /* no other value should happen, but we'll
2617
defensively code and treat them the same as
2621
/* there was an error - we need to get actual error code from sqlite3_finalize */
2622
self->status=C_DONE;
2623
res=resetcursor(self); /* this will get the error code for us */
2624
assert(res!=SQLITE_OK);
2628
/* this would be an error in apsw itself */
2629
self->status=C_DONE;
2630
SET_EXC(self->connection->db,res);
2635
if (PyErr_Occurred())
2637
self->status=C_DONE;
2643
assert(res==SQLITE_DONE);
2645
/* done with that statement, are there any more? */
2646
self->status=C_DONE;
2647
if(!self->zsqlnextpos || !*self->zsqlnextpos)
2652
/* no more so we finalize */
2653
if(resetcursor(self)!=SQLITE_OK)
2655
assert(PyErr_Occurred());
2656
return NULL; /* exception */
2658
return (PyObject*)self;
2660
next=PyIter_Next(self->emiter);
2661
if(PyErr_Occurred())
2665
/* no more from executemanyiter so we finalize */
2666
if(resetcursor(self)!=SQLITE_OK)
2668
assert(PyErr_Occurred());
2671
return (PyObject*)self;
2673
self->zsqlnextpos=self->zsql; /* start at begining of string again */
2674
/* don't need bindings from last round if emiter.next() */
2675
Py_XDECREF(self->bindings);
2677
self->bindingsoffset=0;
2678
/* verify type of next before putting in bindings */
2679
if(PyDict_Check(next))
2680
self->bindings=next;
2683
self->bindings=PySequence_Fast(next, "You must supply a dict or a sequence");
2690
assert(self->bindings);
2693
/* finalise and go again */
2694
res=sqlite3_finalize(self->statement);
2696
SET_EXC(self->connection->db,res);
2699
assert(res!=SQLITE_BUSY); /* finalize shouldn't be returning busy, only step */
2703
assert(!self->statement);
2706
etos.previouszsqlpos=self->zsqlnextpos;
2707
etos.savedbindingsoffset=self->bindingsoffset;
2709
res=sqlite3_prepare(self->connection->db, self->zsqlnextpos, -1, &self->statement, &self->zsqlnextpos);
2710
SET_EXC(self->connection->db,res);
2713
assert(res!=SQLITE_BUSY); /* prepare definitely shouldn't be returning busy */
2718
if(Cursor_dobindings(self))
2720
assert(PyErr_Occurred());
2726
if(Cursor_doexectrace(self, &etos))
2728
assert(self->status==C_DONE);
2729
assert(PyErr_Occurred());
2733
assert(self->status==C_DONE);
2734
self->status=C_BEGIN;
2737
/* you can't actually get here */
2743
Cursor_execute(Cursor *self, PyObject *args)
2746
PyObject *retval=NULL;
2747
exectrace_oldstate etos;
2749
CHECK_THREAD(self->connection, NULL);
2751
res=resetcursor(self);
2755
assert(!self->bindings);
2757
if(!PyArg_ParseTuple(args, "es|O:execute(statements,bindings=())", STRENCODING, &self->zsql, &self->bindings))
2762
if(PyDict_Check(self->bindings))
2763
Py_INCREF(self->bindings);
2766
self->bindings=PySequence_Fast(self->bindings, "You must supply a dict or a sequence");
2772
assert(!self->statement);
2775
etos.previouszsqlpos=self->zsql;
2776
etos.savedbindingsoffset=0;
2778
res=sqlite3_prepare(self->connection->db, self->zsql, -1, &self->statement, &self->zsqlnextpos);
2779
SET_EXC(self->connection->db,res);
2783
self->bindingsoffset=0;
2784
if(Cursor_dobindings(self))
2786
assert(PyErr_Occurred());
2792
if(Cursor_doexectrace(self, &etos))
2794
assert(PyErr_Occurred());
2799
self->status=C_BEGIN;
2801
retval=Cursor_step(self);
2804
assert(PyErr_Occurred());
2812
Cursor_executemany(Cursor *self, PyObject *args)
2815
PyObject *retval=NULL;
2816
PyObject *theiterable=NULL;
2817
PyObject *next=NULL;
2818
exectrace_oldstate etos;
2820
CHECK_THREAD(self->connection, NULL);
2822
res=resetcursor(self);
2826
assert(!self->bindings);
2827
assert(!self->emiter);
2828
assert(!self->zsql);
2829
assert(self->status=C_DONE);
2831
if(!PyArg_ParseTuple(args, "esO:executemany(statements, sequenceofbindings)", STRENCODING, &self->zsql, &theiterable))
2834
self->emiter=PyObject_GetIter(theiterable);
2837
PyErr_Format(PyExc_TypeError, "2nd parameter must be iterable");
2841
next=PyIter_Next(self->emiter);
2842
if(!next && PyErr_Occurred())
2848
return (PyObject*)self;
2851
if(PyDict_Check(next))
2852
self->bindings=next;
2855
self->bindings=PySequence_Fast(next, "You must supply a dict or a sequence");
2856
Py_DECREF(next); /* _Fast makes new reference */
2861
assert(!self->statement);
2864
etos.previouszsqlpos=self->zsql;
2865
etos.savedbindingsoffset=0;
2867
res=sqlite3_prepare(self->connection->db, self->zsql, -1, &self->statement, &self->zsqlnextpos);
2868
SET_EXC(self->connection->db,res);
2872
self->bindingsoffset=0;
2873
if(Cursor_dobindings(self))
2875
assert(PyErr_Occurred());
2881
if(Cursor_doexectrace(self, &etos))
2883
assert(PyErr_Occurred());
2888
self->status=C_BEGIN;
2890
retval=Cursor_step(self);
2893
assert(PyErr_Occurred());
2901
Cursor_next(Cursor *self)
2909
CHECK_THREAD(self->connection, NULL);
2912
if(self->status==C_BEGIN)
2913
if(!Cursor_step(self))
2915
assert(PyErr_Occurred());
2918
if(self->status==C_DONE)
2921
assert(self->status==C_ROW);
2923
self->status=C_BEGIN;
2925
/* DUPLICATE(ish) code: this is substantially similar to the code in
2926
convert_value_to_pyobject. If you fix anything here then do it
2929
/* return the row of data */
2930
numcols=sqlite3_data_count(self->statement);
2931
retval=PyTuple_New(numcols);
2932
if(!retval) return NULL;
2934
for(i=0;i<numcols;i++)
2936
coltype=sqlite3_column_type(self->statement, i);
2940
case SQLITE_INTEGER:
2942
long long vint=sqlite3_column_int64(self->statement, i);
2943
if(vint<INT32_MIN || vint>INT32_MAX)
2944
item=PyLong_FromLongLong(vint);
2946
item=PyInt_FromLong((long)vint);
2951
item=PyFloat_FromDouble(sqlite3_column_double(self->statement, i));
2955
item=convertutf8string(sqlite3_column_text(self->statement, i));
2965
Py_ssize_t sz=sqlite3_column_bytes(self->statement, i);
2966
item=PyBuffer_New(sz);
2971
if(!PyObject_AsWriteBuffer(item, &buffy, &sz2))
2972
memcpy(buffy, sqlite3_column_blob(self->statement, i), sz);
2983
PyErr_Format(APSWException, "Unknown sqlite column type %d!", coltype);
2988
if(!item) return NULL;
2989
PyTuple_SET_ITEM(retval, i, item);
2993
PyObject *r2=Cursor_dorowtrace(self, retval);
2995
if(!r2) return NULL;
3007
Cursor_iter(Cursor *self)
3009
CHECK_THREAD(self->connection, NULL);
3012
return (PyObject*)self;
3016
Cursor_setexectrace(Cursor *self, PyObject *func)
3018
CHECK_THREAD(self->connection, NULL);
3020
if(func!=Py_None && !PyCallable_Check(func))
3022
PyErr_SetString(PyExc_TypeError, "parameter must be callable");
3029
Py_XDECREF(self->exectrace);
3030
self->exectrace=(func!=Py_None)?func:NULL;
3032
return Py_BuildValue("");
3036
Cursor_setrowtrace(Cursor *self, PyObject *func)
3038
CHECK_THREAD(self->connection, NULL);
3040
if(func!=Py_None && !PyCallable_Check(func))
3042
PyErr_SetString(PyExc_TypeError, "parameter must be callable");
3049
Py_XDECREF(self->rowtrace);
3050
self->rowtrace=(func!=Py_None)?func:NULL;
3052
return Py_BuildValue("");
3056
Cursor_getexectrace(Cursor *self)
3058
PyObject *ret=(self->exectrace)?(self->exectrace):Py_None;
3064
Cursor_getrowtrace(Cursor *self)
3066
PyObject *ret=(self->rowtrace)?(self->rowtrace):Py_None;
3072
Cursor_getconnection(Cursor *self)
3074
CHECK_THREAD(self->connection, NULL);
3076
Py_INCREF(self->connection);
3077
return (PyObject*)self->connection;
3080
static PyMethodDef Cursor_methods[] = {
3081
{"execute", (PyCFunction)Cursor_execute, METH_VARARGS,
3082
"Executes one or more statements" },
3083
{"executemany", (PyCFunction)Cursor_executemany, METH_VARARGS,
3084
"Repeatedly executes statements on sequence" },
3085
{"next", (PyCFunction)Cursor_next, METH_NOARGS,
3086
"Returns next row returned from query"},
3087
{"setexectrace", (PyCFunction)Cursor_setexectrace, METH_O,
3088
"Installs a function called for every statement executed"},
3089
{"setrowtrace", (PyCFunction)Cursor_setrowtrace, METH_O,
3090
"Installs a function called for every row returned"},
3091
{"getexectrace", (PyCFunction)Cursor_getexectrace, METH_NOARGS,
3092
"Returns the current exec tracer function"},
3093
{"getrowtrace", (PyCFunction)Cursor_getrowtrace, METH_NOARGS,
3094
"Returns the current row tracer function"},
3095
{"getrowtrace", (PyCFunction)Cursor_getrowtrace, METH_NOARGS,
3096
"Returns the current row tracer function"},
3097
{"getconnection", (PyCFunction)Cursor_getconnection, METH_NOARGS,
3098
"Returns the connection object for this cursor"},
3099
{"getdescription", (PyCFunction)Cursor_getdescription, METH_NOARGS,
3100
"Returns the description for the current row"},
3101
{NULL} /* Sentinel */
3105
static PyTypeObject CursorType = {
3106
PyObject_HEAD_INIT(NULL)
3108
"apsw.Cursor", /*tp_name*/
3109
sizeof(Cursor), /*tp_basicsize*/
3111
(destructor)Cursor_dealloc, /*tp_dealloc*/
3118
0, /*tp_as_sequence*/
3119
0, /*tp_as_mapping*/
3126
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_ITER , /*tp_flags*/
3127
"Cursor object", /* tp_doc */
3128
0, /* tp_traverse */
3130
0, /* tp_richcompare */
3131
0, /* tp_weaklistoffset */
3132
(getiterfunc)Cursor_iter, /* tp_iter */
3133
(iternextfunc)Cursor_next, /* tp_iternext */
3134
Cursor_methods, /* tp_methods */
3139
0, /* tp_descr_get */
3140
0, /* tp_descr_set */
3141
0, /* tp_dictoffset */
3142
(initproc)Cursor_init, /* tp_init */
3144
Cursor_new, /* tp_new */
3147
/* MODULE METHODS */
3149
getsqliteversion(void)
3151
return PyString_FromString(sqlite3_libversion());
3155
getapswversion(void)
3157
return PyString_FromString(APSW_VERSION);
3161
enablesharedcache(PyObject *self, PyObject *args)
3164
if(!PyArg_ParseTuple(args, "i:enablesharedcache(boolean)", &setting))
3167
res=sqlite3_enable_shared_cache(setting);
3173
return Py_BuildValue("");
3176
static PyMethodDef module_methods[] = {
3177
{"sqlitelibversion", (PyCFunction)getsqliteversion, METH_NOARGS,
3178
"Return the version of the SQLite library"},
3179
{"apswversion", (PyCFunction)getapswversion, METH_NOARGS,
3180
"Return the version of the APSW wrapper"},
3181
{"enablesharedcache", (PyCFunction)enablesharedcache, METH_VARARGS,
3182
"Sets shared cache semantics for this thread"},
3184
{NULL} /* Sentinel */
3189
#ifndef PyMODINIT_FUNC /* declarations for DLL import/export */
3190
#define PyMODINIT_FUNC void
3197
assert(sizeof(int)==4); /* we expect 32 bit ints */
3198
assert(sizeof(long long)==8); /* we expect 64 bit long long */
3200
if (PyType_Ready(&ConnectionType) < 0)
3203
if (PyType_Ready(&CursorType) < 0)
3206
/* ensure threads are available */
3207
PyEval_InitThreads();
3210
m = Py_InitModule3("apsw", module_methods,
3211
"Another Python SQLite Wrapper.");
3216
if(init_exceptions(m))
3218
fprintf(stderr, "init_exceptions failed\n");
3222
Py_INCREF(&ConnectionType);
3223
PyModule_AddObject(m, "Connection", (PyObject *)&ConnectionType);
3225
/* we don't add cursor to the module since users shouldn't be able to instantiate them directly */
3227
/* add in some constants */
3229
#define ADDINT(v) PyModule_AddObject(m, #v, Py_BuildValue("i", v));
3231
ADDINT(SQLITE_DENY);
3232
ADDINT(SQLITE_IGNORE);
3235
/* authorizer functions */
3236
ADDINT(SQLITE_CREATE_INDEX);
3237
ADDINT(SQLITE_CREATE_TABLE);
3238
ADDINT(SQLITE_CREATE_TEMP_INDEX);
3239
ADDINT(SQLITE_CREATE_TEMP_TABLE);
3240
ADDINT(SQLITE_CREATE_TEMP_TRIGGER);
3241
ADDINT(SQLITE_CREATE_TEMP_VIEW);
3242
ADDINT(SQLITE_CREATE_TRIGGER);
3243
ADDINT(SQLITE_CREATE_VIEW);
3244
ADDINT(SQLITE_DELETE);
3245
ADDINT(SQLITE_DROP_INDEX);
3246
ADDINT(SQLITE_DROP_TABLE);
3247
ADDINT(SQLITE_DROP_TEMP_INDEX);
3248
ADDINT(SQLITE_DROP_TEMP_TABLE);
3249
ADDINT(SQLITE_DROP_TEMP_TRIGGER);
3250
ADDINT(SQLITE_DROP_TEMP_VIEW);
3251
ADDINT(SQLITE_DROP_TRIGGER);
3252
ADDINT(SQLITE_DROP_VIEW);
3253
ADDINT(SQLITE_INSERT);
3254
ADDINT(SQLITE_PRAGMA);
3255
ADDINT(SQLITE_READ);
3256
ADDINT(SQLITE_SELECT);
3257
ADDINT(SQLITE_TRANSACTION);
3258
ADDINT(SQLITE_UPDATE);
3259
ADDINT(SQLITE_ATTACH);
3260
ADDINT(SQLITE_DETACH);
3261
/* these constants were introduced in SQLite 3.1.3 */
3262
#ifdef SQLITE_ALTER_TABLE
3263
ADDINT(SQLITE_ALTER_TABLE);
3265
#ifdef SQLITE_REINDEX
3266
ADDINT(SQLITE_REINDEX);
3270
ADDINT(SQLITE_COPY);
3272
#ifdef SQLITE_ANALYZE
3273
ADDINT(SQLITE_ANALYZE);
2
Another Python Sqlite Wrapper
4
This wrapper aims to be the minimum necessary layer over SQLite 3
7
It assumes we are running as 32 bit int with a 64 bit long long type
10
Copyright (C) 2004-2007 Roger Binns <rogerb@rogerbinns.com>
12
This software is provided 'as-is', without any express or implied
13
warranty. In no event will the authors be held liable for any
14
damages arising from the use of this software.
16
Permission is granted to anyone to use this software for any
17
purpose, including commercial applications, and to alter it and
18
redistribute it freely, subject to the following restrictions:
20
1. The origin of this software must not be misrepresented; you must
21
not claim that you wrote the original software. If you use this
22
software in a product, an acknowledgment in the product
23
documentation would be appreciated but is not required.
25
2. Altered source versions must be plainly marked as such, and must
26
not be misrepresented as being the original software.
28
3. This notice may not be removed or altered from any source
36
/* Get the version number */
37
#include "apswversion.h"
42
#include "structmember.h"
44
/* Python 2.5 compatibility when size_t types become 64 bit.
45
SQLite3 is limited to 32 bit sizes even on a 64 bit machine. */
46
#if PY_VERSION_HEX < 0x02050000
47
typedef int Py_ssize_t;
50
/* A module to augment tracebacks */
51
#include "traceback.c"
53
/* A list of pointers (used by Connection to keep track of Cursors) */
54
#include "pointerlist.c"
56
/* SQLite 3 headers */
59
#if SQLITE_VERSION_NUMBER < 3003010
60
#error Your SQLite version is too old. It must be at least 3.3.10
63
/* Prepared statement caching */
65
#define STATEMENTCACHE_LINKAGE static
66
#include "statementcache.c"
68
/* used to decide if we will use int or long long */
69
#define APSW_INT32_MIN (-2147483647-1)
70
#define APSW_INT32_MAX 2147483647
72
/* The module object */
75
/* The encoding we use with SQLite. SQLite supports either utf8 or 16
76
bit unicode (host byte order). If the latter is used then all
77
functions have "16" appended to their name. The encoding used also
78
affects how strings are stored in the database. We use utf8 since
79
it is more space efficient, and Python can't make its mind up about
80
Unicode (it uses 16 or 32 bit unichars and often likes to use Byte
82
#define STRENCODING "utf_8"
84
/* Some macros used for frequent operations */
86
#define CHECK_THREAD(x,e) \
87
{ if(x->thread_ident!=PyThread_get_thread_ident()) \
88
{ /* raise exception if we aren't already in one */ \
89
if (!PyErr_Occurred()) \
90
PyErr_Format(ExcThreadingViolation, "All SQLite objects created in a thread can only be used in that same thread. " \
91
"The object was created in thread id %d and this is %d", \
92
(int)(x->thread_ident), (int)(PyThread_get_thread_ident())); \
97
#define CHECK_CLOSED(connection,e) \
98
{ if(!connection->db) { PyErr_Format(ExcConnectionClosed, "The connection has been closed"); return e; } }
100
/* EXCEPTION TYPES */
102
static PyObject *APSWException; /* root exception class */
103
static PyObject *ExcThreadingViolation; /* thread misuse */
104
static PyObject *ExcIncomplete; /* didn't finish previous query */
105
static PyObject *ExcBindings; /* wrong number of bindings */
106
static PyObject *ExcComplete; /* query is finished */
107
static PyObject *ExcTraceAbort; /* aborted by exectrace */
108
static PyObject *ExcTooBig; /* object is too large for SQLite */
109
static PyObject *ExcExtensionLoading; /* error loading extension */
110
static PyObject *ExcConnectionNotClosed; /* connection wasn't closed when destructor called */
111
static PyObject *ExcConnectionClosed; /* connection was closed when function called */
113
static struct { int code; const char *name; PyObject *cls;}
117
{SQLITE_ERROR, "SQL", NULL},
118
{SQLITE_MISMATCH, "Mismatch", NULL},
120
/* Internal Errors */
121
{SQLITE_INTERNAL, "Internal", NULL}, /* NOT USED */
122
{SQLITE_PROTOCOL, "Protocol", NULL},
123
{SQLITE_MISUSE, "Misuse", NULL},
124
{SQLITE_RANGE, "Range", NULL},
126
/* permissions etc */
127
{SQLITE_PERM, "Permissions", NULL},
128
{SQLITE_READONLY, "ReadOnly", NULL},
129
{SQLITE_CANTOPEN, "CantOpen", NULL},
130
{SQLITE_AUTH, "Auth", NULL},
133
{SQLITE_ABORT, "Abort", NULL},
134
{SQLITE_BUSY, "Busy", NULL},
135
{SQLITE_LOCKED, "Locked", NULL},
136
{SQLITE_INTERRUPT,"Interrupt", NULL},
137
{SQLITE_SCHEMA, "SchemaChange", NULL},
138
{SQLITE_CONSTRAINT, "Constraint", NULL},
140
/* memory/disk/corrupt etc */
141
{SQLITE_NOMEM, "NoMem", NULL},
142
{SQLITE_IOERR, "IO", NULL},
143
{SQLITE_CORRUPT, "Corrupt", NULL},
144
{SQLITE_FULL, "Full", NULL},
145
/* {SQLITE_TOOBIG, "TooBig"}, NOT USED by SQLite any more but there is an apsw equivalent with the same name*/
146
{SQLITE_NOLFS, "NoLFS", NULL},
147
{SQLITE_EMPTY, "Empty", NULL},
148
{SQLITE_FORMAT, "Format", NULL},
149
{SQLITE_NOTADB, "NotADB", NULL},
157
static int init_exceptions(PyObject *m)
159
char buffy[100]; /* more than enough for anyone :-) */
163
/* PyModule_AddObject uses borrowed reference so we incref whatever
164
we give to it, so we still have a copy to use */
166
/* custom ones first */
168
APSWException=PyErr_NewException("apsw.Error", NULL, NULL);
169
if(!APSWException) return -1;
170
Py_INCREF(APSWException);
171
if(PyModule_AddObject(m, "Error", (PyObject *)APSWException))
174
#define EXC(varname,name) \
175
varname=PyErr_NewException("apsw." name, APSWException, NULL); \
176
if(!varname) return -1; \
177
Py_INCREF(varname); \
178
if(PyModule_AddObject(m, name, (PyObject *)varname)) \
181
EXC(ExcThreadingViolation, "ThreadingViolationError");
182
EXC(ExcIncomplete, "IncompleteExecutionError");
183
EXC(ExcBindings, "BindingsError");
184
EXC(ExcComplete, "ExecutionCompleteError");
185
EXC(ExcTraceAbort, "ExecTraceAbort");
186
EXC(ExcTooBig, "TooBigError");
187
EXC(ExcExtensionLoading, "ExtensionLoadingError");
188
EXC(ExcConnectionNotClosed, "ConnectionNotClosedError");
189
EXC(ExcConnectionClosed, "ConnectionClosedError");
193
/* all the ones corresponding to SQLITE error codes */
194
for(i=0;exc_descriptors[i].name;i++)
196
sprintf(buffy, "apsw.%sError", exc_descriptors[i].name);
197
obj=PyErr_NewException(buffy, APSWException, NULL);
200
exc_descriptors[i].cls=obj;
201
sprintf(buffy, "%sError", exc_descriptors[i].name);
202
if(PyModule_AddObject(m, buffy, obj))
209
static void make_exception(int res, sqlite3 *db)
213
for(i=0;exc_descriptors[i].name;i++)
214
if (exc_descriptors[i].code==(res&0xff))
216
PyObject *etype, *eval, *etb;
217
assert(exc_descriptors[i].cls);
218
PyErr_Format(exc_descriptors[i].cls, "%sError: %s", exc_descriptors[i].name, db?(sqlite3_errmsg(db)):"error");
219
PyErr_Fetch(&etype, &eval, &etb);
220
PyErr_NormalizeException(&etype, &eval, &etb);
221
PyObject_SetAttrString(eval, "result", Py_BuildValue("i", res&0xff));
222
PyObject_SetAttrString(eval, "extendedresult", Py_BuildValue("i", res));
223
PyErr_Restore(etype, eval, etb);
224
assert(PyErr_Occurred());
228
/* this line should only be reached if SQLite returns an error code not in the main list */
229
PyErr_Format(APSWException, "Error %d: %s", res, db?(sqlite3_errmsg(db)):"error");
232
/* If res indicates an SQLite error then do all the exception creation
233
work. We don't overwrite earlier exceptions hence the PyErr_Occurred
235
#define SET_EXC(db,res) { if(res != SQLITE_OK && !PyErr_Occurred()) make_exception(res,db); }
238
/* The default Python PyErr_WriteUnraiseable is almost useless. It
239
only prints the str() of the exception and the str() of the object
240
passed in. This gives the developer no clue whatsoever where in
241
the code it is happening. It also does funky things to the passed
242
in object which can cause the destructor to fire twice.
243
Consequently we use our version here. It makes a traceback if
244
necessary, invokes sys.excepthook and if that fails then
245
PyErr_Display. When we return, any error will be cleared. */
247
apsw_write_unraiseable(void)
249
PyObject *err_type=NULL, *err_value=NULL, *err_traceback=NULL;
250
PyObject *excepthook=NULL;
252
PyObject *result=NULL;
254
PyErr_Fetch(&err_type, &err_value, &err_traceback);
255
PyErr_NormalizeException(&err_type, &err_value, &err_traceback);
257
/* err_traceback is normally NULL, so lets fake one */
260
PyObject *e2t=NULL, *e2v=NULL, *e2tb=NULL;
261
PyFrameObject *frame = PyThreadState_GET()->frame;
264
PyTraceBack_Here(frame);
267
PyErr_Fetch(&e2t, &e2v, &e2tb);
273
excepthook=PySys_GetObject("excepthook");
275
args=Py_BuildValue("(OOO)", err_type?err_type:Py_None, err_value?err_value:Py_None, err_traceback?err_traceback:Py_None);
276
if(excepthook && args)
277
result=PyEval_CallObject(excepthook, args);
278
if(!excepthook || !args || !result)
279
PyErr_Display(err_type, err_value, err_traceback);
281
/* excepthook is a borrowed reference */
284
Py_XDECREF(err_traceback);
285
Py_XDECREF(err_value);
286
Py_XDECREF(err_type);
290
/* Turns the current Python exception into an SQLite error code and
291
stores the string in the errmsg field (if not NULL). The errmsg
292
field is expected to belong to sqlite and hence uses sqlite
293
semantics/ownership - for example see the pzErr parameter to
297
MakeSqliteMsgFromPyException(char **errmsg)
299
int res=SQLITE_ERROR;
301
PyObject *etype=NULL, *evalue=NULL, *etraceback=NULL;
303
assert(PyErr_Occurred());
306
/* find out if the exception corresponds to an apsw exception descriptor */
308
for(i=0;exc_descriptors[i].code!=-1;i++)
309
if(PyErr_ExceptionMatches(exc_descriptors[i].cls))
311
res=exc_descriptors[i].code;
318
/* I just want a string of the error! */
320
PyErr_Fetch(&etype, &evalue, &etraceback);
322
str=PyObject_Str(evalue);
324
str=PyObject_Str(etype);
326
str=PyString_FromString("python exception with no information");
328
PyErr_Restore(etype, evalue, etraceback);
331
sqlite3_free(*errmsg);
332
*errmsg=sqlite3_mprintf("%s",PyString_AsString(str));
342
/* details of a registered function passed as user data to sqlite3_create_function */
343
typedef struct _funccbinfo
345
struct _funccbinfo *next; /* we use a linked list */
346
char *name; /* ascii function name which we uppercased */
347
PyObject *scalarfunc; /* the function to call for stepping */
348
PyObject *aggregatefactory; /* factory for aggregate functions */
351
/* a particular aggregate function instance used as sqlite3_aggregate_context */
352
typedef struct _aggregatefunctioncontext
354
PyObject *aggvalue; /* the aggregation value passed as first parameter */
355
PyObject *stepfunc; /* step function */
356
PyObject *finalfunc; /* final function */
357
} aggregatefunctioncontext;
359
static funccbinfo *freefunccbinfo(funccbinfo *);
361
typedef struct _collationcbinfo
363
struct _collationcbinfo *next; /* we use a linked list */
364
char *name; /* ascii collation name which we uppercased */
365
PyObject *func; /* the actual function to call */
368
static collationcbinfo *freecollationcbinfo(collationcbinfo *);
370
typedef struct Connection Connection; /* forward declaration */
372
typedef struct _vtableinfo
374
struct _vtableinfo *next; /* we use a linked list */
375
char *name; /* module name */
376
PyObject *datasource; /* object with create/connect methods */
377
Connection *connection; /* the Connection this is registered against so we don't
378
have to have a global table mapping sqlite3_db* to
382
/* forward declarations */
383
static vtableinfo *freevtableinfo(vtableinfo *);
385
/* CONNECTION TYPE */
389
sqlite3 *db; /* the actual database connection */
390
const char *filename; /* utf8 filename of the database */
391
int co_linenumber; /* line number of allocation */
392
PyObject *co_filename; /* filename of allocation */
393
long thread_ident; /* which thread we were made in */
395
pointerlist cursors; /* tracking cursors */
396
StatementCache *stmtcache; /* prepared statement cache */
398
funccbinfo *functions; /* linked list of registered functions */
399
collationcbinfo *collations; /* linked list of registered collations */
400
vtableinfo *vtables; /* linked list of registered vtables */
402
/* registered hooks/handlers (NULL or callable) */
403
PyObject *busyhandler;
404
PyObject *rollbackhook;
406
PyObject *updatehook;
407
PyObject *commithook;
408
PyObject *progresshandler;
409
PyObject *authorizer;
412
static PyTypeObject ConnectionType;
418
Connection *connection; /* pointer to parent connection */
419
sqlite3_stmt *statement; /* current compiled statement */
421
/* see sqlite3_prepare_v2 for the origin of these */
422
const char *zsql; /* current sqlstatement (which may include multiple statements) */
423
const char *zsqlnextpos; /* the next statement to execute (or NULL if no more) */
425
/* what state we are in */
426
enum { C_BEGIN, C_ROW, C_DONE } status;
428
/* bindings for query */
429
PyObject *bindings; /* dict or sequence */
430
Py_ssize_t bindingsoffset; /* for sequence tracks how far along we are when dealing with multiple statements */
432
/* iterator for executemany */
435
/* tracing functions */
441
static PyTypeObject CursorType;
443
/* forward declarations */
444
static PyObject *Cursor_close(Cursor *self, PyObject *args);
447
/* CONVENIENCE FUNCTIONS */
449
/* Convert a NULL terminated UTF-8 string into a Python object. None
450
is returned if NULL is passed in. */
452
convertutf8string(const char *str)
460
/* new behaviour in 3.3.8 - always return unicode strings */
461
return PyUnicode_DecodeUTF8(str, strlen(str), NULL);
464
/* Convert a pointer and size UTF-8 string into a Python object.
465
Pointer must be non-NULL. */
467
convertutf8stringsize(const char *str, Py_ssize_t size)
472
/* new behaviour in 3.3.8 - always return Unicode strings */
473
return PyUnicode_DecodeUTF8(str, size, NULL);
476
/* Returns a PyString encoded in UTF8 - new reference.
477
Use PyString_AsString on the return value to get a
478
const char * to utf8 bytes */
480
getutf8string(PyObject *string)
482
PyObject *inunicode=NULL;
483
PyObject *utf8string=NULL;
485
if(PyUnicode_Check(string))
492
inunicode=PyUnicode_FromObject(string);
496
assert(!PyErr_Occurred());
498
utf8string=PyUnicode_AsUTF8String(inunicode);
499
Py_DECREF(inunicode);
504
Python's handling of Unicode is horrible. It can use 2 or 4 byte
505
unicode chars and the conversion routines like to put out BOMs
506
which makes life even harder. These macros are used in pairs to do
507
the right form of conversion and tell us whether to use the plain
508
or -16 version of the SQLite function that is about to be called.
511
#if Py_UNICODE_SIZE==2
512
#define UNIDATABEGIN(obj) \
515
size_t strbytes=2*PyUnicode_GET_SIZE(obj); \
516
const void *strdata=PyUnicode_AS_DATA(obj);
518
#define UNIDATAEND(obj) \
521
#else /* Py_UNICODE_SIZE!=2 */
523
#define UNIDATABEGIN(obj) \
526
Py_ssize_t strbytes=0; \
527
const char *strdata=NULL; \
528
PyObject *_utf8=NULL; \
530
_utf8=PyUnicode_AsUTF8String(obj); \
533
strbytes=PyString_GET_SIZE(_utf8); \
534
strdata=PyString_AsString(_utf8); \
537
#define UNIDATAEND(obj) \
541
#endif /* Py_UNICODE_SIZE */
543
/* CONNECTION CODE */
546
Connection_internal_cleanup(Connection *self)
550
PyMem_Free((void*)self->filename);
554
Py_XDECREF(self->co_filename);
559
funccbinfo *func=self->functions;
560
while((func=freefunccbinfo(func)));
564
/* free collations */
566
collationcbinfo *coll=self->collations;
567
while((coll=freecollationcbinfo(coll)));
573
vtableinfo *vtinfo=self->vtables;
574
while((vtinfo=freevtableinfo(vtinfo)));
578
Py_XDECREF(self->busyhandler);
581
Py_XDECREF(self->rollbackhook);
582
self->rollbackhook=0;
584
Py_XDECREF(self->profile);
587
Py_XDECREF(self->commithook);
590
Py_XDECREF(self->progresshandler);
591
self->progresshandler=0;
593
Py_XDECREF(self->authorizer);
599
Connection_close(Connection *self, PyObject *args)
601
PyObject *cursorcloseargs=NULL;
603
pointerlist_visit plv;
609
CHECK_THREAD(self,NULL);
611
assert(!PyErr_Occurred());
613
if(!PyArg_ParseTuple(args, "|i:close(force=False)", &force))
616
cursorcloseargs=Py_BuildValue("(i)", force);
617
if(!cursorcloseargs) return NULL;
619
for(pointerlist_visit_begin(&self->cursors, &plv);
620
pointerlist_visit_finished(&plv);
621
pointerlist_visit_next(&plv))
623
PyObject *closeres=NULL;
624
Cursor *cur=(Cursor*)pointerlist_visit_get(&plv);
626
closeres=Cursor_close(cur, args);
627
Py_XDECREF(closeres);
630
Py_DECREF(cursorcloseargs);
635
Py_DECREF(cursorcloseargs);
637
res=statementcache_free(self->stmtcache);
641
Py_BEGIN_ALLOW_THREADS
642
res=sqlite3_close(self->db);
643
Py_END_ALLOW_THREADS;
647
SET_EXC(self->db, res);
652
AddTraceBackHere(__FILE__, __LINE__, "Connection.close", NULL);
655
/* note: SQLite ignores error returns from vtabDisconnect, so the
656
database still ends up closed and we return an exception! */
663
Connection_internal_cleanup(self);
666
return PyErr_Occurred()?NULL:Py_BuildValue("");
671
Connection_dealloc(Connection* self)
675
/* not allowed to clobber existing exception */
676
PyObject *etype=NULL, *evalue=NULL, *etraceback=NULL;
677
PyErr_Fetch(&etype, &evalue, &etraceback);
679
PyErr_Format(ExcConnectionNotClosed,
680
"apsw.Connection on \"%s\" at address %p, allocated at %s:%d. The destructor "
681
"has been called, but you haven't closed the connection. All connections must "
682
"be explicitly closed. The SQLite database object is being leaked.",
683
self->filename?self->filename:"NULL", self,
684
PyString_AsString(self->co_filename), self->co_linenumber);
686
apsw_write_unraiseable();
687
PyErr_Fetch(&etype, &evalue, &etraceback);
690
assert(self->cursors.numentries==0);
691
pointerlist_free(&self->cursors);
693
Connection_internal_cleanup(self);
695
self->ob_type->tp_free((PyObject*)self);
699
Connection_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
703
self = (Connection *)type->tp_alloc(type, 0);
705
/* Strictly speaking the memory was already zeroed. This is
706
just defensive coding. */
709
self->co_linenumber=0;
711
self->thread_ident=PyThread_get_thread_ident();
712
memset(&self->cursors, 0, sizeof(self->cursors));
713
pointerlist_init(&self->cursors);
719
self->rollbackhook=0;
723
self->progresshandler=0;
727
return (PyObject *)self;
731
Connection_init(Connection *self, PyObject *args, PyObject *kwds)
733
PyObject *hooks=NULL, *hook=NULL, *iterator=NULL, *hookargs=NULL, *hookresult=NULL;
737
CHECK_THREAD(self,-1);
739
if(kwds && PyDict_Size(kwds)!=0)
741
PyErr_Format(PyExc_TypeError, "Connection constructor does not take keyword arguments");
745
if(!PyArg_ParseTuple(args, "es:Connection(filename)", STRENCODING, &filename))
748
Py_BEGIN_ALLOW_THREADS
749
res=sqlite3_open(filename, &self->db);
750
Py_END_ALLOW_THREADS;
751
SET_EXC(self->db, res); /* nb sqlite3_open always allocates the db even on error */
756
/* record where it was allocated */
757
PyFrameObject *frame = PyThreadState_GET()->frame;
758
self->co_linenumber=PyCode_Addr2Line(frame->f_code, frame->f_lasti);
759
self->co_filename=frame->f_code->co_filename;
760
Py_INCREF(self->co_filename);
761
self->filename=filename;
762
filename=NULL; /* connection has ownership now */
764
/* get detailed error codes */
765
sqlite3_extended_result_codes(self->db, 1);
767
/* call connection hooks */
768
hooks=PyObject_GetAttrString(apswmodule, "connection_hooks");
772
hookargs=Py_BuildValue("(O)", self);
773
if(!hookargs) goto pyexception;
775
iterator=PyObject_GetIter(hooks);
778
AddTraceBackHere(__FILE__, __LINE__, "Connection.__init__", "{s: i}", "connection_hooks", hooks);
782
while( (hook=PyIter_Next(iterator)) )
784
hookresult=PyEval_CallObject(hook, hookargs);
788
Py_DECREF(hookresult);
791
if(!PyErr_Occurred())
794
self->stmtcache=statementcache_init(self->db, 32);
799
/* clean up db since it is useless - no need for user to call close */
801
sqlite3_close(self->db);
803
Connection_internal_cleanup(self);
806
if(filename) PyMem_Free(filename);
807
Py_XDECREF(hookargs);
808
Py_XDECREF(iterator);
811
Py_XDECREF(hookresult);
815
static void Cursor_init(Cursor *, Connection *);
818
Connection_cursor(Connection *self)
820
Cursor* cursor = NULL;
822
CHECK_THREAD(self,NULL);
823
CHECK_CLOSED(self,NULL);
825
cursor = PyObject_New(Cursor, &CursorType);
829
/* incref me since cursor holds a pointer */
830
Py_INCREF((PyObject*)self);
831
pointerlist_add(&self->cursors, cursor);
832
Cursor_init(cursor, self);
834
return (PyObject*)cursor;
838
Connection_setbusytimeout(Connection *self, PyObject *args)
843
CHECK_THREAD(self,NULL);
844
CHECK_CLOSED(self,NULL);
846
if(!PyArg_ParseTuple(args, "i:setbusytimeout(millseconds)", &ms))
849
res=sqlite3_busy_timeout(self->db, ms);
850
SET_EXC(self->db, res);
851
if(res!=SQLITE_OK) return NULL;
853
/* free any explicit busyhandler we may have had */
854
Py_XDECREF(self->busyhandler);
857
return Py_BuildValue("");
861
Connection_changes(Connection *self)
863
CHECK_THREAD(self,NULL);
864
CHECK_CLOSED(self,NULL);
865
return Py_BuildValue("i", sqlite3_changes(self->db));
869
Connection_totalchanges(Connection *self)
871
CHECK_THREAD(self,NULL);
872
CHECK_CLOSED(self,NULL);
873
return Py_BuildValue("i", sqlite3_total_changes(self->db));
877
Connection_getautocommit(Connection *self)
880
CHECK_THREAD(self,NULL);
881
CHECK_CLOSED(self,NULL);
882
res=(sqlite3_get_autocommit(self->db))?(Py_True):(Py_False);
888
Connection_last_insert_rowid(Connection *self)
892
CHECK_THREAD(self,NULL);
893
CHECK_CLOSED(self,NULL);
895
vint=sqlite3_last_insert_rowid(self->db);
897
if(vint<APSW_INT32_MIN || vint>APSW_INT32_MAX)
898
return PyLong_FromLongLong(vint);
900
return PyInt_FromLong((long)vint);
904
Connection_complete(Connection *self, PyObject *args)
906
char *statements=NULL;
909
CHECK_THREAD(self,NULL);
910
CHECK_CLOSED(self,NULL);
912
if(!PyArg_ParseTuple(args, "es:complete(statement)", STRENCODING, &statements))
915
res=sqlite3_complete(statements);
917
PyMem_Free(statements);
929
Connection_interrupt(Connection *self)
931
CHECK_THREAD(self, NULL);
932
CHECK_CLOSED(self, NULL);
934
sqlite3_interrupt(self->db); /* no return value */
935
return Py_BuildValue("");
939
updatecb(void *context, int updatetype, char const *databasename, char const *tablename, sqlite_int64 rowid)
941
/* The hook returns void. That makes it impossible for us to
942
abort immediately due to an error in the callback */
944
PyGILState_STATE gilstate;
945
PyObject *retval=NULL, *args=NULL;
946
Connection *self=(Connection *)context;
949
assert(self->updatehook);
950
assert(self->updatehook!=Py_None);
952
gilstate=PyGILState_Ensure();
955
goto finally; /* abort hook due to outstanding exception */
957
args=Py_BuildValue("(iO&O&L)", updatetype, convertutf8string, databasename, convertutf8string, tablename, rowid);
958
if(!args) goto finally;
960
retval=PyEval_CallObject(self->updatehook, args);
965
PyGILState_Release(gilstate);
969
Connection_setupdatehook(Connection *self, PyObject *callable)
971
/* sqlite3_update_hook doesn't return an error code */
973
CHECK_THREAD(self,NULL);
974
CHECK_CLOSED(self,NULL);
976
if(callable==Py_None)
978
sqlite3_update_hook(self->db, NULL, NULL);
983
if(!PyCallable_Check(callable))
985
PyErr_Format(PyExc_TypeError, "update hook must be callable");
989
sqlite3_update_hook(self->db, updatecb, self);
995
Py_XDECREF(self->updatehook);
996
self->updatehook=callable;
998
return Py_BuildValue("");
1002
rollbackhookcb(void *context)
1004
/* The hook returns void. That makes it impossible for us to
1005
abort immediately due to an error in the callback */
1007
PyGILState_STATE gilstate;
1008
PyObject *retval=NULL;
1009
Connection *self=(Connection *)context;
1012
assert(self->rollbackhook);
1013
assert(self->rollbackhook!=Py_None);
1015
gilstate=PyGILState_Ensure();
1017
if(PyErr_Occurred())
1018
goto finally; /* abort hook due to outstanding exception */
1020
retval=PyEval_CallObject(self->rollbackhook, NULL);
1024
PyGILState_Release(gilstate);
1028
Connection_setrollbackhook(Connection *self, PyObject *callable)
1030
/* sqlite3_rollback_hook doesn't return an error code */
1032
CHECK_THREAD(self,NULL);
1033
CHECK_CLOSED(self,NULL);
1035
if(callable==Py_None)
1037
sqlite3_rollback_hook(self->db, NULL, NULL);
1042
if(!PyCallable_Check(callable))
1044
PyErr_Format(PyExc_TypeError, "rollback hook must be callable");
1048
sqlite3_rollback_hook(self->db, rollbackhookcb, self);
1050
Py_INCREF(callable);
1054
Py_XDECREF(self->rollbackhook);
1055
self->rollbackhook=callable;
1057
return Py_BuildValue("");
1060
#ifdef EXPERIMENTAL /* sqlite3_profile */
1062
profilecb(void *context, const char *statement, sqlite_uint64 runtime)
1064
/* The hook returns void. That makes it impossible for us to
1065
abort immediately due to an error in the callback */
1067
PyGILState_STATE gilstate;
1068
PyObject *retval=NULL, *args=NULL;
1069
Connection *self=(Connection *)context;
1072
assert(self->profile);
1073
assert(self->profile!=Py_None);
1075
gilstate=PyGILState_Ensure();
1077
if(PyErr_Occurred())
1078
goto finally; /* abort hook due to outstanding exception */
1080
args=Py_BuildValue("(O&K)", convertutf8string, statement, runtime);
1081
if(!args) goto finally;
1083
retval=PyEval_CallObject(self->profile, args);
1088
PyGILState_Release(gilstate);
1092
Connection_setprofile(Connection *self, PyObject *callable)
1094
/* sqlite3_profile doesn't return an error code */
1096
CHECK_THREAD(self,NULL);
1097
CHECK_CLOSED(self,NULL);
1099
if(callable==Py_None)
1101
sqlite3_profile(self->db, NULL, NULL);
1106
if(!PyCallable_Check(callable))
1108
PyErr_Format(PyExc_TypeError, "profile function must be callable");
1112
sqlite3_profile(self->db, profilecb, self);
1114
Py_INCREF(callable);
1118
Py_XDECREF(self->profile);
1119
self->profile=callable;
1121
return Py_BuildValue("");
1123
#endif /* EXPERIMENTAL - sqlite3_profile */
1126
#ifdef EXPERIMENTAL /* commit hook */
1128
commithookcb(void *context)
1130
/* The hook returns 0 for commit to go ahead and non-zero to abort
1131
commit (turn into a rollback). We return non-zero for errors */
1133
PyGILState_STATE gilstate;
1134
PyObject *retval=NULL;
1135
int ok=1; /* error state */
1136
Connection *self=(Connection *)context;
1139
assert(self->commithook);
1140
assert(self->commithook!=Py_None);
1142
gilstate=PyGILState_Ensure();
1144
if(PyErr_Occurred())
1145
goto finally; /* abort hook due to outstanding exception */
1147
retval=PyEval_CallObject(self->commithook, NULL);
1150
goto finally; /* abort hook due to exeception */
1152
ok=PyObject_IsTrue(retval);
1153
assert(ok==-1 || ok==0 || ok==1);
1154
/* the docs say -1 can be returned, but the code for PyObject_IsTrue always returns 1 or 0.
1155
this is a defensive check */
1159
goto finally; /* abort due to exception in return value */
1164
PyGILState_Release(gilstate);
1169
Connection_setcommithook(Connection *self, PyObject *callable)
1171
/* sqlite3_commit_hook doesn't return an error code */
1173
CHECK_THREAD(self,NULL);
1174
CHECK_CLOSED(self,NULL);
1176
if(callable==Py_None)
1178
sqlite3_commit_hook(self->db, NULL, NULL);
1183
if(!PyCallable_Check(callable))
1185
PyErr_Format(PyExc_TypeError, "commit hook must be callable");
1189
sqlite3_commit_hook(self->db, commithookcb, self);
1191
Py_INCREF(callable);
1195
Py_XDECREF(self->commithook);
1196
self->commithook=callable;
1198
return Py_BuildValue("");
1200
#endif /* EXPERIMENTAL sqlite3_commit_hook */
1202
#ifdef EXPERIMENTAL /* sqlite3_progress_handler */
1204
progresshandlercb(void *context)
1206
/* The hook returns 0 for continue and non-zero to abort (rollback).
1207
We return non-zero for errors */
1209
PyGILState_STATE gilstate;
1210
PyObject *retval=NULL;
1211
int ok=1; /* error state */
1212
Connection *self=(Connection *)context;
1215
assert(self->progresshandler);
1217
gilstate=PyGILState_Ensure();
1219
retval=PyEval_CallObject(self->progresshandler, NULL);
1222
goto finally; /* abort due to exeception */
1224
ok=PyObject_IsTrue(retval);
1226
assert(ok==-1 || ok==0 || ok==1);
1227
/* see earlier comment about PyObject_IsTrue */
1231
goto finally; /* abort due to exception in result */
1237
PyGILState_Release(gilstate);
1242
Connection_setprogresshandler(Connection *self, PyObject *args)
1244
/* sqlite3_progress_handler doesn't return an error code */
1246
PyObject *callable=NULL;
1248
CHECK_THREAD(self,NULL);
1249
CHECK_CLOSED(self,NULL);
1251
if(!PyArg_ParseTuple(args, "O|i:setprogresshandler(callable, nsteps=20)", &callable, &nsteps))
1254
if(callable==Py_None)
1256
sqlite3_progress_handler(self->db, 0, NULL, NULL);
1261
if(!PyCallable_Check(callable))
1263
PyErr_Format(PyExc_TypeError, "progress handler must be callable");
1267
sqlite3_progress_handler(self->db, nsteps, progresshandlercb, self);
1268
Py_INCREF(callable);
1272
Py_XDECREF(self->progresshandler);
1273
self->progresshandler=callable;
1275
return Py_BuildValue("");
1277
#endif /* EXPERIMENTAL sqlite3_progress_handler */
1280
authorizercb(void *context, int operation, const char *paramone, const char *paramtwo, const char *databasename, const char *triggerview)
1282
/* should return one of SQLITE_OK, SQLITE_DENY, or
1283
SQLITE_IGNORE. (0, 1 or 2 respectively) */
1285
PyGILState_STATE gilstate;
1286
PyObject *args=NULL, *retval=NULL;
1287
int result=SQLITE_DENY; /* default to deny */
1288
Connection *self=(Connection *)context;
1291
assert(self->authorizer);
1292
assert(self->authorizer!=Py_None);
1294
gilstate=PyGILState_Ensure();
1296
if(PyErr_Occurred())
1297
goto finally; /* abort due to earlier exception */
1300
args=Py_BuildValue("(iO&O&O&O&)", operation, convertutf8string, paramone,
1301
convertutf8string, paramtwo, convertutf8string, databasename,
1302
convertutf8string, triggerview);
1303
if(!args) goto finally;
1305
retval=PyEval_CallObject(self->authorizer, args);
1308
goto finally; /* abort due to exeception */
1310
result=PyInt_AsLong(retval);
1311
if (PyErr_Occurred())
1318
PyGILState_Release(gilstate);
1323
Connection_setauthorizer(Connection *self, PyObject *callable)
1327
CHECK_THREAD(self,NULL);
1328
CHECK_CLOSED(self,NULL);
1330
if(callable==Py_None)
1332
res=sqlite3_set_authorizer(self->db, NULL, NULL);
1337
if(!PyCallable_Check(callable))
1339
PyErr_Format(PyExc_TypeError, "authorizer must be callable");
1343
res=sqlite3_set_authorizer(self->db, authorizercb, self);
1344
SET_EXC(self->db, res);
1346
Py_INCREF(callable);
1349
Py_XDECREF(self->authorizer);
1350
self->authorizer=callable;
1352
return (res==SQLITE_OK)?Py_BuildValue(""):NULL;
1356
busyhandlercb(void *context, int ncall)
1358
/* Return zero for caller to get SQLITE_BUSY error. We default to
1359
zero in case of error. */
1361
PyGILState_STATE gilstate;
1362
PyObject *args, *retval;
1363
int result=0; /* default to fail with SQLITE_BUSY */
1364
Connection *self=(Connection *)context;
1367
assert(self->busyhandler);
1369
gilstate=PyGILState_Ensure();
1371
args=Py_BuildValue("(i)", ncall);
1373
goto finally; /* abort busy due to memory allocation failure */
1375
retval=PyEval_CallObject(self->busyhandler, args);
1379
goto finally; /* abort due to exeception */
1381
result=PyObject_IsTrue(retval);
1382
assert(result==-1 || result==0 || result==1);
1388
goto finally; /* abort due to exception converting retval */
1392
PyGILState_Release(gilstate);
1396
#if defined(EXPERIMENTAL) && !defined(SQLITE_OMIT_LOAD_EXTENSION) /* extension loading */
1398
Connection_enableloadextension(Connection *self, PyObject *enabled)
1402
CHECK_THREAD(self, NULL);
1403
CHECK_CLOSED(self, NULL);
1405
/* get the boolean value */
1406
enabledp=PyObject_IsTrue(enabled);
1407
if(enabledp==-1) return NULL;
1408
if (PyErr_Occurred()) return NULL;
1411
res=sqlite3_enable_load_extension(self->db, enabledp);
1412
SET_EXC(self->db, res); /* the function will currently always succeed */
1415
return (res==SQLITE_OK)?Py_BuildValue(""):NULL;
1419
Connection_loadextension(Connection *self, PyObject *args)
1422
char *zfile=NULL, *zproc=NULL, *errmsg=NULL;
1424
CHECK_THREAD(self, NULL);
1425
CHECK_CLOSED(self, NULL);
1427
if(!PyArg_ParseTuple(args, "s|z:loadextension(filename, entrypoint=None)", &zfile, &zproc))
1430
Py_BEGIN_ALLOW_THREADS
1431
res=sqlite3_load_extension(self->db, zfile, zproc, &errmsg);
1432
Py_END_ALLOW_THREADS;
1434
/* load_extension doesn't set the error message on the db so we have to make exception manually */
1438
PyErr_Format(ExcExtensionLoading, "ExtensionLoadingError: %s", errmsg?errmsg:"unspecified");
1439
sqlite3_free(errmsg);
1442
return Py_BuildValue("");
1445
#endif /* EXPERIMENTAL extension loading */
1448
Connection_setbusyhandler(Connection *self, PyObject *callable)
1452
CHECK_THREAD(self,NULL);
1453
CHECK_CLOSED(self,NULL);
1455
if(callable==Py_None)
1457
res=sqlite3_busy_handler(self->db, NULL, NULL);
1462
if(!PyCallable_Check(callable))
1464
PyErr_Format(PyExc_TypeError, "busyhandler must be callable");
1468
res=sqlite3_busy_handler(self->db, busyhandlercb, self);
1469
SET_EXC(self->db, res);
1471
Py_INCREF(callable);
1474
Py_XDECREF(self->busyhandler);
1475
self->busyhandler=callable;
1477
return (res==SQLITE_OK)?Py_BuildValue(""):NULL;
1481
/* USER DEFINED FUNCTION CODE.*/
1483
/* We store the registered functions in a linked list hooked into the
1484
connection object so we can free them. There is probably a better
1485
data structure to use but this was most convenient. */
1488
freefunccbinfo(funccbinfo *func)
1495
PyMem_Free(func->name);
1496
Py_XDECREF(func->scalarfunc);
1497
Py_XDECREF(func->aggregatefactory);
1504
allocfunccbinfo(void)
1506
funccbinfo *res=PyMem_Malloc(sizeof(funccbinfo));
1508
memset(res, 0, sizeof(funccbinfo));
1512
/* Converts sqlite3_value to PyObject. Returns a new reference. */
1514
convert_value_to_pyobject(sqlite3_value *value)
1516
const int coltype=sqlite3_value_type(value);
1520
case SQLITE_INTEGER:
1522
long long vint=sqlite3_value_int64(value);
1523
if(vint<APSW_INT32_MIN || vint>APSW_INT32_MAX)
1524
return PyLong_FromLongLong(vint);
1526
return PyInt_FromLong((long)vint);
1530
return PyFloat_FromDouble(sqlite3_value_double(value));
1533
return convertutf8stringsize((const char*)sqlite3_value_text(value), sqlite3_value_bytes(value));
1542
Py_ssize_t sz=sqlite3_value_bytes(value);
1543
item=PyBuffer_New(sz);
1548
if(!PyObject_AsWriteBuffer(item, &buffy, &sz2))
1549
memcpy(buffy, sqlite3_value_blob(value), sz);
1561
PyErr_Format(APSWException, "Unknown sqlite column type %d!", coltype);
1564
/* can't get here */
1569
/* converts a python object into a sqlite3_context result */
1571
set_context_result(sqlite3_context *context, PyObject *obj)
1575
assert(PyErr_Occurred());
1576
/* TODO: possibly examine exception and return appropriate error
1577
code eg for BusyError set error to SQLITE_BUSY */
1578
sqlite3_result_error(context, "bad object given to set_context_result", -1);
1582
/* DUPLICATE(ish) code: this is substantially similar to the code in
1583
Cursor_dobinding. If you fix anything here then do it there as
1588
sqlite3_result_null(context);
1591
if(PyInt_Check(obj))
1593
sqlite3_result_int64(context, PyInt_AS_LONG(obj));
1596
if (PyLong_Check(obj))
1598
sqlite3_result_int64(context, PyLong_AsLongLong(obj));
1601
if (PyFloat_Check(obj))
1603
sqlite3_result_double(context, PyFloat_AS_DOUBLE(obj));
1606
if (PyUnicode_Check(obj))
1611
if(strbytes>APSW_INT32_MAX)
1613
PyErr_Format(ExcTooBig, "Unicode object is too large - SQLite only supports up to 2GB");
1618
sqlite3_result_text16(context, strdata, (int)strbytes, SQLITE_TRANSIENT);
1620
sqlite3_result_text(context, strdata, (int)strbytes, SQLITE_TRANSIENT);
1624
sqlite3_result_error(context, "Unicode conversions failed", -1);
1628
if (PyString_Check(obj))
1630
const char *val=PyString_AS_STRING(obj);
1631
const Py_ssize_t lenval=PyString_GET_SIZE(obj);
1632
const char *chk=val;
1633
for(;chk<val+lenval && !((*chk)&0x80); chk++);
1636
PyObject *str2=PyUnicode_FromObject(obj);
1639
sqlite3_result_error(context, "PyUnicode_FromObject failed", -1);
1645
if(strbytes>APSW_INT32_MAX)
1647
PyErr_Format(ExcTooBig, "Unicode object is too large - SQLite only supports up to 2GB");
1652
sqlite3_result_text16(context, strdata, (int)strbytes, SQLITE_TRANSIENT);
1654
sqlite3_result_text(context, strdata, (int)strbytes, SQLITE_TRANSIENT);
1658
sqlite3_result_error(context, "Unicode conversions failed", -1);
1664
if(lenval>APSW_INT32_MAX)
1666
PyErr_Format(ExcTooBig, "String object is too large - SQLite only supports up to 2GB");
1669
sqlite3_result_text(context, val, (int)lenval, SQLITE_TRANSIENT);
1673
if (PyBuffer_Check(obj))
1677
if(PyObject_AsCharBuffer(obj, &buffer, &buflen))
1679
sqlite3_result_error(context, "PyObject_AsCharBuffer failed", -1);
1682
if (buflen>APSW_INT32_MAX)
1683
sqlite3_result_error(context, "Buffer object is too large for SQLite - only up to 2GB is supported", -1);
1685
sqlite3_result_blob(context, buffer, (int)buflen, SQLITE_TRANSIENT);
1689
PyErr_Format(PyExc_TypeError, "Bad return type from function callback");
1690
sqlite3_result_error(context, "Bad return type from function callback", -1);
1693
/* Returns a new reference to a tuple formed from function parameters */
1695
getfunctionargs(sqlite3_context *context, PyObject *firstelement, int argc, sqlite3_value **argv)
1697
PyObject *pyargs=NULL;
1701
/* extra first item */
1705
pyargs=PyTuple_New((long)argc+extra);
1708
sqlite3_result_error(context, "PyTuple_New failed", -1);
1714
Py_INCREF(firstelement);
1715
PyTuple_SET_ITEM(pyargs, 0, firstelement);
1720
PyObject *item=convert_value_to_pyobject(argv[i]);
1724
sqlite3_result_error(context, "convert_value_to_pyobject failed", -1);
1727
PyTuple_SET_ITEM(pyargs, i+extra, item);
1738
/* dispatches scalar function */
1740
cbdispatch_func(sqlite3_context *context, int argc, sqlite3_value **argv)
1742
PyGILState_STATE gilstate;
1745
funccbinfo *cbinfo=(funccbinfo*)sqlite3_user_data(context);
1748
gilstate=PyGILState_Ensure();
1750
assert(cbinfo->scalarfunc);
1752
if(PyErr_Occurred())
1754
sqlite3_result_error(context, "Prior Python Error", -1);
1758
pyargs=getfunctionargs(context, NULL, argc, argv);
1762
assert(!PyErr_Occurred());
1763
retval=PyEval_CallObject(cbinfo->scalarfunc, pyargs);
1766
set_context_result(context, retval);
1770
if (PyErr_Occurred())
1772
char *funname=sqlite3_mprintf("user-defined-scalar-%s", cbinfo->name);
1773
AddTraceBackHere(__FILE__, __LINE__, funname, "{s: i}", "NumberOfArguments", argc);
1774
sqlite3_free(funname);
1777
PyGILState_Release(gilstate);
1780
static aggregatefunctioncontext *
1781
getaggregatefunctioncontext(sqlite3_context *context)
1783
aggregatefunctioncontext *aggfc=sqlite3_aggregate_context(context, sizeof(aggregatefunctioncontext));
1786
/* have we seen it before? */
1790
/* fill in with Py_None so we know it is valid */
1791
aggfc->aggvalue=Py_None;
1794
cbinfo=(funccbinfo*)sqlite3_user_data(context);
1796
assert(cbinfo->aggregatefactory);
1798
/* call the aggregatefactory to get our working objects */
1799
retval=PyEval_CallObject(cbinfo->aggregatefactory, NULL);
1803
/* it should have returned a tuple of 3 items: object, stepfunction and finalfunction */
1804
if(!PyTuple_Check(retval))
1806
PyErr_Format(PyExc_TypeError, "Aggregate factory should return tuple of (object, stepfunction, finalfunction)");
1809
if(PyTuple_GET_SIZE(retval)!=3)
1811
PyErr_Format(PyExc_TypeError, "Aggregate factory should return 3 item tuple of (object, stepfunction, finalfunction)");
1814
/* we don't care about the type of the zeroth item (object) ... */
1817
if (!PyCallable_Check(PyTuple_GET_ITEM(retval,1)))
1819
PyErr_Format(PyExc_TypeError, "stepfunction must be callable");
1824
if (!PyCallable_Check(PyTuple_GET_ITEM(retval,2)))
1826
PyErr_Format(PyExc_TypeError, "final function must be callable");
1830
aggfc->aggvalue=PyTuple_GET_ITEM(retval,0);
1831
aggfc->stepfunc=PyTuple_GET_ITEM(retval,1);
1832
aggfc->finalfunc=PyTuple_GET_ITEM(retval,2);
1834
Py_INCREF(aggfc->aggvalue);
1835
Py_INCREF(aggfc->stepfunc);
1836
Py_INCREF(aggfc->finalfunc);
1838
Py_DECREF(Py_None); /* we used this earlier as a sentinel */
1848
Note that we can't call sqlite3_result_error in the step function as
1849
SQLite doesn't want to you to do that (and core dumps!)
1850
Consequently if an error is returned, we will still be repeatedly
1855
cbdispatch_step(sqlite3_context *context, int argc, sqlite3_value **argv)
1857
PyGILState_STATE gilstate;
1860
aggregatefunctioncontext *aggfc=NULL;
1862
gilstate=PyGILState_Ensure();
1864
if (PyErr_Occurred())
1867
aggfc=getaggregatefunctioncontext(context);
1869
if (PyErr_Occurred())
1874
pyargs=getfunctionargs(context, aggfc->aggvalue, argc, argv);
1878
assert(!PyErr_Occurred());
1879
retval=PyEval_CallObject(aggfc->stepfunc, pyargs);
1885
assert(PyErr_Occurred());
1889
if(PyErr_Occurred())
1892
funccbinfo *cbinfo=(funccbinfo*)sqlite3_user_data(context);
1894
funname=sqlite3_mprintf("user-defined-aggregate-step-%s", cbinfo->name);
1895
AddTraceBackHere(__FILE__, __LINE__, funname, "{s: i}", "NumberOfArguments", argc);
1896
sqlite3_free(funname);
1899
PyGILState_Release(gilstate);
1902
/* this is somewhat similar to cbdispatch_step, except we also have to
1903
do some cleanup of the aggregatefunctioncontext */
1905
cbdispatch_final(sqlite3_context *context)
1907
PyGILState_STATE gilstate;
1908
PyObject *pyargs=NULL;
1909
PyObject *retval=NULL;
1910
aggregatefunctioncontext *aggfc=NULL;
1911
PyObject *err_type=NULL, *err_value=NULL, *err_traceback=NULL;
1913
gilstate=PyGILState_Ensure();
1915
PyErr_Fetch(&err_type, &err_value, &err_traceback);
1918
aggfc=getaggregatefunctioncontext(context);
1922
if((err_type||err_value||err_traceback) || PyErr_Occurred() || !aggfc->finalfunc)
1924
sqlite3_result_error(context, "Prior Python Error in step function", -1);
1928
pyargs=Py_BuildValue("(O)", aggfc->aggvalue);
1929
if(!pyargs) goto finally;
1931
retval=PyEval_CallObject(aggfc->finalfunc, pyargs);
1933
set_context_result(context, retval);
1937
/* we also free the aggregatefunctioncontext here */
1938
assert(aggfc->aggvalue); /* should always be set, perhaps to Py_None */
1939
Py_XDECREF(aggfc->aggvalue);
1940
Py_XDECREF(aggfc->stepfunc);
1941
Py_XDECREF(aggfc->finalfunc);
1943
if(PyErr_Occurred() && (err_type||err_value||err_traceback))
1945
PyErr_Format(PyExc_StandardError, "An exception happened during cleanup of an aggregate function, but there was already error in the step function so only that can be returned");
1946
apsw_write_unraiseable();
1949
if(err_type||err_value||err_traceback)
1950
PyErr_Restore(err_type, err_value, err_traceback);
1952
if(PyErr_Occurred())
1955
funccbinfo *cbinfo=(funccbinfo*)sqlite3_user_data(context);
1957
funname=sqlite3_mprintf("user-defined-aggregate-final-%s", cbinfo->name);
1958
AddTraceBackHere(__FILE__, __LINE__, funname, NULL);
1959
sqlite3_free(funname);
1962
/* sqlite3 frees the actual underlying memory we used (aggfc itself) */
1964
PyGILState_Release(gilstate);
1969
Connection_createscalarfunction(Connection *self, PyObject *args)
1978
CHECK_THREAD(self,NULL);
1979
CHECK_CLOSED(self,NULL);
1981
if(!PyArg_ParseTuple(args, "esO|i:createscalarfunction(name,callback, numargs=-1)", STRENCODING, &name, &callable, &numargs))
1987
/* there isn't a C api to get a (potentially unicode) string and
1988
make it uppercase so we hack around */
1990
/* validate the name */
1991
for(chk=name;*chk && !((*chk)&0x80);chk++);
1995
PyErr_SetString(PyExc_TypeError, "function name must be ascii characters only");
1999
/* convert name to upper case */
2000
for(chk=name;*chk;chk++)
2001
if(*chk>='a' && *chk<='z')
2004
/* ::TODO:: check if name points to already defined function and free relevant funccbinfo */
2006
if(callable!=Py_None && !PyCallable_Check(callable))
2009
PyErr_SetString(PyExc_TypeError, "parameter must be callable");
2013
Py_INCREF(callable);
2015
cbinfo=allocfunccbinfo();
2017
cbinfo->scalarfunc=callable;
2019
res=sqlite3_create_function(self->db,
2022
SQLITE_UTF8, /* it isn't very clear what this parameter does */
2023
(callable!=Py_None)?cbinfo:NULL,
2024
(callable!=Py_None)?cbdispatch_func:NULL,
2030
freefunccbinfo(cbinfo);
2031
SET_EXC(self->db, res);
2035
if(callable!=Py_None)
2037
/* put cbinfo into the linked list */
2038
cbinfo->next=self->functions;
2039
self->functions=cbinfo;
2043
/* free it since we cancelled the function */
2044
freefunccbinfo(cbinfo);
2047
return Py_BuildValue("");
2051
Connection_createaggregatefunction(Connection *self, PyObject *args)
2060
CHECK_THREAD(self,NULL);
2061
CHECK_CLOSED(self,NULL);
2063
if(!PyArg_ParseTuple(args, "esO|i:createaggregatefunction(name, factorycallback, numargs=-1)", STRENCODING, &name, &callable, &numargs))
2069
/* there isn't a C api to get a (potentially unicode) string and make it uppercase so we hack around */
2071
/* validate the name */
2072
for(chk=name;*chk && !((*chk)&0x80);chk++);
2076
PyErr_SetString(PyExc_TypeError, "function name must be ascii characters only");
2080
/* convert name to upper case */
2081
for(chk=name;*chk;chk++)
2082
if(*chk>='a' && *chk<='z')
2085
/* ::TODO:: check if name points to already defined function and free relevant funccbinfo */
2087
if(callable!=Py_None && !PyCallable_Check(callable))
2090
PyErr_SetString(PyExc_TypeError, "parameter must be callable");
2094
Py_INCREF(callable);
2096
cbinfo=allocfunccbinfo();
2098
cbinfo->aggregatefactory=callable;
2100
res=sqlite3_create_function(self->db,
2103
SQLITE_UTF8, /* it isn't very clear what this parameter does */
2104
(callable!=Py_None)?cbinfo:NULL,
2106
(callable!=Py_None)?cbdispatch_step:NULL,
2107
(callable!=Py_None)?cbdispatch_final:NULL);
2111
freefunccbinfo(cbinfo);
2112
SET_EXC(self->db, res);
2116
if(callable!=Py_None)
2118
/* put cbinfo into the linked list */
2119
cbinfo->next=self->functions;
2120
self->functions=cbinfo;
2124
/* free things up */
2125
freefunccbinfo(cbinfo);
2128
return Py_BuildValue("");
2131
/* USER DEFINED COLLATION CODE.*/
2133
/* We store the registered collations in a linked list hooked into
2134
the connection object so we can free them. There is probably a
2135
better data structure to use but this was most convenient. */
2137
static collationcbinfo *
2138
freecollationcbinfo(collationcbinfo *collation)
2140
collationcbinfo *cnext;
2145
PyMem_Free(collation->name);
2146
Py_XDECREF(collation->func);
2147
cnext=collation->next;
2148
PyMem_Free(collation);
2152
static collationcbinfo *
2153
alloccollationcbinfo(void)
2155
collationcbinfo *res=PyMem_Malloc(sizeof(collationcbinfo));
2156
memset(res, 0, sizeof(collationcbinfo));
2161
collation_cb(void *context,
2162
int stringonelen, const void *stringonedata,
2163
int stringtwolen, const void *stringtwodata)
2165
PyGILState_STATE gilstate;
2166
collationcbinfo *cbinfo=(collationcbinfo*)context;
2167
PyObject *pys1=NULL, *pys2=NULL, *retval=NULL, *pyargs=NULL;
2172
gilstate=PyGILState_Ensure();
2174
if(PyErr_Occurred()) goto finally; /* outstanding error */
2176
pys1=convertutf8stringsize(stringonedata, stringonelen);
2177
pys2=convertutf8stringsize(stringtwodata, stringtwolen);
2180
goto finally; /* failed to allocate strings */
2182
pyargs=Py_BuildValue("(NN)", pys1, pys2);
2184
goto finally; /* failed to allocate arg tuple */
2186
pys1=pys2=NULL; /* pyargs owns them now */
2188
assert(!PyErr_Occurred());
2190
retval=PyEval_CallObject(cbinfo->func, pyargs);
2192
if(!retval) goto finally; /* execution failed */
2194
result=PyInt_AsLong(retval);
2195
if(PyErr_Occurred())
2204
PyGILState_Release(gilstate);
2210
Connection_createcollation(Connection *self, PyObject *args)
2215
collationcbinfo *cbinfo;
2218
CHECK_THREAD(self,NULL);
2219
CHECK_CLOSED(self,NULL);
2221
if(!PyArg_ParseTuple(args, "esO:createcollation(name,callback)", STRENCODING, &name, &callable))
2227
/* there isn't a C api to get a (potentially unicode) string and make it uppercase so we hack around */
2229
/* validate the name */
2230
for(chk=name;*chk && !((*chk)&0x80);chk++);
2234
PyErr_SetString(PyExc_TypeError, "function name must be ascii characters only");
2238
/* convert name to upper case */
2239
for(chk=name;*chk;chk++)
2240
if(*chk>='a' && *chk<='z')
2243
/* ::TODO:: check if name points to already defined collation and free relevant collationcbinfo */
2245
if(callable!=Py_None && !PyCallable_Check(callable))
2248
PyErr_SetString(PyExc_TypeError, "parameter must be callable");
2252
Py_INCREF(callable);
2254
cbinfo=alloccollationcbinfo();
2256
cbinfo->func=callable;
2258
res=sqlite3_create_collation(self->db,
2261
(callable!=Py_None)?cbinfo:NULL,
2262
(callable!=Py_None)?collation_cb:NULL);
2265
freecollationcbinfo(cbinfo);
2266
SET_EXC(self->db, res);
2270
if (callable!=Py_None)
2272
/* put cbinfo into the linked list */
2273
cbinfo->next=self->collations;
2274
self->collations=cbinfo;
2279
freecollationcbinfo(cbinfo);
2282
return Py_BuildValue("");
2285
/* Virtual table code */
2287
/* this function is outside of experimental since it is always called by the destructor */
2289
freevtableinfo(vtableinfo *vtinfo)
2296
PyMem_Free(vtinfo->name);
2297
Py_XDECREF(vtinfo->datasource);
2298
/* connection was a borrowed reference so no decref needed */
2308
/* Calls the named method of object with the provided args */
2310
Call_PythonMethod(PyObject *obj, const char *methodname, PyObject *args, int mandatory)
2312
PyObject *method=NULL;
2315
/* we may be called when there is already an error. eg if you return an error in
2316
a cursor method, then SQLite calls vtabClose which calls us. We don't want to
2317
clear pre-existing errors, but we do want to clear ones when the function doesn't
2318
exist but is optional */
2319
PyObject *etype=NULL, *evalue=NULL, *etraceback=NULL;
2320
void *pyerralreadyoccurred=PyErr_Occurred();
2321
if(pyerralreadyoccurred)
2322
PyErr_Fetch(&etype, &evalue, &etraceback);
2325
/* we should only be called with ascii methodnames so no need to do
2326
character set conversions etc */
2327
#if PY_VERSION_HEX < 0x02050000
2328
method=PyObject_GetAttrString(obj, (char*)methodname);
2330
method=PyObject_GetAttrString(obj, methodname);
2336
/* pretend method existed and returned None */
2344
res=PyEval_CallObject(method, args);
2347
if(pyerralreadyoccurred)
2348
PyErr_Restore(etype, evalue, etraceback);
2356
sqlite3_vtab used_by_sqlite; /* I don't touch this */
2357
PyObject *vtable; /* object implementing vtable */
2361
const char *methodname;
2362
const char *declarevtabtracebackname;
2363
const char *pyexceptionname;
2364
} create_or_connect_strings[]=
2368
"VirtualTable.xCreate.sqlite3_declare_vtab",
2369
"VirtualTable.xCreate"
2373
"VirtualTable.xConnect.sqlite3_declare_vtab",
2374
"VirtualTable.xConnect"
2379
vtabCreateOrConnect(sqlite3 *db,
2382
const char *const *argv,
2383
sqlite3_vtab **pVTab,
2385
/* args above are to Create/Connect method */
2388
PyGILState_STATE gilstate;
2390
PyObject *args=NULL, *res=NULL, *schema=NULL, *vtable=NULL;
2391
apsw_vtable *avi=NULL;
2392
int sqliteres=SQLITE_OK;
2395
gilstate=PyGILState_Ensure();
2397
vti=(vtableinfo*) pAux;
2398
assert(db==vti->connection->db);
2400
args=PyTuple_New(1+argc);
2401
if(!args) goto pyexception;
2403
Py_INCREF((PyObject*)(vti->connection));
2404
PyTuple_SET_ITEM(args, 0, (PyObject*)(vti->connection));
2407
PyObject *str=convertutf8string(argv[i]);
2410
PyTuple_SET_ITEM(args, 1+i, str);
2413
res=Call_PythonMethod(vti->datasource, create_or_connect_strings[stringindex].methodname, args, 1);
2417
/* res should be a tuple of two values - a string of sql describing
2418
the table and an object implementing it */
2419
if(!PySequence_Check(res) || PySequence_Size(res)!=2)
2421
PyErr_Format(PyExc_TypeError, "Expected two values - a string with the table schema and a vtable object implementing it");
2425
vtable=PySequence_GetItem(res, 1);
2429
avi=PyMem_Malloc(sizeof(apsw_vtable));
2430
if(!avi) goto pyexception;
2431
assert((void*)avi==(void*)&(avi->used_by_sqlite)); /* detect if wierd padding happens */
2432
memset(avi, 0, sizeof(apsw_vtable));
2434
schema=PySequence_GetItem(res, 0);
2435
if(!schema) goto pyexception;
2438
PyObject *utf8schema=getutf8string(schema);
2441
sqliteres=sqlite3_declare_vtab(db, PyString_AsString(utf8schema));
2442
Py_DECREF(utf8schema);
2443
if(sqliteres!=SQLITE_OK)
2445
SET_EXC(db, sqliteres);
2446
AddTraceBackHere(__FILE__, __LINE__, create_or_connect_strings[stringindex].declarevtabtracebackname, "{s: O}", "schema", schema);
2451
assert(sqliteres==SQLITE_OK);
2452
*pVTab=(sqlite3_vtab*)avi;
2454
Py_INCREF(avi->vtable);
2458
pyexception: /* we had an exception in python code */
2459
sqliteres=MakeSqliteMsgFromPyException(errmsg);
2460
AddTraceBackHere(__FILE__, __LINE__, create_or_connect_strings[stringindex].pyexceptionname,
2461
"{s: s, s: s, s: s, s: O}", "modulename", argv[0], "database", argv[1], "tablename", argv[2], "schema", schema?schema:Py_None);
2463
finally: /* cleanup */
2471
PyGILState_Release(gilstate);
2476
vtabCreate(sqlite3 *db,
2479
const char *const *argv,
2480
sqlite3_vtab **pVTab,
2483
return vtabCreateOrConnect(db, pAux, argc, argv, pVTab, errmsg, 0);
2487
vtabConnect(sqlite3 *db,
2490
const char *const *argv,
2491
sqlite3_vtab **pVTab,
2494
return vtabCreateOrConnect(db, pAux, argc, argv, pVTab, errmsg, 1);
2500
const char *methodname;
2501
const char *pyexceptionname;
2502
} destroy_disconnect_strings[]=
2506
"VirtualTable.xDestroy"
2510
"VirtualTable.xDisconnect"
2514
/* See SQLite ticket 2099 */
2516
vtabDestroyOrDisconnect(sqlite3_vtab *pVtab, int stringindex)
2518
PyObject *vtable, *res=NULL;
2519
PyGILState_STATE gilstate;
2520
int sqliteres=SQLITE_OK;
2522
gilstate=PyGILState_Ensure();
2523
vtable=((apsw_vtable*)pVtab)->vtable;
2525
/* mandatory for Destroy, optional for Disconnect */
2526
res=Call_PythonMethod(vtable, destroy_disconnect_strings[stringindex].methodname, NULL, (stringindex==0));
2527
/* sqlite 3.3.8 ignore return code for disconnect so we always free */
2528
if (res || stringindex==1)
2530
/* see SQLite ticket 2127 */
2532
sqlite3_free(pVtab->zErrMsg);
2541
/* ::TODO:: waiting on ticket 2099 to know if the pVtab should also be freed in case of error return with Destroy. */
2543
/* see SQLite ticket 2127 */
2545
sqlite3_free(pVtab->zErrMsg);
2552
/* pyexception: we had an exception in python code */
2553
sqliteres=MakeSqliteMsgFromPyException(&(pVtab->zErrMsg));
2554
AddTraceBackHere(__FILE__, __LINE__, destroy_disconnect_strings[stringindex].pyexceptionname, "{s: O}", "self", vtable);
2559
PyGILState_Release(gilstate);
2564
vtabDestroy(sqlite3_vtab *pVTab)
2566
return vtabDestroyOrDisconnect(pVTab, 0);
2570
vtabDisconnect(sqlite3_vtab *pVTab)
2572
return vtabDestroyOrDisconnect(pVTab, 1);
2577
vtabBestIndex(sqlite3_vtab *pVtab, sqlite3_index_info *indexinfo)
2579
PyGILState_STATE gilstate;
2581
PyObject *constraints=NULL, *orderbys=NULL;
2582
PyObject *args=NULL, *res=NULL, *indices=NULL;
2585
int sqliteres=SQLITE_OK;
2587
gilstate=PyGILState_Ensure();
2589
vtable=((apsw_vtable*)pVtab)->vtable;
2591
/* count how many usable constraints there are */
2592
for(i=0;i<indexinfo->nConstraint;i++)
2593
if (indexinfo->aConstraint[i].usable)
2596
constraints=PyTuple_New(nconstraints);
2597
if(!constraints) goto pyexception;
2600
for(i=0, j=0;i<indexinfo->nConstraint;i++)
2602
PyObject *constraint=NULL;
2603
if(!indexinfo->aConstraint[i].usable) continue;
2605
constraint=Py_BuildValue("(iB)", indexinfo->aConstraint[i].iColumn, indexinfo->aConstraint[i].op);
2606
if(!constraint) goto pyexception;
2608
PyTuple_SET_ITEM(constraints, j, constraint);
2613
orderbys=PyTuple_New(indexinfo->nOrderBy);
2614
if(!orderbys) goto pyexception;
2617
for(i=0;i<indexinfo->nOrderBy;i++)
2619
PyObject *order=NULL;
2621
order=Py_BuildValue("(iN)", indexinfo->aOrderBy[i].iColumn, PyBool_FromLong(indexinfo->aOrderBy[i].desc));
2622
if(!order) goto pyexception;
2624
PyTuple_SET_ITEM(orderbys, i, order);
2627
/* actually call the function */
2628
args=Py_BuildValue("(NN)", constraints, orderbys);
2631
constraints=orderbys=NULL; /* owned by the tuple now */
2633
res=Call_PythonMethod(vtable, "BestIndex", args, 1);
2637
/* do we have useful index information? */
2641
/* check we have a sequence */
2642
if(!PySequence_Check(res) || PySequence_Size(res)>5)
2644
PyErr_Format(PyExc_TypeError, "Bad result from BestIndex. It should be a sequence of up to 5 items");
2645
AddTraceBackHere(__FILE__, __LINE__, "VirtualTable.xBestIndex.result_check", "{s: O, s: O}", "self", vtable, "result", res);
2649
/* dig the argv indices out */
2650
if(PySequence_Size(res)==0)
2653
indices=PySequence_GetItem(res, 0);
2654
if(indices!=Py_None)
2656
if(!PySequence_Check(indices) || PySequence_Size(indices)!=nconstraints)
2658
PyErr_Format(PyExc_TypeError, "Bad constraints (item 0 in BestIndex return). It should be a sequence the same length as the constraints passed in (%d) items", nconstraints);
2659
AddTraceBackHere(__FILE__, __LINE__, "VirtualTable.xBestIndex.result_indices", "{s: O, s: O, s: O}",
2660
"self", vtable, "result", res, "indices", indices);
2663
/* iterate through the items - i is the SQLite sequence number and j is the apsw one (usable entries) */
2664
for(i=0,j=0;i<indexinfo->nConstraint;i++)
2666
PyObject *constraint=NULL, *argvindex=NULL, *omit=NULL;
2668
if(!indexinfo->aConstraint[i].usable) continue;
2669
constraint=PySequence_GetItem(indices, j);
2670
if(!constraint) goto pyexception;
2672
/* it can be None */
2673
if(constraint==Py_None)
2675
Py_DECREF(constraint);
2679
if(PyInt_Check(constraint))
2681
indexinfo->aConstraintUsage[i].argvIndex=PyInt_AsLong(constraint);
2682
Py_DECREF(constraint);
2685
/* or a sequence two items long */
2686
if(!PySequence_Check(constraint) || PySequence_Size(constraint)!=2)
2688
PyErr_Format(PyExc_TypeError, "Bad constraint (#%d) - it should be one of None, an integer or a tuple of an integer and a boolean", j);
2689
AddTraceBackHere(__FILE__, __LINE__, "VirtualTable.xBestIndex.result_constraint", "{s: O, s: O, s: O, s: O}",
2690
"self", vtable, "result", res, "indices", indices, "constraint", constraint);
2691
Py_DECREF(constraint);
2694
argvindex=PySequence_GetItem(constraint, 0);
2695
omit=PySequence_GetItem(constraint, 1);
2696
if(!argvindex || !omit) goto constraintfail;
2697
if(!PyInt_Check(argvindex))
2699
PyErr_Format(PyExc_TypeError, "argvindex for constraint #%d should be an integer", j);
2700
AddTraceBackHere(__FILE__, __LINE__, "VirtualTable.xBestIndex.result_constraint_argvindex", "{s: O, s: O, s: O, s: O, s: O}",
2701
"self", vtable, "result", res, "indices", indices, "constraint", constraint, "argvindex", argvindex);
2702
goto constraintfail;
2704
omitv=PyObject_IsTrue(omit);
2705
if(omitv==-1) goto constraintfail;
2706
indexinfo->aConstraintUsage[i].argvIndex=PyInt_AsLong(argvindex);
2707
indexinfo->aConstraintUsage[i].omit=omitv;
2708
Py_DECREF(constraint);
2709
Py_DECREF(argvindex);
2714
Py_DECREF(constraint);
2715
Py_XDECREF(argvindex);
2721
/* item #1 is idxnum */
2722
if(PySequence_Size(res)<2)
2725
PyObject *idxnum=PySequence_GetItem(res, 1);
2726
if(!idxnum) goto pyexception;
2729
if(!PyInt_Check(idxnum))
2731
PyErr_Format(PyExc_TypeError, "idxnum must be an integer");
2732
AddTraceBackHere(__FILE__, __LINE__, "VirtualTable.xBestIndex.result_indexnum", "{s: O, s: O, s: O}", "self", vtable, "result", res, "indexnum", idxnum);
2736
indexinfo->idxNum=PyInt_AsLong(idxnum);
2741
/* item #2 is idxStr */
2742
if(PySequence_Size(res)<3)
2745
PyObject *utf8str=NULL, *idxstr=NULL;
2746
idxstr=PySequence_GetItem(res, 2);
2747
if(!idxstr) goto pyexception;
2750
utf8str=getutf8string(idxstr);
2756
indexinfo->idxStr=sqlite3_mprintf("%s", PyString_AsString(utf8str));
2757
indexinfo->needToFreeIdxStr=1;
2759
Py_XDECREF(utf8str);
2763
/* item 3 is orderByConsumed */
2764
if(PySequence_Size(res)<4)
2767
PyObject *orderbyconsumed=NULL;
2768
int iorderbyconsumed;
2769
orderbyconsumed=PySequence_GetItem(res, 3);
2770
if(!orderbyconsumed) goto pyexception;
2771
if(orderbyconsumed!=Py_None)
2773
iorderbyconsumed=PyObject_IsTrue(orderbyconsumed);
2774
if(iorderbyconsumed==-1)
2776
Py_DECREF(orderbyconsumed);
2779
indexinfo->orderByConsumed=iorderbyconsumed;
2781
Py_DECREF(orderbyconsumed);
2784
/* item 4 (final) is estimated cost */
2785
if(PySequence_Size(res)<5)
2787
assert(PySequence_Size(res)==5);
2789
PyObject *estimatedcost=NULL, *festimatedcost=NULL;
2790
estimatedcost=PySequence_GetItem(res,4);
2791
if(!estimatedcost) goto pyexception;
2792
if(estimatedcost!=Py_None)
2794
festimatedcost=PyNumber_Float(estimatedcost);
2797
Py_DECREF(estimatedcost);
2800
indexinfo->estimatedCost=PyFloat_AsDouble(festimatedcost);
2802
Py_XDECREF(festimatedcost);
2803
Py_DECREF(estimatedcost);
2808
pyexception: /* we had an exception in python code */
2809
assert(PyErr_Occurred());
2810
sqliteres=MakeSqliteMsgFromPyException(&(pVtab->zErrMsg));
2811
AddTraceBackHere(__FILE__, __LINE__, "VirtualTable.xBestIndex", "{s: O, s: O, s: O}", "self", vtable, "result", res?res:Py_None, "args", args?args:Py_None);
2814
Py_XDECREF(indices);
2817
Py_XDECREF(constraints);
2818
Py_XDECREF(orderbys);
2819
PyGILState_Release(gilstate);
2824
const char *methodname;
2825
const char *pyexceptionname;
2826
} transaction_strings[]=
2830
"VirtualTable.Begin"
2838
"VirtualTable.Commit"
2842
"VirtualTable.Rollback"
2848
vtabTransactionMethod(sqlite3_vtab *pVtab, int stringindex)
2850
PyObject *vtable, *res=NULL;
2851
PyGILState_STATE gilstate;
2852
int sqliteres=SQLITE_OK;
2854
gilstate=PyGILState_Ensure();
2855
vtable=((apsw_vtable*)pVtab)->vtable;
2857
res=Call_PythonMethod(vtable, transaction_strings[stringindex].methodname, NULL, 0);
2858
if(res) goto finally;
2860
/* pyexception: we had an exception in python code */
2861
sqliteres=MakeSqliteMsgFromPyException(&(pVtab->zErrMsg));
2862
AddTraceBackHere(__FILE__, __LINE__, transaction_strings[stringindex].pyexceptionname, "{s: O}", "self", vtable);
2867
PyGILState_Release(gilstate);
2872
vtabBegin(sqlite3_vtab *pVtab)
2874
return vtabTransactionMethod(pVtab, 0);
2878
vtabSync(sqlite3_vtab *pVtab)
2880
return vtabTransactionMethod(pVtab, 1);
2884
vtabCommit(sqlite3_vtab *pVtab)
2886
return vtabTransactionMethod(pVtab, 2);
2890
vtabRollback(sqlite3_vtab *pVtab)
2892
return vtabTransactionMethod(pVtab, 3);
2896
sqlite3_vtab_cursor used_by_sqlite; /* I don't touch this */
2897
PyObject *cursor; /* Object implementing cursor */
2898
} apsw_vtable_cursor;
2902
vtabOpen(sqlite3_vtab *pVtab, sqlite3_vtab_cursor **ppCursor)
2904
PyObject *vtable=NULL, *res=NULL;
2905
PyGILState_STATE gilstate;
2906
apsw_vtable_cursor *avc=NULL;
2907
int sqliteres=SQLITE_OK;
2909
gilstate=PyGILState_Ensure();
2911
vtable=((apsw_vtable*)pVtab)->vtable;
2913
res=Call_PythonMethod(vtable, "Open", NULL, 1);
2916
avc=PyMem_Malloc(sizeof(apsw_vtable_cursor));
2917
assert((void*)avc==(void*)&(avc->used_by_sqlite)); /* detect if wierd padding happens */
2918
memset(avc, 0, sizeof(apsw_vtable_cursor));
2922
*ppCursor=(sqlite3_vtab_cursor*)avc;
2925
pyexception: /* we had an exception in python code */
2926
assert(PyErr_Occurred());
2927
sqliteres=MakeSqliteMsgFromPyException(&(pVtab->zErrMsg));
2928
AddTraceBackHere(__FILE__, __LINE__, "VirtualTable.xOpen", "{s: O}", "self", vtable);
2932
PyGILState_Release(gilstate);
2937
vtabFilter(sqlite3_vtab_cursor *pCursor, int idxNum, const char *idxStr,
2938
int argc, sqlite3_value **sqliteargv)
2940
PyObject *cursor, *args=NULL, *argv=NULL, *res=NULL;
2941
PyGILState_STATE gilstate;
2942
int sqliteres=SQLITE_OK;
2945
gilstate=PyGILState_Ensure();
2947
cursor=((apsw_vtable_cursor*)pCursor)->cursor;
2950
argv=PyTuple_New(argc);
2951
if(!argv) goto pyexception;
2954
PyObject *value=convert_value_to_pyobject(sqliteargv[i]);
2955
if(!value) goto pyexception;
2956
PyTuple_SET_ITEM(argv, i, value);
2959
args=Py_BuildValue("(iO&N)", idxNum, convertutf8string, idxStr, argv);
2960
if(!args) goto pyexception;
2962
argv=NULL; /* owned by args now */
2964
res=Call_PythonMethod(cursor, "Filter", args, 1);
2965
if(res) goto finally; /* result is ignored */
2967
pyexception: /* we had an exception in python code */
2968
assert(PyErr_Occurred());
2969
sqliteres=MakeSqliteMsgFromPyException(&(pCursor->pVtab->zErrMsg)); /* SQLite flaw: errMsg should be on the cursor not the table! */
2970
AddTraceBackHere(__FILE__, __LINE__, "VirtualTable.xFilter", "{s: O}", "self", cursor);
2977
PyGILState_Release(gilstate);
2981
/* note that we can only return true/false and cannot indicate there was an error */
2983
vtabEof(sqlite3_vtab_cursor *pCursor)
2985
PyObject *cursor, *res=NULL;
2986
PyGILState_STATE gilstate;
2987
int sqliteres=0; /* nb a true/false value not error code */
2989
gilstate=PyGILState_Ensure();
2991
/* is there already an error? */
2992
if(PyErr_Occurred()) goto finally;
2994
cursor=((apsw_vtable_cursor*)pCursor)->cursor;
2996
res=Call_PythonMethod(cursor, "Eof", NULL, 1);
2997
if(!res) goto pyexception;
2999
sqliteres=PyObject_IsTrue(res);
3000
if(sqliteres==0 || sqliteres==1)
3003
sqliteres=0; /* we say there are no more records on error */
3005
pyexception: /* we had an exception in python code */
3006
assert(PyErr_Occurred());
3007
sqliteres=MakeSqliteMsgFromPyException(&(pCursor->pVtab->zErrMsg)); /* SQLite flaw: errMsg should be on the cursor not the table! */
3008
AddTraceBackHere(__FILE__, __LINE__, "VirtualTable.xEof", "{s: O}", "self", cursor);
3013
PyGILState_Release(gilstate);
3018
vtabColumn(sqlite3_vtab_cursor *pCursor, sqlite3_context *result, int ncolumn)
3020
PyObject *cursor, *args=NULL, *res=NULL;
3021
PyGILState_STATE gilstate;
3022
int sqliteres=SQLITE_OK;
3024
gilstate=PyGILState_Ensure();
3026
cursor=((apsw_vtable_cursor*)pCursor)->cursor;
3028
args=Py_BuildValue("(i)", ncolumn);
3029
if(!args) goto pyexception;
3031
res=Call_PythonMethod(cursor, "Column", args, 1);
3032
if(!res) goto pyexception;
3034
set_context_result(result, res);
3035
if(!PyErr_Occurred()) goto finally;
3037
pyexception: /* we had an exception in python code */
3038
assert(PyErr_Occurred());
3039
sqliteres=MakeSqliteMsgFromPyException(&(pCursor->pVtab->zErrMsg)); /* SQLite flaw: errMsg should be on the cursor not the table! */
3040
AddTraceBackHere(__FILE__, __LINE__, "VirtualTable.xColumn", "{s: O}", "self", cursor);
3046
PyGILState_Release(gilstate);
3051
vtabNext(sqlite3_vtab_cursor *pCursor)
3053
PyObject *cursor, *res=NULL;
3054
PyGILState_STATE gilstate;
3055
int sqliteres=SQLITE_OK;
3057
gilstate=PyGILState_Ensure();
3059
cursor=((apsw_vtable_cursor*)pCursor)->cursor;
3061
res=Call_PythonMethod(cursor, "Next", NULL, 1);
3062
if(res) goto finally;
3064
/* pyexception: we had an exception in python code */
3065
assert(PyErr_Occurred());
3066
sqliteres=MakeSqliteMsgFromPyException(&(pCursor->pVtab->zErrMsg)); /* SQLite flaw: errMsg should be on the cursor not the table! */
3067
AddTraceBackHere(__FILE__, __LINE__, "VirtualTable.xNext", "{s: O}", "self", cursor);
3072
PyGILState_Release(gilstate);
3077
vtabClose(sqlite3_vtab_cursor *pCursor)
3079
PyObject *cursor, *res=NULL;
3080
PyGILState_STATE gilstate;
3081
char **zErrMsgLocation=&(pCursor->pVtab->zErrMsg); /* we free pCursor but still need this field */
3082
int sqliteres=SQLITE_OK;
3084
gilstate=PyGILState_Ensure();
3086
cursor=((apsw_vtable_cursor*)pCursor)->cursor;
3088
res=Call_PythonMethod(cursor, "Close", NULL, 1);
3089
PyMem_Free(pCursor); /* always free */
3090
if(res) goto finally;
3092
/* pyexception: we had an exception in python code */
3093
assert(PyErr_Occurred());
3094
sqliteres=MakeSqliteMsgFromPyException(zErrMsgLocation); /* SQLite flaw: errMsg should be on the cursor not the table! */
3095
AddTraceBackHere(__FILE__, __LINE__, "VirtualTable.xClose", "{s: O}", "self", cursor);
3098
Py_DECREF(cursor); /* this is where cursor gets freed */
3101
PyGILState_Release(gilstate);
3106
vtabRowid(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid)
3108
PyObject *cursor, *res=NULL, *pyrowid=NULL;
3109
PyGILState_STATE gilstate;
3110
int sqliteres=SQLITE_OK;
3112
gilstate=PyGILState_Ensure();
3114
cursor=((apsw_vtable_cursor*)pCursor)->cursor;
3116
res=Call_PythonMethod(cursor, "Rowid", NULL, 1);
3117
if(!res) goto pyexception;
3119
/* extract result */
3120
pyrowid=PyNumber_Long(res);
3123
*pRowid=PyLong_AsLongLong(pyrowid);
3124
if(!PyErr_Occurred()) /* could be bigger than 64 bits */
3127
pyexception: /* we had an exception in python code */
3128
assert(PyErr_Occurred());
3129
sqliteres=MakeSqliteMsgFromPyException(&(pCursor->pVtab->zErrMsg)); /* SQLite flaw: errMsg should be on the cursor not the table! */
3130
AddTraceBackHere(__FILE__, __LINE__, "VirtualTable.xRowid", "{s: O}", "self", cursor);
3133
Py_XDECREF(pyrowid);
3136
PyGILState_Release(gilstate);
3141
vtabUpdate(sqlite3_vtab *pVtab, int argc, sqlite3_value **argv, sqlite_int64 *pRowid)
3143
PyObject *vtable, *args=NULL, *res=NULL;
3144
PyGILState_STATE gilstate;
3145
int sqliteres=SQLITE_OK;
3147
const char *methodname="unknown";
3149
assert(argc); /* should always be >0 */
3151
gilstate=PyGILState_Ensure();
3153
vtable=((apsw_vtable*)pVtab)->vtable;
3155
/* case 1 - argc=1 means delete row */
3158
methodname="UpdateDeleteRow";
3159
args=Py_BuildValue("(O&)", convert_value_to_pyobject, argv[0]);
3160
if(!args) goto pyexception;
3162
/* case 2 - insert a row */
3163
else if(sqlite3_value_type(argv[0])==SQLITE_NULL)
3166
methodname="UpdateInsertRow";
3167
args=PyTuple_New(2);
3168
if(!args) goto pyexception;
3169
if(sqlite3_value_type(argv[1])==SQLITE_NULL)
3172
Py_INCREF(newrowid);
3176
newrowid=convert_value_to_pyobject(argv[1]);
3177
if(!newrowid) goto pyexception;
3179
PyTuple_SET_ITEM(args, 0, newrowid);
3181
/* otherwise changing a row */
3184
PyObject *oldrowid=NULL, *newrowid=NULL;
3185
methodname="UpdateChangeRow";
3186
args=PyTuple_New(3);
3187
oldrowid=convert_value_to_pyobject(argv[0]);
3188
if(sqlite3_value_type(argv[1])==SQLITE_NULL)
3191
Py_INCREF(newrowid);
3195
newrowid=convert_value_to_pyobject(argv[1]);
3197
if(!oldrowid || !newrowid)
3199
Py_XDECREF(oldrowid);
3200
Py_XDECREF(newrowid);
3203
PyTuple_SET_ITEM(args,0,oldrowid);
3204
PyTuple_SET_ITEM(args,1,newrowid);
3207
/* new row values */
3210
PyObject *fields=NULL;
3211
fields=PyTuple_New(argc-2);
3212
if(!fields) goto pyexception;
3213
for(i=0;i+2<argc;i++)
3215
PyObject *field=convert_value_to_pyobject(argv[i+2]);
3221
PyTuple_SET_ITEM(fields, i, field);
3223
PyTuple_SET_ITEM(args, PyTuple_GET_SIZE(args)-1, fields);
3226
res=Call_PythonMethod(vtable, methodname, args, 1);
3230
/* if row deleted then we don't care about return */
3234
if(sqlite3_value_type(argv[0])==SQLITE_NULL && sqlite3_value_type(argv[1])==SQLITE_NULL)
3236
/* did an insert and must provide a row id */
3237
PyObject *rowid=PyNumber_Long(res);
3238
if(!rowid) goto pyexception;
3240
*pRowid=PyLong_AsLongLong(rowid);
3242
if(PyErr_Occurred())
3244
AddTraceBackHere(__FILE__, __LINE__, "VirtualTable.xUpdateInsertRow.ReturnedValue", "{s: O}", "result", rowid);
3251
pyexception: /* we had an exception in python code */
3252
assert(PyErr_Occurred());
3253
sqliteres=MakeSqliteMsgFromPyException(&pVtab->zErrMsg);
3254
AddTraceBackHere(__FILE__, __LINE__, "VirtualTable.xUpdate", "{s: O, s: i, s: s, s: O}", "self", vtable, "argc", argc, "methodname", methodname, "args", args?args:Py_None);
3260
PyGILState_Release(gilstate);
3266
/* I can't implement this yet since I need to know when
3267
ppArg will get freed. See SQLite ticket 2095. */
3270
vtabFindFunction(sqlite3_vtab *pVtab, int nArg, const char *zName,
3271
void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),
3279
/* it would be nice to use C99 style initializers here ... */
3280
static struct sqlite3_module apsw_vtable_module=
3283
vtabCreate, /* methods */
3300
0, /* vtabFindFunction */
3304
allocvtableinfo(void)
3306
vtableinfo *res=PyMem_Malloc(sizeof(vtableinfo));
3308
memset(res, 0, sizeof(vtableinfo));
3313
Connection_createmodule(Connection *self, PyObject *args)
3316
PyObject *datasource=NULL;
3320
CHECK_THREAD(self, NULL);
3321
CHECK_CLOSED(self, NULL);
3323
if(!PyArg_ParseTuple(args, "esO:createmodule(name, datasource)", "utf_8", &name, &datasource))
3326
Py_INCREF(datasource);
3327
vti=allocvtableinfo();
3328
vti->connection=self;
3330
vti->datasource=datasource;
3332
/* ::TODO:: - can we call this with NULL to unregister a module? */
3333
res=sqlite3_create_module(self->db, name, &apsw_vtable_module, vti);
3334
SET_EXC(self->db, res);
3338
freevtableinfo(vti);
3342
/* add vti to linked list */
3343
vti->next=self->vtables;
3346
return Py_BuildValue("");
3349
#endif /* EXPERIMENTAL */
3350
/* end of Virtual table code */
3353
static PyMethodDef Connection_methods[] = {
3354
{"cursor", (PyCFunction)Connection_cursor, METH_NOARGS,
3355
"Create a new cursor" },
3356
{"close", (PyCFunction)Connection_close, METH_VARARGS,
3357
"Closes the connection" },
3358
{"setbusytimeout", (PyCFunction)Connection_setbusytimeout, METH_VARARGS,
3359
"Sets the sqlite busy timeout in milliseconds. Use zero to disable the timeout"},
3360
{"interrupt", (PyCFunction)Connection_interrupt, METH_NOARGS,
3361
"Causes any pending database operations to abort at the earliest opportunity"},
3362
{"createscalarfunction", (PyCFunction)Connection_createscalarfunction, METH_VARARGS,
3363
"Creates a scalar function"},
3364
{"createaggregatefunction", (PyCFunction)Connection_createaggregatefunction, METH_VARARGS,
3365
"Creates an aggregate function"},
3366
{"setbusyhandler", (PyCFunction)Connection_setbusyhandler, METH_O,
3367
"Sets the busy handler"},
3368
{"changes", (PyCFunction)Connection_changes, METH_NOARGS,
3369
"Returns the number of rows changed by last query"},
3370
{"totalchanges", (PyCFunction)Connection_totalchanges, METH_NOARGS,
3371
"Returns the total number of changes to database since it was opened"},
3372
{"getautocommit", (PyCFunction)Connection_getautocommit, METH_NOARGS,
3373
"Returns if the database is in auto-commit mode"},
3374
{"createcollation", (PyCFunction)Connection_createcollation, METH_VARARGS,
3375
"Creates a collation function"},
3376
{"last_insert_rowid", (PyCFunction)Connection_last_insert_rowid, METH_NOARGS,
3377
"Returns rowid for last insert"},
3378
{"complete", (PyCFunction)Connection_complete, METH_VARARGS,
3379
"Checks if a SQL statement is complete"},
3380
{"setauthorizer", (PyCFunction)Connection_setauthorizer, METH_O,
3381
"Sets an authorizer function"},
3382
{"setupdatehook", (PyCFunction)Connection_setupdatehook, METH_O,
3383
"Sets an update hook"},
3384
{"setrollbackhook", (PyCFunction)Connection_setrollbackhook, METH_O,
3385
"Sets a callable invoked before each rollback"},
3387
{"setprofile", (PyCFunction)Connection_setprofile, METH_O,
3388
"Sets a callable invoked with profile information after each statement"},
3389
{"setcommithook", (PyCFunction)Connection_setcommithook, METH_O,
3390
"Sets a callable invoked before each commit"},
3391
{"setprogresshandler", (PyCFunction)Connection_setprogresshandler, METH_VARARGS,
3392
"Sets a callback invoked periodically during long running calls"},
3393
#if !defined(SQLITE_OMIT_LOAD_EXTENSION)
3394
{"enableloadextension", (PyCFunction)Connection_enableloadextension, METH_O,
3395
"Enables loading of SQLite extensions from shared libraries"},
3396
{"loadextension", (PyCFunction)Connection_loadextension, METH_VARARGS,
3397
"loads SQLite extension"},
3399
{"createmodule", (PyCFunction)Connection_createmodule, METH_VARARGS,
3400
"registers a virtual table"},
3402
{0, 0, 0, 0} /* Sentinel */
3406
static PyTypeObject ConnectionType = {
3407
PyObject_HEAD_INIT(NULL)
3409
"apsw.Connection", /*tp_name*/
3410
sizeof(Connection), /*tp_basicsize*/
3412
(destructor)Connection_dealloc, /*tp_dealloc*/
3419
0, /*tp_as_sequence*/
3420
0, /*tp_as_mapping*/
3427
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/
3428
"Connection object", /* tp_doc */
3429
0, /* tp_traverse */
3431
0, /* tp_richcompare */
3432
0, /* tp_weaklistoffset */
3434
0, /* tp_iternext */
3435
Connection_methods, /* tp_methods */
3440
0, /* tp_descr_get */
3441
0, /* tp_descr_set */
3442
0, /* tp_dictoffset */
3443
(initproc)Connection_init, /* tp_init */
3445
Connection_new, /* tp_new */
3451
0, /* tp_subclasses */
3452
0, /* tp_weaklist */
3459
/* Do finalization and free resources. Returns the SQLITE error code */
3461
resetcursor(Cursor *self, int force)
3465
Py_XDECREF(self->bindings);
3466
self->bindings=NULL;
3467
self->bindingsoffset=-1;
3471
res=statementcache_finalize(self->connection->stmtcache, self->statement);
3472
if(!force) /* we don't care about errors when forcing */
3473
SET_EXC(self->connection->db, res);
3477
if(!force && (self->status!=C_DONE && self->zsqlnextpos))
3479
if (*self->zsqlnextpos && res==SQLITE_OK)
3481
/* We still have more, so this is actually an abort. */
3483
if(!PyErr_Occurred())
3484
PyErr_Format(ExcIncomplete, "Error: there are still remaining sql statements to execute");
3487
self->zsqlnextpos=NULL;
3489
if(!force && self->status!=C_DONE && self->emiter)
3491
PyObject *next=PyIter_Next(self->emiter);
3496
if (!PyErr_Occurred())
3497
/* Technically this line won't get executed since the
3498
block above will already have set ExcIncomplete.
3499
Leaving it in as defensive coding. */
3500
PyErr_Format(ExcIncomplete, "Error: there are still many remaining sql statements to execute");
3504
Py_XDECREF(self->emiter);
3509
PyMem_Free((void*)self->zsql);
3513
self->status=C_DONE;
3515
if (PyErr_Occurred())
3518
AddTraceBackHere(__FILE__, __LINE__, "resetcursor", NULL);
3525
Cursor_dealloc(Cursor * self)
3527
/* thread check - we can't use macro as it returns*/
3528
PyObject *err_type, *err_value, *err_traceback;
3529
int have_error=PyErr_Occurred()?1:0;
3531
if( (self->status!=C_DONE || self->statement || self->zsqlnextpos || self->emiter) && /* only whine if there was anything left in the Cursor */
3532
self->connection->thread_ident!=PyThread_get_thread_ident())
3535
PyErr_Fetch(&err_type, &err_value, &err_traceback);
3536
PyErr_Format(ExcThreadingViolation, "The destructor for Cursor is called in a different thread than it"
3537
"was created in. All calls must be in the same thread. It was created in thread %d "
3538
"and this is %d. SQLite is not being closed as a result.",
3539
(int)(self->connection->thread_ident), (int)(PyThread_get_thread_ident()));
3540
apsw_write_unraiseable();
3542
PyErr_Restore(err_type, err_value, err_traceback);
3547
/* do our finalisation ... */
3551
/* remember the existing error so that resetcursor won't immediately return */
3552
PyErr_Fetch(&err_type, &err_value, &err_traceback);
3556
resetcursor(self, 1);
3557
if(PyErr_Occurred())
3558
PyErr_Clear(); /* clear out any exceptions from resetcursor since we don't care */
3561
/* restore earlier error if there was one */
3562
PyErr_Restore(err_type, err_value, err_traceback);
3564
/* we no longer need connection */
3565
if(self->connection)
3567
pointerlist_remove(&self->connection->cursors, self);
3568
Py_DECREF(self->connection);
3572
/* executemany iterator */
3573
Py_XDECREF(self->emiter);
3576
/* no need for tracing */
3577
Py_XDECREF(self->exectrace);
3578
Py_XDECREF(self->rowtrace);
3579
self->exectrace=self->rowtrace=0;
3581
self->ob_type->tp_free((PyObject*)self);
3585
Cursor_init(Cursor *self, Connection *connection)
3587
self->connection=connection;
3590
self->zsqlnextpos=0;
3591
self->status=C_DONE;
3593
self->bindingsoffset=0;
3600
Cursor_getdescription(Cursor *self)
3603
PyObject *result=NULL;
3604
PyObject *pair=NULL;
3606
CHECK_THREAD(self->connection,NULL);
3607
CHECK_CLOSED(self->connection,NULL);
3609
if(!self->statement)
3611
PyErr_Format(ExcComplete, "Can't get description for statements that have completed execution");
3615
ncols=sqlite3_column_count(self->statement);
3616
result=PyTuple_New(ncols);
3617
if(!result) goto error;
3619
for(i=0;i<ncols;i++)
3621
pair=Py_BuildValue("(O&O&)",
3622
convertutf8string, sqlite3_column_name(self->statement, i),
3623
convertutf8string, sqlite3_column_decltype(self->statement, i));
3625
if(!pair) goto error;
3627
PyTuple_SET_ITEM(result, i, pair);
3628
/* owned by result now */
3640
/* internal function - returns SQLite error code (ie SQLITE_OK if all is well) */
3642
Cursor_dobinding(Cursor *self, int arg, PyObject *obj)
3645
/* DUPLICATE(ish) code: this is substantially similar to the code in
3646
set_context_result. If you fix anything here then do it there as
3651
if(PyErr_Occurred())
3655
res=sqlite3_bind_null(self->statement, arg);
3656
/* Python uses a 'long' for storage of PyInt. This could
3657
be a 32bit or 64bit quantity depending on the platform. */
3658
else if(PyInt_Check(obj))
3659
res=sqlite3_bind_int64(self->statement, arg, PyInt_AS_LONG(obj));
3660
else if (PyLong_Check(obj))
3661
/* nb: PyLong_AsLongLong can cause Python level error */
3662
res=sqlite3_bind_int64(self->statement, arg, PyLong_AsLongLong(obj));
3663
else if (PyFloat_Check(obj))
3664
res=sqlite3_bind_double(self->statement, arg, PyFloat_AS_DOUBLE(obj));
3665
else if (PyUnicode_Check(obj))
3667
const void *badptr=NULL;
3672
if(strbytes>APSW_INT32_MAX)
3674
PyErr_Format(ExcTooBig, "Unicode object is too large - SQLite only supports up to 2GB");
3679
res=sqlite3_bind_text16(self->statement, arg, strdata, (int)strbytes, SQLITE_TRANSIENT);
3681
res=sqlite3_bind_text(self->statement, arg, strdata, (int)strbytes, SQLITE_TRANSIENT);
3687
assert(PyErr_Occurred());
3691
else if (PyString_Check(obj))
3693
const char *val=PyString_AS_STRING(obj);
3694
const size_t lenval=PyString_GET_SIZE(obj);
3695
const char *chk=val;
3696
for(;chk<val+lenval && !((*chk)&0x80); chk++);
3699
const void *badptr=NULL;
3700
PyObject *str2=PyUnicode_FromObject(obj);
3707
if(strbytes>APSW_INT32_MAX)
3709
PyErr_Format(ExcTooBig, "Unicode object is too large - SQLite only supports up to 2GB");
3714
res=sqlite3_bind_text16(self->statement, arg, strdata, (int)strbytes, SQLITE_TRANSIENT);
3716
res=sqlite3_bind_text(self->statement, arg, strdata, (int)strbytes, SQLITE_TRANSIENT);
3723
assert(PyErr_Occurred());
3729
if(lenval>APSW_INT32_MAX)
3731
PyErr_Format(ExcTooBig, "String object is too large - SQLite only supports up to 2GB");
3734
res=sqlite3_bind_text(self->statement, arg, val, (int)lenval, SQLITE_TRANSIENT);
3737
else if (PyBuffer_Check(obj))
3741
if(PyObject_AsCharBuffer(obj, &buffer, &buflen))
3743
if (buflen>APSW_INT32_MAX)
3745
PyErr_Format(ExcTooBig, "Binding object is too large - SQLite only supports up to 2GB");
3748
res=sqlite3_bind_blob(self->statement, arg, buffer, (int)buflen, SQLITE_TRANSIENT);
3752
PyObject *strrep=PyObject_Str(obj);
3753
PyErr_Format(PyExc_TypeError, "Bad binding argument type supplied - argument #%d: %s", (int)(arg+self->bindingsoffset), strrep?PyString_AsString(strrep):"<str failed>");
3759
SET_EXC(self->connection->db, res);
3762
if(PyErr_Occurred())
3767
/* internal function */
3769
Cursor_dobindings(Cursor *self)
3771
int nargs, arg, res, sz=0;
3774
if(PyErr_Occurred())
3777
assert(self->bindingsoffset>=0);
3779
nargs=sqlite3_bind_parameter_count(self->statement);
3781
if (nargs>0 && !self->bindings)
3783
PyErr_Format(ExcBindings, "Statement has %d bindings but you didn't supply any!", nargs);
3788
if (self->bindings && PyDict_Check(self->bindings))
3790
for(arg=1;arg<=nargs;arg++)
3792
PyObject *keyo=NULL;
3793
const char *key=sqlite3_bind_parameter_name(self->statement, arg);
3797
PyErr_Format(ExcBindings, "Binding %d has no name, but you supplied a dict (which only has names).", arg-1);
3801
assert(*key==':' || *key=='$');
3802
key++; /* first char is a colon or dollar which we skip */
3804
keyo=PyUnicode_DecodeUTF8(key, strlen(key), NULL);
3805
if(!keyo) return -1;
3807
obj=PyDict_GetItem(self->bindings, keyo);
3811
/* this is where we could error on missing keys */
3813
if(Cursor_dobinding(self,arg,obj))
3815
assert(PyErr_Occurred());
3823
/* it must be a fast sequence */
3824
/* verify the number of args supplied */
3826
sz=PySequence_Fast_GET_SIZE(self->bindings);
3827
/* there is another statement after this one ... */
3828
if(*self->zsqlnextpos && sz-self->bindingsoffset<nargs)
3830
PyErr_Format(ExcBindings, "Incorrect number of bindings supplied. The current statement uses %d and there are only %d left. Current offset is %d",
3831
nargs, (self->bindings)?sz:0, (int)(self->bindingsoffset));
3834
/* no more statements */
3835
if(!*self->zsqlnextpos && sz-self->bindingsoffset!=nargs)
3837
PyErr_Format(ExcBindings, "Incorrect number of bindings supplied. The current statement uses %d and there are %d supplied. Current offset is %d",
3838
nargs, (self->bindings)?sz:0, (int)(self->bindingsoffset));
3844
/* nb sqlite starts bind args at one not zero */
3845
for(arg=1;arg<=nargs;arg++)
3847
obj=PySequence_Fast_GET_ITEM(self->bindings, arg-1+self->bindingsoffset);
3848
if(Cursor_dobinding(self, arg, obj))
3850
assert(PyErr_Occurred());
3855
self->bindingsoffset+=nargs;
3861
const char *previouszsqlpos; /* where the begining of the statement was */
3862
Py_ssize_t savedbindingsoffset; /* where the bindings began */
3863
} exectrace_oldstate;
3866
Cursor_doexectrace(Cursor *self, exectrace_oldstate *etos)
3868
PyObject *retval=NULL;
3869
PyObject *args=NULL;
3870
PyObject *sqlcmd=NULL;
3871
PyObject *bindings=NULL;
3874
assert(self->exectrace);
3876
/* make a string of the command */
3877
sqlcmd=convertutf8stringsize(etos->previouszsqlpos, self->zsqlnextpos-etos->previouszsqlpos);
3879
if(!sqlcmd) return -1;
3881
/* now deal with the bindings */
3884
if(PyDict_Check(self->bindings))
3886
bindings=self->bindings;
3887
Py_INCREF(self->bindings);
3891
bindings=PySequence_GetSlice(self->bindings, etos->savedbindingsoffset, self->bindingsoffset);
3894
/* I couldn't work anything into the test suite to actually make this fail! */
3903
Py_INCREF(bindings);
3905
args=Py_BuildValue("(NN)", sqlcmd, bindings); /* owns sqlcmd and bindings now */
3909
Py_DECREF(bindings);
3913
retval=PyEval_CallObject(self->exectrace, args);
3917
assert(PyErr_Occurred());
3920
result=PyObject_IsTrue(retval);
3922
assert (result==-1 || result==0 || result ==1);
3925
assert(PyErr_Occurred());
3931
/* callback didn't want us to continue */
3932
PyErr_Format(ExcTraceAbort, "Aborted by false/null return value of exec tracer");
3937
Cursor_dorowtrace(Cursor *self, PyObject *retval)
3939
assert(self->rowtrace);
3941
retval=PyEval_CallObject(self->rowtrace, retval);
3948
/* Returns a borrowed reference to self if all is ok, else NULL on error */
3950
Cursor_step(Cursor *self)
3953
exectrace_oldstate etos;
3955
if(self->status==C_DONE)
3957
PyErr_Format(ExcComplete, "The statement(s) have finished or errored, so you can't keep running them");
3963
assert(!PyErr_Occurred());
3964
Py_BEGIN_ALLOW_THREADS
3965
res=(self->statement)?(sqlite3_step(self->statement)):(SQLITE_DONE);
3966
Py_END_ALLOW_THREADS;
3971
/* this would be an error in apsw itself */
3972
self->status=C_DONE;
3973
SET_EXC(self->connection->db,res);
3974
resetcursor(self, 0);
3979
return (PyErr_Occurred())?(NULL):((PyObject*)self);
3982
if (PyErr_Occurred())
3984
self->status=C_DONE;
3991
/* This is typically because a cached statement has become
3992
invalid. We figure this out by re-preparing. See SQLite
3996
sqlite3_stmt *newstmt;
3997
res=statementcache_dup(self->connection->stmtcache, self->statement, &newstmt);
4000
assert(res==SQLITE_OK);
4001
sqlite3_transfer_bindings(self->statement, newstmt);
4002
statementcache_finalize(self->connection->stmtcache, self->statement);
4003
self->statement=newstmt;
4006
SET_EXC(self->connection->db,res);
4007
self->status=C_DONE;
4008
resetcursor(self, 0); /* we have handled error */
4012
default: /* sqlite3_prepare_v2 introduced in 3.3.9 means the
4013
error code is returned from step as well as
4016
case SQLITE_ERROR: /* SQLITE_BUSY is handled here as well */
4017
/* there was an error - we need to get actual error code from sqlite3_finalize */
4018
self->status=C_DONE;
4019
res=resetcursor(self, 0); /* this will get the error code for us */
4020
assert(res!=SQLITE_OK);
4025
assert(res==SQLITE_DONE);
4027
/* done with that statement, are there any more? */
4028
self->status=C_DONE;
4029
if(!self->zsqlnextpos || !*self->zsqlnextpos)
4034
/* no more so we finalize */
4035
if(resetcursor(self, 0)!=SQLITE_OK)
4037
assert(PyErr_Occurred());
4038
return NULL; /* exception */
4040
return (PyObject*)self;
4042
next=PyIter_Next(self->emiter);
4043
if(PyErr_Occurred())
4047
/* no more from executemanyiter so we finalize */
4048
if(resetcursor(self, 0)!=SQLITE_OK)
4050
assert(PyErr_Occurred());
4053
return (PyObject*)self;
4055
self->zsqlnextpos=self->zsql; /* start at begining of string again */
4056
/* don't need bindings from last round if emiter.next() */
4057
Py_XDECREF(self->bindings);
4059
self->bindingsoffset=0;
4060
/* verify type of next before putting in bindings */
4061
if(PyDict_Check(next))
4062
self->bindings=next;
4065
self->bindings=PySequence_Fast(next, "You must supply a dict or a sequence");
4066
/* we no longer need next irrespective of what happens in line above */
4071
assert(self->bindings);
4074
/* finalise and go again */
4075
res=statementcache_finalize(self->connection->stmtcache, self->statement);
4077
SET_EXC(self->connection->db,res);
4080
assert((res&0xff)!=SQLITE_BUSY); /* finalize shouldn't be returning busy, only step */
4084
assert(!self->statement);
4087
etos.previouszsqlpos=self->zsqlnextpos;
4088
etos.savedbindingsoffset=self->bindingsoffset;
4090
assert(!PyErr_Occurred());
4091
res=statementcache_prepare(self->connection->stmtcache, self->connection->db, self->zsqlnextpos, -1, &self->statement, &self->zsqlnextpos);
4092
SET_EXC(self->connection->db,res);
4095
assert((res&0xff)!=SQLITE_BUSY); /* prepare definitely shouldn't be returning busy */
4098
assert(!PyErr_Occurred());
4099
if(Cursor_dobindings(self))
4101
assert(PyErr_Occurred());
4107
if(Cursor_doexectrace(self, &etos))
4109
assert(self->status==C_DONE);
4110
assert(PyErr_Occurred());
4114
assert(self->status==C_DONE);
4115
self->status=C_BEGIN;
4118
/* you can't actually get here */
4124
Cursor_execute(Cursor *self, PyObject *args)
4127
PyObject *retval=NULL;
4128
exectrace_oldstate etos;
4130
CHECK_THREAD(self->connection, NULL);
4131
CHECK_CLOSED(self->connection, NULL);
4133
res=resetcursor(self, 0);
4136
assert(PyErr_Occurred());
4140
assert(!self->bindings);
4142
if(!PyArg_ParseTuple(args, "es|O:execute(statements,bindings=())", STRENCODING, &self->zsql, &self->bindings))
4147
if(PyDict_Check(self->bindings))
4148
Py_INCREF(self->bindings);
4151
self->bindings=PySequence_Fast(self->bindings, "You must supply a dict or a sequence");
4157
assert(!self->statement);
4160
etos.previouszsqlpos=self->zsql;
4161
etos.savedbindingsoffset=0;
4163
assert(!PyErr_Occurred());
4164
res=statementcache_prepare(self->connection->stmtcache, self->connection->db, self->zsql, -1, &self->statement, &self->zsqlnextpos);
4165
SET_EXC(self->connection->db,res);
4168
AddTraceBackHere(__FILE__, __LINE__, "Cursor_execute.sqlite3_prepare_v2", "{s: O, s: N}",
4169
"Connection", self->connection,
4170
"statement", PyUnicode_DecodeUTF8(self->zsql, strlen(self->zsql), "strict"));
4173
assert(!PyErr_Occurred());
4175
self->bindingsoffset=0;
4176
if(Cursor_dobindings(self))
4178
assert(PyErr_Occurred());
4184
if(Cursor_doexectrace(self, &etos))
4186
assert(PyErr_Occurred());
4191
self->status=C_BEGIN;
4193
retval=Cursor_step(self);
4196
assert(PyErr_Occurred());
4204
Cursor_executemany(Cursor *self, PyObject *args)
4207
PyObject *retval=NULL;
4208
PyObject *theiterable=NULL;
4209
PyObject *next=NULL;
4210
exectrace_oldstate etos;
4212
CHECK_THREAD(self->connection, NULL);
4213
CHECK_CLOSED(self->connection, NULL);
4215
res=resetcursor(self, 0);
4218
assert(PyErr_Occurred());
4222
assert(!self->bindings);
4223
assert(!self->emiter);
4224
assert(!self->zsql);
4225
assert(self->status=C_DONE);
4227
if(!PyArg_ParseTuple(args, "esO:executemany(statements, sequenceofbindings)", STRENCODING, &self->zsql, &theiterable))
4230
self->emiter=PyObject_GetIter(theiterable);
4233
PyErr_Format(PyExc_TypeError, "2nd parameter must be iterable");
4237
next=PyIter_Next(self->emiter);
4238
if(!next && PyErr_Occurred())
4244
return (PyObject*)self;
4247
if(PyDict_Check(next))
4248
self->bindings=next;
4251
self->bindings=PySequence_Fast(next, "You must supply a dict or a sequence");
4252
Py_DECREF(next); /* _Fast makes new reference */
4257
assert(!self->statement);
4260
etos.previouszsqlpos=self->zsql;
4261
etos.savedbindingsoffset=0;
4263
assert(!PyErr_Occurred());
4264
res=statementcache_prepare(self->connection->stmtcache, self->connection->db, self->zsql, -1, &self->statement, &self->zsqlnextpos);
4265
SET_EXC(self->connection->db,res);
4268
assert(!PyErr_Occurred());
4270
self->bindingsoffset=0;
4271
if(Cursor_dobindings(self))
4273
assert(PyErr_Occurred());
4279
if(Cursor_doexectrace(self, &etos))
4281
assert(PyErr_Occurred());
4286
self->status=C_BEGIN;
4288
retval=Cursor_step(self);
4291
assert(PyErr_Occurred());
4299
Cursor_close(Cursor *self, PyObject *args)
4304
CHECK_THREAD(self->connection, NULL);
4305
if (!self->connection->db) /* if connection is closed, then we must also be closed */
4306
return Py_BuildValue("");
4308
if(!PyArg_ParseTuple(args, "|i:close(force=False)", &force))
4311
res=resetcursor(self, force);
4314
assert(PyErr_Occurred());
4318
return Py_BuildValue("");
4322
Cursor_next(Cursor *self)
4329
CHECK_THREAD(self->connection, NULL);
4330
CHECK_CLOSED(self->connection, NULL);
4333
if(self->status==C_BEGIN)
4334
if(!Cursor_step(self))
4336
assert(PyErr_Occurred());
4339
if(self->status==C_DONE)
4342
assert(self->status==C_ROW);
4344
self->status=C_BEGIN;
4346
/* DUPLICATE(ish) code: this is substantially similar to the code in
4347
convert_value_to_pyobject. If you fix anything here then do it
4350
/* return the row of data */
4351
numcols=sqlite3_data_count(self->statement);
4352
retval=PyTuple_New(numcols);
4356
for(i=0;i<numcols;i++)
4358
item=convert_value_to_pyobject(sqlite3_column_value(self->statement, i));
4361
PyTuple_SET_ITEM(retval, i, item);
4365
PyObject *r2=Cursor_dorowtrace(self, retval);
4380
Cursor_iter(Cursor *self)
4382
CHECK_THREAD(self->connection, NULL);
4383
CHECK_CLOSED(self->connection, NULL);
4386
return (PyObject*)self;
4390
Cursor_setexectrace(Cursor *self, PyObject *func)
4392
CHECK_THREAD(self->connection, NULL);
4393
CHECK_CLOSED(self->connection, NULL);
4395
if(func!=Py_None && !PyCallable_Check(func))
4397
PyErr_SetString(PyExc_TypeError, "parameter must be callable");
4404
Py_XDECREF(self->exectrace);
4405
self->exectrace=(func!=Py_None)?func:NULL;
4407
return Py_BuildValue("");
4411
Cursor_setrowtrace(Cursor *self, PyObject *func)
4413
CHECK_THREAD(self->connection, NULL);
4414
CHECK_CLOSED(self->connection, NULL);
4416
if(func!=Py_None && !PyCallable_Check(func))
4418
PyErr_SetString(PyExc_TypeError, "parameter must be callable");
4425
Py_XDECREF(self->rowtrace);
4426
self->rowtrace=(func!=Py_None)?func:NULL;
4428
return Py_BuildValue("");
4432
Cursor_getexectrace(Cursor *self)
4436
CHECK_THREAD(self->connection, NULL);
4437
CHECK_CLOSED(self->connection, NULL);
4439
ret=(self->exectrace)?(self->exectrace):Py_None;
4445
Cursor_getrowtrace(Cursor *self)
4448
CHECK_THREAD(self->connection, NULL);
4449
CHECK_CLOSED(self->connection, NULL);
4450
ret =(self->rowtrace)?(self->rowtrace):Py_None;
4456
Cursor_getconnection(Cursor *self)
4458
CHECK_THREAD(self->connection, NULL);
4459
CHECK_CLOSED(self->connection, NULL);
4461
Py_INCREF(self->connection);
4462
return (PyObject*)self->connection;
4465
static PyMethodDef Cursor_methods[] = {
4466
{"execute", (PyCFunction)Cursor_execute, METH_VARARGS,
4467
"Executes one or more statements" },
4468
{"executemany", (PyCFunction)Cursor_executemany, METH_VARARGS,
4469
"Repeatedly executes statements on sequence" },
4470
{"next", (PyCFunction)Cursor_next, METH_NOARGS,
4471
"Returns next row returned from query"},
4472
{"setexectrace", (PyCFunction)Cursor_setexectrace, METH_O,
4473
"Installs a function called for every statement executed"},
4474
{"setrowtrace", (PyCFunction)Cursor_setrowtrace, METH_O,
4475
"Installs a function called for every row returned"},
4476
{"getexectrace", (PyCFunction)Cursor_getexectrace, METH_NOARGS,
4477
"Returns the current exec tracer function"},
4478
{"getrowtrace", (PyCFunction)Cursor_getrowtrace, METH_NOARGS,
4479
"Returns the current row tracer function"},
4480
{"getrowtrace", (PyCFunction)Cursor_getrowtrace, METH_NOARGS,
4481
"Returns the current row tracer function"},
4482
{"getconnection", (PyCFunction)Cursor_getconnection, METH_NOARGS,
4483
"Returns the connection object for this cursor"},
4484
{"getdescription", (PyCFunction)Cursor_getdescription, METH_NOARGS,
4485
"Returns the description for the current row"},
4486
{"close", (PyCFunction)Cursor_close, METH_VARARGS,
4487
"Closes the cursor" },
4488
{0, 0, 0, 0} /* Sentinel */
4492
static PyTypeObject CursorType = {
4493
PyObject_HEAD_INIT(NULL)
4495
"apsw.Cursor", /*tp_name*/
4496
sizeof(Cursor), /*tp_basicsize*/
4498
(destructor)Cursor_dealloc, /*tp_dealloc*/
4505
0, /*tp_as_sequence*/
4506
0, /*tp_as_mapping*/
4513
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_ITER , /*tp_flags*/
4514
"Cursor object", /* tp_doc */
4515
0, /* tp_traverse */
4517
0, /* tp_richcompare */
4518
0, /* tp_weaklistoffset */
4519
(getiterfunc)Cursor_iter, /* tp_iter */
4520
(iternextfunc)Cursor_next, /* tp_iternext */
4521
Cursor_methods, /* tp_methods */
4526
0, /* tp_descr_get */
4527
0, /* tp_descr_set */
4528
0, /* tp_dictoffset */
4537
0, /* tp_subclasses */
4538
0, /* tp_weaklist */
4542
/* MODULE METHODS */
4544
getsqliteversion(void)
4546
return PyString_FromString(sqlite3_libversion());
4550
getapswversion(void)
4552
return PyString_FromString(APSW_VERSION);
4556
enablesharedcache(PyObject *self, PyObject *args)
4559
if(!PyArg_ParseTuple(args, "i:enablesharedcache(boolean)", &setting))
4562
res=sqlite3_enable_shared_cache(setting);
4568
return Py_BuildValue("");
4571
static PyMethodDef module_methods[] = {
4572
{"sqlitelibversion", (PyCFunction)getsqliteversion, METH_NOARGS,
4573
"Return the version of the SQLite library"},
4574
{"apswversion", (PyCFunction)getapswversion, METH_NOARGS,
4575
"Return the version of the APSW wrapper"},
4576
{"enablesharedcache", (PyCFunction)enablesharedcache, METH_VARARGS,
4577
"Sets shared cache semantics for this thread"},
4579
{0, 0, 0, 0} /* Sentinel */
4584
#ifndef PyMODINIT_FUNC /* declarations for DLL import/export */
4585
#define PyMODINIT_FUNC void
4594
assert(sizeof(int)==4); /* we expect 32 bit ints */
4595
assert(sizeof(long long)==8); /* we expect 64 bit long long */
4597
if (PyType_Ready(&ConnectionType) < 0)
4600
if (PyType_Ready(&CursorType) < 0)
4603
/* ensure threads are available */
4604
PyEval_InitThreads();
4607
m = apswmodule = Py_InitModule3("apsw", module_methods,
4608
"Another Python SQLite Wrapper.");
4610
if (m == NULL) return;
4612
if(init_exceptions(m)) return;
4614
Py_INCREF(&ConnectionType);
4615
PyModule_AddObject(m, "Connection", (PyObject *)&ConnectionType);
4617
/* we don't add cursor to the module since users shouldn't be able to instantiate them directly */
4619
hooks=PyList_New(0);
4621
PyModule_AddObject(m, "connection_hooks", hooks);
4624
/* add in some constants and also put them in a corresponding mapping dictionary */
4626
#define ADDINT(v) PyModule_AddObject(m, #v, Py_BuildValue("i", v)); \
4627
PyDict_SetItemString(thedict, #v, Py_BuildValue("i", v)); \
4628
PyDict_SetItem(thedict, Py_BuildValue("i", v), Py_BuildValue("s", #v));
4630
thedict=PyDict_New();
4631
if(!thedict) return;
4633
ADDINT(SQLITE_DENY);
4634
ADDINT(SQLITE_IGNORE);
4637
PyModule_AddObject(m, "mapping_authorizer_return", thedict);
4639
/* authorizer functions */
4640
thedict=PyDict_New();
4641
if(!thedict) return;
4643
ADDINT(SQLITE_CREATE_INDEX);
4644
ADDINT(SQLITE_CREATE_TABLE);
4645
ADDINT(SQLITE_CREATE_TEMP_INDEX);
4646
ADDINT(SQLITE_CREATE_TEMP_TABLE);
4647
ADDINT(SQLITE_CREATE_TEMP_TRIGGER);
4648
ADDINT(SQLITE_CREATE_TEMP_VIEW);
4649
ADDINT(SQLITE_CREATE_TRIGGER);
4650
ADDINT(SQLITE_CREATE_VIEW);
4651
ADDINT(SQLITE_DELETE);
4652
ADDINT(SQLITE_DROP_INDEX);
4653
ADDINT(SQLITE_DROP_TABLE);
4654
ADDINT(SQLITE_DROP_TEMP_INDEX);
4655
ADDINT(SQLITE_DROP_TEMP_TABLE);
4656
ADDINT(SQLITE_DROP_TEMP_TRIGGER);
4657
ADDINT(SQLITE_DROP_TEMP_VIEW);
4658
ADDINT(SQLITE_DROP_TRIGGER);
4659
ADDINT(SQLITE_DROP_VIEW);
4660
ADDINT(SQLITE_INSERT);
4661
ADDINT(SQLITE_PRAGMA);
4662
ADDINT(SQLITE_READ);
4663
ADDINT(SQLITE_SELECT);
4664
ADDINT(SQLITE_TRANSACTION);
4665
ADDINT(SQLITE_UPDATE);
4666
ADDINT(SQLITE_ATTACH);
4667
ADDINT(SQLITE_DETACH);
4668
ADDINT(SQLITE_ALTER_TABLE);
4669
ADDINT(SQLITE_REINDEX);
4670
ADDINT(SQLITE_COPY);
4671
ADDINT(SQLITE_ANALYZE);
4672
ADDINT(SQLITE_CREATE_VTABLE);
4673
ADDINT(SQLITE_DROP_VTABLE);
4674
ADDINT(SQLITE_FUNCTION);
4676
PyModule_AddObject(m, "mapping_authorizer_function", thedict);
4678
/* Version number */
4679
PyModule_AddObject(m, "SQLITE_VERSION_NUMBER", Py_BuildValue("i", SQLITE_VERSION_NUMBER));
4681
/* vtable best index constraints */
4682
#if defined(SQLITE_INDEX_CONSTRAINT_EQ) && defined(SQLITE_INDEX_CONSTRAINT_MATCH)
4684
thedict=PyDict_New();
4685
if(!thedict) return;
4687
ADDINT(SQLITE_INDEX_CONSTRAINT_EQ);
4688
ADDINT(SQLITE_INDEX_CONSTRAINT_GT);
4689
ADDINT(SQLITE_INDEX_CONSTRAINT_LE);
4690
ADDINT(SQLITE_INDEX_CONSTRAINT_LT);
4691
ADDINT(SQLITE_INDEX_CONSTRAINT_GE);
4692
ADDINT(SQLITE_INDEX_CONSTRAINT_MATCH);
4694
PyModule_AddObject(m, "mapping_bestindex_constraints", thedict);
4696
#endif /* constraints */
4698
/* extendended result codes */
4699
thedict=PyDict_New();
4700
if(!thedict) return;
4702
ADDINT(SQLITE_IOERR_READ);
4703
ADDINT(SQLITE_IOERR_SHORT_READ);
4704
ADDINT(SQLITE_IOERR_WRITE);
4705
ADDINT(SQLITE_IOERR_FSYNC);
4706
ADDINT(SQLITE_IOERR_DIR_FSYNC);
4707
ADDINT(SQLITE_IOERR_TRUNCATE);
4708
ADDINT(SQLITE_IOERR_FSTAT);
4709
ADDINT(SQLITE_IOERR_UNLOCK);
4710
ADDINT(SQLITE_IOERR_RDLOCK);
4711
PyModule_AddObject(m, "mapping_extended_result_codes", thedict);
4714
thedict=PyDict_New();
4715
if(!thedict) return;
4718
ADDINT(SQLITE_ERROR);
4719
ADDINT(SQLITE_INTERNAL);
4720
ADDINT(SQLITE_PERM);
4721
ADDINT(SQLITE_ABORT);
4722
ADDINT(SQLITE_BUSY);
4723
ADDINT(SQLITE_LOCKED);
4724
ADDINT(SQLITE_NOMEM);
4725
ADDINT(SQLITE_READONLY);
4726
ADDINT(SQLITE_INTERRUPT);
4727
ADDINT(SQLITE_IOERR);
4728
ADDINT(SQLITE_CORRUPT);
4729
ADDINT(SQLITE_FULL);
4730
ADDINT(SQLITE_CANTOPEN);
4731
ADDINT(SQLITE_PROTOCOL);
4732
ADDINT(SQLITE_EMPTY);
4733
ADDINT(SQLITE_SCHEMA);
4734
ADDINT(SQLITE_CONSTRAINT);
4735
ADDINT(SQLITE_MISMATCH);
4736
ADDINT(SQLITE_MISUSE);
4737
ADDINT(SQLITE_NOLFS);
4738
ADDINT(SQLITE_AUTH);
4739
ADDINT(SQLITE_FORMAT);
4740
ADDINT(SQLITE_RANGE);
4741
ADDINT(SQLITE_NOTADB);
4743
PyModule_AddObject(m, "mapping_result_codes", thedict);