2 +++ b/ext/sqlite/config.m4
5 +dnl config.m4 for extension sqlite
8 +PHP_ARG_WITH(sqlite, for sqlite support,
9 +[ --without-sqlite=DIR Do not include sqlite support. DIR is the sqlite base
10 + install directory [BUNDLED]], yes)
12 +PHP_ARG_ENABLE(sqlite-utf8, whether to enable UTF-8 support in sqlite (default: ISO-8859-1),
13 +[ --enable-sqlite-utf8 SQLite: Enable UTF-8 support for SQLite], no, no)
20 +dnl Search for lemon binary and check its version
22 +AC_DEFUN([PHP_PROG_LEMON],[
23 + # we only support certain lemon versions
24 + lemon_version_list="1.0"
26 + AC_CHECK_PROG(LEMON, lemon, lemon)
27 + if test "$LEMON"; then
28 + AC_CACHE_CHECK([for lemon version], php_cv_lemon_version, [
29 + lemon_version=`$LEMON -x 2>/dev/null | $SED -e 's/^.* //'`
30 + php_cv_lemon_version=invalid
31 + for lemon_check_version in $lemon_version_list; do
32 + if test "$lemon_version" = "$lemon_check_version"; then
33 + php_cv_lemon_version="$lemon_check_version (ok)"
40 + case $php_cv_lemon_version in
42 + lemon_msg="lemon versions supported for regeneration of libsqlite parsers: $lemon_version_list (found: $lemon_version)."
43 + AC_MSG_WARN([$lemon_msg])
51 +if test "$PHP_SQLITE" != "no"; then
52 + if test "$PHP_PDO" != "no"; then
53 + PHP_CHECK_PDO_INCLUDES([], [AC_MSG_WARN([Cannot find php_pdo_driver.h.])])
54 + if test -n "$pdo_inc_path"; then
55 + AC_DEFINE([PHP_SQLITE2_HAVE_PDO], [1], [Have PDO])
56 + pdo_inc_path="-I$pdo_inc_path"
60 + if test "$PHP_SQLITE" != "yes"; then
61 + SEARCH_PATH="/usr/local /usr"
62 + SEARCH_FOR="/include/sqlite.h"
63 + if test -r $PHP_SQLITE/; then # path given as parameter
64 + SQLITE_DIR=$PHP_SQLITE
65 + else # search default path list
66 + AC_MSG_CHECKING([for sqlite files in default path])
67 + for i in $SEARCH_PATH ; do
68 + if test -r $i/$SEARCH_FOR; then
70 + AC_MSG_RESULT(found in $i)
75 + if test -z "$SQLITE_DIR"; then
76 + AC_MSG_RESULT([not found])
77 + AC_MSG_ERROR([Please reinstall the sqlite distribution from http://www.sqlite.org])
80 + PHP_CHECK_LIBRARY(sqlite, sqlite_open, [
81 + PHP_ADD_LIBRARY_WITH_PATH(sqlite, $SQLITE_DIR/$PHP_LIBDIR, SQLITE_SHARED_LIBADD)
82 + PHP_ADD_INCLUDE($SQLITE_DIR/include)
84 + AC_MSG_ERROR([wrong sqlite lib version or lib not found])
86 + -L$SQLITE_DIR/$PHP_LIBDIR -lm
88 + SQLITE_MODULE_TYPE=external
89 + PHP_SQLITE_CFLAGS=$pdo_inc_path
90 + sqlite_extra_sources="libsqlite/src/encode.c"
92 + # use bundled library
94 + SQLITE_MODULE_TYPE=builtin
95 + PHP_SQLITE_CFLAGS="-I@ext_srcdir@/libsqlite/src -I@ext_builddir@/libsqlite/src $pdo_inc_path"
96 + sqlite_extra_sources="libsqlite/src/opcodes.c \
97 + libsqlite/src/parse.c libsqlite/src/encode.c \
98 + libsqlite/src/auth.c libsqlite/src/btree.c libsqlite/src/build.c \
99 + libsqlite/src/delete.c libsqlite/src/expr.c libsqlite/src/func.c \
100 + libsqlite/src/hash.c libsqlite/src/insert.c libsqlite/src/main.c \
101 + libsqlite/src/os.c libsqlite/src/pager.c \
102 + libsqlite/src/printf.c libsqlite/src/random.c \
103 + libsqlite/src/select.c libsqlite/src/table.c libsqlite/src/tokenize.c \
104 + libsqlite/src/update.c libsqlite/src/util.c libsqlite/src/vdbe.c \
105 + libsqlite/src/attach.c libsqlite/src/btree_rb.c libsqlite/src/pragma.c \
106 + libsqlite/src/vacuum.c libsqlite/src/copy.c \
107 + libsqlite/src/vdbeaux.c libsqlite/src/date.c \
108 + libsqlite/src/where.c libsqlite/src/trigger.c"
111 + dnl Common for both bundled/external
113 + sqlite_sources="sqlite.c sess_sqlite.c pdo_sqlite2.c $sqlite_extra_sources"
114 + PHP_NEW_EXTENSION(sqlite, $sqlite_sources, $ext_shared,,$PHP_SQLITE_CFLAGS)
115 + PHP_ADD_EXTENSION_DEP(sqlite, spl, true)
116 + PHP_ADD_EXTENSION_DEP(sqlite, pdo, true)
118 + PHP_ADD_MAKEFILE_FRAGMENT
119 + PHP_SUBST(SQLITE_SHARED_LIBADD)
120 + PHP_INSTALL_HEADERS([$ext_builddir/libsqlite/src/sqlite.h])
122 + if test "$SQLITE_MODULE_TYPE" = "builtin"; then
123 + PHP_ADD_BUILD_DIR($ext_builddir/libsqlite/src, 1)
124 + AC_CHECK_SIZEOF(char *, 4)
125 + AC_DEFINE(SQLITE_PTR_SZ, SIZEOF_CHAR_P, [Size of a pointer])
126 + dnl use latin 1 for SQLite older than 2.8.9; the utf-8 handling
127 + dnl in funcs.c uses assert(), which is a bit silly and something
128 + dnl we want to avoid. This assert() was removed in SQLite 2.8.9.
129 + if test "$PHP_SQLITE_UTF8" = "yes"; then
130 + SQLITE_ENCODING="UTF8"
131 + AC_DEFINE(SQLITE_UTF8, 1, [ ])
133 + SQLITE_ENCODING="ISO8859"
135 + PHP_SUBST(SQLITE_ENCODING)
137 + SQLITE_VERSION=`cat $ext_srcdir/libsqlite/VERSION`
138 + PHP_SUBST(SQLITE_VERSION)
140 + sed -e s/--VERS--/$SQLITE_VERSION/ -e s/--ENCODING--/$SQLITE_ENCODING/ $ext_srcdir/libsqlite/src/sqlite.h.in > $ext_builddir/libsqlite/src/sqlite.h
142 + if test "$ext_shared" = "no" || test "$ext_srcdir" != "$abs_srcdir"; then
143 + echo '#include <php_config.h>' > $ext_builddir/libsqlite/src/config.h
145 + echo "#include \"$abs_builddir/config.h\"" > $ext_builddir/libsqlite/src/config.h
148 + cat >> $ext_builddir/libsqlite/src/config.h <<EOF
150 +# define THREADSAFE 1
158 + AC_CHECK_FUNCS(usleep nanosleep)
159 + AC_CHECK_HEADERS(time.h)
162 +++ b/ext/sqlite/config.w32
165 +// vim:ft=javascript
167 +ARG_WITH("sqlite", "SQLite support", "no");
169 +if (PHP_SQLITE != "no") {
170 + copy_and_subst(configure_module_dirname + "\\libsqlite\\src\\sqlite.h.in",
171 + configure_module_dirname + "\\libsqlite\\src\\sqlite.h", new Array(
172 + "--VERS--", file_get_contents(configure_module_dirname + "\\libsqlite\\VERSION").replace(new RegExp("[\r\n]+", "g"), ""),
173 + "--ENCODING--", "ISO8859"
176 + FSO.CopyFile(configure_module_dirname + "\\libsqlite\\src\\sqlite_config.w32.h",
177 + configure_module_dirname + "\\libsqlite\\src\\config.h");
179 + if (FSO.FileExists(configure_module_dirname + "\\..\\pdo\\php_pdo_driver.h")) {
180 + PHP_SQLITE2_PDO_CFLAGS = " /DPHP_SQLITE2_HAVE_PDO=1 /I " + configure_module_dirname + "\\..";
181 + ADD_EXTENSION_DEP('sqlite', 'pdo')
183 + PHP_SQLITE2_PDO_CFLAGS = "";
186 + EXTENSION("sqlite", "sqlite.c sess_sqlite.c pdo_sqlite2.c", null,
187 + "/D PHP_SQLITE_EXPORTS /I " + configure_module_dirname + "/libsqlite/src" +
188 + PHP_SQLITE2_PDO_CFLAGS);
191 + ADD_SOURCES(configure_module_dirname + "/libsqlite/src", "opcodes.c parse.c encode.c \
192 + auth.c btree.c build.c delete.c expr.c func.c hash.c insert.c \
193 + main.c os.c pager.c printf.c random.c select.c table.c tokenize.c \
194 + update.c util.c vdbe.c attach.c btree_rb.c pragma.c vacuum.c \
195 + copy.c where.c trigger.c vdbeaux.c date.c", "sqlite");
197 + AC_DEFINE("HAVE_SQLITE", 1, "SQLite support");
198 + if (!PHP_SQLITE_SHARED) {
199 + ADD_DEF_FILE(configure_module_dirname + "\\php_sqlite.def");
201 + ADD_EXTENSION_DEP('sqlite', 'spl')
204 +++ b/ext/sqlite/CREDITS
207 +Wez Furlong, Tal Peer, Marcus Boerger, Ilia Alshanetsky
209 +++ b/ext/sqlite/libsqlite/README
211 +This directory contains source code to
213 + SQLite: An Embeddable SQL Database Engine
215 +To compile the project, first create a directory in which to place
216 +the build products. It is recommended, but not required, that the
217 +build directory be separate from the source directory. Cd into the
218 +build directory and then from the build directory run the configure
219 +script found at the root of the source tree. Then run "make".
223 + tar xzf sqlite.tar.gz ;# Unpack the source tree into "sqlite"
224 + mkdir bld ;# Build will occur in a sibling directory
225 + cd bld ;# Change to the build directory
226 + ../sqlite/configure ;# Run the configure script
227 + make ;# Run the makefile.
229 +The configure script uses autoconf 2.50 and libtool. If the configure
230 +script does not work out for you, there is a generic makefile named
231 +"Makefile.linux-gcc" in the top directory of the source tree that you
232 +can copy and edit to suite your needs. Comments on the generic makefile
233 +show what changes are needed.
235 +The linux binaries on the website are created using the generic makefile,
236 +not the configure script. The configure script is unmaintained. (You
237 +can volunteer to take over maintenance of the configure script, if you want!)
238 +The windows binaries on the website are created using MinGW32 configured
239 +as a cross-compiler running under Linux. For details, see the ./publish.sh
240 +script at the top-level of the source tree.
244 + http://www.sqlite.org/
245 + http://www.hwaci.com/sw/sqlite/
246 + http://groups.yahoo.com/group/sqlite/
249 +++ b/ext/sqlite/libsqlite/src/attach.c
254 +** The author disclaims copyright to this source code. In place of
255 +** a legal notice, here is a blessing:
257 +** May you do good and not evil.
258 +** May you find forgiveness for yourself and forgive others.
259 +** May you share freely, never taking more than you give.
261 +*************************************************************************
262 +** This file contains code used to implement the ATTACH and DETACH commands.
266 +#include "sqliteInt.h"
269 +** This routine is called by the parser to process an ATTACH statement:
271 +** ATTACH DATABASE filename AS dbname
273 +** The pFilename and pDbname arguments are the tokens that define the
274 +** filename and dbname in the ATTACH statement.
276 +void sqliteAttach(Parse *pParse, Token *pFilename, Token *pDbname, Token *pKey){
279 + char *zFile, *zName;
283 + v = sqliteGetVdbe(pParse);
284 + sqliteVdbeAddOp(v, OP_Halt, 0, 0);
285 + if( pParse->explain ) return;
287 + if( db->file_format<4 ){
288 + sqliteErrorMsg(pParse, "cannot attach auxiliary databases to an "
289 + "older format master database", 0);
290 + pParse->rc = SQLITE_ERROR;
293 + if( db->nDb>=MAX_ATTACHED+2 ){
294 + sqliteErrorMsg(pParse, "too many attached databases - max %d",
296 + pParse->rc = SQLITE_ERROR;
301 + sqliteSetNString(&zFile, pFilename->z, pFilename->n, 0);
302 + if( zFile==0 ) return;
303 + sqliteDequote(zFile);
304 +#ifndef SQLITE_OMIT_AUTHORIZATION
305 + if( sqliteAuthCheck(pParse, SQLITE_ATTACH, zFile, 0, 0)!=SQLITE_OK ){
309 +#endif /* SQLITE_OMIT_AUTHORIZATION */
312 + sqliteSetNString(&zName, pDbname->z, pDbname->n, 0);
313 + if( zName==0 ) return;
314 + sqliteDequote(zName);
315 + for(i=0; i<db->nDb; i++){
316 + if( db->aDb[i].zName && sqliteStrICmp(db->aDb[i].zName, zName)==0 ){
317 + sqliteErrorMsg(pParse, "database %z is already in use", zName);
318 + pParse->rc = SQLITE_ERROR;
324 + if( db->aDb==db->aDbStatic ){
325 + aNew = sqliteMalloc( sizeof(db->aDb[0])*3 );
326 + if( aNew==0 ) return;
327 + memcpy(aNew, db->aDb, sizeof(db->aDb[0])*2);
329 + aNew = sqliteRealloc(db->aDb, sizeof(db->aDb[0])*(db->nDb+1) );
330 + if( aNew==0 ) return;
333 + aNew = &db->aDb[db->nDb++];
334 + memset(aNew, 0, sizeof(*aNew));
335 + sqliteHashInit(&aNew->tblHash, SQLITE_HASH_STRING, 0);
336 + sqliteHashInit(&aNew->idxHash, SQLITE_HASH_STRING, 0);
337 + sqliteHashInit(&aNew->trigHash, SQLITE_HASH_STRING, 0);
338 + sqliteHashInit(&aNew->aFKey, SQLITE_HASH_STRING, 1);
339 + aNew->zName = zName;
340 + rc = sqliteBtreeFactory(db, zFile, 0, MAX_PAGES, &aNew->pBt);
342 + sqliteErrorMsg(pParse, "unable to open database: %s", zFile);
344 +#if SQLITE_HAS_CODEC
346 + extern int sqliteCodecAttach(sqlite*, int, void*, int);
349 + if( pKey && pKey->z && pKey->n ){
350 + sqliteSetNString(&zKey, pKey->z, pKey->n, 0);
351 + sqliteDequote(zKey);
352 + nKey = strlen(zKey);
357 + sqliteCodecAttach(db, db->nDb-1, zKey, nKey);
361 + db->flags &= ~SQLITE_Initialized;
362 + if( pParse->nErr ) return;
363 + if( rc==SQLITE_OK ){
364 + rc = sqliteInit(pParse->db, &pParse->zErrMsg);
367 + int i = db->nDb - 1;
369 + if( db->aDb[i].pBt ){
370 + sqliteBtreeClose(db->aDb[i].pBt);
371 + db->aDb[i].pBt = 0;
373 + sqliteResetInternalSchema(db, 0);
375 + pParse->rc = SQLITE_ERROR;
380 +** This routine is called by the parser to process a DETACH statement:
382 +** DETACH DATABASE dbname
384 +** The pDbname argument is the name of the database in the DETACH statement.
386 +void sqliteDetach(Parse *pParse, Token *pDbname){
392 + v = sqliteGetVdbe(pParse);
393 + sqliteVdbeAddOp(v, OP_Halt, 0, 0);
394 + if( pParse->explain ) return;
396 + for(i=0; i<db->nDb; i++){
398 + if( pDb->pBt==0 || pDb->zName==0 ) continue;
399 + if( strlen(pDb->zName)!=pDbname->n ) continue;
400 + if( sqliteStrNICmp(pDb->zName, pDbname->z, pDbname->n)==0 ) break;
403 + sqliteErrorMsg(pParse, "no such database: %T", pDbname);
407 + sqliteErrorMsg(pParse, "cannot detach database %T", pDbname);
410 +#ifndef SQLITE_OMIT_AUTHORIZATION
411 + if( sqliteAuthCheck(pParse,SQLITE_DETACH,db->aDb[i].zName,0,0)!=SQLITE_OK ){
414 +#endif /* SQLITE_OMIT_AUTHORIZATION */
415 + sqliteBtreeClose(pDb->pBt);
417 + sqliteFree(pDb->zName);
418 + sqliteResetInternalSchema(db, i);
419 + if( pDb->pAux && pDb->xFreeAux ) pDb->xFreeAux(pDb->pAux);
422 + db->aDb[i] = db->aDb[db->nDb];
423 + memset(&db->aDb[db->nDb], 0, sizeof(db->aDb[0]));
424 + sqliteResetInternalSchema(db, i);
429 +** Initialize a DbFixer structure. This routine must be called prior
430 +** to passing the structure to one of the sqliteFixAAAA() routines below.
432 +** The return value indicates whether or not fixation is required. TRUE
433 +** means we do need to fix the database references, FALSE means we do not.
436 + DbFixer *pFix, /* The fixer to be initialized */
437 + Parse *pParse, /* Error messages will be written here */
438 + int iDb, /* This is the database that must must be used */
439 + const char *zType, /* "view", "trigger", or "index" */
440 + const Token *pName /* Name of the view, trigger, or index */
444 + if( iDb<0 || iDb==1 ) return 0;
446 + assert( db->nDb>iDb );
447 + pFix->pParse = pParse;
448 + pFix->zDb = db->aDb[iDb].zName;
449 + pFix->zType = zType;
450 + pFix->pName = pName;
455 +** The following set of routines walk through the parse tree and assign
456 +** a specific database to all table references where the database name
457 +** was left unspecified in the original SQL statement. The pFix structure
458 +** must have been initialized by a prior call to sqliteFixInit().
460 +** These routines are used to make sure that an index, trigger, or
461 +** view in one database does not refer to objects in a different database.
462 +** (Exception: indices, triggers, and views in the TEMP database are
463 +** allowed to refer to anything.) If a reference is explicitly made
464 +** to an object in a different database, an error message is added to
465 +** pParse->zErrMsg and these routines return non-zero. If everything
466 +** checks out, these routines return 0.
468 +int sqliteFixSrcList(
469 + DbFixer *pFix, /* Context of the fixation */
470 + SrcList *pList /* The Source list to check and modify */
475 + if( pList==0 ) return 0;
477 + for(i=0; i<pList->nSrc; i++){
478 + if( pList->a[i].zDatabase==0 ){
479 + pList->a[i].zDatabase = sqliteStrDup(zDb);
480 + }else if( sqliteStrICmp(pList->a[i].zDatabase,zDb)!=0 ){
481 + sqliteErrorMsg(pFix->pParse,
482 + "%s %z cannot reference objects in database %s",
483 + pFix->zType, sqliteStrNDup(pFix->pName->z, pFix->pName->n),
484 + pList->a[i].zDatabase);
487 + if( sqliteFixSelect(pFix, pList->a[i].pSelect) ) return 1;
488 + if( sqliteFixExpr(pFix, pList->a[i].pOn) ) return 1;
492 +int sqliteFixSelect(
493 + DbFixer *pFix, /* Context of the fixation */
494 + Select *pSelect /* The SELECT statement to be fixed to one database */
497 + if( sqliteFixExprList(pFix, pSelect->pEList) ){
500 + if( sqliteFixSrcList(pFix, pSelect->pSrc) ){
503 + if( sqliteFixExpr(pFix, pSelect->pWhere) ){
506 + if( sqliteFixExpr(pFix, pSelect->pHaving) ){
509 + pSelect = pSelect->pPrior;
514 + DbFixer *pFix, /* Context of the fixation */
515 + Expr *pExpr /* The expression to be fixed to one database */
518 + if( sqliteFixSelect(pFix, pExpr->pSelect) ){
521 + if( sqliteFixExprList(pFix, pExpr->pList) ){
524 + if( sqliteFixExpr(pFix, pExpr->pRight) ){
527 + pExpr = pExpr->pLeft;
531 +int sqliteFixExprList(
532 + DbFixer *pFix, /* Context of the fixation */
533 + ExprList *pList /* The expression to be fixed to one database */
536 + if( pList==0 ) return 0;
537 + for(i=0; i<pList->nExpr; i++){
538 + if( sqliteFixExpr(pFix, pList->a[i].pExpr) ){
544 +int sqliteFixTriggerStep(
545 + DbFixer *pFix, /* Context of the fixation */
546 + TriggerStep *pStep /* The trigger step be fixed to one database */
549 + if( sqliteFixSelect(pFix, pStep->pSelect) ){
552 + if( sqliteFixExpr(pFix, pStep->pWhere) ){
555 + if( sqliteFixExprList(pFix, pStep->pExprList) ){
558 + pStep = pStep->pNext;
563 +++ b/ext/sqlite/libsqlite/src/auth.c
568 +** The author disclaims copyright to this source code. In place of
569 +** a legal notice, here is a blessing:
571 +** May you do good and not evil.
572 +** May you find forgiveness for yourself and forgive others.
573 +** May you share freely, never taking more than you give.
575 +*************************************************************************
576 +** This file contains code used to implement the sqlite_set_authorizer()
577 +** API. This facility is an optional feature of the library. Embedded
578 +** systems that do not need this facility may omit it by recompiling
579 +** the library with -DSQLITE_OMIT_AUTHORIZATION=1
583 +#include "sqliteInt.h"
586 +** All of the code in this file may be omitted by defining a single
589 +#ifndef SQLITE_OMIT_AUTHORIZATION
592 +** Set or clear the access authorization function.
594 +** The access authorization function is be called during the compilation
595 +** phase to verify that the user has read and/or write access permission on
596 +** various fields of the database. The first argument to the auth function
597 +** is a copy of the 3rd argument to this routine. The second argument
598 +** to the auth function is one of these constants:
601 +** SQLITE_CREATE_INDEX
602 +** SQLITE_CREATE_TABLE
603 +** SQLITE_CREATE_TEMP_INDEX
604 +** SQLITE_CREATE_TEMP_TABLE
605 +** SQLITE_CREATE_TEMP_TRIGGER
606 +** SQLITE_CREATE_TEMP_VIEW
607 +** SQLITE_CREATE_TRIGGER
608 +** SQLITE_CREATE_VIEW
610 +** SQLITE_DROP_INDEX
611 +** SQLITE_DROP_TABLE
612 +** SQLITE_DROP_TEMP_INDEX
613 +** SQLITE_DROP_TEMP_TABLE
614 +** SQLITE_DROP_TEMP_TRIGGER
615 +** SQLITE_DROP_TEMP_VIEW
616 +** SQLITE_DROP_TRIGGER
622 +** SQLITE_TRANSACTION
625 +** The third and fourth arguments to the auth function are the name of
626 +** the table and the column that are being accessed. The auth function
627 +** should return either SQLITE_OK, SQLITE_DENY, or SQLITE_IGNORE. If
628 +** SQLITE_OK is returned, it means that access is allowed. SQLITE_DENY
629 +** means that the SQL statement will never-run - the sqlite_exec() call
630 +** will return with an error. SQLITE_IGNORE means that the SQL statement
631 +** should run but attempts to read the specified column will return NULL
632 +** and attempts to write the column will be ignored.
634 +** Setting the auth function to NULL disables this hook. The default
635 +** setting of the auth function is NULL.
637 +int sqlite_set_authorizer(
639 + int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
643 + db->pAuthArg = pArg;
648 +** Write an error message into pParse->zErrMsg that explains that the
649 +** user-supplied authorization function returned an illegal value.
651 +static void sqliteAuthBadReturnCode(Parse *pParse, int rc){
652 + sqliteErrorMsg(pParse, "illegal return value (%d) from the "
653 + "authorization function - should be SQLITE_OK, SQLITE_IGNORE, "
654 + "or SQLITE_DENY", rc);
655 + pParse->rc = SQLITE_MISUSE;
659 +** The pExpr should be a TK_COLUMN expression. The table referred to
660 +** is in pTabList or else it is the NEW or OLD table of a trigger.
661 +** Check to see if it is OK to read this particular column.
663 +** If the auth function returns SQLITE_IGNORE, change the TK_COLUMN
664 +** instruction into a TK_NULL. If the auth function returns SQLITE_DENY,
665 +** then generate an error.
667 +void sqliteAuthRead(
668 + Parse *pParse, /* The parser context */
669 + Expr *pExpr, /* The expression to check authorization on */
670 + SrcList *pTabList /* All table that pExpr might refer to */
672 + sqlite *db = pParse->db;
674 + Table *pTab; /* The table being read */
675 + const char *zCol; /* Name of the column of the table */
676 + int iSrc; /* Index in pTabList->a[] of table being read */
677 + const char *zDBase; /* Name of database being accessed */
678 + TriggerStack *pStack; /* The stack of current triggers */
680 + if( db->xAuth==0 ) return;
681 + assert( pExpr->op==TK_COLUMN );
682 + for(iSrc=0; iSrc<pTabList->nSrc; iSrc++){
683 + if( pExpr->iTable==pTabList->a[iSrc].iCursor ) break;
685 + if( iSrc>=0 && iSrc<pTabList->nSrc ){
686 + pTab = pTabList->a[iSrc].pTab;
687 + }else if( (pStack = pParse->trigStack)!=0 ){
688 + /* This must be an attempt to read the NEW or OLD pseudo-tables
691 + assert( pExpr->iTable==pStack->newIdx || pExpr->iTable==pStack->oldIdx );
692 + pTab = pStack->pTab;
696 + if( pTab==0 ) return;
697 + if( pExpr->iColumn>=0 ){
698 + assert( pExpr->iColumn<pTab->nCol );
699 + zCol = pTab->aCol[pExpr->iColumn].zName;
700 + }else if( pTab->iPKey>=0 ){
701 + assert( pTab->iPKey<pTab->nCol );
702 + zCol = pTab->aCol[pTab->iPKey].zName;
706 + assert( pExpr->iDb<db->nDb );
707 + zDBase = db->aDb[pExpr->iDb].zName;
708 + rc = db->xAuth(db->pAuthArg, SQLITE_READ, pTab->zName, zCol, zDBase,
709 + pParse->zAuthContext);
710 + if( rc==SQLITE_IGNORE ){
711 + pExpr->op = TK_NULL;
712 + }else if( rc==SQLITE_DENY ){
713 + if( db->nDb>2 || pExpr->iDb!=0 ){
714 + sqliteErrorMsg(pParse, "access to %s.%s.%s is prohibited",
715 + zDBase, pTab->zName, zCol);
717 + sqliteErrorMsg(pParse, "access to %s.%s is prohibited", pTab->zName,zCol);
719 + pParse->rc = SQLITE_AUTH;
720 + }else if( rc!=SQLITE_OK ){
721 + sqliteAuthBadReturnCode(pParse, rc);
726 +** Do an authorization check using the code and arguments given. Return
727 +** either SQLITE_OK (zero) or SQLITE_IGNORE or SQLITE_DENY. If SQLITE_DENY
728 +** is returned, then the error count and error message in pParse are
729 +** modified appropriately.
731 +int sqliteAuthCheck(
738 + sqlite *db = pParse->db;
741 + if( db->init.busy || db->xAuth==0 ){
744 + rc = db->xAuth(db->pAuthArg, code, zArg1, zArg2, zArg3, pParse->zAuthContext);
745 + if( rc==SQLITE_DENY ){
746 + sqliteErrorMsg(pParse, "not authorized");
747 + pParse->rc = SQLITE_AUTH;
748 + }else if( rc!=SQLITE_OK && rc!=SQLITE_IGNORE ){
750 + sqliteAuthBadReturnCode(pParse, rc);
756 +** Push an authorization context. After this routine is called, the
757 +** zArg3 argument to authorization callbacks will be zContext until
758 +** popped. Or if pParse==0, this routine is a no-op.
760 +void sqliteAuthContextPush(
762 + AuthContext *pContext,
763 + const char *zContext
765 + pContext->pParse = pParse;
767 + pContext->zAuthContext = pParse->zAuthContext;
768 + pParse->zAuthContext = zContext;
773 +** Pop an authorization context that was previously pushed
774 +** by sqliteAuthContextPush
776 +void sqliteAuthContextPop(AuthContext *pContext){
777 + if( pContext->pParse ){
778 + pContext->pParse->zAuthContext = pContext->zAuthContext;
779 + pContext->pParse = 0;
783 +#endif /* SQLITE_OMIT_AUTHORIZATION */
785 +++ b/ext/sqlite/libsqlite/src/btree.c
788 +** 2001 September 15
790 +** The author disclaims copyright to this source code. In place of
791 +** a legal notice, here is a blessing:
793 +** May you do good and not evil.
794 +** May you find forgiveness for yourself and forgive others.
795 +** May you share freely, never taking more than you give.
797 +*************************************************************************
800 +** This file implements a external (disk-based) database using BTrees.
801 +** For a detailed discussion of BTrees, refer to
803 +** Donald E. Knuth, THE ART OF COMPUTER PROGRAMMING, Volume 3:
804 +** "Sorting And Searching", pages 473-480. Addison-Wesley
805 +** Publishing Company, Reading, Massachusetts.
807 +** The basic idea is that each page of the file contains N database
808 +** entries and N+1 pointers to subpages.
810 +** ----------------------------------------------------------------
811 +** | Ptr(0) | Key(0) | Ptr(1) | Key(1) | ... | Key(N) | Ptr(N+1) |
812 +** ----------------------------------------------------------------
814 +** All of the keys on the page that Ptr(0) points to have values less
815 +** than Key(0). All of the keys on page Ptr(1) and its subpages have
816 +** values greater than Key(0) and less than Key(1). All of the keys
817 +** on Ptr(N+1) and its subpages have values greater than Key(N). And
820 +** Finding a particular key requires reading O(log(M)) pages from the
821 +** disk where M is the number of entries in the tree.
823 +** In this implementation, a single file can hold one or more separate
824 +** BTrees. Each BTree is identified by the index of its root page. The
825 +** key and data for any entry are combined to form the "payload". Up to
826 +** MX_LOCAL_PAYLOAD bytes of payload can be carried directly on the
827 +** database page. If the payload is larger than MX_LOCAL_PAYLOAD bytes
828 +** then surplus bytes are stored on overflow pages. The payload for an
829 +** entry and the preceding pointer are combined to form a "Cell". Each
830 +** page has a small header which contains the Ptr(N+1) pointer.
832 +** The first page of the file contains a magic string used to verify that
833 +** the file really is a valid BTree database, a pointer to a list of unused
834 +** pages in the file, and some meta information. The root of the first
835 +** BTree begins on page 2 of the file. (Pages are numbered beginning with
836 +** 1, not 0.) Thus a minimum database contains 2 pages.
838 +#include "sqliteInt.h"
843 +/* Forward declarations */
844 +static BtOps sqliteBtreeOps;
845 +static BtCursorOps sqliteBtreeCursorOps;
848 +** Macros used for byteswapping. B is a pointer to the Btree
849 +** structure. This is needed to access the Btree.needSwab boolean
850 +** in order to tell if byte swapping is needed or not.
851 +** X is an unsigned integer. SWAB16 byte swaps a 16-bit integer.
852 +** SWAB32 byteswaps a 32-bit integer.
854 +#define SWAB16(B,X) ((B)->needSwab? swab16((u16)X) : ((u16)X))
855 +#define SWAB32(B,X) ((B)->needSwab? swab32(X) : (X))
856 +#define SWAB_ADD(B,X,A) \
857 + if((B)->needSwab){ X=swab32(swab32(X)+A); }else{ X += (A); }
860 +** The following global variable - available only if SQLITE_TEST is
861 +** defined - is used to determine whether new databases are created in
862 +** native byte order or in non-native byte order. Non-native byte order
863 +** databases are created for testing purposes only. Under normal operation,
864 +** only native byte-order databases should be created, but we should be
865 +** able to read or write existing databases regardless of the byteorder.
868 +int btree_native_byte_order = 1;
870 +# define btree_native_byte_order 1
874 +** Forward declarations of structures used only in this file.
876 +typedef struct PageOne PageOne;
877 +typedef struct MemPage MemPage;
878 +typedef struct PageHdr PageHdr;
879 +typedef struct Cell Cell;
880 +typedef struct CellHdr CellHdr;
881 +typedef struct FreeBlk FreeBlk;
882 +typedef struct OverflowPage OverflowPage;
883 +typedef struct FreelistInfo FreelistInfo;
886 +** All structures on a database page are aligned to 4-byte boundries.
887 +** This routine rounds up a number of bytes to the next multiple of 4.
889 +** This might need to change for computer architectures that require
890 +** and 8-byte alignment boundry for structures.
892 +#define ROUNDUP(X) ((X+3) & ~3)
895 +** This is a magic string that appears at the beginning of every
896 +** SQLite database in order to identify the file as a real database.
898 +static const char zMagicHeader[] =
899 + "** This file contains an SQLite 2.1 database **";
900 +#define MAGIC_SIZE (sizeof(zMagicHeader))
903 +** This is a magic integer also used to test the integrity of the database
904 +** file. This integer is used in addition to the string above so that
905 +** if the file is written on a little-endian architecture and read
906 +** on a big-endian architectures (or vice versa) we can detect the
909 +** The number used was obtained at random and has no special
910 +** significance other than the fact that it represents a different
911 +** integer on little-endian and big-endian machines.
913 +#define MAGIC 0xdae37528
916 +** The first page of the database file contains a magic header string
917 +** to identify the file as an SQLite database file. It also contains
918 +** a pointer to the first free page of the file. Page 2 contains the
919 +** root of the principle BTree. The file might contain other BTrees
920 +** rooted on pages above 2.
922 +** The first page also contains SQLITE_N_BTREE_META integers that
923 +** can be used by higher-level routines.
925 +** Remember that pages are numbered beginning with 1. (See pager.c
926 +** for additional information.) Page 0 does not exist and a page
927 +** number of 0 is used to mean "no such page".
930 + char zMagic[MAGIC_SIZE]; /* String that identifies the file as a database */
931 + int iMagic; /* Integer to verify correct byte order */
932 + Pgno freeList; /* First free page in a list of all free pages */
933 + int nFree; /* Number of pages on the free list */
934 + int aMeta[SQLITE_N_BTREE_META-1]; /* User defined integers */
938 +** Each database page has a header that is an instance of this
941 +** PageHdr.firstFree is 0 if there is no free space on this page.
942 +** Otherwise, PageHdr.firstFree is the index in MemPage.u.aDisk[] of a
943 +** FreeBlk structure that describes the first block of free space.
944 +** All free space is defined by a linked list of FreeBlk structures.
946 +** Data is stored in a linked list of Cell structures. PageHdr.firstCell
947 +** is the index into MemPage.u.aDisk[] of the first cell on the page. The
948 +** Cells are kept in sorted order.
950 +** A Cell contains all information about a database entry and a pointer
951 +** to a child page that contains other entries less than itself. In
952 +** other words, the i-th Cell contains both Ptr(i) and Key(i). The
953 +** right-most pointer of the page is contained in PageHdr.rightChild.
956 + Pgno rightChild; /* Child page that comes after all cells on this page */
957 + u16 firstCell; /* Index in MemPage.u.aDisk[] of the first cell */
958 + u16 firstFree; /* Index in MemPage.u.aDisk[] of the first free block */
962 +** Entries on a page of the database are called "Cells". Each Cell
963 +** has a header and data. This structure defines the header. The
964 +** key and data (collectively the "payload") follow this header on
965 +** the database page.
967 +** A definition of the complete Cell structure is given below. The
968 +** header for the cell must be defined first in order to do some
969 +** of the sizing #defines that follow.
972 + Pgno leftChild; /* Child page that comes before this cell */
973 + u16 nKey; /* Number of bytes in the key */
974 + u16 iNext; /* Index in MemPage.u.aDisk[] of next cell in sorted order */
975 + u8 nKeyHi; /* Upper 8 bits of key size for keys larger than 64K bytes */
976 + u8 nDataHi; /* Upper 8 bits of data size when the size is more than 64K */
977 + u16 nData; /* Number of bytes of data */
981 +** The key and data size are split into a lower 16-bit segment and an
982 +** upper 8-bit segment in order to pack them together into a smaller
983 +** space. The following macros reassembly a key or data size back
986 +#define NKEY(b,h) (SWAB16(b,h.nKey) + h.nKeyHi*65536)
987 +#define NDATA(b,h) (SWAB16(b,h.nData) + h.nDataHi*65536)
990 +** The minimum size of a complete Cell. The Cell must contain a header
991 +** and at least 4 bytes of payload.
993 +#define MIN_CELL_SIZE (sizeof(CellHdr)+4)
996 +** The maximum number of database entries that can be held in a single
997 +** page of the database.
999 +#define MX_CELL ((SQLITE_USABLE_SIZE-sizeof(PageHdr))/MIN_CELL_SIZE)
1002 +** The amount of usable space on a single page of the BTree. This is the
1003 +** page size minus the overhead of the page header.
1005 +#define USABLE_SPACE (SQLITE_USABLE_SIZE - sizeof(PageHdr))
1008 +** The maximum amount of payload (in bytes) that can be stored locally for
1009 +** a database entry. If the entry contains more data than this, the
1010 +** extra goes onto overflow pages.
1012 +** This number is chosen so that at least 4 cells will fit on every page.
1014 +#define MX_LOCAL_PAYLOAD ((USABLE_SPACE/4-(sizeof(CellHdr)+sizeof(Pgno)))&~3)
1017 +** Data on a database page is stored as a linked list of Cell structures.
1018 +** Both the key and the data are stored in aPayload[]. The key always comes
1019 +** first. The aPayload[] field grows as necessary to hold the key and data,
1020 +** up to a maximum of MX_LOCAL_PAYLOAD bytes. If the size of the key and
1021 +** data combined exceeds MX_LOCAL_PAYLOAD bytes, then Cell.ovfl is the
1022 +** page number of the first overflow page.
1024 +** Though this structure is fixed in size, the Cell on the database
1025 +** page varies in size. Every cell has a CellHdr and at least 4 bytes
1026 +** of payload space. Additional payload bytes (up to the maximum of
1027 +** MX_LOCAL_PAYLOAD) and the Cell.ovfl value are allocated only as
1031 + CellHdr h; /* The cell header */
1032 + char aPayload[MX_LOCAL_PAYLOAD]; /* Key and data */
1033 + Pgno ovfl; /* The first overflow page */
1037 +** Free space on a page is remembered using a linked list of the FreeBlk
1038 +** structures. Space on a database page is allocated in increments of
1039 +** at least 4 bytes and is always aligned to a 4-byte boundry. The
1040 +** linked list of FreeBlks is always kept in order by address.
1043 + u16 iSize; /* Number of bytes in this block of free space */
1044 + u16 iNext; /* Index in MemPage.u.aDisk[] of the next free block */
1048 +** The number of bytes of payload that will fit on a single overflow page.
1050 +#define OVERFLOW_SIZE (SQLITE_USABLE_SIZE-sizeof(Pgno))
1053 +** When the key and data for a single entry in the BTree will not fit in
1054 +** the MX_LOCAL_PAYLOAD bytes of space available on the database page,
1055 +** then all extra bytes are written to a linked list of overflow pages.
1056 +** Each overflow page is an instance of the following structure.
1058 +** Unused pages in the database are also represented by instances of
1059 +** the OverflowPage structure. The PageOne.freeList field is the
1060 +** page number of the first page in a linked list of unused database
1063 +struct OverflowPage {
1065 + char aPayload[OVERFLOW_SIZE];
1069 +** The PageOne.freeList field points to a linked list of overflow pages
1070 +** hold information about free pages. The aPayload section of each
1071 +** overflow page contains an instance of the following structure. The
1072 +** aFree[] array holds the page number of nFree unused pages in the disk
1075 +struct FreelistInfo {
1077 + Pgno aFree[(OVERFLOW_SIZE-sizeof(int))/sizeof(Pgno)];
1081 +** For every page in the database file, an instance of the following structure
1082 +** is stored in memory. The u.aDisk[] array contains the raw bits read from
1083 +** the disk. The rest is auxiliary information held in memory only. The
1084 +** auxiliary info is only valid for regular database pages - it is not
1085 +** used for overflow pages and pages on the freelist.
1087 +** Of particular interest in the auxiliary info is the apCell[] entry. Each
1088 +** apCell[] entry is a pointer to a Cell structure in u.aDisk[]. The cells are
1089 +** put in this array so that they can be accessed in constant time, rather
1090 +** than in linear time which would be needed if we had to walk the linked
1091 +** list on every access.
1093 +** Note that apCell[] contains enough space to hold up to two more Cells
1094 +** than can possibly fit on one page. In the steady state, every apCell[]
1095 +** points to memory inside u.aDisk[]. But in the middle of an insert
1096 +** operation, some apCell[] entries may temporarily point to data space
1097 +** outside of u.aDisk[]. This is a transient situation that is quickly
1098 +** resolved. But while it is happening, it is possible for a database
1099 +** page to hold as many as two more cells than it might otherwise hold.
1100 +** The extra two entries in apCell[] are an allowance for this situation.
1102 +** The pParent field points back to the parent page. This allows us to
1103 +** walk up the BTree from any leaf to the root. Care must be taken to
1104 +** unref() the parent page pointer when this page is no longer referenced.
1105 +** The pageDestructor() routine handles that chore.
1108 + union u_page_data {
1109 + char aDisk[SQLITE_PAGE_SIZE]; /* Page data stored on disk */
1110 + PageHdr hdr; /* Overlay page header */
1112 + u8 isInit; /* True if auxiliary data is initialized */
1113 + u8 idxShift; /* True if apCell[] indices have changed */
1114 + u8 isOverfull; /* Some apCell[] points outside u.aDisk[] */
1115 + MemPage *pParent; /* The parent of this page. NULL for root */
1116 + int idxParent; /* Index in pParent->apCell[] of this node */
1117 + int nFree; /* Number of free bytes in u.aDisk[] */
1118 + int nCell; /* Number of entries on this page */
1119 + Cell *apCell[MX_CELL+2]; /* All data entires in sorted order */
1123 +** The in-memory image of a disk page has the auxiliary information appended
1124 +** to the end. EXTRA_SIZE is the number of bytes of space needed to hold
1125 +** that extra information.
1127 +#define EXTRA_SIZE (sizeof(MemPage)-sizeof(union u_page_data))
1130 +** Everything we need to know about an open database
1133 + BtOps *pOps; /* Function table */
1134 + Pager *pPager; /* The page cache */
1135 + BtCursor *pCursor; /* A list of all open cursors */
1136 + PageOne *page1; /* First page of the database */
1137 + u8 inTrans; /* True if a transaction is in progress */
1138 + u8 inCkpt; /* True if there is a checkpoint on the transaction */
1139 + u8 readOnly; /* True if the underlying file is readonly */
1140 + u8 needSwab; /* Need to byte-swapping */
1145 +** A cursor is a pointer to a particular entry in the BTree.
1146 +** The entry is identified by its MemPage and the index in
1147 +** MemPage.apCell[] of the entry.
1150 + BtCursorOps *pOps; /* Function table */
1151 + Btree *pBt; /* The Btree to which this cursor belongs */
1152 + BtCursor *pNext, *pPrev; /* Forms a linked list of all cursors */
1153 + BtCursor *pShared; /* Loop of cursors with the same root page */
1154 + Pgno pgnoRoot; /* The root page of this tree */
1155 + MemPage *pPage; /* Page that contains the entry */
1156 + int idx; /* Index of the entry in pPage->apCell[] */
1157 + u8 wrFlag; /* True if writable */
1158 + u8 eSkip; /* Determines if next step operation is a no-op */
1159 + u8 iMatch; /* compare result from last sqliteBtreeMoveto() */
1163 +** Legal values for BtCursor.eSkip.
1165 +#define SKIP_NONE 0 /* Always step the cursor */
1166 +#define SKIP_NEXT 1 /* The next sqliteBtreeNext() is a no-op */
1167 +#define SKIP_PREV 2 /* The next sqliteBtreePrevious() is a no-op */
1168 +#define SKIP_INVALID 3 /* Calls to Next() and Previous() are invalid */
1170 +/* Forward declarations */
1171 +static int fileBtreeCloseCursor(BtCursor *pCur);
1174 +** Routines for byte swapping.
1177 + return ((x & 0xff)<<8) | ((x>>8)&0xff);
1180 + return ((x & 0xff)<<24) | ((x & 0xff00)<<8) |
1181 + ((x>>8) & 0xff00) | ((x>>24)&0xff);
1185 +** Compute the total number of bytes that a Cell needs on the main
1186 +** database page. The number returned includes the Cell header,
1187 +** local payload storage, and the pointer to overflow pages (if
1188 +** applicable). Additional space allocated on overflow pages
1189 +** is NOT included in the value returned from this routine.
1191 +static int cellSize(Btree *pBt, Cell *pCell){
1192 + int n = NKEY(pBt, pCell->h) + NDATA(pBt, pCell->h);
1193 + if( n>MX_LOCAL_PAYLOAD ){
1194 + n = MX_LOCAL_PAYLOAD + sizeof(Pgno);
1198 + n += sizeof(CellHdr);
1203 +** Defragment the page given. All Cells are moved to the
1204 +** beginning of the page and all free space is collected
1205 +** into one big FreeBlk at the end of the page.
1207 +static void defragmentPage(Btree *pBt, MemPage *pPage){
1210 + char newPage[SQLITE_USABLE_SIZE];
1212 + assert( sqlitepager_iswriteable(pPage) );
1213 + assert( pPage->isInit );
1214 + pc = sizeof(PageHdr);
1215 + pPage->u.hdr.firstCell = SWAB16(pBt, pc);
1216 + memcpy(newPage, pPage->u.aDisk, pc);
1217 + for(i=0; i<pPage->nCell; i++){
1218 + Cell *pCell = pPage->apCell[i];
1220 + /* This routine should never be called on an overfull page. The
1221 + ** following asserts verify that constraint. */
1222 + assert( Addr(pCell) > Addr(pPage) );
1223 + assert( Addr(pCell) < Addr(pPage) + SQLITE_USABLE_SIZE );
1225 + n = cellSize(pBt, pCell);
1226 + pCell->h.iNext = SWAB16(pBt, pc + n);
1227 + memcpy(&newPage[pc], pCell, n);
1228 + pPage->apCell[i] = (Cell*)&pPage->u.aDisk[pc];
1231 + assert( pPage->nFree==SQLITE_USABLE_SIZE-pc );
1232 + memcpy(pPage->u.aDisk, newPage, pc);
1233 + if( pPage->nCell>0 ){
1234 + pPage->apCell[pPage->nCell-1]->h.iNext = 0;
1236 + pFBlk = (FreeBlk*)&pPage->u.aDisk[pc];
1237 + pFBlk->iSize = SWAB16(pBt, SQLITE_USABLE_SIZE - pc);
1239 + pPage->u.hdr.firstFree = SWAB16(pBt, pc);
1240 + memset(&pFBlk[1], 0, SQLITE_USABLE_SIZE - pc - sizeof(FreeBlk));
1244 +** Allocate nByte bytes of space on a page. nByte must be a
1247 +** Return the index into pPage->u.aDisk[] of the first byte of
1248 +** the new allocation. Or return 0 if there is not enough free
1249 +** space on the page to satisfy the allocation request.
1251 +** If the page contains nBytes of free space but does not contain
1252 +** nBytes of contiguous free space, then this routine automatically
1253 +** calls defragementPage() to consolidate all free space before
1254 +** allocating the new chunk.
1256 +static int allocateSpace(Btree *pBt, MemPage *pPage, int nByte){
1265 + assert( sqlitepager_iswriteable(pPage) );
1266 + assert( nByte==ROUNDUP(nByte) );
1267 + assert( pPage->isInit );
1268 + if( pPage->nFree<nByte || pPage->isOverfull ) return 0;
1269 + pIdx = &pPage->u.hdr.firstFree;
1270 + p = (FreeBlk*)&pPage->u.aDisk[SWAB16(pBt, *pIdx)];
1271 + while( (iSize = SWAB16(pBt, p->iSize))<nByte ){
1272 + assert( cnt++ < SQLITE_USABLE_SIZE/4 );
1273 + if( p->iNext==0 ){
1274 + defragmentPage(pBt, pPage);
1275 + pIdx = &pPage->u.hdr.firstFree;
1279 + p = (FreeBlk*)&pPage->u.aDisk[SWAB16(pBt, *pIdx)];
1281 + if( iSize==nByte ){
1282 + start = SWAB16(pBt, *pIdx);
1286 + start = SWAB16(pBt, *pIdx);
1287 + pNew = (FreeBlk*)&pPage->u.aDisk[start + nByte];
1288 + pNew->iNext = p->iNext;
1289 + pNew->iSize = SWAB16(pBt, iSize - nByte);
1290 + *pIdx = SWAB16(pBt, start + nByte);
1292 + pPage->nFree -= nByte;
1297 +** Return a section of the MemPage.u.aDisk[] to the freelist.
1298 +** The first byte of the new free block is pPage->u.aDisk[start]
1299 +** and the size of the block is "size" bytes. Size must be
1300 +** a multiple of 4.
1302 +** Most of the effort here is involved in coalesing adjacent
1303 +** free blocks into a single big free block.
1305 +static void freeSpace(Btree *pBt, MemPage *pPage, int start, int size){
1306 + int end = start + size;
1313 + assert( sqlitepager_iswriteable(pPage) );
1314 + assert( size == ROUNDUP(size) );
1315 + assert( start == ROUNDUP(start) );
1316 + assert( pPage->isInit );
1317 + pIdx = &pPage->u.hdr.firstFree;
1318 + idx = SWAB16(pBt, *pIdx);
1319 + while( idx!=0 && idx<start ){
1320 + pFBlk = (FreeBlk*)&pPage->u.aDisk[idx];
1321 + iSize = SWAB16(pBt, pFBlk->iSize);
1322 + if( idx + iSize == start ){
1323 + pFBlk->iSize = SWAB16(pBt, iSize + size);
1324 + if( idx + iSize + size == SWAB16(pBt, pFBlk->iNext) ){
1325 + pNext = (FreeBlk*)&pPage->u.aDisk[idx + iSize + size];
1326 + if( pBt->needSwab ){
1327 + pFBlk->iSize = swab16((u16)swab16(pNext->iSize)+iSize+size);
1329 + pFBlk->iSize += pNext->iSize;
1331 + pFBlk->iNext = pNext->iNext;
1333 + pPage->nFree += size;
1336 + pIdx = &pFBlk->iNext;
1337 + idx = SWAB16(pBt, *pIdx);
1339 + pNew = (FreeBlk*)&pPage->u.aDisk[start];
1341 + pNew->iSize = SWAB16(pBt, size);
1342 + pNew->iNext = SWAB16(pBt, idx);
1344 + pNext = (FreeBlk*)&pPage->u.aDisk[idx];
1345 + pNew->iSize = SWAB16(pBt, size + SWAB16(pBt, pNext->iSize));
1346 + pNew->iNext = pNext->iNext;
1348 + *pIdx = SWAB16(pBt, start);
1349 + pPage->nFree += size;
1353 +** Initialize the auxiliary information for a disk block.
1355 +** The pParent parameter must be a pointer to the MemPage which
1356 +** is the parent of the page being initialized. The root of the
1357 +** BTree (usually page 2) has no parent and so for that page,
1360 +** Return SQLITE_OK on success. If we see that the page does
1361 +** not contain a well-formed database page, then return
1362 +** SQLITE_CORRUPT. Note that a return of SQLITE_OK does not
1363 +** guarantee that the page is well-formed. It only shows that
1364 +** we failed to detect any corruption.
1366 +static int initPage(Bt *pBt, MemPage *pPage, Pgno pgnoThis, MemPage *pParent){
1367 + int idx; /* An index into pPage->u.aDisk[] */
1368 + Cell *pCell; /* A pointer to a Cell in pPage->u.aDisk[] */
1369 + FreeBlk *pFBlk; /* A pointer to a free block in pPage->u.aDisk[] */
1370 + int sz; /* The size of a Cell in bytes */
1371 + int freeSpace; /* Amount of free space on the page */
1373 + if( pPage->pParent ){
1374 + assert( pPage->pParent==pParent );
1378 + pPage->pParent = pParent;
1379 + sqlitepager_ref(pParent);
1381 + if( pPage->isInit ) return SQLITE_OK;
1382 + pPage->isInit = 1;
1384 + freeSpace = USABLE_SPACE;
1385 + idx = SWAB16(pBt, pPage->u.hdr.firstCell);
1387 + if( idx>SQLITE_USABLE_SIZE-MIN_CELL_SIZE ) goto page_format_error;
1388 + if( idx<sizeof(PageHdr) ) goto page_format_error;
1389 + if( idx!=ROUNDUP(idx) ) goto page_format_error;
1390 + pCell = (Cell*)&pPage->u.aDisk[idx];
1391 + sz = cellSize(pBt, pCell);
1392 + if( idx+sz > SQLITE_USABLE_SIZE ) goto page_format_error;
1394 + pPage->apCell[pPage->nCell++] = pCell;
1395 + idx = SWAB16(pBt, pCell->h.iNext);
1398 + idx = SWAB16(pBt, pPage->u.hdr.firstFree);
1401 + if( idx>SQLITE_USABLE_SIZE-sizeof(FreeBlk) ) goto page_format_error;
1402 + if( idx<sizeof(PageHdr) ) goto page_format_error;
1403 + pFBlk = (FreeBlk*)&pPage->u.aDisk[idx];
1404 + pPage->nFree += SWAB16(pBt, pFBlk->iSize);
1405 + iNext = SWAB16(pBt, pFBlk->iNext);
1406 + if( iNext>0 && iNext <= idx ) goto page_format_error;
1409 + if( pPage->nCell==0 && pPage->nFree==0 ){
1410 + /* As a special case, an uninitialized root page appears to be
1411 + ** an empty database */
1414 + if( pPage->nFree!=freeSpace ) goto page_format_error;
1418 + return SQLITE_CORRUPT;
1422 +** Set up a raw page so that it looks like a database page holding
1425 +static void zeroPage(Btree *pBt, MemPage *pPage){
1428 + assert( sqlitepager_iswriteable(pPage) );
1429 + memset(pPage, 0, SQLITE_USABLE_SIZE);
1430 + pHdr = &pPage->u.hdr;
1431 + pHdr->firstCell = 0;
1432 + pHdr->firstFree = SWAB16(pBt, sizeof(*pHdr));
1433 + pFBlk = (FreeBlk*)&pHdr[1];
1435 + pPage->nFree = SQLITE_USABLE_SIZE - sizeof(*pHdr);
1436 + pFBlk->iSize = SWAB16(pBt, pPage->nFree);
1438 + pPage->isOverfull = 0;
1442 +** This routine is called when the reference count for a page
1443 +** reaches zero. We need to unref the pParent pointer when that
1446 +static void pageDestructor(void *pData){
1447 + MemPage *pPage = (MemPage*)pData;
1448 + if( pPage->pParent ){
1449 + MemPage *pParent = pPage->pParent;
1450 + pPage->pParent = 0;
1451 + sqlitepager_unref(pParent);
1456 +** Open a new database.
1458 +** Actually, this routine just sets up the internal data structures
1459 +** for accessing the database. We do not open the database file
1460 +** until the first page is loaded.
1462 +** zFilename is the name of the database file. If zFilename is NULL
1463 +** a new database with a random name is created. This randomly named
1464 +** database file will be deleted when sqliteBtreeClose() is called.
1466 +int sqliteBtreeOpen(
1467 + const char *zFilename, /* Name of the file containing the BTree database */
1468 + int omitJournal, /* if TRUE then do not journal this file */
1469 + int nCache, /* How many pages in the page cache */
1470 + Btree **ppBtree /* Pointer to new Btree object written here */
1476 + ** The following asserts make sure that structures used by the btree are
1477 + ** the right size. This is to guard against size changes that result
1478 + ** when compiling on a different architecture.
1480 + assert( sizeof(u32)==4 );
1481 + assert( sizeof(u16)==2 );
1482 + assert( sizeof(Pgno)==4 );
1483 + assert( sizeof(PageHdr)==8 );
1484 + assert( sizeof(CellHdr)==12 );
1485 + assert( sizeof(FreeBlk)==4 );
1486 + assert( sizeof(OverflowPage)==SQLITE_USABLE_SIZE );
1487 + assert( sizeof(FreelistInfo)==OVERFLOW_SIZE );
1488 + assert( sizeof(ptr)==sizeof(char*) );
1489 + assert( sizeof(uptr)==sizeof(ptr) );
1491 + pBt = sqliteMalloc( sizeof(*pBt) );
1494 + return SQLITE_NOMEM;
1496 + if( nCache<10 ) nCache = 10;
1497 + rc = sqlitepager_open(&pBt->pPager, zFilename, nCache, EXTRA_SIZE,
1499 + if( rc!=SQLITE_OK ){
1500 + if( pBt->pPager ) sqlitepager_close(pBt->pPager);
1505 + sqlitepager_set_destructor(pBt->pPager, pageDestructor);
1508 + pBt->readOnly = sqlitepager_isreadonly(pBt->pPager);
1509 + pBt->pOps = &sqliteBtreeOps;
1515 +** Close an open database and invalidate all cursors.
1517 +static int fileBtreeClose(Btree *pBt){
1518 + while( pBt->pCursor ){
1519 + fileBtreeCloseCursor(pBt->pCursor);
1521 + sqlitepager_close(pBt->pPager);
1527 +** Change the limit on the number of pages allowed in the cache.
1529 +** The maximum number of cache pages is set to the absolute
1530 +** value of mxPage. If mxPage is negative, the pager will
1531 +** operate asynchronously - it will not stop to do fsync()s
1532 +** to insure data is written to the disk surface before
1533 +** continuing. Transactions still work if synchronous is off,
1534 +** and the database cannot be corrupted if this program
1535 +** crashes. But if the operating system crashes or there is
1536 +** an abrupt power failure when synchronous is off, the database
1537 +** could be left in an inconsistent and unrecoverable state.
1538 +** Synchronous is on by default so database corruption is not
1539 +** normally a worry.
1541 +static int fileBtreeSetCacheSize(Btree *pBt, int mxPage){
1542 + sqlitepager_set_cachesize(pBt->pPager, mxPage);
1547 +** Change the way data is synced to disk in order to increase or decrease
1548 +** how well the database resists damage due to OS crashes and power
1549 +** failures. Level 1 is the same as asynchronous (no syncs() occur and
1550 +** there is a high probability of damage) Level 2 is the default. There
1551 +** is a very low but non-zero probability of damage. Level 3 reduces the
1552 +** probability of damage to near zero but with a write performance reduction.
1554 +static int fileBtreeSetSafetyLevel(Btree *pBt, int level){
1555 + sqlitepager_set_safety_level(pBt->pPager, level);
1560 +** Get a reference to page1 of the database file. This will
1561 +** also acquire a readlock on that file.
1563 +** SQLITE_OK is returned on success. If the file is not a
1564 +** well-formed database file, then SQLITE_CORRUPT is returned.
1565 +** SQLITE_BUSY is returned if the database is locked. SQLITE_NOMEM
1566 +** is returned if we run out of memory. SQLITE_PROTOCOL is returned
1567 +** if there is a locking protocol violation.
1569 +static int lockBtree(Btree *pBt){
1571 + if( pBt->page1 ) return SQLITE_OK;
1572 + rc = sqlitepager_get(pBt->pPager, 1, (void**)&pBt->page1);
1573 + if( rc!=SQLITE_OK ) return rc;
1575 + /* Do some checking to help insure the file we opened really is
1576 + ** a valid database file.
1578 + if( sqlitepager_pagecount(pBt->pPager)>0 ){
1579 + PageOne *pP1 = pBt->page1;
1580 + if( strcmp(pP1->zMagic,zMagicHeader)!=0 ||
1581 + (pP1->iMagic!=MAGIC && swab32(pP1->iMagic)!=MAGIC) ){
1582 + rc = SQLITE_NOTADB;
1583 + goto page1_init_failed;
1585 + pBt->needSwab = pP1->iMagic!=MAGIC;
1590 + sqlitepager_unref(pBt->page1);
1596 +** If there are no outstanding cursors and we are not in the middle
1597 +** of a transaction but there is a read lock on the database, then
1598 +** this routine unrefs the first page of the database file which
1599 +** has the effect of releasing the read lock.
1601 +** If there are any outstanding cursors, this routine is a no-op.
1603 +** If there is a transaction in progress, this routine is a no-op.
1605 +static void unlockBtreeIfUnused(Btree *pBt){
1606 + if( pBt->inTrans==0 && pBt->pCursor==0 && pBt->page1!=0 ){
1607 + sqlitepager_unref(pBt->page1);
1615 +** Create a new database by initializing the first two pages of the
1618 +static int newDatabase(Btree *pBt){
1622 + if( sqlitepager_pagecount(pBt->pPager)>1 ) return SQLITE_OK;
1624 + rc = sqlitepager_write(pBt->page1);
1625 + if( rc ) return rc;
1626 + rc = sqlitepager_get(pBt->pPager, 2, (void**)&pRoot);
1627 + if( rc ) return rc;
1628 + rc = sqlitepager_write(pRoot);
1630 + sqlitepager_unref(pRoot);
1633 + strcpy(pP1->zMagic, zMagicHeader);
1634 + if( btree_native_byte_order ){
1635 + pP1->iMagic = MAGIC;
1636 + pBt->needSwab = 0;
1638 + pP1->iMagic = swab32(MAGIC);
1639 + pBt->needSwab = 1;
1641 + zeroPage(pBt, pRoot);
1642 + sqlitepager_unref(pRoot);
1647 +** Attempt to start a new transaction.
1649 +** A transaction must be started before attempting any changes
1650 +** to the database. None of the following routines will work
1651 +** unless a transaction is started first:
1653 +** sqliteBtreeCreateTable()
1654 +** sqliteBtreeCreateIndex()
1655 +** sqliteBtreeClearTable()
1656 +** sqliteBtreeDropTable()
1657 +** sqliteBtreeInsert()
1658 +** sqliteBtreeDelete()
1659 +** sqliteBtreeUpdateMeta()
1661 +static int fileBtreeBeginTrans(Btree *pBt){
1663 + if( pBt->inTrans ) return SQLITE_ERROR;
1664 + if( pBt->readOnly ) return SQLITE_READONLY;
1665 + if( pBt->page1==0 ){
1666 + rc = lockBtree(pBt);
1667 + if( rc!=SQLITE_OK ){
1671 + rc = sqlitepager_begin(pBt->page1);
1672 + if( rc==SQLITE_OK ){
1673 + rc = newDatabase(pBt);
1675 + if( rc==SQLITE_OK ){
1679 + unlockBtreeIfUnused(pBt);
1685 +** Commit the transaction currently in progress.
1687 +** This will release the write lock on the database file. If there
1688 +** are no active cursors, it also releases the read lock.
1690 +static int fileBtreeCommit(Btree *pBt){
1692 + rc = pBt->readOnly ? SQLITE_OK : sqlitepager_commit(pBt->pPager);
1695 + unlockBtreeIfUnused(pBt);
1700 +** Rollback the transaction in progress. All cursors will be
1701 +** invalided by this operation. Any attempt to use a cursor
1702 +** that was open at the beginning of this operation will result
1705 +** This will release the write lock on the database file. If there
1706 +** are no active cursors, it also releases the read lock.
1708 +static int fileBtreeRollback(Btree *pBt){
1711 + if( pBt->inTrans==0 ) return SQLITE_OK;
1714 + rc = pBt->readOnly ? SQLITE_OK : sqlitepager_rollback(pBt->pPager);
1715 + for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
1716 + if( pCur->pPage && pCur->pPage->isInit==0 ){
1717 + sqlitepager_unref(pCur->pPage);
1721 + unlockBtreeIfUnused(pBt);
1726 +** Set the checkpoint for the current transaction. The checkpoint serves
1727 +** as a sub-transaction that can be rolled back independently of the
1728 +** main transaction. You must start a transaction before starting a
1729 +** checkpoint. The checkpoint is ended automatically if the transaction
1730 +** commits or rolls back.
1732 +** Only one checkpoint may be active at a time. It is an error to try
1733 +** to start a new checkpoint if another checkpoint is already active.
1735 +static int fileBtreeBeginCkpt(Btree *pBt){
1737 + if( !pBt->inTrans || pBt->inCkpt ){
1738 + return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
1740 + rc = pBt->readOnly ? SQLITE_OK : sqlitepager_ckpt_begin(pBt->pPager);
1747 +** Commit a checkpoint to transaction currently in progress. If no
1748 +** checkpoint is active, this is a no-op.
1750 +static int fileBtreeCommitCkpt(Btree *pBt){
1752 + if( pBt->inCkpt && !pBt->readOnly ){
1753 + rc = sqlitepager_ckpt_commit(pBt->pPager);
1762 +** Rollback the checkpoint to the current transaction. If there
1763 +** is no active checkpoint or transaction, this routine is a no-op.
1765 +** All cursors will be invalided by this operation. Any attempt
1766 +** to use a cursor that was open at the beginning of this operation
1767 +** will result in an error.
1769 +static int fileBtreeRollbackCkpt(Btree *pBt){
1772 + if( pBt->inCkpt==0 || pBt->readOnly ) return SQLITE_OK;
1773 + rc = sqlitepager_ckpt_rollback(pBt->pPager);
1774 + for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
1775 + if( pCur->pPage && pCur->pPage->isInit==0 ){
1776 + sqlitepager_unref(pCur->pPage);
1785 +** Create a new cursor for the BTree whose root is on the page
1786 +** iTable. The act of acquiring a cursor gets a read lock on
1787 +** the database file.
1789 +** If wrFlag==0, then the cursor can only be used for reading.
1790 +** If wrFlag==1, then the cursor can be used for reading or for
1791 +** writing if other conditions for writing are also met. These
1792 +** are the conditions that must be met in order for writing to
1795 +** 1: The cursor must have been opened with wrFlag==1
1797 +** 2: No other cursors may be open with wrFlag==0 on the same table
1799 +** 3: The database must be writable (not on read-only media)
1801 +** 4: There must be an active transaction.
1803 +** Condition 2 warrants further discussion. If any cursor is opened
1804 +** on a table with wrFlag==0, that prevents all other cursors from
1805 +** writing to that table. This is a kind of "read-lock". When a cursor
1806 +** is opened with wrFlag==0 it is guaranteed that the table will not
1807 +** change as long as the cursor is open. This allows the cursor to
1808 +** do a sequential scan of the table without having to worry about
1809 +** entries being inserted or deleted during the scan. Cursors should
1810 +** be opened with wrFlag==0 only if this read-lock property is needed.
1811 +** That is to say, cursors should be opened with wrFlag==0 only if they
1812 +** intend to use the sqliteBtreeNext() system call. All other cursors
1813 +** should be opened with wrFlag==1 even if they never really intend
1816 +** No checking is done to make sure that page iTable really is the
1817 +** root page of a b-tree. If it is not, then the cursor acquired
1818 +** will not work correctly.
1821 +int fileBtreeCursor(Btree *pBt, int iTable, int wrFlag, BtCursor **ppCur){
1823 + BtCursor *pCur, *pRing;
1825 + if( pBt->readOnly && wrFlag ){
1827 + return SQLITE_READONLY;
1829 + if( pBt->page1==0 ){
1830 + rc = lockBtree(pBt);
1831 + if( rc!=SQLITE_OK ){
1836 + pCur = sqliteMalloc( sizeof(*pCur) );
1838 + rc = SQLITE_NOMEM;
1839 + goto create_cursor_exception;
1841 + pCur->pgnoRoot = (Pgno)iTable;
1842 + rc = sqlitepager_get(pBt->pPager, pCur->pgnoRoot, (void**)&pCur->pPage);
1843 + if( rc!=SQLITE_OK ){
1844 + goto create_cursor_exception;
1846 + rc = initPage(pBt, pCur->pPage, pCur->pgnoRoot, 0);
1847 + if( rc!=SQLITE_OK ){
1848 + goto create_cursor_exception;
1850 + pCur->pOps = &sqliteBtreeCursorOps;
1852 + pCur->wrFlag = wrFlag;
1854 + pCur->eSkip = SKIP_INVALID;
1855 + pCur->pNext = pBt->pCursor;
1856 + if( pCur->pNext ){
1857 + pCur->pNext->pPrev = pCur;
1860 + pRing = pBt->pCursor;
1861 + while( pRing && pRing->pgnoRoot!=pCur->pgnoRoot ){ pRing = pRing->pNext; }
1863 + pCur->pShared = pRing->pShared;
1864 + pRing->pShared = pCur;
1866 + pCur->pShared = pCur;
1868 + pBt->pCursor = pCur;
1872 +create_cursor_exception:
1875 + if( pCur->pPage ) sqlitepager_unref(pCur->pPage);
1878 + unlockBtreeIfUnused(pBt);
1883 +** Close a cursor. The read lock on the database file is released
1884 +** when the last cursor is closed.
1886 +static int fileBtreeCloseCursor(BtCursor *pCur){
1887 + Btree *pBt = pCur->pBt;
1888 + if( pCur->pPrev ){
1889 + pCur->pPrev->pNext = pCur->pNext;
1891 + pBt->pCursor = pCur->pNext;
1893 + if( pCur->pNext ){
1894 + pCur->pNext->pPrev = pCur->pPrev;
1896 + if( pCur->pPage ){
1897 + sqlitepager_unref(pCur->pPage);
1899 + if( pCur->pShared!=pCur ){
1900 + BtCursor *pRing = pCur->pShared;
1901 + while( pRing->pShared!=pCur ){ pRing = pRing->pShared; }
1902 + pRing->pShared = pCur->pShared;
1904 + unlockBtreeIfUnused(pBt);
1910 +** Make a temporary cursor by filling in the fields of pTempCur.
1911 +** The temporary cursor is not on the cursor list for the Btree.
1913 +static void getTempCursor(BtCursor *pCur, BtCursor *pTempCur){
1914 + memcpy(pTempCur, pCur, sizeof(*pCur));
1915 + pTempCur->pNext = 0;
1916 + pTempCur->pPrev = 0;
1917 + if( pTempCur->pPage ){
1918 + sqlitepager_ref(pTempCur->pPage);
1923 +** Delete a temporary cursor such as was made by the CreateTemporaryCursor()
1926 +static void releaseTempCursor(BtCursor *pCur){
1927 + if( pCur->pPage ){
1928 + sqlitepager_unref(pCur->pPage);
1933 +** Set *pSize to the number of bytes of key in the entry the
1934 +** cursor currently points to. Always return SQLITE_OK.
1935 +** Failure is not possible. If the cursor is not currently
1936 +** pointing to an entry (which can happen, for example, if
1937 +** the database is empty) then *pSize is set to 0.
1939 +static int fileBtreeKeySize(BtCursor *pCur, int *pSize){
1943 + pPage = pCur->pPage;
1944 + assert( pPage!=0 );
1945 + if( pCur->idx >= pPage->nCell ){
1948 + pCell = pPage->apCell[pCur->idx];
1949 + *pSize = NKEY(pCur->pBt, pCell->h);
1955 +** Read payload information from the entry that the pCur cursor is
1956 +** pointing to. Begin reading the payload at "offset" and read
1957 +** a total of "amt" bytes. Put the result in zBuf.
1959 +** This routine does not make a distinction between key and data.
1960 +** It just reads bytes from the payload area.
1962 +static int getPayload(BtCursor *pCur, int offset, int amt, char *zBuf){
1966 + Btree *pBt = pCur->pBt;
1967 + assert( pCur!=0 && pCur->pPage!=0 );
1968 + assert( pCur->idx>=0 && pCur->idx<pCur->pPage->nCell );
1969 + aPayload = pCur->pPage->apCell[pCur->idx]->aPayload;
1970 + if( offset<MX_LOCAL_PAYLOAD ){
1972 + if( a+offset>MX_LOCAL_PAYLOAD ){
1973 + a = MX_LOCAL_PAYLOAD - offset;
1975 + memcpy(zBuf, &aPayload[offset], a);
1983 + offset -= MX_LOCAL_PAYLOAD;
1986 + nextPage = SWAB32(pBt, pCur->pPage->apCell[pCur->idx]->ovfl);
1988 + while( amt>0 && nextPage ){
1989 + OverflowPage *pOvfl;
1990 + rc = sqlitepager_get(pBt->pPager, nextPage, (void**)&pOvfl);
1994 + nextPage = SWAB32(pBt, pOvfl->iNext);
1995 + if( offset<OVERFLOW_SIZE ){
1997 + if( a + offset > OVERFLOW_SIZE ){
1998 + a = OVERFLOW_SIZE - offset;
2000 + memcpy(zBuf, &pOvfl->aPayload[offset], a);
2005 + offset -= OVERFLOW_SIZE;
2007 + sqlitepager_unref(pOvfl);
2010 + return SQLITE_CORRUPT;
2016 +** Read part of the key associated with cursor pCur. A maximum
2017 +** of "amt" bytes will be transfered into zBuf[]. The transfer
2018 +** begins at "offset". The number of bytes actually read is
2021 +** Change: It used to be that the amount returned will be smaller
2022 +** than the amount requested if there are not enough bytes in the key
2023 +** to satisfy the request. But now, it must be the case that there
2024 +** is enough data available to satisfy the request. If not, an exception
2025 +** is raised. The change was made in an effort to boost performance
2026 +** by eliminating unneeded tests.
2028 +static int fileBtreeKey(BtCursor *pCur, int offset, int amt, char *zBuf){
2032 + assert( offset>=0 );
2033 + assert( pCur->pPage!=0 );
2034 + pPage = pCur->pPage;
2035 + if( pCur->idx >= pPage->nCell ){
2038 + assert( amt+offset <= NKEY(pCur->pBt, pPage->apCell[pCur->idx]->h) );
2039 + getPayload(pCur, offset, amt, zBuf);
2044 +** Set *pSize to the number of bytes of data in the entry the
2045 +** cursor currently points to. Always return SQLITE_OK.
2046 +** Failure is not possible. If the cursor is not currently
2047 +** pointing to an entry (which can happen, for example, if
2048 +** the database is empty) then *pSize is set to 0.
2050 +static int fileBtreeDataSize(BtCursor *pCur, int *pSize){
2054 + pPage = pCur->pPage;
2055 + assert( pPage!=0 );
2056 + if( pCur->idx >= pPage->nCell ){
2059 + pCell = pPage->apCell[pCur->idx];
2060 + *pSize = NDATA(pCur->pBt, pCell->h);
2066 +** Read part of the data associated with cursor pCur. A maximum
2067 +** of "amt" bytes will be transfered into zBuf[]. The transfer
2068 +** begins at "offset". The number of bytes actually read is
2069 +** returned. The amount returned will be smaller than the
2070 +** amount requested if there are not enough bytes in the data
2071 +** to satisfy the request.
2073 +static int fileBtreeData(BtCursor *pCur, int offset, int amt, char *zBuf){
2078 + assert( offset>=0 );
2079 + assert( pCur->pPage!=0 );
2080 + pPage = pCur->pPage;
2081 + if( pCur->idx >= pPage->nCell ){
2084 + pCell = pPage->apCell[pCur->idx];
2085 + assert( amt+offset <= NDATA(pCur->pBt, pCell->h) );
2086 + getPayload(pCur, offset + NKEY(pCur->pBt, pCell->h), amt, zBuf);
2091 +** Compare an external key against the key on the entry that pCur points to.
2093 +** The external key is pKey and is nKey bytes long. The last nIgnore bytes
2094 +** of the key associated with pCur are ignored, as if they do not exist.
2095 +** (The normal case is for nIgnore to be zero in which case the entire
2096 +** internal key is used in the comparison.)
2098 +** The comparison result is written to *pRes as follows:
2100 +** *pRes<0 This means pCur<pKey
2102 +** *pRes==0 This means pCur==pKey for all nKey bytes
2104 +** *pRes>0 This means pCur>pKey
2106 +** When one key is an exact prefix of the other, the shorter key is
2107 +** considered less than the longer one. In order to be equal the
2108 +** keys must be exactly the same length. (The length of the pCur key
2109 +** is the actual key length minus nIgnore bytes.)
2111 +static int fileBtreeKeyCompare(
2112 + BtCursor *pCur, /* Pointer to entry to compare against */
2113 + const void *pKey, /* Key to compare against entry that pCur points to */
2114 + int nKey, /* Number of bytes in pKey */
2115 + int nIgnore, /* Ignore this many bytes at the end of pCur */
2116 + int *pResult /* Write the result here */
2119 + int n, c, rc, nLocal;
2121 + Btree *pBt = pCur->pBt;
2122 + const char *zKey = (const char*)pKey;
2124 + assert( pCur->pPage );
2125 + assert( pCur->idx>=0 && pCur->idx<pCur->pPage->nCell );
2126 + pCell = pCur->pPage->apCell[pCur->idx];
2127 + nLocal = NKEY(pBt, pCell->h) - nIgnore;
2128 + if( nLocal<0 ) nLocal = 0;
2129 + n = nKey<nLocal ? nKey : nLocal;
2130 + if( n>MX_LOCAL_PAYLOAD ){
2131 + n = MX_LOCAL_PAYLOAD;
2133 + c = memcmp(pCell->aPayload, zKey, n);
2141 + nextPage = SWAB32(pBt, pCell->ovfl);
2142 + while( nKey>0 && nLocal>0 ){
2143 + OverflowPage *pOvfl;
2144 + if( nextPage==0 ){
2145 + return SQLITE_CORRUPT;
2147 + rc = sqlitepager_get(pBt->pPager, nextPage, (void**)&pOvfl);
2151 + nextPage = SWAB32(pBt, pOvfl->iNext);
2152 + n = nKey<nLocal ? nKey : nLocal;
2153 + if( n>OVERFLOW_SIZE ){
2154 + n = OVERFLOW_SIZE;
2156 + c = memcmp(pOvfl->aPayload, zKey, n);
2157 + sqlitepager_unref(pOvfl);
2167 + c = nLocal - nKey;
2174 +** Move the cursor down to a new child page. The newPgno argument is the
2175 +** page number of the child page in the byte order of the disk image.
2177 +static int moveToChild(BtCursor *pCur, int newPgno){
2179 + MemPage *pNewPage;
2180 + Btree *pBt = pCur->pBt;
2182 + newPgno = SWAB32(pBt, newPgno);
2183 + rc = sqlitepager_get(pBt->pPager, newPgno, (void**)&pNewPage);
2184 + if( rc ) return rc;
2185 + rc = initPage(pBt, pNewPage, newPgno, pCur->pPage);
2186 + if( rc ) return rc;
2187 + assert( pCur->idx>=pCur->pPage->nCell
2188 + || pCur->pPage->apCell[pCur->idx]->h.leftChild==SWAB32(pBt,newPgno) );
2189 + assert( pCur->idx<pCur->pPage->nCell
2190 + || pCur->pPage->u.hdr.rightChild==SWAB32(pBt,newPgno) );
2191 + pNewPage->idxParent = pCur->idx;
2192 + pCur->pPage->idxShift = 0;
2193 + sqlitepager_unref(pCur->pPage);
2194 + pCur->pPage = pNewPage;
2196 + if( pNewPage->nCell<1 ){
2197 + return SQLITE_CORRUPT;
2203 +** Move the cursor up to the parent page.
2205 +** pCur->idx is set to the cell index that contains the pointer
2206 +** to the page we are coming from. If we are coming from the
2207 +** right-most child page then pCur->idx is set to one more than
2208 +** the largest cell index.
2210 +static void moveToParent(BtCursor *pCur){
2215 + pPage = pCur->pPage;
2216 + assert( pPage!=0 );
2217 + pParent = pPage->pParent;
2218 + assert( pParent!=0 );
2219 + idxParent = pPage->idxParent;
2220 + sqlitepager_ref(pParent);
2221 + sqlitepager_unref(pPage);
2222 + pCur->pPage = pParent;
2223 + assert( pParent->idxShift==0 );
2224 + if( pParent->idxShift==0 ){
2225 + pCur->idx = idxParent;
2227 + /* Verify that pCur->idx is the correct index to point back to the child
2228 + ** page we just came from
2230 + oldPgno = SWAB32(pCur->pBt, sqlitepager_pagenumber(pPage));
2231 + if( pCur->idx<pParent->nCell ){
2232 + assert( pParent->apCell[idxParent]->h.leftChild==oldPgno );
2234 + assert( pParent->u.hdr.rightChild==oldPgno );
2238 + /* The MemPage.idxShift flag indicates that cell indices might have
2239 + ** changed since idxParent was set and hence idxParent might be out
2240 + ** of date. So recompute the parent cell index by scanning all cells
2241 + ** and locating the one that points to the child we just came from.
2244 + pCur->idx = pParent->nCell;
2245 + oldPgno = SWAB32(pCur->pBt, sqlitepager_pagenumber(pPage));
2246 + for(i=0; i<pParent->nCell; i++){
2247 + if( pParent->apCell[i]->h.leftChild==oldPgno ){
2256 +** Move the cursor to the root page
2258 +static int moveToRoot(BtCursor *pCur){
2261 + Btree *pBt = pCur->pBt;
2263 + rc = sqlitepager_get(pBt->pPager, pCur->pgnoRoot, (void**)&pNew);
2264 + if( rc ) return rc;
2265 + rc = initPage(pBt, pNew, pCur->pgnoRoot, 0);
2266 + if( rc ) return rc;
2267 + sqlitepager_unref(pCur->pPage);
2268 + pCur->pPage = pNew;
2274 +** Move the cursor down to the left-most leaf entry beneath the
2275 +** entry to which it is currently pointing.
2277 +static int moveToLeftmost(BtCursor *pCur){
2281 + while( (pgno = pCur->pPage->apCell[pCur->idx]->h.leftChild)!=0 ){
2282 + rc = moveToChild(pCur, pgno);
2283 + if( rc ) return rc;
2289 +** Move the cursor down to the right-most leaf entry beneath the
2290 +** page to which it is currently pointing. Notice the difference
2291 +** between moveToLeftmost() and moveToRightmost(). moveToLeftmost()
2292 +** finds the left-most entry beneath the *entry* whereas moveToRightmost()
2293 +** finds the right-most entry beneath the *page*.
2295 +static int moveToRightmost(BtCursor *pCur){
2299 + while( (pgno = pCur->pPage->u.hdr.rightChild)!=0 ){
2300 + pCur->idx = pCur->pPage->nCell;
2301 + rc = moveToChild(pCur, pgno);
2302 + if( rc ) return rc;
2304 + pCur->idx = pCur->pPage->nCell - 1;
2308 +/* Move the cursor to the first entry in the table. Return SQLITE_OK
2309 +** on success. Set *pRes to 0 if the cursor actually points to something
2310 +** or set *pRes to 1 if the table is empty.
2312 +static int fileBtreeFirst(BtCursor *pCur, int *pRes){
2314 + if( pCur->pPage==0 ) return SQLITE_ABORT;
2315 + rc = moveToRoot(pCur);
2316 + if( rc ) return rc;
2317 + if( pCur->pPage->nCell==0 ){
2322 + rc = moveToLeftmost(pCur);
2323 + pCur->eSkip = SKIP_NONE;
2327 +/* Move the cursor to the last entry in the table. Return SQLITE_OK
2328 +** on success. Set *pRes to 0 if the cursor actually points to something
2329 +** or set *pRes to 1 if the table is empty.
2331 +static int fileBtreeLast(BtCursor *pCur, int *pRes){
2333 + if( pCur->pPage==0 ) return SQLITE_ABORT;
2334 + rc = moveToRoot(pCur);
2335 + if( rc ) return rc;
2336 + assert( pCur->pPage->isInit );
2337 + if( pCur->pPage->nCell==0 ){
2342 + rc = moveToRightmost(pCur);
2343 + pCur->eSkip = SKIP_NONE;
2347 +/* Move the cursor so that it points to an entry near pKey.
2348 +** Return a success code.
2350 +** If an exact match is not found, then the cursor is always
2351 +** left pointing at a leaf page which would hold the entry if it
2352 +** were present. The cursor might point to an entry that comes
2353 +** before or after the key.
2355 +** The result of comparing the key with the entry to which the
2356 +** cursor is left pointing is stored in pCur->iMatch. The same
2357 +** value is also written to *pRes if pRes!=NULL. The meaning of
2358 +** this value is as follows:
2360 +** *pRes<0 The cursor is left pointing at an entry that
2361 +** is smaller than pKey or if the table is empty
2362 +** and the cursor is therefore left point to nothing.
2364 +** *pRes==0 The cursor is left pointing at an entry that
2365 +** exactly matches pKey.
2367 +** *pRes>0 The cursor is left pointing at an entry that
2368 +** is larger than pKey.
2371 +int fileBtreeMoveto(BtCursor *pCur, const void *pKey, int nKey, int *pRes){
2373 + if( pCur->pPage==0 ) return SQLITE_ABORT;
2374 + pCur->eSkip = SKIP_NONE;
2375 + rc = moveToRoot(pCur);
2376 + if( rc ) return rc;
2380 + MemPage *pPage = pCur->pPage;
2381 + int c = -1; /* pRes return if table is empty must be -1 */
2383 + upr = pPage->nCell-1;
2384 + while( lwr<=upr ){
2385 + pCur->idx = (lwr+upr)/2;
2386 + rc = fileBtreeKeyCompare(pCur, pKey, nKey, 0, &c);
2387 + if( rc ) return rc;
2390 + if( pRes ) *pRes = 0;
2394 + lwr = pCur->idx+1;
2396 + upr = pCur->idx-1;
2399 + assert( lwr==upr+1 );
2400 + assert( pPage->isInit );
2401 + if( lwr>=pPage->nCell ){
2402 + chldPg = pPage->u.hdr.rightChild;
2404 + chldPg = pPage->apCell[lwr]->h.leftChild;
2408 + if( pRes ) *pRes = c;
2412 + rc = moveToChild(pCur, chldPg);
2413 + if( rc ) return rc;
2419 +** Advance the cursor to the next entry in the database. If
2420 +** successful then set *pRes=0. If the cursor
2421 +** was already pointing to the last entry in the database before
2422 +** this routine was called, then set *pRes=1.
2424 +static int fileBtreeNext(BtCursor *pCur, int *pRes){
2426 + MemPage *pPage = pCur->pPage;
2427 + assert( pRes!=0 );
2430 + return SQLITE_ABORT;
2432 + assert( pPage->isInit );
2433 + assert( pCur->eSkip!=SKIP_INVALID );
2434 + if( pPage->nCell==0 ){
2438 + assert( pCur->idx<pPage->nCell );
2439 + if( pCur->eSkip==SKIP_NEXT ){
2440 + pCur->eSkip = SKIP_NONE;
2444 + pCur->eSkip = SKIP_NONE;
2446 + if( pCur->idx>=pPage->nCell ){
2447 + if( pPage->u.hdr.rightChild ){
2448 + rc = moveToChild(pCur, pPage->u.hdr.rightChild);
2449 + if( rc ) return rc;
2450 + rc = moveToLeftmost(pCur);
2455 + if( pPage->pParent==0 ){
2459 + moveToParent(pCur);
2460 + pPage = pCur->pPage;
2461 + }while( pCur->idx>=pPage->nCell );
2466 + if( pPage->u.hdr.rightChild==0 ){
2469 + rc = moveToLeftmost(pCur);
2474 +** Step the cursor to the back to the previous entry in the database. If
2475 +** successful then set *pRes=0. If the cursor
2476 +** was already pointing to the first entry in the database before
2477 +** this routine was called, then set *pRes=1.
2479 +static int fileBtreePrevious(BtCursor *pCur, int *pRes){
2483 + pPage = pCur->pPage;
2486 + return SQLITE_ABORT;
2488 + assert( pPage->isInit );
2489 + assert( pCur->eSkip!=SKIP_INVALID );
2490 + if( pPage->nCell==0 ){
2494 + if( pCur->eSkip==SKIP_PREV ){
2495 + pCur->eSkip = SKIP_NONE;
2499 + pCur->eSkip = SKIP_NONE;
2500 + assert( pCur->idx>=0 );
2501 + if( (pgno = pPage->apCell[pCur->idx]->h.leftChild)!=0 ){
2502 + rc = moveToChild(pCur, pgno);
2503 + if( rc ) return rc;
2504 + rc = moveToRightmost(pCur);
2506 + while( pCur->idx==0 ){
2507 + if( pPage->pParent==0 ){
2508 + if( pRes ) *pRes = 1;
2511 + moveToParent(pCur);
2512 + pPage = pCur->pPage;
2522 +** Allocate a new page from the database file.
2524 +** The new page is marked as dirty. (In other words, sqlitepager_write()
2525 +** has already been called on the new page.) The new page has also
2526 +** been referenced and the calling routine is responsible for calling
2527 +** sqlitepager_unref() on the new page when it is done.
2529 +** SQLITE_OK is returned on success. Any other return value indicates
2530 +** an error. *ppPage and *pPgno are undefined in the event of an error.
2531 +** Do not invoke sqlitepager_unref() on *ppPage if an error is returned.
2533 +** If the "nearby" parameter is not 0, then a (feeble) effort is made to
2534 +** locate a page close to the page number "nearby". This can be used in an
2535 +** attempt to keep related pages close to each other in the database file,
2536 +** which in turn can make database access faster.
2538 +static int allocatePage(Btree *pBt, MemPage **ppPage, Pgno *pPgno, Pgno nearby){
2539 + PageOne *pPage1 = pBt->page1;
2541 + if( pPage1->freeList ){
2542 + OverflowPage *pOvfl;
2543 + FreelistInfo *pInfo;
2545 + rc = sqlitepager_write(pPage1);
2546 + if( rc ) return rc;
2547 + SWAB_ADD(pBt, pPage1->nFree, -1);
2548 + rc = sqlitepager_get(pBt->pPager, SWAB32(pBt, pPage1->freeList),
2550 + if( rc ) return rc;
2551 + rc = sqlitepager_write(pOvfl);
2553 + sqlitepager_unref(pOvfl);
2556 + pInfo = (FreelistInfo*)pOvfl->aPayload;
2557 + if( pInfo->nFree==0 ){
2558 + *pPgno = SWAB32(pBt, pPage1->freeList);
2559 + pPage1->freeList = pOvfl->iNext;
2560 + *ppPage = (MemPage*)pOvfl;
2563 + n = SWAB32(pBt, pInfo->nFree);
2564 + if( n>1 && nearby>0 ){
2567 + dist = SWAB32(pBt, pInfo->aFree[0]) - nearby;
2568 + if( dist<0 ) dist = -dist;
2569 + for(i=1; i<n; i++){
2570 + int d2 = SWAB32(pBt, pInfo->aFree[i]) - nearby;
2571 + if( d2<0 ) d2 = -d2;
2572 + if( d2<dist ) closest = i;
2577 + SWAB_ADD(pBt, pInfo->nFree, -1);
2578 + *pPgno = SWAB32(pBt, pInfo->aFree[closest]);
2579 + pInfo->aFree[closest] = pInfo->aFree[n-1];
2580 + rc = sqlitepager_get(pBt->pPager, *pPgno, (void**)ppPage);
2581 + sqlitepager_unref(pOvfl);
2582 + if( rc==SQLITE_OK ){
2583 + sqlitepager_dont_rollback(*ppPage);
2584 + rc = sqlitepager_write(*ppPage);
2588 + *pPgno = sqlitepager_pagecount(pBt->pPager) + 1;
2589 + rc = sqlitepager_get(pBt->pPager, *pPgno, (void**)ppPage);
2590 + if( rc ) return rc;
2591 + rc = sqlitepager_write(*ppPage);
2597 +** Add a page of the database file to the freelist. Either pgno or
2598 +** pPage but not both may be 0.
2600 +** sqlitepager_unref() is NOT called for pPage.
2602 +static int freePage(Btree *pBt, void *pPage, Pgno pgno){
2603 + PageOne *pPage1 = pBt->page1;
2604 + OverflowPage *pOvfl = (OverflowPage*)pPage;
2606 + int needUnref = 0;
2607 + MemPage *pMemPage;
2610 + assert( pOvfl!=0 );
2611 + pgno = sqlitepager_pagenumber(pOvfl);
2614 + assert( sqlitepager_pagenumber(pOvfl)==pgno );
2615 + pMemPage = (MemPage*)pPage;
2616 + pMemPage->isInit = 0;
2617 + if( pMemPage->pParent ){
2618 + sqlitepager_unref(pMemPage->pParent);
2619 + pMemPage->pParent = 0;
2621 + rc = sqlitepager_write(pPage1);
2625 + SWAB_ADD(pBt, pPage1->nFree, 1);
2626 + if( pPage1->nFree!=0 && pPage1->freeList!=0 ){
2627 + OverflowPage *pFreeIdx;
2628 + rc = sqlitepager_get(pBt->pPager, SWAB32(pBt, pPage1->freeList),
2629 + (void**)&pFreeIdx);
2630 + if( rc==SQLITE_OK ){
2631 + FreelistInfo *pInfo = (FreelistInfo*)pFreeIdx->aPayload;
2632 + int n = SWAB32(pBt, pInfo->nFree);
2633 + if( n<(sizeof(pInfo->aFree)/sizeof(pInfo->aFree[0])) ){
2634 + rc = sqlitepager_write(pFreeIdx);
2635 + if( rc==SQLITE_OK ){
2636 + pInfo->aFree[n] = SWAB32(pBt, pgno);
2637 + SWAB_ADD(pBt, pInfo->nFree, 1);
2638 + sqlitepager_unref(pFreeIdx);
2639 + sqlitepager_dont_write(pBt->pPager, pgno);
2643 + sqlitepager_unref(pFreeIdx);
2648 + rc = sqlitepager_get(pBt->pPager, pgno, (void**)&pOvfl);
2649 + if( rc ) return rc;
2652 + rc = sqlitepager_write(pOvfl);
2654 + if( needUnref ) sqlitepager_unref(pOvfl);
2657 + pOvfl->iNext = pPage1->freeList;
2658 + pPage1->freeList = SWAB32(pBt, pgno);
2659 + memset(pOvfl->aPayload, 0, OVERFLOW_SIZE);
2660 + if( needUnref ) rc = sqlitepager_unref(pOvfl);
2665 +** Erase all the data out of a cell. This involves returning overflow
2666 +** pages back the freelist.
2668 +static int clearCell(Btree *pBt, Cell *pCell){
2669 + Pager *pPager = pBt->pPager;
2670 + OverflowPage *pOvfl;
2671 + Pgno ovfl, nextOvfl;
2674 + if( NKEY(pBt, pCell->h) + NDATA(pBt, pCell->h) <= MX_LOCAL_PAYLOAD ){
2677 + ovfl = SWAB32(pBt, pCell->ovfl);
2680 + rc = sqlitepager_get(pPager, ovfl, (void**)&pOvfl);
2681 + if( rc ) return rc;
2682 + nextOvfl = SWAB32(pBt, pOvfl->iNext);
2683 + rc = freePage(pBt, pOvfl, ovfl);
2684 + if( rc ) return rc;
2685 + sqlitepager_unref(pOvfl);
2692 +** Create a new cell from key and data. Overflow pages are allocated as
2693 +** necessary and linked to this cell.
2695 +static int fillInCell(
2696 + Btree *pBt, /* The whole Btree. Needed to allocate pages */
2697 + Cell *pCell, /* Populate this Cell structure */
2698 + const void *pKey, int nKey, /* The key */
2699 + const void *pData,int nData /* The data */
2701 + OverflowPage *pOvfl, *pPrior;
2706 + const char *pPayload;
2710 + pCell->h.leftChild = 0;
2711 + pCell->h.nKey = SWAB16(pBt, nKey & 0xffff);
2712 + pCell->h.nKeyHi = nKey >> 16;
2713 + pCell->h.nData = SWAB16(pBt, nData & 0xffff);
2714 + pCell->h.nDataHi = nData >> 16;
2715 + pCell->h.iNext = 0;
2717 + pNext = &pCell->ovfl;
2718 + pSpace = pCell->aPayload;
2719 + spaceLeft = MX_LOCAL_PAYLOAD;
2724 + while( nPayload>0 ){
2725 + if( spaceLeft==0 ){
2726 + rc = allocatePage(pBt, (MemPage**)&pOvfl, pNext, nearby);
2732 + if( pPrior ) sqlitepager_unref(pPrior);
2734 + clearCell(pBt, pCell);
2737 + if( pBt->needSwab ) *pNext = swab32(*pNext);
2739 + spaceLeft = OVERFLOW_SIZE;
2740 + pSpace = pOvfl->aPayload;
2741 + pNext = &pOvfl->iNext;
2744 + if( n>spaceLeft ) n = spaceLeft;
2745 + memcpy(pSpace, pPayload, n);
2747 + if( nPayload==0 && pData ){
2759 + sqlitepager_unref(pPrior);
2765 +** Change the MemPage.pParent pointer on the page whose number is
2766 +** given in the second argument so that MemPage.pParent holds the
2767 +** pointer in the third argument.
2769 +static void reparentPage(Pager *pPager, Pgno pgno, MemPage *pNewParent,int idx){
2772 + if( pgno==0 ) return;
2773 + assert( pPager!=0 );
2774 + pThis = sqlitepager_lookup(pPager, pgno);
2775 + if( pThis && pThis->isInit ){
2776 + if( pThis->pParent!=pNewParent ){
2777 + if( pThis->pParent ) sqlitepager_unref(pThis->pParent);
2778 + pThis->pParent = pNewParent;
2779 + if( pNewParent ) sqlitepager_ref(pNewParent);
2781 + pThis->idxParent = idx;
2782 + sqlitepager_unref(pThis);
2787 +** Reparent all children of the given page to be the given page.
2788 +** In other words, for every child of pPage, invoke reparentPage()
2789 +** to make sure that each child knows that pPage is its parent.
2791 +** This routine gets called after you memcpy() one page into
2794 +static void reparentChildPages(Btree *pBt, MemPage *pPage){
2796 + Pager *pPager = pBt->pPager;
2797 + for(i=0; i<pPage->nCell; i++){
2798 + reparentPage(pPager, SWAB32(pBt, pPage->apCell[i]->h.leftChild), pPage, i);
2800 + reparentPage(pPager, SWAB32(pBt, pPage->u.hdr.rightChild), pPage, i);
2801 + pPage->idxShift = 0;
2805 +** Remove the i-th cell from pPage. This routine effects pPage only.
2806 +** The cell content is not freed or deallocated. It is assumed that
2807 +** the cell content has been copied someplace else. This routine just
2808 +** removes the reference to the cell from pPage.
2810 +** "sz" must be the number of bytes in the cell.
2812 +** Do not bother maintaining the integrity of the linked list of Cells.
2813 +** Only the pPage->apCell[] array is important. The relinkCellList()
2814 +** routine will be called soon after this routine in order to rebuild
2815 +** the linked list.
2817 +static void dropCell(Btree *pBt, MemPage *pPage, int idx, int sz){
2819 + assert( idx>=0 && idx<pPage->nCell );
2820 + assert( sz==cellSize(pBt, pPage->apCell[idx]) );
2821 + assert( sqlitepager_iswriteable(pPage) );
2822 + freeSpace(pBt, pPage, Addr(pPage->apCell[idx]) - Addr(pPage), sz);
2823 + for(j=idx; j<pPage->nCell-1; j++){
2824 + pPage->apCell[j] = pPage->apCell[j+1];
2827 + pPage->idxShift = 1;
2831 +** Insert a new cell on pPage at cell index "i". pCell points to the
2832 +** content of the cell.
2834 +** If the cell content will fit on the page, then put it there. If it
2835 +** will not fit, then just make pPage->apCell[i] point to the content
2836 +** and set pPage->isOverfull.
2838 +** Do not bother maintaining the integrity of the linked list of Cells.
2839 +** Only the pPage->apCell[] array is important. The relinkCellList()
2840 +** routine will be called soon after this routine in order to rebuild
2841 +** the linked list.
2843 +static void insertCell(Btree *pBt, MemPage *pPage, int i, Cell *pCell, int sz){
2845 + assert( i>=0 && i<=pPage->nCell );
2846 + assert( sz==cellSize(pBt, pCell) );
2847 + assert( sqlitepager_iswriteable(pPage) );
2848 + idx = allocateSpace(pBt, pPage, sz);
2849 + for(j=pPage->nCell; j>i; j--){
2850 + pPage->apCell[j] = pPage->apCell[j-1];
2854 + pPage->isOverfull = 1;
2855 + pPage->apCell[i] = pCell;
2857 + memcpy(&pPage->u.aDisk[idx], pCell, sz);
2858 + pPage->apCell[i] = (Cell*)&pPage->u.aDisk[idx];
2860 + pPage->idxShift = 1;
2864 +** Rebuild the linked list of cells on a page so that the cells
2865 +** occur in the order specified by the pPage->apCell[] array.
2866 +** Invoke this routine once to repair damage after one or more
2867 +** invocations of either insertCell() or dropCell().
2869 +static void relinkCellList(Btree *pBt, MemPage *pPage){
2872 + assert( sqlitepager_iswriteable(pPage) );
2873 + pIdx = &pPage->u.hdr.firstCell;
2874 + for(i=0; i<pPage->nCell; i++){
2875 + int idx = Addr(pPage->apCell[i]) - Addr(pPage);
2876 + assert( idx>0 && idx<SQLITE_USABLE_SIZE );
2877 + *pIdx = SWAB16(pBt, idx);
2878 + pIdx = &pPage->apCell[i]->h.iNext;
2884 +** Make a copy of the contents of pFrom into pTo. The pFrom->apCell[]
2885 +** pointers that point into pFrom->u.aDisk[] must be adjusted to point
2886 +** into pTo->u.aDisk[] instead. But some pFrom->apCell[] entries might
2887 +** not point to pFrom->u.aDisk[]. Those are unchanged.
2889 +static void copyPage(MemPage *pTo, MemPage *pFrom){
2892 + memcpy(pTo->u.aDisk, pFrom->u.aDisk, SQLITE_USABLE_SIZE);
2895 + pTo->nCell = pFrom->nCell;
2896 + pTo->nFree = pFrom->nFree;
2897 + pTo->isOverfull = pFrom->isOverfull;
2899 + from = Addr(pFrom);
2900 + for(i=0; i<pTo->nCell; i++){
2901 + uptr x = Addr(pFrom->apCell[i]);
2902 + if( x>from && x<from+SQLITE_USABLE_SIZE ){
2903 + *((uptr*)&pTo->apCell[i]) = x + to - from;
2905 + pTo->apCell[i] = pFrom->apCell[i];
2911 +** The following parameters determine how many adjacent pages get involved
2912 +** in a balancing operation. NN is the number of neighbors on either side
2913 +** of the page that participate in the balancing operation. NB is the
2914 +** total number of pages that participate, including the target page and
2915 +** NN neighbors on either side.
2917 +** The minimum value of NN is 1 (of course). Increasing NN above 1
2918 +** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
2919 +** in exchange for a larger degradation in INSERT and UPDATE performance.
2920 +** The value of NN appears to give the best results overall.
2922 +#define NN 1 /* Number of neighbors on either side of pPage */
2923 +#define NB (NN*2+1) /* Total pages involved in the balance */
2926 +** This routine redistributes Cells on pPage and up to two siblings
2927 +** of pPage so that all pages have about the same amount of free space.
2928 +** Usually one sibling on either side of pPage is used in the balancing,
2929 +** though both siblings might come from one side if pPage is the first
2930 +** or last child of its parent. If pPage has fewer than two siblings
2931 +** (something which can only happen if pPage is the root page or a
2932 +** child of root) then all available siblings participate in the balancing.
2934 +** The number of siblings of pPage might be increased or decreased by
2935 +** one in an effort to keep pages between 66% and 100% full. The root page
2936 +** is special and is allowed to be less than 66% full. If pPage is
2937 +** the root page, then the depth of the tree might be increased
2938 +** or decreased by one, as necessary, to keep the root page from being
2939 +** overfull or empty.
2941 +** This routine calls relinkCellList() on its input page regardless of
2942 +** whether or not it does any real balancing. Client routines will typically
2943 +** invoke insertCell() or dropCell() before calling this routine, so we
2944 +** need to call relinkCellList() to clean up the mess that those other
2945 +** routines left behind.
2947 +** pCur is left pointing to the same cell as when this routine was called
2948 +** even if that cell gets moved to a different page. pCur may be NULL.
2949 +** Set the pCur parameter to NULL if you do not care about keeping track
2950 +** of a cell as that will save this routine the work of keeping track of it.
2952 +** Note that when this routine is called, some of the Cells on pPage
2953 +** might not actually be stored in pPage->u.aDisk[]. This can happen
2954 +** if the page is overfull. Part of the job of this routine is to
2955 +** make sure all Cells for pPage once again fit in pPage->u.aDisk[].
2957 +** In the course of balancing the siblings of pPage, the parent of pPage
2958 +** might become overfull or underfull. If that happens, then this routine
2959 +** is called recursively on the parent.
2961 +** If this routine fails for any reason, it might leave the database
2962 +** in a corrupted state. So if this routine fails, the database should
2965 +static int balance(Btree *pBt, MemPage *pPage, BtCursor *pCur){
2966 + MemPage *pParent; /* The parent of pPage */
2967 + int nCell; /* Number of cells in apCell[] */
2968 + int nOld; /* Number of pages in apOld[] */
2969 + int nNew; /* Number of pages in apNew[] */
2970 + int nDiv; /* Number of cells in apDiv[] */
2971 + int i, j, k; /* Loop counters */
2972 + int idx; /* Index of pPage in pParent->apCell[] */
2973 + int nxDiv; /* Next divider slot in pParent->apCell[] */
2974 + int rc; /* The return code */
2975 + int iCur; /* apCell[iCur] is the cell of the cursor */
2976 + MemPage *pOldCurPage; /* The cursor originally points to this page */
2977 + int subtotal; /* Subtotal of bytes in cells on one page */
2978 + MemPage *extraUnref = 0; /* A page that needs to be unref-ed */
2979 + MemPage *apOld[NB]; /* pPage and up to two siblings */
2980 + Pgno pgnoOld[NB]; /* Page numbers for each page in apOld[] */
2981 + MemPage *apNew[NB+1]; /* pPage and up to NB siblings after balancing */
2982 + Pgno pgnoNew[NB+1]; /* Page numbers for each page in apNew[] */
2983 + int idxDiv[NB]; /* Indices of divider cells in pParent */
2984 + Cell *apDiv[NB]; /* Divider cells in pParent */
2985 + Cell aTemp[NB]; /* Temporary holding area for apDiv[] */
2986 + int cntNew[NB+1]; /* Index in apCell[] of cell after i-th page */
2987 + int szNew[NB+1]; /* Combined size of cells place on i-th page */
2988 + MemPage aOld[NB]; /* Temporary copies of pPage and its siblings */
2989 + Cell *apCell[(MX_CELL+2)*NB]; /* All cells from pages being balanced */
2990 + int szCell[(MX_CELL+2)*NB]; /* Local size of all cells */
2993 + ** Return without doing any work if pPage is neither overfull nor
2996 + assert( sqlitepager_iswriteable(pPage) );
2997 + if( !pPage->isOverfull && pPage->nFree<SQLITE_USABLE_SIZE/2
2998 + && pPage->nCell>=2){
2999 + relinkCellList(pBt, pPage);
3004 + ** Find the parent of the page to be balanceed.
3005 + ** If there is no parent, it means this page is the root page and
3006 + ** special rules apply.
3008 + pParent = pPage->pParent;
3012 + assert( pPage->isInit );
3013 + if( pPage->nCell==0 ){
3014 + if( pPage->u.hdr.rightChild ){
3016 + ** The root page is empty. Copy the one child page
3017 + ** into the root page and return. This reduces the depth
3018 + ** of the BTree by one.
3020 + pgnoChild = SWAB32(pBt, pPage->u.hdr.rightChild);
3021 + rc = sqlitepager_get(pBt->pPager, pgnoChild, (void**)&pChild);
3022 + if( rc ) return rc;
3023 + memcpy(pPage, pChild, SQLITE_USABLE_SIZE);
3024 + pPage->isInit = 0;
3025 + rc = initPage(pBt, pPage, sqlitepager_pagenumber(pPage), 0);
3026 + assert( rc==SQLITE_OK );
3027 + reparentChildPages(pBt, pPage);
3028 + if( pCur && pCur->pPage==pChild ){
3029 + sqlitepager_unref(pChild);
3030 + pCur->pPage = pPage;
3031 + sqlitepager_ref(pPage);
3033 + freePage(pBt, pChild, pgnoChild);
3034 + sqlitepager_unref(pChild);
3036 + relinkCellList(pBt, pPage);
3040 + if( !pPage->isOverfull ){
3041 + /* It is OK for the root page to be less than half full.
3043 + relinkCellList(pBt, pPage);
3047 + ** If we get to here, it means the root page is overfull.
3048 + ** When this happens, Create a new child page and copy the
3049 + ** contents of the root into the child. Then make the root
3050 + ** page an empty page with rightChild pointing to the new
3051 + ** child. Then fall thru to the code below which will cause
3052 + ** the overfull child page to be split.
3054 + rc = sqlitepager_write(pPage);
3055 + if( rc ) return rc;
3056 + rc = allocatePage(pBt, &pChild, &pgnoChild, sqlitepager_pagenumber(pPage));
3057 + if( rc ) return rc;
3058 + assert( sqlitepager_iswriteable(pChild) );
3059 + copyPage(pChild, pPage);
3060 + pChild->pParent = pPage;
3061 + pChild->idxParent = 0;
3062 + sqlitepager_ref(pPage);
3063 + pChild->isOverfull = 1;
3064 + if( pCur && pCur->pPage==pPage ){
3065 + sqlitepager_unref(pPage);
3066 + pCur->pPage = pChild;
3068 + extraUnref = pChild;
3070 + zeroPage(pBt, pPage);
3071 + pPage->u.hdr.rightChild = SWAB32(pBt, pgnoChild);
3075 + rc = sqlitepager_write(pParent);
3076 + if( rc ) return rc;
3077 + assert( pParent->isInit );
3080 + ** Find the Cell in the parent page whose h.leftChild points back
3081 + ** to pPage. The "idx" variable is the index of that cell. If pPage
3082 + ** is the rightmost child of pParent then set idx to pParent->nCell
3084 + if( pParent->idxShift ){
3085 + Pgno pgno, swabPgno;
3086 + pgno = sqlitepager_pagenumber(pPage);
3087 + swabPgno = SWAB32(pBt, pgno);
3088 + for(idx=0; idx<pParent->nCell; idx++){
3089 + if( pParent->apCell[idx]->h.leftChild==swabPgno ){
3093 + assert( idx<pParent->nCell || pParent->u.hdr.rightChild==swabPgno );
3095 + idx = pPage->idxParent;
3099 + ** Initialize variables so that it will be safe to jump
3100 + ** directly to balance_cleanup at any moment.
3103 + sqlitepager_ref(pParent);
3106 + ** Find sibling pages to pPage and the Cells in pParent that divide
3107 + ** the siblings. An attempt is made to find NN siblings on either
3108 + ** side of pPage. More siblings are taken from one side, however, if
3109 + ** pPage there are fewer than NN siblings on the other side. If pParent
3110 + ** has NB or fewer children then all children of pParent are taken.
3113 + if( nxDiv + NB > pParent->nCell ){
3114 + nxDiv = pParent->nCell - NB + 1;
3120 + for(i=0, k=nxDiv; i<NB; i++, k++){
3121 + if( k<pParent->nCell ){
3123 + apDiv[i] = pParent->apCell[k];
3125 + pgnoOld[i] = SWAB32(pBt, apDiv[i]->h.leftChild);
3126 + }else if( k==pParent->nCell ){
3127 + pgnoOld[i] = SWAB32(pBt, pParent->u.hdr.rightChild);
3131 + rc = sqlitepager_get(pBt->pPager, pgnoOld[i], (void**)&apOld[i]);
3132 + if( rc ) goto balance_cleanup;
3133 + rc = initPage(pBt, apOld[i], pgnoOld[i], pParent);
3134 + if( rc ) goto balance_cleanup;
3135 + apOld[i]->idxParent = k;
3140 + ** Set iCur to be the index in apCell[] of the cell that the cursor
3141 + ** is pointing to. We will need this later on in order to keep the
3142 + ** cursor pointing at the same cell. If pCur points to a page that
3143 + ** has no involvement with this rebalancing, then set iCur to a large
3144 + ** number so that the iCur==j tests always fail in the main cell
3145 + ** distribution loop below.
3149 + for(i=0; i<nOld; i++){
3150 + if( pCur->pPage==apOld[i] ){
3151 + iCur += pCur->idx;
3154 + iCur += apOld[i]->nCell;
3155 + if( i<nOld-1 && pCur->pPage==pParent && pCur->idx==idxDiv[i] ){
3160 + pOldCurPage = pCur->pPage;
3164 + ** Make copies of the content of pPage and its siblings into aOld[].
3165 + ** The rest of this function will use data from the copies rather
3166 + ** that the original pages since the original pages will be in the
3167 + ** process of being overwritten.
3169 + for(i=0; i<nOld; i++){
3170 + copyPage(&aOld[i], apOld[i]);
3174 + ** Load pointers to all cells on sibling pages and the divider cells
3175 + ** into the local apCell[] array. Make copies of the divider cells
3176 + ** into aTemp[] and remove the the divider Cells from pParent.
3179 + for(i=0; i<nOld; i++){
3180 + MemPage *pOld = &aOld[i];
3181 + for(j=0; j<pOld->nCell; j++){
3182 + apCell[nCell] = pOld->apCell[j];
3183 + szCell[nCell] = cellSize(pBt, apCell[nCell]);
3187 + szCell[nCell] = cellSize(pBt, apDiv[i]);
3188 + memcpy(&aTemp[i], apDiv[i], szCell[nCell]);
3189 + apCell[nCell] = &aTemp[i];
3190 + dropCell(pBt, pParent, nxDiv, szCell[nCell]);
3191 + assert( SWAB32(pBt, apCell[nCell]->h.leftChild)==pgnoOld[i] );
3192 + apCell[nCell]->h.leftChild = pOld->u.hdr.rightChild;
3198 + ** Figure out the number of pages needed to hold all nCell cells.
3199 + ** Store this number in "k". Also compute szNew[] which is the total
3200 + ** size of all cells on the i-th page and cntNew[] which is the index
3201 + ** in apCell[] of the cell that divides path i from path i+1.
3202 + ** cntNew[k] should equal nCell.
3204 + ** This little patch of code is critical for keeping the tree
3207 + for(subtotal=k=i=0; i<nCell; i++){
3208 + subtotal += szCell[i];
3209 + if( subtotal > USABLE_SPACE ){
3210 + szNew[k] = subtotal - szCell[i];
3216 + szNew[k] = subtotal;
3217 + cntNew[k] = nCell;
3219 + for(i=k-1; i>0; i--){
3220 + while( szNew[i]<USABLE_SPACE/2 ){
3222 + assert( cntNew[i-1]>0 );
3223 + szNew[i] += szCell[cntNew[i-1]];
3224 + szNew[i-1] -= szCell[cntNew[i-1]-1];
3227 + assert( cntNew[0]>0 );
3230 + ** Allocate k new pages. Reuse old pages where possible.
3232 + for(i=0; i<k; i++){
3234 + apNew[i] = apOld[i];
3235 + pgnoNew[i] = pgnoOld[i];
3237 + sqlitepager_write(apNew[i]);
3239 + rc = allocatePage(pBt, &apNew[i], &pgnoNew[i], pgnoNew[i-1]);
3240 + if( rc ) goto balance_cleanup;
3243 + zeroPage(pBt, apNew[i]);
3244 + apNew[i]->isInit = 1;
3247 + /* Free any old pages that were not reused as new pages.
3250 + rc = freePage(pBt, apOld[i], pgnoOld[i]);
3251 + if( rc ) goto balance_cleanup;
3252 + sqlitepager_unref(apOld[i]);
3258 + ** Put the new pages in accending order. This helps to
3259 + ** keep entries in the disk file in order so that a scan
3260 + ** of the table is a linear scan through the file. That
3261 + ** in turn helps the operating system to deliver pages
3262 + ** from the disk more rapidly.
3264 + ** An O(n^2) insertion sort algorithm is used, but since
3265 + ** n is never more than NB (a small constant), that should
3266 + ** not be a problem.
3268 + ** When NB==3, this one optimization makes the database
3269 + ** about 25% faster for large insertions and deletions.
3271 + for(i=0; i<k-1; i++){
3272 + int minV = pgnoNew[i];
3274 + for(j=i+1; j<k; j++){
3275 + if( pgnoNew[j]<(unsigned)minV ){
3277 + minV = pgnoNew[j];
3285 + pgnoNew[i] = pgnoNew[minI];
3286 + apNew[i] = apNew[minI];
3287 + pgnoNew[minI] = t;
3293 + ** Evenly distribute the data in apCell[] across the new pages.
3294 + ** Insert divider cells into pParent as necessary.
3297 + for(i=0; i<nNew; i++){
3298 + MemPage *pNew = apNew[i];
3299 + while( j<cntNew[i] ){
3300 + assert( pNew->nFree>=szCell[j] );
3301 + if( pCur && iCur==j ){ pCur->pPage = pNew; pCur->idx = pNew->nCell; }
3302 + insertCell(pBt, pNew, pNew->nCell, apCell[j], szCell[j]);
3305 + assert( pNew->nCell>0 );
3306 + assert( !pNew->isOverfull );
3307 + relinkCellList(pBt, pNew);
3308 + if( i<nNew-1 && j<nCell ){
3309 + pNew->u.hdr.rightChild = apCell[j]->h.leftChild;
3310 + apCell[j]->h.leftChild = SWAB32(pBt, pgnoNew[i]);
3311 + if( pCur && iCur==j ){ pCur->pPage = pParent; pCur->idx = nxDiv; }
3312 + insertCell(pBt, pParent, nxDiv, apCell[j], szCell[j]);
3317 + assert( j==nCell );
3318 + apNew[nNew-1]->u.hdr.rightChild = aOld[nOld-1].u.hdr.rightChild;
3319 + if( nxDiv==pParent->nCell ){
3320 + pParent->u.hdr.rightChild = SWAB32(pBt, pgnoNew[nNew-1]);
3322 + pParent->apCell[nxDiv]->h.leftChild = SWAB32(pBt, pgnoNew[nNew-1]);
3325 + if( j<=iCur && pCur->pPage==pParent && pCur->idx>idxDiv[nOld-1] ){
3326 + assert( pCur->pPage==pOldCurPage );
3327 + pCur->idx += nNew - nOld;
3329 + assert( pOldCurPage!=0 );
3330 + sqlitepager_ref(pCur->pPage);
3331 + sqlitepager_unref(pOldCurPage);
3336 + ** Reparent children of all cells.
3338 + for(i=0; i<nNew; i++){
3339 + reparentChildPages(pBt, apNew[i]);
3341 + reparentChildPages(pBt, pParent);
3344 + ** balance the parent page.
3346 + rc = balance(pBt, pParent, pCur);
3349 + ** Cleanup before returning.
3353 + sqlitepager_unref(extraUnref);
3355 + for(i=0; i<nOld; i++){
3356 + if( apOld[i]!=0 && apOld[i]!=&aOld[i] ) sqlitepager_unref(apOld[i]);
3358 + for(i=0; i<nNew; i++){
3359 + sqlitepager_unref(apNew[i]);
3361 + if( pCur && pCur->pPage==0 ){
3362 + pCur->pPage = pParent;
3365 + sqlitepager_unref(pParent);
3371 +** This routine checks all cursors that point to the same table
3372 +** as pCur points to. If any of those cursors were opened with
3373 +** wrFlag==0 then this routine returns SQLITE_LOCKED. If all
3374 +** cursors point to the same table were opened with wrFlag==1
3375 +** then this routine returns SQLITE_OK.
3377 +** In addition to checking for read-locks (where a read-lock
3378 +** means a cursor opened with wrFlag==0) this routine also moves
3379 +** all cursors other than pCur so that they are pointing to the
3380 +** first Cell on root page. This is necessary because an insert
3381 +** or delete might change the number of cells on a page or delete
3382 +** a page entirely and we do not want to leave any cursors
3383 +** pointing to non-existant pages or cells.
3385 +static int checkReadLocks(BtCursor *pCur){
3387 + assert( pCur->wrFlag );
3388 + for(p=pCur->pShared; p!=pCur; p=p->pShared){
3390 + assert( p->pgnoRoot==pCur->pgnoRoot );
3391 + if( p->wrFlag==0 ) return SQLITE_LOCKED;
3392 + if( sqlitepager_pagenumber(p->pPage)!=p->pgnoRoot ){
3400 +** Insert a new record into the BTree. The key is given by (pKey,nKey)
3401 +** and the data is given by (pData,nData). The cursor is used only to
3402 +** define what database the record should be inserted into. The cursor
3403 +** is left pointing at the new record.
3405 +static int fileBtreeInsert(
3406 + BtCursor *pCur, /* Insert data into the table of this cursor */
3407 + const void *pKey, int nKey, /* The key of the new record */
3408 + const void *pData, int nData /* The data of the new record */
3415 + Btree *pBt = pCur->pBt;
3417 + if( pCur->pPage==0 ){
3418 + return SQLITE_ABORT; /* A rollback destroyed this cursor */
3420 + if( !pBt->inTrans || nKey+nData==0 ){
3421 + /* Must start a transaction before doing an insert */
3422 + return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
3424 + assert( !pBt->readOnly );
3425 + if( !pCur->wrFlag ){
3426 + return SQLITE_PERM; /* Cursor not open for writing */
3428 + if( checkReadLocks(pCur) ){
3429 + return SQLITE_LOCKED; /* The table pCur points to has a read lock */
3431 + rc = fileBtreeMoveto(pCur, pKey, nKey, &loc);
3432 + if( rc ) return rc;
3433 + pPage = pCur->pPage;
3434 + assert( pPage->isInit );
3435 + rc = sqlitepager_write(pPage);
3436 + if( rc ) return rc;
3437 + rc = fillInCell(pBt, &newCell, pKey, nKey, pData, nData);
3438 + if( rc ) return rc;
3439 + szNew = cellSize(pBt, &newCell);
3441 + newCell.h.leftChild = pPage->apCell[pCur->idx]->h.leftChild;
3442 + rc = clearCell(pBt, pPage->apCell[pCur->idx]);
3443 + if( rc ) return rc;
3444 + dropCell(pBt, pPage, pCur->idx, cellSize(pBt, pPage->apCell[pCur->idx]));
3445 + }else if( loc<0 && pPage->nCell>0 ){
3446 + assert( pPage->u.hdr.rightChild==0 ); /* Must be a leaf page */
3449 + assert( pPage->u.hdr.rightChild==0 ); /* Must be a leaf page */
3451 + insertCell(pBt, pPage, pCur->idx, &newCell, szNew);
3452 + rc = balance(pCur->pBt, pPage, pCur);
3453 + /* sqliteBtreePageDump(pCur->pBt, pCur->pgnoRoot, 1); */
3454 + /* fflush(stdout); */
3455 + pCur->eSkip = SKIP_INVALID;
3460 +** Delete the entry that the cursor is pointing to.
3462 +** The cursor is left pointing at either the next or the previous
3463 +** entry. If the cursor is left pointing to the next entry, then
3464 +** the pCur->eSkip flag is set to SKIP_NEXT which forces the next call to
3465 +** sqliteBtreeNext() to be a no-op. That way, you can always call
3466 +** sqliteBtreeNext() after a delete and the cursor will be left
3467 +** pointing to the first entry after the deleted entry. Similarly,
3468 +** pCur->eSkip is set to SKIP_PREV is the cursor is left pointing to
3469 +** the entry prior to the deleted entry so that a subsequent call to
3470 +** sqliteBtreePrevious() will always leave the cursor pointing at the
3471 +** entry immediately before the one that was deleted.
3473 +static int fileBtreeDelete(BtCursor *pCur){
3474 + MemPage *pPage = pCur->pPage;
3478 + Btree *pBt = pCur->pBt;
3480 + assert( pPage->isInit );
3481 + if( pCur->pPage==0 ){
3482 + return SQLITE_ABORT; /* A rollback destroyed this cursor */
3484 + if( !pBt->inTrans ){
3485 + /* Must start a transaction before doing a delete */
3486 + return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
3488 + assert( !pBt->readOnly );
3489 + if( pCur->idx >= pPage->nCell ){
3490 + return SQLITE_ERROR; /* The cursor is not pointing to anything */
3492 + if( !pCur->wrFlag ){
3493 + return SQLITE_PERM; /* Did not open this cursor for writing */
3495 + if( checkReadLocks(pCur) ){
3496 + return SQLITE_LOCKED; /* The table pCur points to has a read lock */
3498 + rc = sqlitepager_write(pPage);
3499 + if( rc ) return rc;
3500 + pCell = pPage->apCell[pCur->idx];
3501 + pgnoChild = SWAB32(pBt, pCell->h.leftChild);
3502 + clearCell(pBt, pCell);
3505 + ** The entry we are about to delete is not a leaf so if we do not
3506 + ** do something we will leave a hole on an internal page.
3507 + ** We have to fill the hole by moving in a cell from a leaf. The
3508 + ** next Cell after the one to be deleted is guaranteed to exist and
3509 + ** to be a leaf so we can use it.
3515 + getTempCursor(pCur, &leafCur);
3516 + rc = fileBtreeNext(&leafCur, ¬Used);
3517 + if( rc!=SQLITE_OK ){
3518 + if( rc!=SQLITE_NOMEM ) rc = SQLITE_CORRUPT;
3521 + rc = sqlitepager_write(leafCur.pPage);
3522 + if( rc ) return rc;
3523 + dropCell(pBt, pPage, pCur->idx, cellSize(pBt, pCell));
3524 + pNext = leafCur.pPage->apCell[leafCur.idx];
3525 + szNext = cellSize(pBt, pNext);
3526 + pNext->h.leftChild = SWAB32(pBt, pgnoChild);
3527 + insertCell(pBt, pPage, pCur->idx, pNext, szNext);
3528 + rc = balance(pBt, pPage, pCur);
3529 + if( rc ) return rc;
3530 + pCur->eSkip = SKIP_NEXT;
3531 + dropCell(pBt, leafCur.pPage, leafCur.idx, szNext);
3532 + rc = balance(pBt, leafCur.pPage, pCur);
3533 + releaseTempCursor(&leafCur);
3535 + dropCell(pBt, pPage, pCur->idx, cellSize(pBt, pCell));
3536 + if( pCur->idx>=pPage->nCell ){
3537 + pCur->idx = pPage->nCell-1;
3538 + if( pCur->idx<0 ){
3540 + pCur->eSkip = SKIP_NEXT;
3542 + pCur->eSkip = SKIP_PREV;
3545 + pCur->eSkip = SKIP_NEXT;
3547 + rc = balance(pBt, pPage, pCur);
3553 +** Create a new BTree table. Write into *piTable the page
3554 +** number for the root page of the new table.
3556 +** In the current implementation, BTree tables and BTree indices are the
3557 +** the same. In the future, we may change this so that BTree tables
3558 +** are restricted to having a 4-byte integer key and arbitrary data and
3559 +** BTree indices are restricted to having an arbitrary key and no data.
3560 +** But for now, this routine also serves to create indices.
3562 +static int fileBtreeCreateTable(Btree *pBt, int *piTable){
3566 + if( !pBt->inTrans ){
3567 + /* Must start a transaction first */
3568 + return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
3570 + if( pBt->readOnly ){
3571 + return SQLITE_READONLY;
3573 + rc = allocatePage(pBt, &pRoot, &pgnoRoot, 0);
3574 + if( rc ) return rc;
3575 + assert( sqlitepager_iswriteable(pRoot) );
3576 + zeroPage(pBt, pRoot);
3577 + sqlitepager_unref(pRoot);
3578 + *piTable = (int)pgnoRoot;
3583 +** Erase the given database page and all its children. Return
3584 +** the page to the freelist.
3586 +static int clearDatabasePage(Btree *pBt, Pgno pgno, int freePageFlag){
3592 + rc = sqlitepager_get(pBt->pPager, pgno, (void**)&pPage);
3593 + if( rc ) return rc;
3594 + rc = sqlitepager_write(pPage);
3595 + if( rc ) return rc;
3596 + rc = initPage(pBt, pPage, pgno, 0);
3597 + if( rc ) return rc;
3598 + idx = SWAB16(pBt, pPage->u.hdr.firstCell);
3600 + pCell = (Cell*)&pPage->u.aDisk[idx];
3601 + idx = SWAB16(pBt, pCell->h.iNext);
3602 + if( pCell->h.leftChild ){
3603 + rc = clearDatabasePage(pBt, SWAB32(pBt, pCell->h.leftChild), 1);
3604 + if( rc ) return rc;
3606 + rc = clearCell(pBt, pCell);
3607 + if( rc ) return rc;
3609 + if( pPage->u.hdr.rightChild ){
3610 + rc = clearDatabasePage(pBt, SWAB32(pBt, pPage->u.hdr.rightChild), 1);
3611 + if( rc ) return rc;
3613 + if( freePageFlag ){
3614 + rc = freePage(pBt, pPage, pgno);
3616 + zeroPage(pBt, pPage);
3618 + sqlitepager_unref(pPage);
3623 +** Delete all information from a single table in the database.
3625 +static int fileBtreeClearTable(Btree *pBt, int iTable){
3628 + if( !pBt->inTrans ){
3629 + return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
3631 + for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
3632 + if( pCur->pgnoRoot==(Pgno)iTable ){
3633 + if( pCur->wrFlag==0 ) return SQLITE_LOCKED;
3637 + rc = clearDatabasePage(pBt, (Pgno)iTable, 0);
3639 + fileBtreeRollback(pBt);
3645 +** Erase all information in a table and add the root of the table to
3646 +** the freelist. Except, the root of the principle table (the one on
3647 +** page 2) is never added to the freelist.
3649 +static int fileBtreeDropTable(Btree *pBt, int iTable){
3653 + if( !pBt->inTrans ){
3654 + return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
3656 + for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
3657 + if( pCur->pgnoRoot==(Pgno)iTable ){
3658 + return SQLITE_LOCKED; /* Cannot drop a table that has a cursor */
3661 + rc = sqlitepager_get(pBt->pPager, (Pgno)iTable, (void**)&pPage);
3662 + if( rc ) return rc;
3663 + rc = fileBtreeClearTable(pBt, iTable);
3664 + if( rc ) return rc;
3666 + rc = freePage(pBt, pPage, iTable);
3668 + zeroPage(pBt, pPage);
3670 + sqlitepager_unref(pPage);
3674 +#if 0 /* UNTESTED */
3676 +** Copy all cell data from one database file into another.
3677 +** pages back the freelist.
3679 +static int copyCell(Btree *pBtFrom, BTree *pBtTo, Cell *pCell){
3680 + Pager *pFromPager = pBtFrom->pPager;
3681 + OverflowPage *pOvfl;
3682 + Pgno ovfl, nextOvfl;
3684 + int rc = SQLITE_OK;
3685 + MemPage *pNew, *pPrevPg;
3688 + if( NKEY(pBtTo, pCell->h) + NDATA(pBtTo, pCell->h) <= MX_LOCAL_PAYLOAD ){
3691 + pPrev = &pCell->ovfl;
3693 + ovfl = SWAB32(pBtTo, pCell->ovfl);
3694 + while( ovfl && rc==SQLITE_OK ){
3695 + rc = sqlitepager_get(pFromPager, ovfl, (void**)&pOvfl);
3696 + if( rc ) return rc;
3697 + nextOvfl = SWAB32(pBtFrom, pOvfl->iNext);
3698 + rc = allocatePage(pBtTo, &pNew, &new, 0);
3699 + if( rc==SQLITE_OK ){
3700 + rc = sqlitepager_write(pNew);
3701 + if( rc==SQLITE_OK ){
3702 + memcpy(pNew, pOvfl, SQLITE_USABLE_SIZE);
3703 + *pPrev = SWAB32(pBtTo, new);
3705 + sqlitepager_unref(pPrevPg);
3707 + pPrev = &pOvfl->iNext;
3711 + sqlitepager_unref(pOvfl);
3715 + sqlitepager_unref(pPrevPg);
3722 +#if 0 /* UNTESTED */
3724 +** Copy a page of data from one database over to another.
3726 +static int copyDatabasePage(
3732 + MemPage *pPageFrom, *pPage;
3738 + rc = sqlitepager_get(pBtFrom->pPager, pgno, (void**)&pPageFrom);
3739 + if( rc ) return rc;
3740 + rc = allocatePage(pBt, &pPage, pTo, 0);
3741 + if( rc==SQLITE_OK ){
3742 + rc = sqlitepager_write(pPage);
3744 + if( rc==SQLITE_OK ){
3745 + memcpy(pPage, pPageFrom, SQLITE_USABLE_SIZE);
3746 + idx = SWAB16(pBt, pPage->u.hdr.firstCell);
3748 + pCell = (Cell*)&pPage->u.aDisk[idx];
3749 + idx = SWAB16(pBt, pCell->h.iNext);
3750 + if( pCell->h.leftChild ){
3752 + rc = copyDatabasePage(pBtFrom, SWAB32(pBtFrom, pCell->h.leftChild),
3754 + if( rc ) return rc;
3755 + pCell->h.leftChild = SWAB32(pBtFrom, newChld);
3757 + rc = copyCell(pBtFrom, pBtTo, pCell);
3758 + if( rc ) return rc;
3760 + if( pPage->u.hdr.rightChild ){
3762 + rc = copyDatabasePage(pBtFrom, SWAB32(pBtFrom, pPage->u.hdr.rightChild),
3764 + if( rc ) return rc;
3765 + pPage->u.hdr.rightChild = SWAB32(pBtTo, newChild);
3768 + sqlitepager_unref(pPage);
3774 +** Read the meta-information out of a database file.
3776 +static int fileBtreeGetMeta(Btree *pBt, int *aMeta){
3781 + rc = sqlitepager_get(pBt->pPager, 1, (void**)&pP1);
3782 + if( rc ) return rc;
3783 + aMeta[0] = SWAB32(pBt, pP1->nFree);
3784 + for(i=0; i<sizeof(pP1->aMeta)/sizeof(pP1->aMeta[0]); i++){
3785 + aMeta[i+1] = SWAB32(pBt, pP1->aMeta[i]);
3787 + sqlitepager_unref(pP1);
3792 +** Write meta-information back into the database.
3794 +static int fileBtreeUpdateMeta(Btree *pBt, int *aMeta){
3797 + if( !pBt->inTrans ){
3798 + return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
3801 + rc = sqlitepager_write(pP1);
3802 + if( rc ) return rc;
3803 + for(i=0; i<sizeof(pP1->aMeta)/sizeof(pP1->aMeta[0]); i++){
3804 + pP1->aMeta[i] = SWAB32(pBt, aMeta[i+1]);
3809 +/******************************************************************************
3810 +** The complete implementation of the BTree subsystem is above this line.
3811 +** All the code the follows is for testing and troubleshooting the BTree
3812 +** subsystem. None of the code that follows is used during normal operation.
3813 +******************************************************************************/
3816 +** Print a disassembly of the given page on standard output. This routine
3817 +** is used for debugging and testing only.
3820 +static int fileBtreePageDump(Btree *pBt, int pgno, int recursive){
3827 + unsigned char payload[20];
3828 + rc = sqlitepager_get(pBt->pPager, (Pgno)pgno, (void**)&pPage);
3832 + if( recursive ) printf("PAGE %d:\n", pgno);
3834 + idx = SWAB16(pBt, pPage->u.hdr.firstCell);
3835 + while( idx>0 && idx<=SQLITE_USABLE_SIZE-MIN_CELL_SIZE ){
3836 + Cell *pCell = (Cell*)&pPage->u.aDisk[idx];
3837 + int sz = cellSize(pBt, pCell);
3838 + sprintf(range,"%d..%d", idx, idx+sz-1);
3839 + sz = NKEY(pBt, pCell->h) + NDATA(pBt, pCell->h);
3840 + if( sz>sizeof(payload)-1 ) sz = sizeof(payload)-1;
3841 + memcpy(payload, pCell->aPayload, sz);
3842 + for(j=0; j<sz; j++){
3843 + if( payload[j]<0x20 || payload[j]>0x7f ) payload[j] = '.';
3847 + "cell %2d: i=%-10s chld=%-4d nk=%-4d nd=%-4d payload=%s\n",
3848 + i, range, (int)pCell->h.leftChild,
3849 + NKEY(pBt, pCell->h), NDATA(pBt, pCell->h),
3852 + if( pPage->isInit && pPage->apCell[i]!=pCell ){
3853 + printf("**** apCell[%d] does not match on prior entry ****\n", i);
3856 + idx = SWAB16(pBt, pCell->h.iNext);
3859 + printf("ERROR: next cell index out of range: %d\n", idx);
3861 + printf("right_child: %d\n", SWAB32(pBt, pPage->u.hdr.rightChild));
3864 + idx = SWAB16(pBt, pPage->u.hdr.firstFree);
3865 + while( idx>0 && idx<SQLITE_USABLE_SIZE ){
3866 + FreeBlk *p = (FreeBlk*)&pPage->u.aDisk[idx];
3867 + sprintf(range,"%d..%d", idx, idx+p->iSize-1);
3868 + nFree += SWAB16(pBt, p->iSize);
3869 + printf("freeblock %2d: i=%-10s size=%-4d total=%d\n",
3870 + i, range, SWAB16(pBt, p->iSize), nFree);
3871 + idx = SWAB16(pBt, p->iNext);
3875 + printf("ERROR: next freeblock index out of range: %d\n", idx);
3877 + if( recursive && pPage->u.hdr.rightChild!=0 ){
3878 + idx = SWAB16(pBt, pPage->u.hdr.firstCell);
3879 + while( idx>0 && idx<SQLITE_USABLE_SIZE-MIN_CELL_SIZE ){
3880 + Cell *pCell = (Cell*)&pPage->u.aDisk[idx];
3881 + fileBtreePageDump(pBt, SWAB32(pBt, pCell->h.leftChild), 1);
3882 + idx = SWAB16(pBt, pCell->h.iNext);
3884 + fileBtreePageDump(pBt, SWAB32(pBt, pPage->u.hdr.rightChild), 1);
3886 + sqlitepager_unref(pPage);
3893 +** Fill aResult[] with information about the entry and page that the
3894 +** cursor is pointing to.
3896 +** aResult[0] = The page number
3897 +** aResult[1] = The entry number
3898 +** aResult[2] = Total number of entries on this page
3899 +** aResult[3] = Size of this entry
3900 +** aResult[4] = Number of free bytes on this page
3901 +** aResult[5] = Number of free blocks on the page
3902 +** aResult[6] = Page number of the left child of this entry
3903 +** aResult[7] = Page number of the right child for the whole page
3905 +** This routine is used for testing and debugging only.
3907 +static int fileBtreeCursorDump(BtCursor *pCur, int *aResult){
3909 + MemPage *pPage = pCur->pPage;
3910 + Btree *pBt = pCur->pBt;
3911 + aResult[0] = sqlitepager_pagenumber(pPage);
3912 + aResult[1] = pCur->idx;
3913 + aResult[2] = pPage->nCell;
3914 + if( pCur->idx>=0 && pCur->idx<pPage->nCell ){
3915 + aResult[3] = cellSize(pBt, pPage->apCell[pCur->idx]);
3916 + aResult[6] = SWAB32(pBt, pPage->apCell[pCur->idx]->h.leftChild);
3921 + aResult[4] = pPage->nFree;
3923 + idx = SWAB16(pBt, pPage->u.hdr.firstFree);
3924 + while( idx>0 && idx<SQLITE_USABLE_SIZE ){
3926 + idx = SWAB16(pBt, ((FreeBlk*)&pPage->u.aDisk[idx])->iNext);
3929 + aResult[7] = SWAB32(pBt, pPage->u.hdr.rightChild);
3935 +** Return the pager associated with a BTree. This routine is used for
3936 +** testing and debugging only.
3938 +static Pager *fileBtreePager(Btree *pBt){
3939 + return pBt->pPager;
3943 +** This structure is passed around through all the sanity checking routines
3944 +** in order to keep track of some global state information.
3946 +typedef struct IntegrityCk IntegrityCk;
3947 +struct IntegrityCk {
3948 + Btree *pBt; /* The tree being checked out */
3949 + Pager *pPager; /* The associated pager. Also accessible by pBt->pPager */
3950 + int nPage; /* Number of pages in the database */
3951 + int *anRef; /* Number of times each page is referenced */
3952 + char *zErrMsg; /* An error message. NULL of no errors seen. */
3956 +** Append a message to the error message string.
3958 +static void checkAppendMsg(IntegrityCk *pCheck, char *zMsg1, char *zMsg2){
3959 + if( pCheck->zErrMsg ){
3960 + char *zOld = pCheck->zErrMsg;
3961 + pCheck->zErrMsg = 0;
3962 + sqliteSetString(&pCheck->zErrMsg, zOld, "\n", zMsg1, zMsg2, (char*)0);
3965 + sqliteSetString(&pCheck->zErrMsg, zMsg1, zMsg2, (char*)0);
3970 +** Add 1 to the reference count for page iPage. If this is the second
3971 +** reference to the page, add an error message to pCheck->zErrMsg.
3972 +** Return 1 if there are 2 ore more references to the page and 0 if
3973 +** if this is the first reference to the page.
3975 +** Also check that the page number is in bounds.
3977 +static int checkRef(IntegrityCk *pCheck, int iPage, char *zContext){
3978 + if( iPage==0 ) return 1;
3979 + if( iPage>pCheck->nPage || iPage<0 ){
3981 + sprintf(zBuf, "invalid page number %d", iPage);
3982 + checkAppendMsg(pCheck, zContext, zBuf);
3985 + if( pCheck->anRef[iPage]==1 ){
3987 + sprintf(zBuf, "2nd reference to page %d", iPage);
3988 + checkAppendMsg(pCheck, zContext, zBuf);
3991 + return (pCheck->anRef[iPage]++)>1;
3995 +** Check the integrity of the freelist or of an overflow page list.
3996 +** Verify that the number of pages on the list is N.
3998 +static void checkList(
3999 + IntegrityCk *pCheck, /* Integrity checking context */
4000 + int isFreeList, /* True for a freelist. False for overflow page list */
4001 + int iPage, /* Page number for first page in the list */
4002 + int N, /* Expected number of pages in the list */
4003 + char *zContext /* Context for error messages */
4008 + OverflowPage *pOvfl;
4010 + sprintf(zMsg, "%d pages missing from overflow list", N+1);
4011 + checkAppendMsg(pCheck, zContext, zMsg);
4014 + if( checkRef(pCheck, iPage, zContext) ) break;
4015 + if( sqlitepager_get(pCheck->pPager, (Pgno)iPage, (void**)&pOvfl) ){
4016 + sprintf(zMsg, "failed to get page %d", iPage);
4017 + checkAppendMsg(pCheck, zContext, zMsg);
4021 + FreelistInfo *pInfo = (FreelistInfo*)pOvfl->aPayload;
4022 + int n = SWAB32(pCheck->pBt, pInfo->nFree);
4023 + for(i=0; i<n; i++){
4024 + checkRef(pCheck, SWAB32(pCheck->pBt, pInfo->aFree[i]), zContext);
4028 + iPage = SWAB32(pCheck->pBt, pOvfl->iNext);
4029 + sqlitepager_unref(pOvfl);
4034 +** Return negative if zKey1<zKey2.
4035 +** Return zero if zKey1==zKey2.
4036 +** Return positive if zKey1>zKey2.
4038 +static int keyCompare(
4039 + const char *zKey1, int nKey1,
4040 + const char *zKey2, int nKey2
4042 + int min = nKey1>nKey2 ? nKey2 : nKey1;
4043 + int c = memcmp(zKey1, zKey2, min);
4045 + c = nKey1 - nKey2;
4051 +** Do various sanity checks on a single page of a tree. Return
4052 +** the tree depth. Root pages return 0. Parents of root pages
4053 +** return 1, and so forth.
4055 +** These checks are done:
4057 +** 1. Make sure that cells and freeblocks do not overlap
4058 +** but combine to completely cover the page.
4059 +** 2. Make sure cell keys are in order.
4060 +** 3. Make sure no key is less than or equal to zLowerBound.
4061 +** 4. Make sure no key is greater than or equal to zUpperBound.
4062 +** 5. Check the integrity of overflow pages.
4063 +** 6. Recursively call checkTreePage on all children.
4064 +** 7. Verify that the depth of all children is the same.
4065 +** 8. Make sure this page is at least 33% full or else it is
4066 +** the root of the tree.
4068 +static int checkTreePage(
4069 + IntegrityCk *pCheck, /* Context for the sanity check */
4070 + int iPage, /* Page number of the page to check */
4071 + MemPage *pParent, /* Parent page */
4072 + char *zParentContext, /* Parent context */
4073 + char *zLowerBound, /* All keys should be greater than this, if not NULL */
4074 + int nLower, /* Number of characters in zLowerBound */
4075 + char *zUpperBound, /* All keys should be less than this, if not NULL */
4076 + int nUpper /* Number of characters in zUpperBound */
4079 + int i, rc, depth, d2, pgno;
4080 + char *zKey1, *zKey2;
4085 + char zContext[100];
4086 + char hit[SQLITE_USABLE_SIZE];
4088 + /* Check that the page exists
4090 + cur.pBt = pBt = pCheck->pBt;
4091 + if( iPage==0 ) return 0;
4092 + if( checkRef(pCheck, iPage, zParentContext) ) return 0;
4093 + sprintf(zContext, "On tree page %d: ", iPage);
4094 + if( (rc = sqlitepager_get(pCheck->pPager, (Pgno)iPage, (void**)&pPage))!=0 ){
4095 + sprintf(zMsg, "unable to get the page. error code=%d", rc);
4096 + checkAppendMsg(pCheck, zContext, zMsg);
4099 + if( (rc = initPage(pBt, pPage, (Pgno)iPage, pParent))!=0 ){
4100 + sprintf(zMsg, "initPage() returns error code %d", rc);
4101 + checkAppendMsg(pCheck, zContext, zMsg);
4102 + sqlitepager_unref(pPage);
4106 + /* Check out all the cells.
4109 + if( zLowerBound ){
4110 + zKey1 = sqliteMalloc( nLower+1 );
4111 + memcpy(zKey1, zLowerBound, nLower);
4112 + zKey1[nLower] = 0;
4117 + cur.pPage = pPage;
4118 + for(i=0; i<pPage->nCell; i++){
4119 + Cell *pCell = pPage->apCell[i];
4122 + /* Check payload overflow pages
4124 + nKey2 = NKEY(pBt, pCell->h);
4125 + sz = nKey2 + NDATA(pBt, pCell->h);
4126 + sprintf(zContext, "On page %d cell %d: ", iPage, i);
4127 + if( sz>MX_LOCAL_PAYLOAD ){
4128 + int nPage = (sz - MX_LOCAL_PAYLOAD + OVERFLOW_SIZE - 1)/OVERFLOW_SIZE;
4129 + checkList(pCheck, 0, SWAB32(pBt, pCell->ovfl), nPage, zContext);
4132 + /* Check that keys are in the right order
4135 + zKey2 = sqliteMallocRaw( nKey2+1 );
4136 + getPayload(&cur, 0, nKey2, zKey2);
4137 + if( zKey1 && keyCompare(zKey1, nKey1, zKey2, nKey2)>=0 ){
4138 + checkAppendMsg(pCheck, zContext, "Key is out of order");
4141 + /* Check sanity of left child page.
4143 + pgno = SWAB32(pBt, pCell->h.leftChild);
4144 + d2 = checkTreePage(pCheck, pgno, pPage, zContext, zKey1,nKey1,zKey2,nKey2);
4145 + if( i>0 && d2!=depth ){
4146 + checkAppendMsg(pCheck, zContext, "Child page depth differs");
4149 + sqliteFree(zKey1);
4153 + pgno = SWAB32(pBt, pPage->u.hdr.rightChild);
4154 + sprintf(zContext, "On page %d at right child: ", iPage);
4155 + checkTreePage(pCheck, pgno, pPage, zContext, zKey1,nKey1,zUpperBound,nUpper);
4156 + sqliteFree(zKey1);
4158 + /* Check for complete coverage of the page
4160 + memset(hit, 0, sizeof(hit));
4161 + memset(hit, 1, sizeof(PageHdr));
4162 + for(i=SWAB16(pBt, pPage->u.hdr.firstCell); i>0 && i<SQLITE_USABLE_SIZE; ){
4163 + Cell *pCell = (Cell*)&pPage->u.aDisk[i];
4165 + for(j=i+cellSize(pBt, pCell)-1; j>=i; j--) hit[j]++;
4166 + i = SWAB16(pBt, pCell->h.iNext);
4168 + for(i=SWAB16(pBt,pPage->u.hdr.firstFree); i>0 && i<SQLITE_USABLE_SIZE; ){
4169 + FreeBlk *pFBlk = (FreeBlk*)&pPage->u.aDisk[i];
4171 + for(j=i+SWAB16(pBt,pFBlk->iSize)-1; j>=i; j--) hit[j]++;
4172 + i = SWAB16(pBt,pFBlk->iNext);
4174 + for(i=0; i<SQLITE_USABLE_SIZE; i++){
4176 + sprintf(zMsg, "Unused space at byte %d of page %d", i, iPage);
4177 + checkAppendMsg(pCheck, zMsg, 0);
4179 + }else if( hit[i]>1 ){
4180 + sprintf(zMsg, "Multiple uses for byte %d of page %d", i, iPage);
4181 + checkAppendMsg(pCheck, zMsg, 0);
4186 + /* Check that free space is kept to a minimum
4189 + if( pParent && pParent->nCell>2 && pPage->nFree>3*SQLITE_USABLE_SIZE/4 ){
4190 + sprintf(zMsg, "free space (%d) greater than max (%d)", pPage->nFree,
4191 + SQLITE_USABLE_SIZE/3);
4192 + checkAppendMsg(pCheck, zContext, zMsg);
4196 + sqlitepager_unref(pPage);
4201 +** This routine does a complete check of the given BTree file. aRoot[] is
4202 +** an array of pages numbers were each page number is the root page of
4203 +** a table. nRoot is the number of entries in aRoot.
4205 +** If everything checks out, this routine returns NULL. If something is
4206 +** amiss, an error message is written into memory obtained from malloc()
4207 +** and a pointer to that error message is returned. The calling function
4208 +** is responsible for freeing the error message when it is done.
4210 +char *fileBtreeIntegrityCheck(Btree *pBt, int *aRoot, int nRoot){
4213 + IntegrityCk sCheck;
4215 + nRef = *sqlitepager_stats(pBt->pPager);
4216 + if( lockBtree(pBt)!=SQLITE_OK ){
4217 + return sqliteStrDup("Unable to acquire a read lock on the database");
4220 + sCheck.pPager = pBt->pPager;
4221 + sCheck.nPage = sqlitepager_pagecount(sCheck.pPager);
4222 + if( sCheck.nPage==0 ){
4223 + unlockBtreeIfUnused(pBt);
4226 + sCheck.anRef = sqliteMallocRaw( (sCheck.nPage+1)*sizeof(sCheck.anRef[0]) );
4227 + sCheck.anRef[1] = 1;
4228 + for(i=2; i<=sCheck.nPage; i++){ sCheck.anRef[i] = 0; }
4229 + sCheck.zErrMsg = 0;
4231 + /* Check the integrity of the freelist
4233 + checkList(&sCheck, 1, SWAB32(pBt, pBt->page1->freeList),
4234 + SWAB32(pBt, pBt->page1->nFree), "Main freelist: ");
4236 + /* Check all the tables.
4238 + for(i=0; i<nRoot; i++){
4239 + if( aRoot[i]==0 ) continue;
4240 + checkTreePage(&sCheck, aRoot[i], 0, "List of tree roots: ", 0,0,0,0);
4243 + /* Make sure every page in the file is referenced
4245 + for(i=1; i<=sCheck.nPage; i++){
4246 + if( sCheck.anRef[i]==0 ){
4248 + sprintf(zBuf, "Page %d is never used", i);
4249 + checkAppendMsg(&sCheck, zBuf, 0);
4253 + /* Make sure this analysis did not leave any unref() pages
4255 + unlockBtreeIfUnused(pBt);
4256 + if( nRef != *sqlitepager_stats(pBt->pPager) ){
4259 + "Outstanding page count goes from %d to %d during this analysis",
4260 + nRef, *sqlitepager_stats(pBt->pPager)
4262 + checkAppendMsg(&sCheck, zBuf, 0);
4265 + /* Clean up and report errors.
4267 + sqliteFree(sCheck.anRef);
4268 + return sCheck.zErrMsg;
4272 +** Return the full pathname of the underlying database file.
4274 +static const char *fileBtreeGetFilename(Btree *pBt){
4275 + assert( pBt->pPager!=0 );
4276 + return sqlitepager_filename(pBt->pPager);
4280 +** Copy the complete content of pBtFrom into pBtTo. A transaction
4281 +** must be active for both files.
4283 +** The size of file pBtFrom may be reduced by this operation.
4284 +** If anything goes wrong, the transaction on pBtFrom is rolled back.
4286 +static int fileBtreeCopyFile(Btree *pBtTo, Btree *pBtFrom){
4287 + int rc = SQLITE_OK;
4288 + Pgno i, nPage, nToPage;
4290 + if( !pBtTo->inTrans || !pBtFrom->inTrans ) return SQLITE_ERROR;
4291 + if( pBtTo->needSwab!=pBtFrom->needSwab ) return SQLITE_ERROR;
4292 + if( pBtTo->pCursor ) return SQLITE_BUSY;
4293 + memcpy(pBtTo->page1, pBtFrom->page1, SQLITE_USABLE_SIZE);
4294 + rc = sqlitepager_overwrite(pBtTo->pPager, 1, pBtFrom->page1);
4295 + nToPage = sqlitepager_pagecount(pBtTo->pPager);
4296 + nPage = sqlitepager_pagecount(pBtFrom->pPager);
4297 + for(i=2; rc==SQLITE_OK && i<=nPage; i++){
4299 + rc = sqlitepager_get(pBtFrom->pPager, i, &pPage);
4301 + rc = sqlitepager_overwrite(pBtTo->pPager, i, pPage);
4303 + sqlitepager_unref(pPage);
4305 + for(i=nPage+1; rc==SQLITE_OK && i<=nToPage; i++){
4307 + rc = sqlitepager_get(pBtTo->pPager, i, &pPage);
4309 + rc = sqlitepager_write(pPage);
4310 + sqlitepager_unref(pPage);
4311 + sqlitepager_dont_write(pBtTo->pPager, i);
4313 + if( !rc && nPage<nToPage ){
4314 + rc = sqlitepager_truncate(pBtTo->pPager, nPage);
4317 + fileBtreeRollback(pBtTo);
4323 +** The following tables contain pointers to all of the interface
4324 +** routines for this implementation of the B*Tree backend. To
4325 +** substitute a different implemention of the backend, one has merely
4326 +** to provide pointers to alternative functions in similar tables.
4328 +static BtOps sqliteBtreeOps = {
4330 + fileBtreeSetCacheSize,
4331 + fileBtreeSetSafetyLevel,
4332 + fileBtreeBeginTrans,
4334 + fileBtreeRollback,
4335 + fileBtreeBeginCkpt,
4336 + fileBtreeCommitCkpt,
4337 + fileBtreeRollbackCkpt,
4338 + fileBtreeCreateTable,
4339 + fileBtreeCreateTable, /* Really sqliteBtreeCreateIndex() */
4340 + fileBtreeDropTable,
4341 + fileBtreeClearTable,
4344 + fileBtreeUpdateMeta,
4345 + fileBtreeIntegrityCheck,
4346 + fileBtreeGetFilename,
4347 + fileBtreeCopyFile,
4350 + fileBtreePageDump,
4353 +static BtCursorOps sqliteBtreeCursorOps = {
4360 + fileBtreePrevious,
4363 + fileBtreeKeyCompare,
4364 + fileBtreeDataSize,
4366 + fileBtreeCloseCursor,
4368 + fileBtreeCursorDump,
4372 +++ b/ext/sqlite/libsqlite/src/btree.h
4375 +** 2001 September 15
4377 +** The author disclaims copyright to this source code. In place of
4378 +** a legal notice, here is a blessing:
4380 +** May you do good and not evil.
4381 +** May you find forgiveness for yourself and forgive others.
4382 +** May you share freely, never taking more than you give.
4384 +*************************************************************************
4385 +** This header file defines the interface that the sqlite B-Tree file
4386 +** subsystem. See comments in the source code for a detailed description
4387 +** of what each interface routine does.
4395 +** Forward declarations of structure
4397 +typedef struct Btree Btree;
4398 +typedef struct BtCursor BtCursor;
4399 +typedef struct BtOps BtOps;
4400 +typedef struct BtCursorOps BtCursorOps;
4404 +** An instance of the following structure contains pointers to all
4405 +** methods against an open BTree. Alternative BTree implementations
4406 +** (examples: file based versus in-memory) can be created by substituting
4407 +** different methods. Users of the BTree cannot tell the difference.
4409 +** In C++ we could do this by defining a virtual base class and then
4410 +** creating subclasses for each different implementation. But this is
4411 +** C not C++ so we have to be a little more explicit.
4414 + int (*Close)(Btree*);
4415 + int (*SetCacheSize)(Btree*, int);
4416 + int (*SetSafetyLevel)(Btree*, int);
4417 + int (*BeginTrans)(Btree*);
4418 + int (*Commit)(Btree*);
4419 + int (*Rollback)(Btree*);
4420 + int (*BeginCkpt)(Btree*);
4421 + int (*CommitCkpt)(Btree*);
4422 + int (*RollbackCkpt)(Btree*);
4423 + int (*CreateTable)(Btree*, int*);
4424 + int (*CreateIndex)(Btree*, int*);
4425 + int (*DropTable)(Btree*, int);
4426 + int (*ClearTable)(Btree*, int);
4427 + int (*Cursor)(Btree*, int iTable, int wrFlag, BtCursor **ppCur);
4428 + int (*GetMeta)(Btree*, int*);
4429 + int (*UpdateMeta)(Btree*, int*);
4430 + char *(*IntegrityCheck)(Btree*, int*, int);
4431 + const char *(*GetFilename)(Btree*);
4432 + int (*Copyfile)(Btree*,Btree*);
4433 + struct Pager *(*Pager)(Btree*);
4435 + int (*PageDump)(Btree*, int, int);
4440 +** An instance of this structure defines all of the methods that can
4441 +** be executed against a cursor.
4443 +struct BtCursorOps {
4444 + int (*Moveto)(BtCursor*, const void *pKey, int nKey, int *pRes);
4445 + int (*Delete)(BtCursor*);
4446 + int (*Insert)(BtCursor*, const void *pKey, int nKey,
4447 + const void *pData, int nData);
4448 + int (*First)(BtCursor*, int *pRes);
4449 + int (*Last)(BtCursor*, int *pRes);
4450 + int (*Next)(BtCursor*, int *pRes);
4451 + int (*Previous)(BtCursor*, int *pRes);
4452 + int (*KeySize)(BtCursor*, int *pSize);
4453 + int (*Key)(BtCursor*, int offset, int amt, char *zBuf);
4454 + int (*KeyCompare)(BtCursor*, const void *pKey, int nKey,
4455 + int nIgnore, int *pRes);
4456 + int (*DataSize)(BtCursor*, int *pSize);
4457 + int (*Data)(BtCursor*, int offset, int amt, char *zBuf);
4458 + int (*CloseCursor)(BtCursor*);
4460 + int (*CursorDump)(BtCursor*, int*);
4465 +** The number of 4-byte "meta" values contained on the first page of each
4468 +#define SQLITE_N_BTREE_META 10
4470 +int sqliteBtreeOpen(const char *zFilename, int mode, int nPg, Btree **ppBtree);
4471 +int sqliteRbtreeOpen(const char *zFilename, int mode, int nPg, Btree **ppBtree);
4473 +#define btOps(pBt) (*((BtOps **)(pBt)))
4474 +#define btCOps(pCur) (*((BtCursorOps **)(pCur)))
4476 +#define sqliteBtreeClose(pBt) (btOps(pBt)->Close(pBt))
4477 +#define sqliteBtreeSetCacheSize(pBt, sz) (btOps(pBt)->SetCacheSize(pBt, sz))
4478 +#define sqliteBtreeSetSafetyLevel(pBt, sl) (btOps(pBt)->SetSafetyLevel(pBt, sl))
4479 +#define sqliteBtreeBeginTrans(pBt) (btOps(pBt)->BeginTrans(pBt))
4480 +#define sqliteBtreeCommit(pBt) (btOps(pBt)->Commit(pBt))
4481 +#define sqliteBtreeRollback(pBt) (btOps(pBt)->Rollback(pBt))
4482 +#define sqliteBtreeBeginCkpt(pBt) (btOps(pBt)->BeginCkpt(pBt))
4483 +#define sqliteBtreeCommitCkpt(pBt) (btOps(pBt)->CommitCkpt(pBt))
4484 +#define sqliteBtreeRollbackCkpt(pBt) (btOps(pBt)->RollbackCkpt(pBt))
4485 +#define sqliteBtreeCreateTable(pBt,piTable)\
4486 + (btOps(pBt)->CreateTable(pBt,piTable))
4487 +#define sqliteBtreeCreateIndex(pBt, piIndex)\
4488 + (btOps(pBt)->CreateIndex(pBt, piIndex))
4489 +#define sqliteBtreeDropTable(pBt, iTable) (btOps(pBt)->DropTable(pBt, iTable))
4490 +#define sqliteBtreeClearTable(pBt, iTable)\
4491 + (btOps(pBt)->ClearTable(pBt, iTable))
4492 +#define sqliteBtreeCursor(pBt, iTable, wrFlag, ppCur)\
4493 + (btOps(pBt)->Cursor(pBt, iTable, wrFlag, ppCur))
4494 +#define sqliteBtreeMoveto(pCur, pKey, nKey, pRes)\
4495 + (btCOps(pCur)->Moveto(pCur, pKey, nKey, pRes))
4496 +#define sqliteBtreeDelete(pCur) (btCOps(pCur)->Delete(pCur))
4497 +#define sqliteBtreeInsert(pCur, pKey, nKey, pData, nData) \
4498 + (btCOps(pCur)->Insert(pCur, pKey, nKey, pData, nData))
4499 +#define sqliteBtreeFirst(pCur, pRes) (btCOps(pCur)->First(pCur, pRes))
4500 +#define sqliteBtreeLast(pCur, pRes) (btCOps(pCur)->Last(pCur, pRes))
4501 +#define sqliteBtreeNext(pCur, pRes) (btCOps(pCur)->Next(pCur, pRes))
4502 +#define sqliteBtreePrevious(pCur, pRes) (btCOps(pCur)->Previous(pCur, pRes))
4503 +#define sqliteBtreeKeySize(pCur, pSize) (btCOps(pCur)->KeySize(pCur, pSize) )
4504 +#define sqliteBtreeKey(pCur, offset, amt, zBuf)\
4505 + (btCOps(pCur)->Key(pCur, offset, amt, zBuf))
4506 +#define sqliteBtreeKeyCompare(pCur, pKey, nKey, nIgnore, pRes)\
4507 + (btCOps(pCur)->KeyCompare(pCur, pKey, nKey, nIgnore, pRes))
4508 +#define sqliteBtreeDataSize(pCur, pSize) (btCOps(pCur)->DataSize(pCur, pSize))
4509 +#define sqliteBtreeData(pCur, offset, amt, zBuf)\
4510 + (btCOps(pCur)->Data(pCur, offset, amt, zBuf))
4511 +#define sqliteBtreeCloseCursor(pCur) (btCOps(pCur)->CloseCursor(pCur))
4512 +#define sqliteBtreeGetMeta(pBt, aMeta) (btOps(pBt)->GetMeta(pBt, aMeta))
4513 +#define sqliteBtreeUpdateMeta(pBt, aMeta) (btOps(pBt)->UpdateMeta(pBt, aMeta))
4514 +#define sqliteBtreeIntegrityCheck(pBt, aRoot, nRoot)\
4515 + (btOps(pBt)->IntegrityCheck(pBt, aRoot, nRoot))
4516 +#define sqliteBtreeGetFilename(pBt) (btOps(pBt)->GetFilename(pBt))
4517 +#define sqliteBtreeCopyFile(pBt1, pBt2) (btOps(pBt1)->Copyfile(pBt1, pBt2))
4518 +#define sqliteBtreePager(pBt) (btOps(pBt)->Pager(pBt))
4521 +#define sqliteBtreePageDump(pBt, pgno, recursive)\
4522 + (btOps(pBt)->PageDump(pBt, pgno, recursive))
4523 +#define sqliteBtreeCursorDump(pCur, aResult)\
4524 + (btCOps(pCur)->CursorDump(pCur, aResult))
4525 +int btree_native_byte_order;
4526 +#endif /* SQLITE_TEST */
4529 +#endif /* _BTREE_H_ */
4531 +++ b/ext/sqlite/libsqlite/src/btree_rb.c
4536 +** The author disclaims copyright to this source code. In place of
4537 +** a legal notice, here is a blessing:
4539 +** May you do good and not evil.
4540 +** May you find forgiveness for yourself and forgive others.
4541 +** May you share freely, never taking more than you give.
4543 +*************************************************************************
4546 +** This file implements an in-core database using Red-Black balanced
4549 +** It was contributed to SQLite by anonymous on 2003-Feb-04 23:24:49 UTC.
4552 +#include "sqliteInt.h"
4553 +#include <assert.h>
4556 +** Omit this whole file if the SQLITE_OMIT_INMEMORYDB macro is
4557 +** defined. This allows a lot of code to be omitted for installations
4558 +** that do not need it.
4560 +#ifndef SQLITE_OMIT_INMEMORYDB
4563 +typedef struct BtRbTree BtRbTree;
4564 +typedef struct BtRbNode BtRbNode;
4565 +typedef struct BtRollbackOp BtRollbackOp;
4566 +typedef struct Rbtree Rbtree;
4567 +typedef struct RbtCursor RbtCursor;
4569 +/* Forward declarations */
4570 +static BtOps sqliteRbtreeOps;
4571 +static BtCursorOps sqliteRbtreeCursorOps;
4574 + * During each transaction (or checkpoint), a linked-list of
4575 + * "rollback-operations" is accumulated. If the transaction is rolled back,
4576 + * then the list of operations must be executed (to restore the database to
4577 + * it's state before the transaction started). If the transaction is to be
4578 + * committed, just delete the list.
4580 + * Each operation is represented as follows, depending on the value of eOp:
4582 + * ROLLBACK_INSERT -> Need to insert (pKey, pData) into table iTab.
4583 + * ROLLBACK_DELETE -> Need to delete the record (pKey) into table iTab.
4584 + * ROLLBACK_CREATE -> Need to create table iTab.
4585 + * ROLLBACK_DROP -> Need to drop table iTab.
4587 +struct BtRollbackOp {
4594 + BtRollbackOp *pNext;
4598 +** Legal values for BtRollbackOp.eOp:
4600 +#define ROLLBACK_INSERT 1 /* Insert a record */
4601 +#define ROLLBACK_DELETE 2 /* Delete a record */
4602 +#define ROLLBACK_CREATE 3 /* Create a table */
4603 +#define ROLLBACK_DROP 4 /* Drop a table */
4606 + BtOps *pOps; /* Function table */
4607 + int aMetaData[SQLITE_N_BTREE_META];
4609 + int next_idx; /* next available table index */
4610 + Hash tblHash; /* All created tables, by index */
4611 + u8 isAnonymous; /* True if this Rbtree is to be deleted when closed */
4612 + u8 eTransState; /* State of this Rbtree wrt transactions */
4614 + BtRollbackOp *pTransRollback;
4615 + BtRollbackOp *pCheckRollback;
4616 + BtRollbackOp *pCheckRollbackTail;
4620 +** Legal values for Rbtree.eTransState.
4622 +#define TRANS_NONE 0 /* No transaction is in progress */
4623 +#define TRANS_INTRANSACTION 1 /* A transaction is in progress */
4624 +#define TRANS_INCHECKPOINT 2 /* A checkpoint is in progress */
4625 +#define TRANS_ROLLBACK 3 /* We are currently rolling back a checkpoint or
4629 + BtCursorOps *pOps; /* Function table */
4632 + int iTree; /* Index of pTree in pRbtree */
4634 + RbtCursor *pShared; /* List of all cursors on the same Rbtree */
4635 + u8 eSkip; /* Determines if next step operation is a no-op */
4636 + u8 wrFlag; /* True if this cursor is open for writing */
4640 +** Legal values for RbtCursor.eSkip.
4642 +#define SKIP_NONE 0 /* Always step the cursor */
4643 +#define SKIP_NEXT 1 /* The next sqliteRbtreeNext() is a no-op */
4644 +#define SKIP_PREV 2 /* The next sqliteRbtreePrevious() is a no-op */
4645 +#define SKIP_INVALID 3 /* Calls to Next() and Previous() are invalid */
4648 + RbtCursor *pCursors; /* All cursors pointing to this tree */
4649 + BtRbNode *pHead; /* Head of the tree, or NULL */
4657 + u8 isBlack; /* true for a black node, 0 for a red node */
4658 + BtRbNode *pParent; /* Nodes parent node, NULL for the tree head */
4659 + BtRbNode *pLeft; /* Nodes left child, or NULL */
4660 + BtRbNode *pRight; /* Nodes right child, or NULL */
4662 + int nBlackHeight; /* Only used during the red-black integrity check */
4665 +/* Forward declarations */
4666 +static int memRbtreeMoveto(
4672 +static int memRbtreeClearTable(Rbtree* tree, int n);
4673 +static int memRbtreeNext(RbtCursor* pCur, int *pRes);
4674 +static int memRbtreeLast(RbtCursor* pCur, int *pRes);
4675 +static int memRbtreePrevious(RbtCursor* pCur, int *pRes);
4679 +** This routine checks all cursors that point to the same table
4680 +** as pCur points to. If any of those cursors were opened with
4681 +** wrFlag==0 then this routine returns SQLITE_LOCKED. If all
4682 +** cursors point to the same table were opened with wrFlag==1
4683 +** then this routine returns SQLITE_OK.
4685 +** In addition to checking for read-locks (where a read-lock
4686 +** means a cursor opened with wrFlag==0) this routine also NULLs
4687 +** out the pNode field of all other cursors.
4688 +** This is necessary because an insert
4689 +** or delete might change erase the node out from under
4692 +static int checkReadLocks(RbtCursor *pCur){
4694 + assert( pCur->wrFlag );
4695 + for(p=pCur->pTree->pCursors; p; p=p->pShared){
4697 + if( p->wrFlag==0 ) return SQLITE_LOCKED;
4705 + * The key-compare function for the red-black trees. Returns as follows:
4707 + * (key1 < key2) -1
4708 + * (key1 == key2) 0
4711 + * Keys are compared using memcmp(). If one key is an exact prefix of the
4712 + * other, then the shorter key is less than the longer key.
4714 +static int key_compare(void const*pKey1, int nKey1, void const*pKey2, int nKey2)
4716 + int mcmp = memcmp(pKey1, pKey2, (nKey1 <= nKey2)?nKey1:nKey2);
4718 + if( nKey1 == nKey2 ) return 0;
4719 + return ((nKey1 < nKey2)?-1:1);
4721 + return ((mcmp>0)?1:-1);
4725 + * Perform the LEFT-rotate transformation on node X of tree pTree. This
4726 + * transform is part of the red-black balancing code.
4737 +static void leftRotate(BtRbTree *pTree, BtRbNode *pX)
4744 + pY->pParent = pX->pParent;
4745 + if( pX->pParent ){
4746 + if( pX->pParent->pLeft == pX ) pX->pParent->pLeft = pY;
4747 + else pX->pParent->pRight = pY;
4752 + if( pb ) pb->pParent = pX;
4753 + if( pTree->pHead == pX ) pTree->pHead = pY;
4757 + * Perform the RIGHT-rotate transformation on node X of tree pTree. This
4758 + * transform is part of the red-black balancing code.
4769 +static void rightRotate(BtRbTree *pTree, BtRbNode *pX)
4776 + pY->pParent = pX->pParent;
4777 + if( pX->pParent ){
4778 + if( pX->pParent->pLeft == pX ) pX->pParent->pLeft = pY;
4779 + else pX->pParent->pRight = pY;
4784 + if( pb ) pb->pParent = pX;
4785 + if( pTree->pHead == pX ) pTree->pHead = pY;
4789 + * A string-manipulation helper function for check_redblack_tree(). If (orig ==
4790 + * NULL) a copy of val is returned. If (orig != NULL) then a copy of the *
4791 + * concatenation of orig and val is returned. The original orig is deleted
4792 + * (using sqliteFree()).
4794 +static char *append_val(char * orig, char const * val){
4797 + z = sqliteStrDup( val );
4800 + sqliteSetString(&z, orig, val, (char*)0);
4801 + sqliteFree( orig );
4807 + * Append a string representation of the entire node to orig and return it.
4808 + * This is used to produce debugging information if check_redblack_tree() finds
4809 + * a problem with a red-black binary tree.
4811 +static char *append_node(char * orig, BtRbNode *pNode, int indent)
4816 + for( i=0; i<indent; i++ ){
4817 + orig = append_val(orig, " ");
4820 + sprintf(buf, "%p", pNode);
4821 + orig = append_val(orig, buf);
4825 + if( pNode->isBlack ){
4826 + orig = append_val(orig, " B \n");
4828 + orig = append_val(orig, " R \n");
4830 + orig = append_node( orig, pNode->pLeft, indent );
4831 + orig = append_node( orig, pNode->pRight, indent );
4833 + orig = append_val(orig, "\n");
4839 + * Print a representation of a node to stdout. This function is only included
4840 + * so you can call it from within a debugger if things get really bad. It
4841 + * is not called from anyplace in the code.
4843 +static void print_node(BtRbNode *pNode)
4845 + char * str = append_node(0, pNode, 0);
4846 + printf("%s", str);
4848 + /* Suppress a warning message about print_node() being unused */
4853 + * Check the following properties of the red-black tree:
4854 + * (1) - If a node is red, both of it's children are black
4855 + * (2) - Each path from a given node to a leaf (NULL) node passes thru the
4856 + * same number of black nodes
4858 + * If there is a problem, append a description (using append_val() ) to *msg.
4860 +static void check_redblack_tree(BtRbTree * tree, char ** msg)
4864 + /* 0 -> came from parent
4865 + * 1 -> came from left
4866 + * 2 -> came from right */
4867 + int prev_step = 0;
4869 + pNode = tree->pHead;
4871 + switch( prev_step ){
4873 + if( pNode->pLeft ){
4874 + pNode = pNode->pLeft;
4880 + if( pNode->pRight ){
4881 + pNode = pNode->pRight;
4888 + /* Check red-black property (1) */
4889 + if( !pNode->isBlack &&
4890 + ( (pNode->pLeft && !pNode->pLeft->isBlack) ||
4891 + (pNode->pRight && !pNode->pRight->isBlack) )
4894 + sprintf(buf, "Red node with red child at %p\n", pNode);
4895 + *msg = append_val(*msg, buf);
4896 + *msg = append_node(*msg, tree->pHead, 0);
4897 + *msg = append_val(*msg, "\n");
4900 + /* Check red-black property (2) */
4902 + int leftHeight = 0;
4903 + int rightHeight = 0;
4904 + if( pNode->pLeft ){
4905 + leftHeight += pNode->pLeft->nBlackHeight;
4906 + leftHeight += (pNode->pLeft->isBlack?1:0);
4908 + if( pNode->pRight ){
4909 + rightHeight += pNode->pRight->nBlackHeight;
4910 + rightHeight += (pNode->pRight->isBlack?1:0);
4912 + if( leftHeight != rightHeight ){
4914 + sprintf(buf, "Different black-heights at %p\n", pNode);
4915 + *msg = append_val(*msg, buf);
4916 + *msg = append_node(*msg, tree->pHead, 0);
4917 + *msg = append_val(*msg, "\n");
4919 + pNode->nBlackHeight = leftHeight;
4922 + if( pNode->pParent ){
4923 + if( pNode == pNode->pParent->pLeft ) prev_step = 1;
4924 + else prev_step = 2;
4926 + pNode = pNode->pParent;
4928 + default: assert(0);
4934 + * Node pX has just been inserted into pTree (by code in sqliteRbtreeInsert()).
4935 + * It is possible that pX is a red node with a red parent, which is a violation
4936 + * of the red-black tree properties. This function performs rotations and
4937 + * color changes to rebalance the tree
4939 +static void do_insert_balancing(BtRbTree *pTree, BtRbNode *pX)
4941 + /* In the first iteration of this loop, pX points to the red node just
4942 + * inserted in the tree. If the parent of pX exists (pX is not the root
4943 + * node) and is red, then the properties of the red-black tree are
4946 + * At the start of any subsequent iterations, pX points to a red node
4947 + * with a red parent. In all other respects the tree is a legal red-black
4949 + while( pX != pTree->pHead && !pX->pParent->isBlack ){
4951 + BtRbNode *pGrandparent;
4953 + /* Grandparent of pX must exist and must be black. */
4954 + pGrandparent = pX->pParent->pParent;
4955 + assert( pGrandparent );
4956 + assert( pGrandparent->isBlack );
4958 + /* Uncle of pX may or may not exist. */
4959 + if( pX->pParent == pGrandparent->pLeft )
4960 + pUncle = pGrandparent->pRight;
4962 + pUncle = pGrandparent->pLeft;
4964 + /* If the uncle of pX exists and is red, we do the following:
4968 + * U(r) P(r) U(b) P(b)
4973 + * pX is then set to G. If the parent of G is red, then the while loop
4974 + * will run again. */
4975 + if( pUncle && !pUncle->isBlack ){
4976 + pGrandparent->isBlack = 0;
4977 + pUncle->isBlack = 1;
4978 + pX->pParent->isBlack = 1;
4979 + pX = pGrandparent;
4982 + if( pX->pParent == pGrandparent->pLeft ){
4983 + if( pX == pX->pParent->pRight ){
4984 + /* If pX is a right-child, do the following transform, essentially
4985 + * to change pX into a left-child:
4989 + * P(r) U(b) X(r) U(b)
4991 + * X(r) P(r) <-- new X
4996 + leftRotate(pTree, pX);
4999 + /* Do the following transform, which balances the tree :)
5003 + * P(r) U(b) X(r) G(r)
5009 + assert( pGrandparent == pX->pParent->pParent );
5010 + pGrandparent->isBlack = 0;
5011 + pX->pParent->isBlack = 1;
5012 + rightRotate( pTree, pGrandparent );
5015 + /* This code is symetric to the illustrated case above. */
5016 + if( pX == pX->pParent->pLeft ){
5018 + rightRotate(pTree, pX);
5020 + assert( pGrandparent == pX->pParent->pParent );
5021 + pGrandparent->isBlack = 0;
5022 + pX->pParent->isBlack = 1;
5023 + leftRotate( pTree, pGrandparent );
5027 + pTree->pHead->isBlack = 1;
5031 + * A child of pParent, which in turn had child pX, has just been removed from
5032 + * pTree (the figure below depicts the operation, Z is being removed). pParent
5033 + * or pX, or both may be NULL.
5041 + * This function is only called if Z was black. In this case the red-black tree
5042 + * properties have been violated, and pX has an "extra black". This function
5043 + * performs rotations and color-changes to re-balance the tree.
5046 +void do_delete_balancing(BtRbTree *pTree, BtRbNode *pX, BtRbNode *pParent)
5050 + /* TODO: Comment this code! */
5051 + while( pX != pTree->pHead && (!pX || pX->isBlack) ){
5052 + if( pX == pParent->pLeft ){
5053 + pSib = pParent->pRight;
5054 + if( pSib && !(pSib->isBlack) ){
5055 + pSib->isBlack = 1;
5056 + pParent->isBlack = 0;
5057 + leftRotate(pTree, pParent);
5058 + pSib = pParent->pRight;
5063 + (!pSib->pLeft || pSib->pLeft->isBlack) &&
5064 + (!pSib->pRight || pSib->pRight->isBlack) ) {
5065 + pSib->isBlack = 0;
5068 + if( (!pSib->pRight || pSib->pRight->isBlack) ){
5069 + if( pSib->pLeft ) pSib->pLeft->isBlack = 1;
5070 + pSib->isBlack = 0;
5071 + rightRotate( pTree, pSib );
5072 + pSib = pParent->pRight;
5074 + pSib->isBlack = pParent->isBlack;
5075 + pParent->isBlack = 1;
5076 + if( pSib->pRight ) pSib->pRight->isBlack = 1;
5077 + leftRotate(pTree, pParent);
5078 + pX = pTree->pHead;
5081 + pSib = pParent->pLeft;
5082 + if( pSib && !(pSib->isBlack) ){
5083 + pSib->isBlack = 1;
5084 + pParent->isBlack = 0;
5085 + rightRotate(pTree, pParent);
5086 + pSib = pParent->pLeft;
5091 + (!pSib->pLeft || pSib->pLeft->isBlack) &&
5092 + (!pSib->pRight || pSib->pRight->isBlack) ){
5093 + pSib->isBlack = 0;
5096 + if( (!pSib->pLeft || pSib->pLeft->isBlack) ){
5097 + if( pSib->pRight ) pSib->pRight->isBlack = 1;
5098 + pSib->isBlack = 0;
5099 + leftRotate( pTree, pSib );
5100 + pSib = pParent->pLeft;
5102 + pSib->isBlack = pParent->isBlack;
5103 + pParent->isBlack = 1;
5104 + if( pSib->pLeft ) pSib->pLeft->isBlack = 1;
5105 + rightRotate(pTree, pParent);
5106 + pX = pTree->pHead;
5109 + pParent = pX->pParent;
5111 + if( pX ) pX->isBlack = 1;
5115 + * Create table n in tree pRbtree. Table n must not exist.
5117 +static void btreeCreateTable(Rbtree* pRbtree, int n)
5119 + BtRbTree *pNewTbl = sqliteMalloc(sizeof(BtRbTree));
5120 + sqliteHashInsert(&pRbtree->tblHash, 0, n, pNewTbl);
5124 + * Log a single "rollback-op" for the given Rbtree. See comments for struct
5127 +static void btreeLogRollbackOp(Rbtree* pRbtree, BtRollbackOp *pRollbackOp)
5129 + assert( pRbtree->eTransState == TRANS_INCHECKPOINT ||
5130 + pRbtree->eTransState == TRANS_INTRANSACTION );
5131 + if( pRbtree->eTransState == TRANS_INTRANSACTION ){
5132 + pRollbackOp->pNext = pRbtree->pTransRollback;
5133 + pRbtree->pTransRollback = pRollbackOp;
5135 + if( pRbtree->eTransState == TRANS_INCHECKPOINT ){
5136 + if( !pRbtree->pCheckRollback ){
5137 + pRbtree->pCheckRollbackTail = pRollbackOp;
5139 + pRollbackOp->pNext = pRbtree->pCheckRollback;
5140 + pRbtree->pCheckRollback = pRollbackOp;
5144 +int sqliteRbtreeOpen(
5145 + const char *zFilename,
5150 + Rbtree **ppRbtree = (Rbtree**)ppBtree;
5151 + *ppRbtree = (Rbtree *)sqliteMalloc(sizeof(Rbtree));
5152 + if( sqlite_malloc_failed ) goto open_no_mem;
5153 + sqliteHashInit(&(*ppRbtree)->tblHash, SQLITE_HASH_INT, 0);
5155 + /* Create a binary tree for the SQLITE_MASTER table at location 2 */
5156 + btreeCreateTable(*ppRbtree, 2);
5157 + if( sqlite_malloc_failed ) goto open_no_mem;
5158 + (*ppRbtree)->next_idx = 3;
5159 + (*ppRbtree)->pOps = &sqliteRbtreeOps;
5160 + /* Set file type to 4; this is so that "attach ':memory:' as ...." does not
5161 + ** think that the database in uninitialised and refuse to attach
5163 + (*ppRbtree)->aMetaData[2] = 4;
5169 + return SQLITE_NOMEM;
5173 + * Create a new table in the supplied Rbtree. Set *n to the new table number.
5174 + * Return SQLITE_OK if the operation is a success.
5176 +static int memRbtreeCreateTable(Rbtree* tree, int* n)
5178 + assert( tree->eTransState != TRANS_NONE );
5180 + *n = tree->next_idx++;
5181 + btreeCreateTable(tree, *n);
5182 + if( sqlite_malloc_failed ) return SQLITE_NOMEM;
5184 + /* Set up the rollback structure (if we are not doing this as part of a
5186 + if( tree->eTransState != TRANS_ROLLBACK ){
5187 + BtRollbackOp *pRollbackOp = sqliteMalloc(sizeof(BtRollbackOp));
5188 + if( pRollbackOp==0 ) return SQLITE_NOMEM;
5189 + pRollbackOp->eOp = ROLLBACK_DROP;
5190 + pRollbackOp->iTab = *n;
5191 + btreeLogRollbackOp(tree, pRollbackOp);
5198 + * Delete table n from the supplied Rbtree.
5200 +static int memRbtreeDropTable(Rbtree* tree, int n)
5203 + assert( tree->eTransState != TRANS_NONE );
5205 + memRbtreeClearTable(tree, n);
5206 + pTree = sqliteHashInsert(&tree->tblHash, 0, n, 0);
5208 + assert( pTree->pCursors==0 );
5209 + sqliteFree(pTree);
5211 + if( tree->eTransState != TRANS_ROLLBACK ){
5212 + BtRollbackOp *pRollbackOp = sqliteMalloc(sizeof(BtRollbackOp));
5213 + if( pRollbackOp==0 ) return SQLITE_NOMEM;
5214 + pRollbackOp->eOp = ROLLBACK_CREATE;
5215 + pRollbackOp->iTab = n;
5216 + btreeLogRollbackOp(tree, pRollbackOp);
5222 +static int memRbtreeKeyCompare(RbtCursor* pCur, const void *pKey, int nKey,
5223 + int nIgnore, int *pRes)
5227 + if( !pCur->pNode ) {
5230 + if( (pCur->pNode->nKey - nIgnore) < 0 ){
5233 + *pRes = key_compare(pCur->pNode->pKey, pCur->pNode->nKey-nIgnore,
5241 + * Get a new cursor for table iTable of the supplied Rbtree. The wrFlag
5242 + * parameter indicates that the cursor is open for writing.
5244 + * Note that RbtCursor.eSkip and RbtCursor.pNode both initialize to 0.
5246 +static int memRbtreeCursor(
5254 + pCur = *ppCur = sqliteMalloc(sizeof(RbtCursor));
5255 + if( sqlite_malloc_failed ) return SQLITE_NOMEM;
5256 + pCur->pTree = sqliteHashFind(&tree->tblHash, 0, iTable);
5257 + assert( pCur->pTree );
5258 + pCur->pRbtree = tree;
5259 + pCur->iTree = iTable;
5260 + pCur->pOps = &sqliteRbtreeCursorOps;
5261 + pCur->wrFlag = wrFlag;
5262 + pCur->pShared = pCur->pTree->pCursors;
5263 + pCur->pTree->pCursors = pCur;
5265 + assert( (*ppCur)->pTree );
5270 + * Insert a new record into the Rbtree. The key is given by (pKey,nKey)
5271 + * and the data is given by (pData,nData). The cursor is used only to
5272 + * define what database the record should be inserted into. The cursor
5273 + * is left pointing at the new record.
5275 + * If the key exists already in the tree, just replace the data.
5277 +static int memRbtreeInsert(
5281 + const void *pDataInput,
5287 + /* It is illegal to call sqliteRbtreeInsert() if we are
5288 + ** not in a transaction */
5289 + assert( pCur->pRbtree->eTransState != TRANS_NONE );
5291 + /* Make sure some other cursor isn't trying to read this same table */
5292 + if( checkReadLocks(pCur) ){
5293 + return SQLITE_LOCKED; /* The table pCur points to has a read lock */
5296 + /* Take a copy of the input data now, in case we need it for the
5298 + pData = sqliteMallocRaw(nData);
5299 + if( sqlite_malloc_failed ) return SQLITE_NOMEM;
5300 + memcpy(pData, pDataInput, nData);
5302 + /* Move the cursor to a node near the key to be inserted. If the key already
5303 + * exists in the table, then (match == 0). In this case we can just replace
5304 + * the data associated with the entry, we don't need to manipulate the tree.
5306 + * If there is no exact match, then the cursor points at what would be either
5307 + * the predecessor (match == -1) or successor (match == 1) of the
5308 + * searched-for key, were it to be inserted. The new node becomes a child of
5311 + * The new node is initially red.
5313 + memRbtreeMoveto( pCur, pKey, nKey, &match);
5315 + BtRbNode *pNode = sqliteMalloc(sizeof(BtRbNode));
5316 + if( pNode==0 ) return SQLITE_NOMEM;
5317 + pNode->nKey = nKey;
5318 + pNode->pKey = sqliteMallocRaw(nKey);
5319 + if( sqlite_malloc_failed ) return SQLITE_NOMEM;
5320 + memcpy(pNode->pKey, pKey, nKey);
5321 + pNode->nData = nData;
5322 + pNode->pData = pData;
5323 + if( pCur->pNode ){
5326 + assert( !pCur->pNode->pRight );
5327 + pNode->pParent = pCur->pNode;
5328 + pCur->pNode->pRight = pNode;
5331 + assert( !pCur->pNode->pLeft );
5332 + pNode->pParent = pCur->pNode;
5333 + pCur->pNode->pLeft = pNode;
5339 + pCur->pTree->pHead = pNode;
5342 + /* Point the cursor at the node just inserted, as per SQLite requirements */
5343 + pCur->pNode = pNode;
5345 + /* A new node has just been inserted, so run the balancing code */
5346 + do_insert_balancing(pCur->pTree, pNode);
5348 + /* Set up a rollback-op in case we have to roll this operation back */
5349 + if( pCur->pRbtree->eTransState != TRANS_ROLLBACK ){
5350 + BtRollbackOp *pOp = sqliteMalloc( sizeof(BtRollbackOp) );
5351 + if( pOp==0 ) return SQLITE_NOMEM;
5352 + pOp->eOp = ROLLBACK_DELETE;
5353 + pOp->iTab = pCur->iTree;
5354 + pOp->nKey = pNode->nKey;
5355 + pOp->pKey = sqliteMallocRaw( pOp->nKey );
5356 + if( sqlite_malloc_failed ) return SQLITE_NOMEM;
5357 + memcpy( pOp->pKey, pNode->pKey, pOp->nKey );
5358 + btreeLogRollbackOp(pCur->pRbtree, pOp);
5362 + /* No need to insert a new node in the tree, as the key already exists.
5363 + * Just clobber the current nodes data. */
5365 + /* Set up a rollback-op in case we have to roll this operation back */
5366 + if( pCur->pRbtree->eTransState != TRANS_ROLLBACK ){
5367 + BtRollbackOp *pOp = sqliteMalloc( sizeof(BtRollbackOp) );
5368 + if( pOp==0 ) return SQLITE_NOMEM;
5369 + pOp->iTab = pCur->iTree;
5370 + pOp->nKey = pCur->pNode->nKey;
5371 + pOp->pKey = sqliteMallocRaw( pOp->nKey );
5372 + if( sqlite_malloc_failed ) return SQLITE_NOMEM;
5373 + memcpy( pOp->pKey, pCur->pNode->pKey, pOp->nKey );
5374 + pOp->nData = pCur->pNode->nData;
5375 + pOp->pData = pCur->pNode->pData;
5376 + pOp->eOp = ROLLBACK_INSERT;
5377 + btreeLogRollbackOp(pCur->pRbtree, pOp);
5379 + sqliteFree( pCur->pNode->pData );
5382 + /* Actually clobber the nodes data */
5383 + pCur->pNode->pData = pData;
5384 + pCur->pNode->nData = nData;
5390 +/* Move the cursor so that it points to an entry near pKey.
5391 +** Return a success code.
5393 +** *pRes<0 The cursor is left pointing at an entry that
5394 +** is smaller than pKey or if the table is empty
5395 +** and the cursor is therefore left point to nothing.
5397 +** *pRes==0 The cursor is left pointing at an entry that
5398 +** exactly matches pKey.
5400 +** *pRes>0 The cursor is left pointing at an entry that
5401 +** is larger than pKey.
5403 +static int memRbtreeMoveto(
5409 + BtRbNode *pTmp = 0;
5411 + pCur->pNode = pCur->pTree->pHead;
5413 + while( pCur->pNode && *pRes ) {
5414 + *pRes = key_compare(pCur->pNode->pKey, pCur->pNode->nKey, pKey, nKey);
5415 + pTmp = pCur->pNode;
5417 + case 1: /* cursor > key */
5418 + pCur->pNode = pCur->pNode->pLeft;
5420 + case -1: /* cursor < key */
5421 + pCur->pNode = pCur->pNode->pRight;
5426 + /* If (pCur->pNode == NULL), then we have failed to find a match. Set
5427 + * pCur->pNode to pTmp, which is either NULL (if the tree is empty) or the
5428 + * last node traversed in the search. In either case the relation ship
5429 + * between pTmp and the searched for key is already stored in *pRes. pTmp is
5430 + * either the successor or predecessor of the key we tried to move to. */
5431 + if( !pCur->pNode ) pCur->pNode = pTmp;
5432 + pCur->eSkip = SKIP_NONE;
5439 +** Delete the entry that the cursor is pointing to.
5441 +** The cursor is left pointing at either the next or the previous
5442 +** entry. If the cursor is left pointing to the next entry, then
5443 +** the pCur->eSkip flag is set to SKIP_NEXT which forces the next call to
5444 +** sqliteRbtreeNext() to be a no-op. That way, you can always call
5445 +** sqliteRbtreeNext() after a delete and the cursor will be left
5446 +** pointing to the first entry after the deleted entry. Similarly,
5447 +** pCur->eSkip is set to SKIP_PREV is the cursor is left pointing to
5448 +** the entry prior to the deleted entry so that a subsequent call to
5449 +** sqliteRbtreePrevious() will always leave the cursor pointing at the
5450 +** entry immediately before the one that was deleted.
5452 +static int memRbtreeDelete(RbtCursor* pCur)
5454 + BtRbNode *pZ; /* The one being deleted */
5455 + BtRbNode *pChild; /* The child of the spliced out node */
5457 + /* It is illegal to call sqliteRbtreeDelete() if we are
5458 + ** not in a transaction */
5459 + assert( pCur->pRbtree->eTransState != TRANS_NONE );
5461 + /* Make sure some other cursor isn't trying to read this same table */
5462 + if( checkReadLocks(pCur) ){
5463 + return SQLITE_LOCKED; /* The table pCur points to has a read lock */
5471 + /* If we are not currently doing a rollback, set up a rollback op for this
5473 + if( pCur->pRbtree->eTransState != TRANS_ROLLBACK ){
5474 + BtRollbackOp *pOp = sqliteMalloc( sizeof(BtRollbackOp) );
5475 + if( pOp==0 ) return SQLITE_NOMEM;
5476 + pOp->iTab = pCur->iTree;
5477 + pOp->nKey = pZ->nKey;
5478 + pOp->pKey = pZ->pKey;
5479 + pOp->nData = pZ->nData;
5480 + pOp->pData = pZ->pData;
5481 + pOp->eOp = ROLLBACK_INSERT;
5482 + btreeLogRollbackOp(pCur->pRbtree, pOp);
5485 + /* First do a standard binary-tree delete (node pZ is to be deleted). How
5486 + * to do this depends on how many children pZ has:
5488 + * If pZ has no children or one child, then splice out pZ. If pZ has two
5489 + * children, splice out the successor of pZ and replace the key and data of
5490 + * pZ with the key and data of the spliced out successor. */
5491 + if( pZ->pLeft && pZ->pRight ){
5494 + pCur->eSkip = SKIP_NONE;
5495 + memRbtreeNext(pCur, &dummy);
5496 + assert( dummy == 0 );
5497 + if( pCur->pRbtree->eTransState == TRANS_ROLLBACK ){
5498 + sqliteFree(pZ->pKey);
5499 + sqliteFree(pZ->pData);
5501 + pZ->pData = pCur->pNode->pData;
5502 + pZ->nData = pCur->pNode->nData;
5503 + pZ->pKey = pCur->pNode->pKey;
5504 + pZ->nKey = pCur->pNode->nKey;
5507 + pCur->pNode = pTmp;
5508 + pCur->eSkip = SKIP_NEXT;
5511 + pCur->eSkip = SKIP_NONE;
5512 + memRbtreeNext(pCur, &res);
5513 + pCur->eSkip = SKIP_NEXT;
5515 + memRbtreeLast(pCur, &res);
5516 + memRbtreePrevious(pCur, &res);
5517 + pCur->eSkip = SKIP_PREV;
5519 + if( pCur->pRbtree->eTransState == TRANS_ROLLBACK ){
5520 + sqliteFree(pZ->pKey);
5521 + sqliteFree(pZ->pData);
5525 + /* pZ now points at the node to be spliced out. This block does the
5528 + BtRbNode **ppParentSlot = 0;
5529 + assert( !pZ->pLeft || !pZ->pRight ); /* pZ has at most one child */
5530 + pChild = ((pZ->pLeft)?pZ->pLeft:pZ->pRight);
5531 + if( pZ->pParent ){
5532 + assert( pZ == pZ->pParent->pLeft || pZ == pZ->pParent->pRight );
5533 + ppParentSlot = ((pZ == pZ->pParent->pLeft)
5534 + ?&pZ->pParent->pLeft:&pZ->pParent->pRight);
5535 + *ppParentSlot = pChild;
5537 + pCur->pTree->pHead = pChild;
5539 + if( pChild ) pChild->pParent = pZ->pParent;
5542 + /* pZ now points at the spliced out node. pChild is the only child of pZ, or
5543 + * NULL if pZ has no children. If pZ is black, and not the tree root, then we
5544 + * will have violated the "same number of black nodes in every path to a
5545 + * leaf" property of the red-black tree. The code in do_delete_balancing()
5546 + * repairs this. */
5547 + if( pZ->isBlack ){
5548 + do_delete_balancing(pCur->pTree, pChild, pZ->pParent);
5556 + * Empty table n of the Rbtree.
5558 +static int memRbtreeClearTable(Rbtree* tree, int n)
5563 + pTree = sqliteHashFind(&tree->tblHash, 0, n);
5566 + pNode = pTree->pHead;
5568 + if( pNode->pLeft ){
5569 + pNode = pNode->pLeft;
5571 + else if( pNode->pRight ){
5572 + pNode = pNode->pRight;
5575 + BtRbNode *pTmp = pNode->pParent;
5576 + if( tree->eTransState == TRANS_ROLLBACK ){
5577 + sqliteFree( pNode->pKey );
5578 + sqliteFree( pNode->pData );
5580 + BtRollbackOp *pRollbackOp = sqliteMallocRaw(sizeof(BtRollbackOp));
5581 + if( pRollbackOp==0 ) return SQLITE_NOMEM;
5582 + pRollbackOp->eOp = ROLLBACK_INSERT;
5583 + pRollbackOp->iTab = n;
5584 + pRollbackOp->nKey = pNode->nKey;
5585 + pRollbackOp->pKey = pNode->pKey;
5586 + pRollbackOp->nData = pNode->nData;
5587 + pRollbackOp->pData = pNode->pData;
5588 + btreeLogRollbackOp(tree, pRollbackOp);
5590 + sqliteFree( pNode );
5592 + if( pTmp->pLeft == pNode ) pTmp->pLeft = 0;
5593 + else if( pTmp->pRight == pNode ) pTmp->pRight = 0;
5603 +static int memRbtreeFirst(RbtCursor* pCur, int *pRes)
5605 + if( pCur->pTree->pHead ){
5606 + pCur->pNode = pCur->pTree->pHead;
5607 + while( pCur->pNode->pLeft ){
5608 + pCur->pNode = pCur->pNode->pLeft;
5611 + if( pCur->pNode ){
5616 + pCur->eSkip = SKIP_NONE;
5620 +static int memRbtreeLast(RbtCursor* pCur, int *pRes)
5622 + if( pCur->pTree->pHead ){
5623 + pCur->pNode = pCur->pTree->pHead;
5624 + while( pCur->pNode->pRight ){
5625 + pCur->pNode = pCur->pNode->pRight;
5628 + if( pCur->pNode ){
5633 + pCur->eSkip = SKIP_NONE;
5638 +** Advance the cursor to the next entry in the database. If
5639 +** successful then set *pRes=0. If the cursor
5640 +** was already pointing to the last entry in the database before
5641 +** this routine was called, then set *pRes=1.
5643 +static int memRbtreeNext(RbtCursor* pCur, int *pRes)
5645 + if( pCur->pNode && pCur->eSkip != SKIP_NEXT ){
5646 + if( pCur->pNode->pRight ){
5647 + pCur->pNode = pCur->pNode->pRight;
5648 + while( pCur->pNode->pLeft )
5649 + pCur->pNode = pCur->pNode->pLeft;
5651 + BtRbNode * pX = pCur->pNode;
5652 + pCur->pNode = pX->pParent;
5653 + while( pCur->pNode && (pCur->pNode->pRight == pX) ){
5655 + pCur->pNode = pX->pParent;
5659 + pCur->eSkip = SKIP_NONE;
5661 + if( !pCur->pNode ){
5670 +static int memRbtreePrevious(RbtCursor* pCur, int *pRes)
5672 + if( pCur->pNode && pCur->eSkip != SKIP_PREV ){
5673 + if( pCur->pNode->pLeft ){
5674 + pCur->pNode = pCur->pNode->pLeft;
5675 + while( pCur->pNode->pRight )
5676 + pCur->pNode = pCur->pNode->pRight;
5678 + BtRbNode * pX = pCur->pNode;
5679 + pCur->pNode = pX->pParent;
5680 + while( pCur->pNode && (pCur->pNode->pLeft == pX) ){
5682 + pCur->pNode = pX->pParent;
5686 + pCur->eSkip = SKIP_NONE;
5688 + if( !pCur->pNode ){
5697 +static int memRbtreeKeySize(RbtCursor* pCur, int *pSize)
5699 + if( pCur->pNode ){
5700 + *pSize = pCur->pNode->nKey;
5707 +static int memRbtreeKey(RbtCursor* pCur, int offset, int amt, char *zBuf)
5709 + if( !pCur->pNode ) return 0;
5710 + if( !pCur->pNode->pKey || ((amt + offset) <= pCur->pNode->nKey) ){
5711 + memcpy(zBuf, ((char*)pCur->pNode->pKey)+offset, amt);
5713 + memcpy(zBuf, ((char*)pCur->pNode->pKey)+offset, pCur->pNode->nKey-offset);
5714 + amt = pCur->pNode->nKey-offset;
5719 +static int memRbtreeDataSize(RbtCursor* pCur, int *pSize)
5721 + if( pCur->pNode ){
5722 + *pSize = pCur->pNode->nData;
5729 +static int memRbtreeData(RbtCursor *pCur, int offset, int amt, char *zBuf)
5731 + if( !pCur->pNode ) return 0;
5732 + if( (amt + offset) <= pCur->pNode->nData ){
5733 + memcpy(zBuf, ((char*)pCur->pNode->pData)+offset, amt);
5735 + memcpy(zBuf, ((char*)pCur->pNode->pData)+offset ,pCur->pNode->nData-offset);
5736 + amt = pCur->pNode->nData-offset;
5741 +static int memRbtreeCloseCursor(RbtCursor* pCur)
5743 + if( pCur->pTree->pCursors==pCur ){
5744 + pCur->pTree->pCursors = pCur->pShared;
5746 + RbtCursor *p = pCur->pTree->pCursors;
5747 + while( p && p->pShared!=pCur ){ p = p->pShared; }
5750 + p->pShared = pCur->pShared;
5757 +static int memRbtreeGetMeta(Rbtree* tree, int* aMeta)
5759 + memcpy( aMeta, tree->aMetaData, sizeof(int) * SQLITE_N_BTREE_META );
5763 +static int memRbtreeUpdateMeta(Rbtree* tree, int* aMeta)
5765 + memcpy( tree->aMetaData, aMeta, sizeof(int) * SQLITE_N_BTREE_META );
5770 + * Check that each table in the Rbtree meets the requirements for a red-black
5771 + * binary tree. If an error is found, return an explanation of the problem in
5772 + * memory obtained from sqliteMalloc(). Parameters aRoot and nRoot are ignored.
5774 +static char *memRbtreeIntegrityCheck(Rbtree* tree, int* aRoot, int nRoot)
5779 + for(p=sqliteHashFirst(&tree->tblHash); p; p=sqliteHashNext(p)){
5780 + BtRbTree *pTree = sqliteHashData(p);
5781 + check_redblack_tree(pTree, &msg);
5787 +static int memRbtreeSetCacheSize(Rbtree* tree, int sz)
5792 +static int memRbtreeSetSafetyLevel(Rbtree *pBt, int level){
5796 +static int memRbtreeBeginTrans(Rbtree* tree)
5798 + if( tree->eTransState != TRANS_NONE )
5799 + return SQLITE_ERROR;
5801 + assert( tree->pTransRollback == 0 );
5802 + tree->eTransState = TRANS_INTRANSACTION;
5807 +** Delete a linked list of BtRollbackOp structures.
5809 +static void deleteRollbackList(BtRollbackOp *pOp){
5811 + BtRollbackOp *pTmp = pOp->pNext;
5812 + sqliteFree(pOp->pData);
5813 + sqliteFree(pOp->pKey);
5819 +static int memRbtreeCommit(Rbtree* tree){
5820 + /* Just delete pTransRollback and pCheckRollback */
5821 + deleteRollbackList(tree->pCheckRollback);
5822 + deleteRollbackList(tree->pTransRollback);
5823 + tree->pTransRollback = 0;
5824 + tree->pCheckRollback = 0;
5825 + tree->pCheckRollbackTail = 0;
5826 + tree->eTransState = TRANS_NONE;
5831 + * Close the supplied Rbtree. Delete everything associated with it.
5833 +static int memRbtreeClose(Rbtree* tree)
5836 + memRbtreeCommit(tree);
5837 + while( (p=sqliteHashFirst(&tree->tblHash))!=0 ){
5838 + tree->eTransState = TRANS_ROLLBACK;
5839 + memRbtreeDropTable(tree, sqliteHashKeysize(p));
5841 + sqliteHashClear(&tree->tblHash);
5847 + * Execute and delete the supplied rollback-list on pRbtree.
5849 +static void execute_rollback_list(Rbtree *pRbtree, BtRollbackOp *pList)
5851 + BtRollbackOp *pTmp;
5855 + cur.pRbtree = pRbtree;
5858 + switch( pList->eOp ){
5859 + case ROLLBACK_INSERT:
5860 + cur.pTree = sqliteHashFind( &pRbtree->tblHash, 0, pList->iTab );
5861 + assert(cur.pTree);
5862 + cur.iTree = pList->iTab;
5863 + cur.eSkip = SKIP_NONE;
5864 + memRbtreeInsert( &cur, pList->pKey,
5865 + pList->nKey, pList->pData, pList->nData );
5867 + case ROLLBACK_DELETE:
5868 + cur.pTree = sqliteHashFind( &pRbtree->tblHash, 0, pList->iTab );
5869 + assert(cur.pTree);
5870 + cur.iTree = pList->iTab;
5871 + cur.eSkip = SKIP_NONE;
5872 + memRbtreeMoveto(&cur, pList->pKey, pList->nKey, &res);
5874 + memRbtreeDelete( &cur );
5876 + case ROLLBACK_CREATE:
5877 + btreeCreateTable(pRbtree, pList->iTab);
5879 + case ROLLBACK_DROP:
5880 + memRbtreeDropTable(pRbtree, pList->iTab);
5885 + sqliteFree(pList->pKey);
5886 + sqliteFree(pList->pData);
5887 + pTmp = pList->pNext;
5888 + sqliteFree(pList);
5893 +static int memRbtreeRollback(Rbtree* tree)
5895 + tree->eTransState = TRANS_ROLLBACK;
5896 + execute_rollback_list(tree, tree->pCheckRollback);
5897 + execute_rollback_list(tree, tree->pTransRollback);
5898 + tree->pTransRollback = 0;
5899 + tree->pCheckRollback = 0;
5900 + tree->pCheckRollbackTail = 0;
5901 + tree->eTransState = TRANS_NONE;
5905 +static int memRbtreeBeginCkpt(Rbtree* tree)
5907 + if( tree->eTransState != TRANS_INTRANSACTION )
5908 + return SQLITE_ERROR;
5910 + assert( tree->pCheckRollback == 0 );
5911 + assert( tree->pCheckRollbackTail == 0 );
5912 + tree->eTransState = TRANS_INCHECKPOINT;
5916 +static int memRbtreeCommitCkpt(Rbtree* tree)
5918 + if( tree->eTransState == TRANS_INCHECKPOINT ){
5919 + if( tree->pCheckRollback ){
5920 + tree->pCheckRollbackTail->pNext = tree->pTransRollback;
5921 + tree->pTransRollback = tree->pCheckRollback;
5922 + tree->pCheckRollback = 0;
5923 + tree->pCheckRollbackTail = 0;
5925 + tree->eTransState = TRANS_INTRANSACTION;
5930 +static int memRbtreeRollbackCkpt(Rbtree* tree)
5932 + if( tree->eTransState != TRANS_INCHECKPOINT ) return SQLITE_OK;
5933 + tree->eTransState = TRANS_ROLLBACK;
5934 + execute_rollback_list(tree, tree->pCheckRollback);
5935 + tree->pCheckRollback = 0;
5936 + tree->pCheckRollbackTail = 0;
5937 + tree->eTransState = TRANS_INTRANSACTION;
5942 +static int memRbtreePageDump(Rbtree* tree, int pgno, int rec)
5944 + assert(!"Cannot call sqliteRbtreePageDump");
5948 +static int memRbtreeCursorDump(RbtCursor* pCur, int* aRes)
5950 + assert(!"Cannot call sqliteRbtreeCursorDump");
5955 +static struct Pager *memRbtreePager(Rbtree* tree)
5961 +** Return the full pathname of the underlying database file.
5963 +static const char *memRbtreeGetFilename(Rbtree *pBt){
5964 + return 0; /* A NULL return indicates there is no underlying file */
5968 +** The copy file function is not implemented for the in-memory database
5970 +static int memRbtreeCopyFile(Rbtree *pBt, Rbtree *pBt2){
5971 + return SQLITE_INTERNAL; /* Not implemented */
5974 +static BtOps sqliteRbtreeOps = {
5975 + (int(*)(Btree*)) memRbtreeClose,
5976 + (int(*)(Btree*,int)) memRbtreeSetCacheSize,
5977 + (int(*)(Btree*,int)) memRbtreeSetSafetyLevel,
5978 + (int(*)(Btree*)) memRbtreeBeginTrans,
5979 + (int(*)(Btree*)) memRbtreeCommit,
5980 + (int(*)(Btree*)) memRbtreeRollback,
5981 + (int(*)(Btree*)) memRbtreeBeginCkpt,
5982 + (int(*)(Btree*)) memRbtreeCommitCkpt,
5983 + (int(*)(Btree*)) memRbtreeRollbackCkpt,
5984 + (int(*)(Btree*,int*)) memRbtreeCreateTable,
5985 + (int(*)(Btree*,int*)) memRbtreeCreateTable,
5986 + (int(*)(Btree*,int)) memRbtreeDropTable,
5987 + (int(*)(Btree*,int)) memRbtreeClearTable,
5988 + (int(*)(Btree*,int,int,BtCursor**)) memRbtreeCursor,
5989 + (int(*)(Btree*,int*)) memRbtreeGetMeta,
5990 + (int(*)(Btree*,int*)) memRbtreeUpdateMeta,
5991 + (char*(*)(Btree*,int*,int)) memRbtreeIntegrityCheck,
5992 + (const char*(*)(Btree*)) memRbtreeGetFilename,
5993 + (int(*)(Btree*,Btree*)) memRbtreeCopyFile,
5994 + (struct Pager*(*)(Btree*)) memRbtreePager,
5996 + (int(*)(Btree*,int,int)) memRbtreePageDump,
6000 +static BtCursorOps sqliteRbtreeCursorOps = {
6001 + (int(*)(BtCursor*,const void*,int,int*)) memRbtreeMoveto,
6002 + (int(*)(BtCursor*)) memRbtreeDelete,
6003 + (int(*)(BtCursor*,const void*,int,const void*,int)) memRbtreeInsert,
6004 + (int(*)(BtCursor*,int*)) memRbtreeFirst,
6005 + (int(*)(BtCursor*,int*)) memRbtreeLast,
6006 + (int(*)(BtCursor*,int*)) memRbtreeNext,
6007 + (int(*)(BtCursor*,int*)) memRbtreePrevious,
6008 + (int(*)(BtCursor*,int*)) memRbtreeKeySize,
6009 + (int(*)(BtCursor*,int,int,char*)) memRbtreeKey,
6010 + (int(*)(BtCursor*,const void*,int,int,int*)) memRbtreeKeyCompare,
6011 + (int(*)(BtCursor*,int*)) memRbtreeDataSize,
6012 + (int(*)(BtCursor*,int,int,char*)) memRbtreeData,
6013 + (int(*)(BtCursor*)) memRbtreeCloseCursor,
6015 + (int(*)(BtCursor*,int*)) memRbtreeCursorDump,
6020 +#endif /* SQLITE_OMIT_INMEMORYDB */
6022 +++ b/ext/sqlite/libsqlite/src/build.c
6025 +** 2001 September 15
6027 +** The author disclaims copyright to this source code. In place of
6028 +** a legal notice, here is a blessing:
6030 +** May you do good and not evil.
6031 +** May you find forgiveness for yourself and forgive others.
6032 +** May you share freely, never taking more than you give.
6034 +*************************************************************************
6035 +** This file contains C code routines that are called by the SQLite parser
6036 +** when syntax rules are reduced. The routines in this file handle the
6037 +** following kinds of SQL syntax:
6043 +** creating ID lists
6044 +** BEGIN TRANSACTION
6051 +#include "sqliteInt.h"
6055 +** This routine is called when a new SQL statement is beginning to
6056 +** be parsed. Check to see if the schema for the database needs
6057 +** to be read from the SQLITE_MASTER and SQLITE_TEMP_MASTER tables.
6058 +** If it does, then read it.
6060 +void sqliteBeginParse(Parse *pParse, int explainFlag){
6061 + sqlite *db = pParse->db;
6063 + pParse->explain = explainFlag;
6064 + if((db->flags & SQLITE_Initialized)==0 && db->init.busy==0 ){
6065 + int rc = sqliteInit(db, &pParse->zErrMsg);
6066 + if( rc!=SQLITE_OK ){
6071 + for(i=0; i<db->nDb; i++){
6072 + DbClearProperty(db, i, DB_Locked);
6073 + if( !db->aDb[i].inTrans ){
6074 + DbClearProperty(db, i, DB_Cookie);
6081 +** This routine is called after a single SQL statement has been
6082 +** parsed and we want to execute the VDBE code to implement
6083 +** that statement. Prior action routines should have already
6084 +** constructed VDBE code to do the work of the SQL statement.
6085 +** This routine just has to execute the VDBE code.
6087 +** Note that if an error occurred, it might be the case that
6088 +** no VDBE code was generated.
6090 +void sqliteExec(Parse *pParse){
6091 + sqlite *db = pParse->db;
6092 + Vdbe *v = pParse->pVdbe;
6094 + if( v==0 && (v = sqliteGetVdbe(pParse))!=0 ){
6095 + sqliteVdbeAddOp(v, OP_Halt, 0, 0);
6097 + if( sqlite_malloc_failed ) return;
6098 + if( v && pParse->nErr==0 ){
6099 + FILE *trace = (db->flags & SQLITE_VdbeTrace)!=0 ? stdout : 0;
6100 + sqliteVdbeTrace(v, trace);
6101 + sqliteVdbeMakeReady(v, pParse->nVar, pParse->explain);
6102 + pParse->rc = pParse->nErr ? SQLITE_ERROR : SQLITE_DONE;
6103 + pParse->colNamesSet = 0;
6104 + }else if( pParse->rc==SQLITE_OK ){
6105 + pParse->rc = SQLITE_ERROR;
6115 +** Locate the in-memory structure that describes
6116 +** a particular database table given the name
6117 +** of that table and (optionally) the name of the database
6118 +** containing the table. Return NULL if not found.
6120 +** If zDatabase is 0, all databases are searched for the
6121 +** table and the first matching table is returned. (No checking
6122 +** for duplicate table names is done.) The search order is
6123 +** TEMP first, then MAIN, then any auxiliary databases added
6124 +** using the ATTACH command.
6126 +** See also sqliteLocateTable().
6128 +Table *sqliteFindTable(sqlite *db, const char *zName, const char *zDatabase){
6131 + for(i=0; i<db->nDb; i++){
6132 + int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
6133 + if( zDatabase!=0 && sqliteStrICmp(zDatabase, db->aDb[j].zName) ) continue;
6134 + p = sqliteHashFind(&db->aDb[j].tblHash, zName, strlen(zName)+1);
6141 +** Locate the in-memory structure that describes
6142 +** a particular database table given the name
6143 +** of that table and (optionally) the name of the database
6144 +** containing the table. Return NULL if not found.
6145 +** Also leave an error message in pParse->zErrMsg.
6147 +** The difference between this routine and sqliteFindTable()
6148 +** is that this routine leaves an error message in pParse->zErrMsg
6149 +** where sqliteFindTable() does not.
6151 +Table *sqliteLocateTable(Parse *pParse, const char *zName, const char *zDbase){
6154 + p = sqliteFindTable(pParse->db, zName, zDbase);
6157 + sqliteErrorMsg(pParse, "no such table: %s.%s", zDbase, zName);
6158 + }else if( sqliteFindTable(pParse->db, zName, 0)!=0 ){
6159 + sqliteErrorMsg(pParse, "table \"%s\" is not in database \"%s\"",
6162 + sqliteErrorMsg(pParse, "no such table: %s", zName);
6169 +** Locate the in-memory structure that describes
6170 +** a particular index given the name of that index
6171 +** and the name of the database that contains the index.
6172 +** Return NULL if not found.
6174 +** If zDatabase is 0, all databases are searched for the
6175 +** table and the first matching index is returned. (No checking
6176 +** for duplicate index names is done.) The search order is
6177 +** TEMP first, then MAIN, then any auxiliary databases added
6178 +** using the ATTACH command.
6180 +Index *sqliteFindIndex(sqlite *db, const char *zName, const char *zDb){
6183 + for(i=0; i<db->nDb; i++){
6184 + int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
6185 + if( zDb && sqliteStrICmp(zDb, db->aDb[j].zName) ) continue;
6186 + p = sqliteHashFind(&db->aDb[j].idxHash, zName, strlen(zName)+1);
6193 +** Remove the given index from the index hash table, and free
6194 +** its memory structures.
6196 +** The index is removed from the database hash tables but
6197 +** it is not unlinked from the Table that it indexes.
6198 +** Unlinking from the Table must be done by the calling function.
6200 +static void sqliteDeleteIndex(sqlite *db, Index *p){
6203 + assert( db!=0 && p->zName!=0 );
6204 + pOld = sqliteHashInsert(&db->aDb[p->iDb].idxHash, p->zName,
6205 + strlen(p->zName)+1, 0);
6206 + if( pOld!=0 && pOld!=p ){
6207 + sqliteHashInsert(&db->aDb[p->iDb].idxHash, pOld->zName,
6208 + strlen(pOld->zName)+1, pOld);
6214 +** Unlink the given index from its table, then remove
6215 +** the index from the index hash table and free its memory
6218 +void sqliteUnlinkAndDeleteIndex(sqlite *db, Index *pIndex){
6219 + if( pIndex->pTable->pIndex==pIndex ){
6220 + pIndex->pTable->pIndex = pIndex->pNext;
6223 + for(p=pIndex->pTable->pIndex; p && p->pNext!=pIndex; p=p->pNext){}
6224 + if( p && p->pNext==pIndex ){
6225 + p->pNext = pIndex->pNext;
6228 + sqliteDeleteIndex(db, pIndex);
6232 +** Erase all schema information from the in-memory hash tables of
6233 +** database connection. This routine is called to reclaim memory
6234 +** before the connection closes. It is also called during a rollback
6235 +** if there were schema changes during the transaction.
6237 +** If iDb<=0 then reset the internal schema tables for all database
6238 +** files. If iDb>=2 then reset the internal schema for only the
6239 +** single file indicated.
6241 +void sqliteResetInternalSchema(sqlite *db, int iDb){
6247 + assert( iDb>=0 && iDb<db->nDb );
6248 + db->flags &= ~SQLITE_Initialized;
6249 + for(i=iDb; i<db->nDb; i++){
6250 + Db *pDb = &db->aDb[i];
6251 + temp1 = pDb->tblHash;
6252 + temp2 = pDb->trigHash;
6253 + sqliteHashInit(&pDb->trigHash, SQLITE_HASH_STRING, 0);
6254 + sqliteHashClear(&pDb->aFKey);
6255 + sqliteHashClear(&pDb->idxHash);
6256 + for(pElem=sqliteHashFirst(&temp2); pElem; pElem=sqliteHashNext(pElem)){
6257 + Trigger *pTrigger = sqliteHashData(pElem);
6258 + sqliteDeleteTrigger(pTrigger);
6260 + sqliteHashClear(&temp2);
6261 + sqliteHashInit(&pDb->tblHash, SQLITE_HASH_STRING, 0);
6262 + for(pElem=sqliteHashFirst(&temp1); pElem; pElem=sqliteHashNext(pElem)){
6263 + Table *pTab = sqliteHashData(pElem);
6264 + sqliteDeleteTable(db, pTab);
6266 + sqliteHashClear(&temp1);
6267 + DbClearProperty(db, i, DB_SchemaLoaded);
6268 + if( iDb>0 ) return;
6271 + db->flags &= ~SQLITE_InternChanges;
6273 + /* If one or more of the auxiliary database files has been closed,
6274 + ** then remove then from the auxiliary database list. We take the
6275 + ** opportunity to do this here since we have just deleted all of the
6276 + ** schema hash tables and therefore do not have to make any changes
6277 + ** to any of those tables.
6279 + for(i=0; i<db->nDb; i++){
6280 + struct Db *pDb = &db->aDb[i];
6281 + if( pDb->pBt==0 ){
6282 + if( pDb->pAux && pDb->xFreeAux ) pDb->xFreeAux(pDb->pAux);
6286 + for(i=j=2; i<db->nDb; i++){
6287 + struct Db *pDb = &db->aDb[i];
6288 + if( pDb->pBt==0 ){
6289 + sqliteFree(pDb->zName);
6294 + db->aDb[j] = db->aDb[i];
6298 + memset(&db->aDb[j], 0, (db->nDb-j)*sizeof(db->aDb[j]));
6300 + if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
6301 + memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
6302 + sqliteFree(db->aDb);
6303 + db->aDb = db->aDbStatic;
6308 +** This routine is called whenever a rollback occurs. If there were
6309 +** schema changes during the transaction, then we have to reset the
6310 +** internal hash tables and reload them from disk.
6312 +void sqliteRollbackInternalChanges(sqlite *db){
6313 + if( db->flags & SQLITE_InternChanges ){
6314 + sqliteResetInternalSchema(db, 0);
6319 +** This routine is called when a commit occurs.
6321 +void sqliteCommitInternalChanges(sqlite *db){
6322 + db->aDb[0].schema_cookie = db->next_cookie;
6323 + db->flags &= ~SQLITE_InternChanges;
6327 +** Remove the memory data structures associated with the given
6328 +** Table. No changes are made to disk by this routine.
6330 +** This routine just deletes the data structure. It does not unlink
6331 +** the table data structure from the hash table. Nor does it remove
6332 +** foreign keys from the sqlite.aFKey hash table. But it does destroy
6333 +** memory structures of the indices and foreign keys associated with
6336 +** Indices associated with the table are unlinked from the "db"
6337 +** data structure if db!=NULL. If db==NULL, indices attached to
6338 +** the table are deleted, but it is assumed they have already been
6341 +void sqliteDeleteTable(sqlite *db, Table *pTable){
6343 + Index *pIndex, *pNext;
6344 + FKey *pFKey, *pNextFKey;
6346 + if( pTable==0 ) return;
6348 + /* Delete all indices associated with this table
6350 + for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
6351 + pNext = pIndex->pNext;
6352 + assert( pIndex->iDb==pTable->iDb || (pTable->iDb==0 && pIndex->iDb==1) );
6353 + sqliteDeleteIndex(db, pIndex);
6356 + /* Delete all foreign keys associated with this table. The keys
6357 + ** should have already been unlinked from the db->aFKey hash table
6359 + for(pFKey=pTable->pFKey; pFKey; pFKey=pNextFKey){
6360 + pNextFKey = pFKey->pNextFrom;
6361 + assert( pTable->iDb<db->nDb );
6362 + assert( sqliteHashFind(&db->aDb[pTable->iDb].aFKey,
6363 + pFKey->zTo, strlen(pFKey->zTo)+1)!=pFKey );
6364 + sqliteFree(pFKey);
6367 + /* Delete the Table structure itself.
6369 + for(i=0; i<pTable->nCol; i++){
6370 + sqliteFree(pTable->aCol[i].zName);
6371 + sqliteFree(pTable->aCol[i].zDflt);
6372 + sqliteFree(pTable->aCol[i].zType);
6374 + sqliteFree(pTable->zName);
6375 + sqliteFree(pTable->aCol);
6376 + sqliteSelectDelete(pTable->pSelect);
6377 + sqliteFree(pTable);
6381 +** Unlink the given table from the hash tables and the delete the
6382 +** table structure with all its indices and foreign keys.
6384 +static void sqliteUnlinkAndDeleteTable(sqlite *db, Table *p){
6389 + pOld = sqliteHashInsert(&db->aDb[i].tblHash, p->zName, strlen(p->zName)+1, 0);
6390 + assert( pOld==0 || pOld==p );
6391 + for(pF1=p->pFKey; pF1; pF1=pF1->pNextFrom){
6392 + int nTo = strlen(pF1->zTo) + 1;
6393 + pF2 = sqliteHashFind(&db->aDb[i].aFKey, pF1->zTo, nTo);
6395 + sqliteHashInsert(&db->aDb[i].aFKey, pF1->zTo, nTo, pF1->pNextTo);
6397 + while( pF2 && pF2->pNextTo!=pF1 ){ pF2=pF2->pNextTo; }
6399 + pF2->pNextTo = pF1->pNextTo;
6403 + sqliteDeleteTable(db, p);
6407 +** Construct the name of a user table or index from a token.
6409 +** Space to hold the name is obtained from sqliteMalloc() and must
6410 +** be freed by the calling function.
6412 +char *sqliteTableNameFromToken(Token *pName){
6413 + char *zName = sqliteStrNDup(pName->z, pName->n);
6414 + sqliteDequote(zName);
6419 +** Generate code to open the appropriate master table. The table
6420 +** opened will be SQLITE_MASTER for persistent tables and
6421 +** SQLITE_TEMP_MASTER for temporary tables. The table is opened
6424 +void sqliteOpenMasterTable(Vdbe *v, int isTemp){
6425 + sqliteVdbeAddOp(v, OP_Integer, isTemp, 0);
6426 + sqliteVdbeAddOp(v, OP_OpenWrite, 0, 2);
6430 +** Begin constructing a new table representation in memory. This is
6431 +** the first of several action routines that get called in response
6432 +** to a CREATE TABLE statement. In particular, this routine is called
6433 +** after seeing tokens "CREATE" and "TABLE" and the table name. The
6434 +** pStart token is the CREATE and pName is the table name. The isTemp
6435 +** flag is true if the table should be stored in the auxiliary database
6436 +** file instead of in the main database file. This is normally the case
6437 +** when the "TEMP" or "TEMPORARY" keyword occurs in between
6438 +** CREATE and TABLE.
6440 +** The new table record is initialized and put in pParse->pNewTable.
6441 +** As more of the CREATE TABLE statement is parsed, additional action
6442 +** routines will be called to add more information to this record.
6443 +** At the end of the CREATE TABLE statement, the sqliteEndTable() routine
6444 +** is called to complete the construction of the new table record.
6446 +void sqliteStartTable(
6447 + Parse *pParse, /* Parser context */
6448 + Token *pStart, /* The "CREATE" token */
6449 + Token *pName, /* Name of table or view to create */
6450 + int isTemp, /* True if this is a TEMP table */
6451 + int isView /* True if this is a VIEW */
6456 + sqlite *db = pParse->db;
6460 + pParse->sFirstToken = *pStart;
6461 + zName = sqliteTableNameFromToken(pName);
6462 + if( zName==0 ) return;
6463 + if( db->init.iDb==1 ) isTemp = 1;
6464 +#ifndef SQLITE_OMIT_AUTHORIZATION
6465 + assert( (isTemp & 1)==isTemp );
6468 + char *zDb = isTemp ? "temp" : "main";
6469 + if( sqliteAuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
6470 + sqliteFree(zName);
6475 + code = SQLITE_CREATE_TEMP_VIEW;
6477 + code = SQLITE_CREATE_VIEW;
6481 + code = SQLITE_CREATE_TEMP_TABLE;
6483 + code = SQLITE_CREATE_TABLE;
6486 + if( sqliteAuthCheck(pParse, code, zName, 0, zDb) ){
6487 + sqliteFree(zName);
6494 + /* Before trying to create a temporary table, make sure the Btree for
6495 + ** holding temporary tables is open.
6497 + if( isTemp && db->aDb[1].pBt==0 && !pParse->explain ){
6498 + int rc = sqliteBtreeFactory(db, 0, 0, MAX_PAGES, &db->aDb[1].pBt);
6499 + if( rc!=SQLITE_OK ){
6500 + sqliteErrorMsg(pParse, "unable to open a temporary database "
6501 + "file for storing temporary tables");
6505 + if( db->flags & SQLITE_InTrans ){
6506 + rc = sqliteBtreeBeginTrans(db->aDb[1].pBt);
6507 + if( rc!=SQLITE_OK ){
6508 + sqliteErrorMsg(pParse, "unable to get a write lock on "
6509 + "the temporary database file");
6515 + /* Make sure the new table name does not collide with an existing
6516 + ** index or table name. Issue an error message if it does.
6518 + ** If we are re-reading the sqlite_master table because of a schema
6519 + ** change and a new permanent table is found whose name collides with
6520 + ** an existing temporary table, that is not an error.
6522 + pTable = sqliteFindTable(db, zName, 0);
6523 + iDb = isTemp ? 1 : db->init.iDb;
6524 + if( pTable!=0 && (pTable->iDb==iDb || !db->init.busy) ){
6525 + sqliteErrorMsg(pParse, "table %T already exists", pName);
6526 + sqliteFree(zName);
6529 + if( (pIdx = sqliteFindIndex(db, zName, 0))!=0 &&
6530 + (pIdx->iDb==0 || !db->init.busy) ){
6531 + sqliteErrorMsg(pParse, "there is already an index named %s", zName);
6532 + sqliteFree(zName);
6535 + pTable = sqliteMalloc( sizeof(Table) );
6537 + sqliteFree(zName);
6540 + pTable->zName = zName;
6543 + pTable->iPKey = -1;
6544 + pTable->pIndex = 0;
6545 + pTable->iDb = iDb;
6546 + if( pParse->pNewTable ) sqliteDeleteTable(db, pParse->pNewTable);
6547 + pParse->pNewTable = pTable;
6549 + /* Begin generating the code that will insert the table record into
6550 + ** the SQLITE_MASTER table. Note in particular that we must go ahead
6551 + ** and allocate the record number for the table entry now. Before any
6552 + ** PRIMARY KEY or UNIQUE keywords are parsed. Those keywords will cause
6553 + ** indices to be created and the table record must come before the
6554 + ** indices. Hence, the record number for the table must be allocated
6557 + if( !db->init.busy && (v = sqliteGetVdbe(pParse))!=0 ){
6558 + sqliteBeginWriteOperation(pParse, 0, isTemp);
6560 + sqliteVdbeAddOp(v, OP_Integer, db->file_format, 0);
6561 + sqliteVdbeAddOp(v, OP_SetCookie, 0, 1);
6563 + sqliteOpenMasterTable(v, isTemp);
6564 + sqliteVdbeAddOp(v, OP_NewRecno, 0, 0);
6565 + sqliteVdbeAddOp(v, OP_Dup, 0, 0);
6566 + sqliteVdbeAddOp(v, OP_String, 0, 0);
6567 + sqliteVdbeAddOp(v, OP_PutIntKey, 0, 0);
6572 +** Add a new column to the table currently being constructed.
6574 +** The parser calls this routine once for each column declaration
6575 +** in a CREATE TABLE statement. sqliteStartTable() gets called
6576 +** first to get things going. Then this routine is called for each
6579 +void sqliteAddColumn(Parse *pParse, Token *pName){
6584 + if( (p = pParse->pNewTable)==0 ) return;
6585 + sqliteSetNString(&z, pName->z, pName->n, 0);
6586 + if( z==0 ) return;
6588 + for(i=0; i<p->nCol; i++){
6589 + if( sqliteStrICmp(z, p->aCol[i].zName)==0 ){
6590 + sqliteErrorMsg(pParse, "duplicate column name: %s", z);
6595 + if( (p->nCol & 0x7)==0 ){
6597 + aNew = sqliteRealloc( p->aCol, (p->nCol+8)*sizeof(p->aCol[0]));
6598 + if( aNew==0 ) return;
6601 + pCol = &p->aCol[p->nCol];
6602 + memset(pCol, 0, sizeof(p->aCol[0]));
6604 + pCol->sortOrder = SQLITE_SO_NUM;
6609 +** This routine is called by the parser while in the middle of
6610 +** parsing a CREATE TABLE statement. A "NOT NULL" constraint has
6611 +** been seen on a column. This routine sets the notNull flag on
6612 +** the column currently under construction.
6614 +void sqliteAddNotNull(Parse *pParse, int onError){
6617 + if( (p = pParse->pNewTable)==0 ) return;
6619 + if( i>=0 ) p->aCol[i].notNull = onError;
6623 +** This routine is called by the parser while in the middle of
6624 +** parsing a CREATE TABLE statement. The pFirst token is the first
6625 +** token in the sequence of tokens that describe the type of the
6626 +** column currently under construction. pLast is the last token
6627 +** in the sequence. Use this information to construct a string
6628 +** that contains the typename of the column and store that string
6631 +void sqliteAddColumnType(Parse *pParse, Token *pFirst, Token *pLast){
6637 + if( (p = pParse->pNewTable)==0 ) return;
6640 + pCol = &p->aCol[i];
6641 + pz = &pCol->zType;
6642 + n = pLast->n + Addr(pLast->z) - Addr(pFirst->z);
6643 + sqliteSetNString(pz, pFirst->z, n, 0);
6645 + if( z==0 ) return;
6646 + for(i=j=0; z[i]; i++){
6648 + if( isspace(c) ) continue;
6652 + if( pParse->db->file_format>=4 ){
6653 + pCol->sortOrder = sqliteCollateType(z, n);
6655 + pCol->sortOrder = SQLITE_SO_NUM;
6660 +** The given token is the default value for the last column added to
6661 +** the table currently under construction. If "minusFlag" is true, it
6662 +** means the value token was preceded by a minus sign.
6664 +** This routine is called by the parser while in the middle of
6665 +** parsing a CREATE TABLE statement.
6667 +void sqliteAddDefaultValue(Parse *pParse, Token *pVal, int minusFlag){
6671 + if( (p = pParse->pNewTable)==0 ) return;
6674 + pz = &p->aCol[i].zDflt;
6676 + sqliteSetNString(pz, "-", 1, pVal->z, pVal->n, 0);
6678 + sqliteSetNString(pz, pVal->z, pVal->n, 0);
6680 + sqliteDequote(*pz);
6684 +** Designate the PRIMARY KEY for the table. pList is a list of names
6685 +** of columns that form the primary key. If pList is NULL, then the
6686 +** most recently added column of the table is the primary key.
6688 +** A table can have at most one primary key. If the table already has
6689 +** a primary key (and this is the second primary key) then create an
6692 +** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
6693 +** then we will try to use that column as the row id. (Exception:
6694 +** For backwards compatibility with older databases, do not do this
6695 +** if the file format version number is less than 1.) Set the Table.iPKey
6696 +** field of the table under construction to be the index of the
6697 +** INTEGER PRIMARY KEY column. Table.iPKey is set to -1 if there is
6698 +** no INTEGER PRIMARY KEY.
6700 +** If the key is not an INTEGER PRIMARY KEY, then create a unique
6701 +** index for the key. No index is created for INTEGER PRIMARY KEYs.
6703 +void sqliteAddPrimaryKey(Parse *pParse, IdList *pList, int onError){
6704 + Table *pTab = pParse->pNewTable;
6707 + if( pTab==0 ) goto primary_key_exit;
6708 + if( pTab->hasPrimKey ){
6709 + sqliteErrorMsg(pParse,
6710 + "table \"%s\" has more than one primary key", pTab->zName);
6711 + goto primary_key_exit;
6713 + pTab->hasPrimKey = 1;
6715 + iCol = pTab->nCol - 1;
6716 + pTab->aCol[iCol].isPrimKey = 1;
6718 + for(i=0; i<pList->nId; i++){
6719 + for(iCol=0; iCol<pTab->nCol; iCol++){
6720 + if( sqliteStrICmp(pList->a[i].zName, pTab->aCol[iCol].zName)==0 ) break;
6722 + if( iCol<pTab->nCol ) pTab->aCol[iCol].isPrimKey = 1;
6724 + if( pList->nId>1 ) iCol = -1;
6726 + if( iCol>=0 && iCol<pTab->nCol ){
6727 + zType = pTab->aCol[iCol].zType;
6729 + if( pParse->db->file_format>=1 &&
6730 + zType && sqliteStrICmp(zType, "INTEGER")==0 ){
6731 + pTab->iPKey = iCol;
6732 + pTab->keyConf = onError;
6734 + sqliteCreateIndex(pParse, 0, 0, pList, onError, 0, 0);
6739 + sqliteIdListDelete(pList);
6744 +** Return the appropriate collating type given a type name.
6746 +** The collation type is text (SQLITE_SO_TEXT) if the type
6747 +** name contains the character stream "text" or "blob" or
6748 +** "clob". Any other type name is collated as numeric
6749 +** (SQLITE_SO_NUM).
6751 +int sqliteCollateType(const char *zType, int nType){
6753 + for(i=0; i<nType-3; i++){
6754 + int c = *(zType++) | 0x60;
6755 + if( (c=='b' || c=='c') && sqliteStrNICmp(zType, "lob", 3)==0 ){
6756 + return SQLITE_SO_TEXT;
6758 + if( c=='c' && sqliteStrNICmp(zType, "har", 3)==0 ){
6759 + return SQLITE_SO_TEXT;
6761 + if( c=='t' && sqliteStrNICmp(zType, "ext", 3)==0 ){
6762 + return SQLITE_SO_TEXT;
6765 + return SQLITE_SO_NUM;
6769 +** This routine is called by the parser while in the middle of
6770 +** parsing a CREATE TABLE statement. A "COLLATE" clause has
6771 +** been seen on a column. This routine sets the Column.sortOrder on
6772 +** the column currently under construction.
6774 +void sqliteAddCollateType(Parse *pParse, int collType){
6777 + if( (p = pParse->pNewTable)==0 ) return;
6779 + if( i>=0 ) p->aCol[i].sortOrder = collType;
6783 +** Come up with a new random value for the schema cookie. Make sure
6784 +** the new value is different from the old.
6786 +** The schema cookie is used to determine when the schema for the
6787 +** database changes. After each schema change, the cookie value
6788 +** changes. When a process first reads the schema it records the
6789 +** cookie. Thereafter, whenever it goes to access the database,
6790 +** it checks the cookie to make sure the schema has not changed
6791 +** since it was last read.
6793 +** This plan is not completely bullet-proof. It is possible for
6794 +** the schema to change multiple times and for the cookie to be
6795 +** set back to prior value. But schema changes are infrequent
6796 +** and the probability of hitting the same cookie value is only
6797 +** 1 chance in 2^32. So we're safe enough.
6799 +void sqliteChangeCookie(sqlite *db, Vdbe *v){
6800 + if( db->next_cookie==db->aDb[0].schema_cookie ){
6802 + sqliteRandomness(1, &r);
6803 + db->next_cookie = db->aDb[0].schema_cookie + r + 1;
6804 + db->flags |= SQLITE_InternChanges;
6805 + sqliteVdbeAddOp(v, OP_Integer, db->next_cookie, 0);
6806 + sqliteVdbeAddOp(v, OP_SetCookie, 0, 0);
6811 +** Measure the number of characters needed to output the given
6812 +** identifier. The number returned includes any quotes used
6813 +** but does not include the null terminator.
6815 +static int identLength(const char *z){
6817 + int needQuote = 0;
6818 + for(n=0; *z; n++, z++){
6819 + if( *z=='\'' ){ n++; needQuote=1; }
6821 + return n + needQuote*2;
6825 +** Write an identifier onto the end of the given string. Add
6826 +** quote characters as needed.
6828 +static void identPut(char *z, int *pIdx, char *zIdent){
6829 + int i, j, needQuote;
6831 + for(j=0; zIdent[j]; j++){
6832 + if( !isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
6834 + needQuote = zIdent[j]!=0 || isdigit(zIdent[0])
6835 + || sqliteKeywordCode(zIdent, j)!=TK_ID;
6836 + if( needQuote ) z[i++] = '\'';
6837 + for(j=0; zIdent[j]; j++){
6838 + z[i++] = zIdent[j];
6839 + if( zIdent[j]=='\'' ) z[i++] = '\'';
6841 + if( needQuote ) z[i++] = '\'';
6847 +** Generate a CREATE TABLE statement appropriate for the given
6848 +** table. Memory to hold the text of the statement is obtained
6849 +** from sqliteMalloc() and must be freed by the calling function.
6851 +static char *createTableStmt(Table *p){
6854 + char *zSep, *zSep2, *zEnd;
6856 + for(i=0; i<p->nCol; i++){
6857 + n += identLength(p->aCol[i].zName);
6859 + n += identLength(p->zName);
6869 + n += 35 + 6*p->nCol;
6870 + zStmt = sqliteMallocRaw( n );
6871 + if( zStmt==0 ) return 0;
6872 + strcpy(zStmt, p->iDb==1 ? "CREATE TEMP TABLE " : "CREATE TABLE ");
6873 + k = strlen(zStmt);
6874 + identPut(zStmt, &k, p->zName);
6876 + for(i=0; i<p->nCol; i++){
6877 + strcpy(&zStmt[k], zSep);
6878 + k += strlen(&zStmt[k]);
6880 + identPut(zStmt, &k, p->aCol[i].zName);
6882 + strcpy(&zStmt[k], zEnd);
6887 +** This routine is called to report the final ")" that terminates
6888 +** a CREATE TABLE statement.
6890 +** The table structure that other action routines have been building
6891 +** is added to the internal hash tables, assuming no errors have
6894 +** An entry for the table is made in the master table on disk, unless
6895 +** this is a temporary table or db->init.busy==1. When db->init.busy==1
6896 +** it means we are reading the sqlite_master table because we just
6897 +** connected to the database or because the sqlite_master table has
6898 +** recently changes, so the entry for this table already exists in
6899 +** the sqlite_master table. We do not want to create it again.
6901 +** If the pSelect argument is not NULL, it means that this routine
6902 +** was called to create a table generated from a
6903 +** "CREATE TABLE ... AS SELECT ..." statement. The column names of
6904 +** the new table will match the result set of the SELECT.
6906 +void sqliteEndTable(Parse *pParse, Token *pEnd, Select *pSelect){
6908 + sqlite *db = pParse->db;
6910 + if( (pEnd==0 && pSelect==0) || pParse->nErr || sqlite_malloc_failed ) return;
6911 + p = pParse->pNewTable;
6912 + if( p==0 ) return;
6914 + /* If the table is generated from a SELECT, then construct the
6915 + ** list of columns and the text of the table.
6918 + Table *pSelTab = sqliteResultSetOfSelect(pParse, 0, pSelect);
6919 + if( pSelTab==0 ) return;
6920 + assert( p->aCol==0 );
6921 + p->nCol = pSelTab->nCol;
6922 + p->aCol = pSelTab->aCol;
6923 + pSelTab->nCol = 0;
6924 + pSelTab->aCol = 0;
6925 + sqliteDeleteTable(0, pSelTab);
6928 + /* If the db->init.busy is 1 it means we are reading the SQL off the
6929 + ** "sqlite_master" or "sqlite_temp_master" table on the disk.
6930 + ** So do not write to the disk again. Extract the root page number
6931 + ** for the table from the db->init.newTnum field. (The page number
6932 + ** should have been put there by the sqliteOpenCb routine.)
6934 + if( db->init.busy ){
6935 + p->tnum = db->init.newTnum;
6938 + /* If not initializing, then create a record for the new table
6939 + ** in the SQLITE_MASTER table of the database. The record number
6940 + ** for the new table entry should already be on the stack.
6942 + ** If this is a TEMPORARY table, write the entry into the auxiliary
6943 + ** file instead of into the main database file.
6945 + if( !db->init.busy ){
6949 + v = sqliteGetVdbe(pParse);
6950 + if( v==0 ) return;
6951 + if( p->pSelect==0 ){
6952 + /* A regular table */
6953 + sqliteVdbeOp3(v, OP_CreateTable, 0, p->iDb, (char*)&p->tnum, P3_POINTER);
6956 + sqliteVdbeAddOp(v, OP_Integer, 0, 0);
6959 + sqliteVdbeAddOp(v, OP_Pull, 1, 0);
6960 + sqliteVdbeOp3(v, OP_String, 0, 0, p->pSelect==0?"table":"view", P3_STATIC);
6961 + sqliteVdbeOp3(v, OP_String, 0, 0, p->zName, 0);
6962 + sqliteVdbeOp3(v, OP_String, 0, 0, p->zName, 0);
6963 + sqliteVdbeAddOp(v, OP_Dup, 4, 0);
6964 + sqliteVdbeAddOp(v, OP_String, 0, 0);
6966 + char *z = createTableStmt(p);
6967 + n = z ? strlen(z) : 0;
6968 + sqliteVdbeChangeP3(v, -1, z, n);
6971 + assert( pEnd!=0 );
6972 + n = Addr(pEnd->z) - Addr(pParse->sFirstToken.z) + 1;
6973 + sqliteVdbeChangeP3(v, -1, pParse->sFirstToken.z, n);
6975 + sqliteVdbeAddOp(v, OP_MakeRecord, 5, 0);
6976 + sqliteVdbeAddOp(v, OP_PutIntKey, 0, 0);
6978 + sqliteChangeCookie(db, v);
6980 + sqliteVdbeAddOp(v, OP_Close, 0, 0);
6982 + sqliteVdbeAddOp(v, OP_Integer, p->iDb, 0);
6983 + sqliteVdbeAddOp(v, OP_OpenWrite, 1, 0);
6985 + sqliteSelect(pParse, pSelect, SRT_Table, 1, 0, 0, 0);
6987 + sqliteEndWriteOperation(pParse);
6990 + /* Add the table to the in-memory representation of the database.
6992 + if( pParse->explain==0 && pParse->nErr==0 ){
6995 + pOld = sqliteHashInsert(&db->aDb[p->iDb].tblHash,
6996 + p->zName, strlen(p->zName)+1, p);
6998 + assert( p==pOld ); /* Malloc must have failed inside HashInsert() */
7001 + for(pFKey=p->pFKey; pFKey; pFKey=pFKey->pNextFrom){
7002 + int nTo = strlen(pFKey->zTo) + 1;
7003 + pFKey->pNextTo = sqliteHashFind(&db->aDb[p->iDb].aFKey, pFKey->zTo, nTo);
7004 + sqliteHashInsert(&db->aDb[p->iDb].aFKey, pFKey->zTo, nTo, pFKey);
7006 + pParse->pNewTable = 0;
7008 + db->flags |= SQLITE_InternChanges;
7013 +** The parser calls this routine in order to create a new VIEW
7015 +void sqliteCreateView(
7016 + Parse *pParse, /* The parsing context */
7017 + Token *pBegin, /* The CREATE token that begins the statement */
7018 + Token *pName, /* The token that holds the name of the view */
7019 + Select *pSelect, /* A SELECT statement that will become the new view */
7020 + int isTemp /* TRUE for a TEMPORARY view */
7028 + sqliteStartTable(pParse, pBegin, pName, isTemp, 1);
7029 + p = pParse->pNewTable;
7030 + if( p==0 || pParse->nErr ){
7031 + sqliteSelectDelete(pSelect);
7034 + if( sqliteFixInit(&sFix, pParse, p->iDb, "view", pName)
7035 + && sqliteFixSelect(&sFix, pSelect)
7037 + sqliteSelectDelete(pSelect);
7041 + /* Make a copy of the entire SELECT statement that defines the view.
7042 + ** This will force all the Expr.token.z values to be dynamically
7043 + ** allocated rather than point to the input string - which means that
7044 + ** they will persist after the current sqlite_exec() call returns.
7046 + p->pSelect = sqliteSelectDup(pSelect);
7047 + sqliteSelectDelete(pSelect);
7048 + if( !pParse->db->init.busy ){
7049 + sqliteViewGetColumnNames(pParse, p);
7052 + /* Locate the end of the CREATE VIEW statement. Make sEnd point to
7055 + sEnd = pParse->sLastToken;
7056 + if( sEnd.z[0]!=0 && sEnd.z[0]!=';' ){
7060 + n = sEnd.z - pBegin->z;
7062 + while( n>0 && (z[n-1]==';' || isspace(z[n-1])) ){ n--; }
7066 + /* Use sqliteEndTable() to add the view to the SQLITE_MASTER table */
7067 + sqliteEndTable(pParse, &sEnd, 0);
7072 +** The Table structure pTable is really a VIEW. Fill in the names of
7073 +** the columns of the view in the pTable structure. Return the number
7074 +** of errors. If an error is seen leave an error message in pParse->zErrMsg.
7076 +int sqliteViewGetColumnNames(Parse *pParse, Table *pTable){
7084 + /* A positive nCol means the columns names for this view are
7087 + if( pTable->nCol>0 ) return 0;
7089 + /* A negative nCol is a special marker meaning that we are currently
7090 + ** trying to compute the column names. If we enter this routine with
7091 + ** a negative nCol, it means two or more views form a loop, like this:
7093 + ** CREATE VIEW one AS SELECT * FROM two;
7094 + ** CREATE VIEW two AS SELECT * FROM one;
7096 + ** Actually, this error is caught previously and so the following test
7097 + ** should always fail. But we will leave it in place just to be safe.
7099 + if( pTable->nCol<0 ){
7100 + sqliteErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
7104 + /* If we get this far, it means we need to compute the table names.
7106 + assert( pTable->pSelect ); /* If nCol==0, then pTable must be a VIEW */
7107 + pSel = pTable->pSelect;
7109 + /* Note that the call to sqliteResultSetOfSelect() will expand any
7110 + ** "*" elements in this list. But we will need to restore the list
7111 + ** back to its original configuration afterwards, so we save a copy of
7112 + ** the original in pEList.
7114 + pEList = pSel->pEList;
7115 + pSel->pEList = sqliteExprListDup(pEList);
7116 + if( pSel->pEList==0 ){
7117 + pSel->pEList = pEList;
7118 + return 1; /* Malloc failed */
7120 + pTable->nCol = -1;
7121 + pSelTab = sqliteResultSetOfSelect(pParse, 0, pSel);
7123 + assert( pTable->aCol==0 );
7124 + pTable->nCol = pSelTab->nCol;
7125 + pTable->aCol = pSelTab->aCol;
7126 + pSelTab->nCol = 0;
7127 + pSelTab->aCol = 0;
7128 + sqliteDeleteTable(0, pSelTab);
7129 + DbSetProperty(pParse->db, pTable->iDb, DB_UnresetViews);
7134 + sqliteSelectUnbind(pSel);
7135 + sqliteExprListDelete(pSel->pEList);
7136 + pSel->pEList = pEList;
7141 +** Clear the column names from the VIEW pTable.
7143 +** This routine is called whenever any other table or view is modified.
7144 +** The view passed into this routine might depend directly or indirectly
7145 +** on the modified or deleted table so we need to clear the old column
7146 +** names so that they will be recomputed.
7148 +static void sqliteViewResetColumnNames(Table *pTable){
7151 + assert( pTable!=0 && pTable->pSelect!=0 );
7152 + for(i=0, pCol=pTable->aCol; i<pTable->nCol; i++, pCol++){
7153 + sqliteFree(pCol->zName);
7154 + sqliteFree(pCol->zDflt);
7155 + sqliteFree(pCol->zType);
7157 + sqliteFree(pTable->aCol);
7163 +** Clear the column names from every VIEW in database idx.
7165 +static void sqliteViewResetAll(sqlite *db, int idx){
7167 + if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
7168 + for(i=sqliteHashFirst(&db->aDb[idx].tblHash); i; i=sqliteHashNext(i)){
7169 + Table *pTab = sqliteHashData(i);
7170 + if( pTab->pSelect ){
7171 + sqliteViewResetColumnNames(pTab);
7174 + DbClearProperty(db, idx, DB_UnresetViews);
7178 +** Given a token, look up a table with that name. If not found, leave
7179 +** an error for the parser to find and return NULL.
7181 +Table *sqliteTableFromToken(Parse *pParse, Token *pTok){
7184 + zName = sqliteTableNameFromToken(pTok);
7185 + if( zName==0 ) return 0;
7186 + pTab = sqliteFindTable(pParse->db, zName, 0);
7187 + sqliteFree(zName);
7189 + sqliteErrorMsg(pParse, "no such table: %T", pTok);
7195 +** This routine is called to do the work of a DROP TABLE statement.
7196 +** pName is the name of the table to be dropped.
7198 +void sqliteDropTable(Parse *pParse, Token *pName, int isView){
7202 + sqlite *db = pParse->db;
7205 + if( pParse->nErr || sqlite_malloc_failed ) return;
7206 + pTable = sqliteTableFromToken(pParse, pName);
7207 + if( pTable==0 ) return;
7208 + iDb = pTable->iDb;
7209 + assert( iDb>=0 && iDb<db->nDb );
7210 +#ifndef SQLITE_OMIT_AUTHORIZATION
7213 + const char *zTab = SCHEMA_TABLE(pTable->iDb);
7214 + const char *zDb = db->aDb[pTable->iDb].zName;
7215 + if( sqliteAuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
7220 + code = SQLITE_DROP_TEMP_VIEW;
7222 + code = SQLITE_DROP_VIEW;
7226 + code = SQLITE_DROP_TEMP_TABLE;
7228 + code = SQLITE_DROP_TABLE;
7231 + if( sqliteAuthCheck(pParse, code, pTable->zName, 0, zDb) ){
7234 + if( sqliteAuthCheck(pParse, SQLITE_DELETE, pTable->zName, 0, zDb) ){
7239 + if( pTable->readOnly ){
7240 + sqliteErrorMsg(pParse, "table %s may not be dropped", pTable->zName);
7244 + if( isView && pTable->pSelect==0 ){
7245 + sqliteErrorMsg(pParse, "use DROP TABLE to delete table %s", pTable->zName);
7248 + if( !isView && pTable->pSelect ){
7249 + sqliteErrorMsg(pParse, "use DROP VIEW to delete view %s", pTable->zName);
7253 + /* Generate code to remove the table from the master table
7256 + v = sqliteGetVdbe(pParse);
7258 + static VdbeOpList dropTable[] = {
7259 + { OP_Rewind, 0, ADDR(8), 0},
7260 + { OP_String, 0, 0, 0}, /* 1 */
7261 + { OP_MemStore, 1, 1, 0},
7262 + { OP_MemLoad, 1, 0, 0}, /* 3 */
7263 + { OP_Column, 0, 2, 0},
7264 + { OP_Ne, 0, ADDR(7), 0},
7265 + { OP_Delete, 0, 0, 0},
7266 + { OP_Next, 0, ADDR(3), 0}, /* 7 */
7269 + Trigger *pTrigger;
7270 + sqliteBeginWriteOperation(pParse, 0, pTable->iDb);
7272 + /* Drop all triggers associated with the table being dropped */
7273 + pTrigger = pTable->pTrigger;
7274 + while( pTrigger ){
7275 + assert( pTrigger->iDb==pTable->iDb || pTrigger->iDb==1 );
7276 + sqliteDropTriggerPtr(pParse, pTrigger, 1);
7277 + if( pParse->explain ){
7278 + pTrigger = pTrigger->pNext;
7280 + pTrigger = pTable->pTrigger;
7284 + /* Drop all SQLITE_MASTER entries that refer to the table */
7285 + sqliteOpenMasterTable(v, pTable->iDb);
7286 + base = sqliteVdbeAddOpList(v, ArraySize(dropTable), dropTable);
7287 + sqliteVdbeChangeP3(v, base+1, pTable->zName, 0);
7289 + /* Drop all SQLITE_TEMP_MASTER entries that refer to the table */
7290 + if( pTable->iDb!=1 ){
7291 + sqliteOpenMasterTable(v, 1);
7292 + base = sqliteVdbeAddOpList(v, ArraySize(dropTable), dropTable);
7293 + sqliteVdbeChangeP3(v, base+1, pTable->zName, 0);
7296 + if( pTable->iDb==0 ){
7297 + sqliteChangeCookie(db, v);
7299 + sqliteVdbeAddOp(v, OP_Close, 0, 0);
7301 + sqliteVdbeAddOp(v, OP_Destroy, pTable->tnum, pTable->iDb);
7302 + for(pIdx=pTable->pIndex; pIdx; pIdx=pIdx->pNext){
7303 + sqliteVdbeAddOp(v, OP_Destroy, pIdx->tnum, pIdx->iDb);
7306 + sqliteEndWriteOperation(pParse);
7309 + /* Delete the in-memory description of the table.
7311 + ** Exception: if the SQL statement began with the EXPLAIN keyword,
7312 + ** then no changes should be made.
7314 + if( !pParse->explain ){
7315 + sqliteUnlinkAndDeleteTable(db, pTable);
7316 + db->flags |= SQLITE_InternChanges;
7318 + sqliteViewResetAll(db, iDb);
7322 +** This routine constructs a P3 string suitable for an OP_MakeIdxKey
7323 +** opcode and adds that P3 string to the most recently inserted instruction
7324 +** in the virtual machine. The P3 string consists of a single character
7325 +** for each column in the index pIdx of table pTab. If the column uses
7326 +** a numeric sort order, then the P3 string character corresponding to
7327 +** that column is 'n'. If the column uses a text sort order, then the
7328 +** P3 string is 't'. See the OP_MakeIdxKey opcode documentation for
7329 +** additional information. See also the sqliteAddKeyType() routine.
7331 +void sqliteAddIdxKeyType(Vdbe *v, Index *pIdx){
7335 + assert( pIdx!=0 && pIdx->pTable!=0 );
7336 + pTab = pIdx->pTable;
7337 + n = pIdx->nColumn;
7338 + zType = sqliteMallocRaw( n+1 );
7339 + if( zType==0 ) return;
7340 + for(i=0; i<n; i++){
7341 + int iCol = pIdx->aiColumn[i];
7342 + assert( iCol>=0 && iCol<pTab->nCol );
7343 + if( (pTab->aCol[iCol].sortOrder & SQLITE_SO_TYPEMASK)==SQLITE_SO_TEXT ){
7350 + sqliteVdbeChangeP3(v, -1, zType, n);
7351 + sqliteFree(zType);
7355 +** This routine is called to create a new foreign key on the table
7356 +** currently under construction. pFromCol determines which columns
7357 +** in the current table point to the foreign key. If pFromCol==0 then
7358 +** connect the key to the last column inserted. pTo is the name of
7359 +** the table referred to. pToCol is a list of tables in the other
7360 +** pTo table that the foreign key points to. flags contains all
7361 +** information about the conflict resolution algorithms specified
7362 +** in the ON DELETE, ON UPDATE and ON INSERT clauses.
7364 +** An FKey structure is created and added to the table currently
7365 +** under construction in the pParse->pNewTable field. The new FKey
7366 +** is not linked into db->aFKey at this point - that does not happen
7367 +** until sqliteEndTable().
7369 +** The foreign key is set for IMMEDIATE processing. A subsequent call
7370 +** to sqliteDeferForeignKey() might change this to DEFERRED.
7372 +void sqliteCreateForeignKey(
7373 + Parse *pParse, /* Parsing context */
7374 + IdList *pFromCol, /* Columns in this table that point to other table */
7375 + Token *pTo, /* Name of the other table */
7376 + IdList *pToCol, /* Columns in the other table */
7377 + int flags /* Conflict resolution algorithms. */
7379 + Table *p = pParse->pNewTable;
7387 + if( p==0 || pParse->nErr ) goto fk_end;
7388 + if( pFromCol==0 ){
7389 + int iCol = p->nCol-1;
7390 + if( iCol<0 ) goto fk_end;
7391 + if( pToCol && pToCol->nId!=1 ){
7392 + sqliteErrorMsg(pParse, "foreign key on %s"
7393 + " should reference only one column of table %T",
7394 + p->aCol[iCol].zName, pTo);
7398 + }else if( pToCol && pToCol->nId!=pFromCol->nId ){
7399 + sqliteErrorMsg(pParse,
7400 + "number of columns in foreign key does not match the number of "
7401 + "columns in the referenced table");
7404 + nCol = pFromCol->nId;
7406 + nByte = sizeof(*pFKey) + nCol*sizeof(pFKey->aCol[0]) + pTo->n + 1;
7408 + for(i=0; i<pToCol->nId; i++){
7409 + nByte += strlen(pToCol->a[i].zName) + 1;
7412 + pFKey = sqliteMalloc( nByte );
7413 + if( pFKey==0 ) goto fk_end;
7415 + pFKey->pNextFrom = p->pFKey;
7416 + z = (char*)&pFKey[1];
7417 + pFKey->aCol = (struct sColMap*)z;
7418 + z += sizeof(struct sColMap)*nCol;
7420 + memcpy(z, pTo->z, pTo->n);
7423 + pFKey->pNextTo = 0;
7424 + pFKey->nCol = nCol;
7425 + if( pFromCol==0 ){
7426 + pFKey->aCol[0].iFrom = p->nCol-1;
7428 + for(i=0; i<nCol; i++){
7430 + for(j=0; j<p->nCol; j++){
7431 + if( sqliteStrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
7432 + pFKey->aCol[i].iFrom = j;
7437 + sqliteErrorMsg(pParse,
7438 + "unknown column \"%s\" in foreign key definition",
7439 + pFromCol->a[i].zName);
7445 + for(i=0; i<nCol; i++){
7446 + int n = strlen(pToCol->a[i].zName);
7447 + pFKey->aCol[i].zCol = z;
7448 + memcpy(z, pToCol->a[i].zName, n);
7453 + pFKey->isDeferred = 0;
7454 + pFKey->deleteConf = flags & 0xff;
7455 + pFKey->updateConf = (flags >> 8 ) & 0xff;
7456 + pFKey->insertConf = (flags >> 16 ) & 0xff;
7458 + /* Link the foreign key to the table as the last step.
7464 + sqliteFree(pFKey);
7465 + sqliteIdListDelete(pFromCol);
7466 + sqliteIdListDelete(pToCol);
7470 +** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
7471 +** clause is seen as part of a foreign key definition. The isDeferred
7472 +** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
7473 +** The behavior of the most recently created foreign key is adjusted
7476 +void sqliteDeferForeignKey(Parse *pParse, int isDeferred){
7479 + if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
7480 + pFKey->isDeferred = isDeferred;
7484 +** Create a new index for an SQL table. pIndex is the name of the index
7485 +** and pTable is the name of the table that is to be indexed. Both will
7486 +** be NULL for a primary key or an index that is created to satisfy a
7487 +** UNIQUE constraint. If pTable and pIndex are NULL, use pParse->pNewTable
7488 +** as the table to be indexed. pParse->pNewTable is a table that is
7489 +** currently being constructed by a CREATE TABLE statement.
7491 +** pList is a list of columns to be indexed. pList will be NULL if this
7492 +** is a primary key or unique-constraint on the most recent column added
7493 +** to the table currently under construction.
7495 +void sqliteCreateIndex(
7496 + Parse *pParse, /* All information about this parse */
7497 + Token *pName, /* Name of the index. May be NULL */
7498 + SrcList *pTable, /* Name of the table to index. Use pParse->pNewTable if 0 */
7499 + IdList *pList, /* A list of columns to be indexed */
7500 + int onError, /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
7501 + Token *pStart, /* The CREATE token that begins a CREATE TABLE statement */
7502 + Token *pEnd /* The ")" that closes the CREATE INDEX statement */
7504 + Table *pTab; /* Table to be indexed */
7505 + Index *pIndex; /* The index to be created */
7508 + Token nullId; /* Fake token for an empty ID list */
7509 + DbFixer sFix; /* For assigning database names to pTable */
7510 + int isTemp; /* True for a temporary index */
7511 + sqlite *db = pParse->db;
7513 + if( pParse->nErr || sqlite_malloc_failed ) goto exit_create_index;
7515 + && sqliteFixInit(&sFix, pParse, db->init.iDb, "index", pName)
7516 + && sqliteFixSrcList(&sFix, pTable)
7518 + goto exit_create_index;
7522 + ** Find the table that is to be indexed. Return early if not found.
7525 + assert( pName!=0 );
7526 + assert( pTable->nSrc==1 );
7527 + pTab = sqliteSrcListLookup(pParse, pTable);
7529 + assert( pName==0 );
7530 + pTab = pParse->pNewTable;
7532 + if( pTab==0 || pParse->nErr ) goto exit_create_index;
7533 + if( pTab->readOnly ){
7534 + sqliteErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
7535 + goto exit_create_index;
7537 + if( pTab->iDb>=2 && db->init.busy==0 ){
7538 + sqliteErrorMsg(pParse, "table %s may not have indices added", pTab->zName);
7539 + goto exit_create_index;
7541 + if( pTab->pSelect ){
7542 + sqliteErrorMsg(pParse, "views may not be indexed");
7543 + goto exit_create_index;
7545 + isTemp = pTab->iDb==1;
7548 + ** Find the name of the index. Make sure there is not already another
7549 + ** index or table with the same name.
7551 + ** Exception: If we are reading the names of permanent indices from the
7552 + ** sqlite_master table (because some other process changed the schema) and
7553 + ** one of the index names collides with the name of a temporary table or
7554 + ** index, then we will continue to process this index.
7556 + ** If pName==0 it means that we are
7557 + ** dealing with a primary key or UNIQUE constraint. We have to invent our
7560 + if( pName && !db->init.busy ){
7561 + Index *pISameName; /* Another index with the same name */
7562 + Table *pTSameName; /* A table with same name as the index */
7563 + zName = sqliteTableNameFromToken(pName);
7564 + if( zName==0 ) goto exit_create_index;
7565 + if( (pISameName = sqliteFindIndex(db, zName, 0))!=0 ){
7566 + sqliteErrorMsg(pParse, "index %s already exists", zName);
7567 + goto exit_create_index;
7569 + if( (pTSameName = sqliteFindTable(db, zName, 0))!=0 ){
7570 + sqliteErrorMsg(pParse, "there is already a table named %s", zName);
7571 + goto exit_create_index;
7573 + }else if( pName==0 ){
7577 + for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
7578 + sprintf(zBuf,"%d)",n);
7580 + sqliteSetString(&zName, "(", pTab->zName, " autoindex ", zBuf, (char*)0);
7581 + if( zName==0 ) goto exit_create_index;
7583 + zName = sqliteTableNameFromToken(pName);
7586 + /* Check for authorization to create an index.
7588 +#ifndef SQLITE_OMIT_AUTHORIZATION
7590 + const char *zDb = db->aDb[pTab->iDb].zName;
7592 + assert( pTab->iDb==db->init.iDb || isTemp );
7593 + if( sqliteAuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
7594 + goto exit_create_index;
7596 + i = SQLITE_CREATE_INDEX;
7597 + if( isTemp ) i = SQLITE_CREATE_TEMP_INDEX;
7598 + if( sqliteAuthCheck(pParse, i, zName, pTab->zName, zDb) ){
7599 + goto exit_create_index;
7604 + /* If pList==0, it means this routine was called to make a primary
7605 + ** key out of the last column added to the table under construction.
7606 + ** So create a fake list to simulate this.
7609 + nullId.z = pTab->aCol[pTab->nCol-1].zName;
7610 + nullId.n = strlen(nullId.z);
7611 + pList = sqliteIdListAppend(0, &nullId);
7612 + if( pList==0 ) goto exit_create_index;
7616 + ** Allocate the index structure.
7618 + pIndex = sqliteMalloc( sizeof(Index) + strlen(zName) + 1 +
7619 + sizeof(int)*pList->nId );
7620 + if( pIndex==0 ) goto exit_create_index;
7621 + pIndex->aiColumn = (int*)&pIndex[1];
7622 + pIndex->zName = (char*)&pIndex->aiColumn[pList->nId];
7623 + strcpy(pIndex->zName, zName);
7624 + pIndex->pTable = pTab;
7625 + pIndex->nColumn = pList->nId;
7626 + pIndex->onError = onError;
7627 + pIndex->autoIndex = pName==0;
7628 + pIndex->iDb = isTemp ? 1 : db->init.iDb;
7630 + /* Scan the names of the columns of the table to be indexed and
7631 + ** load the column indices into the Index structure. Report an error
7632 + ** if any column is not found.
7634 + for(i=0; i<pList->nId; i++){
7635 + for(j=0; j<pTab->nCol; j++){
7636 + if( sqliteStrICmp(pList->a[i].zName, pTab->aCol[j].zName)==0 ) break;
7638 + if( j>=pTab->nCol ){
7639 + sqliteErrorMsg(pParse, "table %s has no column named %s",
7640 + pTab->zName, pList->a[i].zName);
7641 + sqliteFree(pIndex);
7642 + goto exit_create_index;
7644 + pIndex->aiColumn[i] = j;
7647 + /* Link the new Index structure to its table and to the other
7648 + ** in-memory database structures.
7650 + if( !pParse->explain ){
7652 + p = sqliteHashInsert(&db->aDb[pIndex->iDb].idxHash,
7653 + pIndex->zName, strlen(pIndex->zName)+1, pIndex);
7655 + assert( p==pIndex ); /* Malloc must have failed */
7656 + sqliteFree(pIndex);
7657 + goto exit_create_index;
7659 + db->flags |= SQLITE_InternChanges;
7662 + /* When adding an index to the list of indices for a table, make
7663 + ** sure all indices labeled OE_Replace come after all those labeled
7664 + ** OE_Ignore. This is necessary for the correct operation of UPDATE
7667 + if( onError!=OE_Replace || pTab->pIndex==0
7668 + || pTab->pIndex->onError==OE_Replace){
7669 + pIndex->pNext = pTab->pIndex;
7670 + pTab->pIndex = pIndex;
7672 + Index *pOther = pTab->pIndex;
7673 + while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
7674 + pOther = pOther->pNext;
7676 + pIndex->pNext = pOther->pNext;
7677 + pOther->pNext = pIndex;
7680 + /* If the db->init.busy is 1 it means we are reading the SQL off the
7681 + ** "sqlite_master" table on the disk. So do not write to the disk
7682 + ** again. Extract the table number from the db->init.newTnum field.
7684 + if( db->init.busy && pTable!=0 ){
7685 + pIndex->tnum = db->init.newTnum;
7688 + /* If the db->init.busy is 0 then create the index on disk. This
7689 + ** involves writing the index into the master table and filling in the
7690 + ** index with the current table contents.
7692 + ** The db->init.busy is 0 when the user first enters a CREATE INDEX
7693 + ** command. db->init.busy is 1 when a database is opened and
7694 + ** CREATE INDEX statements are read out of the master table. In
7695 + ** the latter case the index already exists on disk, which is why
7696 + ** we don't want to recreate it.
7698 + ** If pTable==0 it means this index is generated as a primary key
7699 + ** or UNIQUE constraint of a CREATE TABLE statement. Since the table
7700 + ** has just been created, it contains no data and the index initialization
7701 + ** step can be skipped.
7703 + else if( db->init.busy==0 ){
7710 + v = sqliteGetVdbe(pParse);
7711 + if( v==0 ) goto exit_create_index;
7713 + sqliteBeginWriteOperation(pParse, 0, isTemp);
7714 + sqliteOpenMasterTable(v, isTemp);
7716 + sqliteVdbeAddOp(v, OP_NewRecno, 0, 0);
7717 + sqliteVdbeOp3(v, OP_String, 0, 0, "index", P3_STATIC);
7718 + sqliteVdbeOp3(v, OP_String, 0, 0, pIndex->zName, 0);
7719 + sqliteVdbeOp3(v, OP_String, 0, 0, pTab->zName, 0);
7720 + sqliteVdbeOp3(v, OP_CreateIndex, 0, isTemp,(char*)&pIndex->tnum,P3_POINTER);
7725 + OP_Integer, isTemp, 0,
7726 + OP_OpenWrite, 1, 0,
7729 + addr = sqliteVdbeAddOp(v, OP_String, 0, 0);
7730 + if( pStart && pEnd ){
7731 + n = Addr(pEnd->z) - Addr(pStart->z) + 1;
7732 + sqliteVdbeChangeP3(v, addr, pStart->z, n);
7734 + sqliteVdbeAddOp(v, OP_MakeRecord, 5, 0);
7735 + sqliteVdbeAddOp(v, OP_PutIntKey, 0, 0);
7737 + sqliteVdbeAddOp(v, OP_Integer, pTab->iDb, 0);
7738 + sqliteVdbeOp3(v, OP_OpenRead, 2, pTab->tnum, pTab->zName, 0);
7739 + lbl2 = sqliteVdbeMakeLabel(v);
7740 + sqliteVdbeAddOp(v, OP_Rewind, 2, lbl2);
7741 + lbl1 = sqliteVdbeAddOp(v, OP_Recno, 2, 0);
7742 + for(i=0; i<pIndex->nColumn; i++){
7743 + int iCol = pIndex->aiColumn[i];
7744 + if( pTab->iPKey==iCol ){
7745 + sqliteVdbeAddOp(v, OP_Dup, i, 0);
7747 + sqliteVdbeAddOp(v, OP_Column, 2, iCol);
7750 + sqliteVdbeAddOp(v, OP_MakeIdxKey, pIndex->nColumn, 0);
7751 + if( db->file_format>=4 ) sqliteAddIdxKeyType(v, pIndex);
7752 + sqliteVdbeOp3(v, OP_IdxPut, 1, pIndex->onError!=OE_None,
7753 + "indexed columns are not unique", P3_STATIC);
7754 + sqliteVdbeAddOp(v, OP_Next, 2, lbl1);
7755 + sqliteVdbeResolveLabel(v, lbl2);
7756 + sqliteVdbeAddOp(v, OP_Close, 2, 0);
7757 + sqliteVdbeAddOp(v, OP_Close, 1, 0);
7761 + sqliteChangeCookie(db, v);
7763 + sqliteVdbeAddOp(v, OP_Close, 0, 0);
7764 + sqliteEndWriteOperation(pParse);
7768 + /* Clean up before exiting */
7770 + sqliteIdListDelete(pList);
7771 + sqliteSrcListDelete(pTable);
7772 + sqliteFree(zName);
7777 +** This routine will drop an existing named index. This routine
7778 +** implements the DROP INDEX statement.
7780 +void sqliteDropIndex(Parse *pParse, SrcList *pName){
7783 + sqlite *db = pParse->db;
7785 + if( pParse->nErr || sqlite_malloc_failed ) return;
7786 + assert( pName->nSrc==1 );
7787 + pIndex = sqliteFindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
7789 + sqliteErrorMsg(pParse, "no such index: %S", pName, 0);
7790 + goto exit_drop_index;
7792 + if( pIndex->autoIndex ){
7793 + sqliteErrorMsg(pParse, "index associated with UNIQUE "
7794 + "or PRIMARY KEY constraint cannot be dropped", 0);
7795 + goto exit_drop_index;
7797 + if( pIndex->iDb>1 ){
7798 + sqliteErrorMsg(pParse, "cannot alter schema of attached "
7800 + goto exit_drop_index;
7802 +#ifndef SQLITE_OMIT_AUTHORIZATION
7804 + int code = SQLITE_DROP_INDEX;
7805 + Table *pTab = pIndex->pTable;
7806 + const char *zDb = db->aDb[pIndex->iDb].zName;
7807 + const char *zTab = SCHEMA_TABLE(pIndex->iDb);
7808 + if( sqliteAuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
7809 + goto exit_drop_index;
7811 + if( pIndex->iDb ) code = SQLITE_DROP_TEMP_INDEX;
7812 + if( sqliteAuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
7813 + goto exit_drop_index;
7818 + /* Generate code to remove the index and from the master table */
7819 + v = sqliteGetVdbe(pParse);
7821 + static VdbeOpList dropIndex[] = {
7822 + { OP_Rewind, 0, ADDR(9), 0},
7823 + { OP_String, 0, 0, 0}, /* 1 */
7824 + { OP_MemStore, 1, 1, 0},
7825 + { OP_MemLoad, 1, 0, 0}, /* 3 */
7826 + { OP_Column, 0, 1, 0},
7827 + { OP_Eq, 0, ADDR(8), 0},
7828 + { OP_Next, 0, ADDR(3), 0},
7829 + { OP_Goto, 0, ADDR(9), 0},
7830 + { OP_Delete, 0, 0, 0}, /* 8 */
7834 + sqliteBeginWriteOperation(pParse, 0, pIndex->iDb);
7835 + sqliteOpenMasterTable(v, pIndex->iDb);
7836 + base = sqliteVdbeAddOpList(v, ArraySize(dropIndex), dropIndex);
7837 + sqliteVdbeChangeP3(v, base+1, pIndex->zName, 0);
7838 + if( pIndex->iDb==0 ){
7839 + sqliteChangeCookie(db, v);
7841 + sqliteVdbeAddOp(v, OP_Close, 0, 0);
7842 + sqliteVdbeAddOp(v, OP_Destroy, pIndex->tnum, pIndex->iDb);
7843 + sqliteEndWriteOperation(pParse);
7846 + /* Delete the in-memory description of this index.
7848 + if( !pParse->explain ){
7849 + sqliteUnlinkAndDeleteIndex(db, pIndex);
7850 + db->flags |= SQLITE_InternChanges;
7854 + sqliteSrcListDelete(pName);
7858 +** Append a new element to the given IdList. Create a new IdList if
7861 +** A new IdList is returned, or NULL if malloc() fails.
7863 +IdList *sqliteIdListAppend(IdList *pList, Token *pToken){
7865 + pList = sqliteMalloc( sizeof(IdList) );
7866 + if( pList==0 ) return 0;
7867 + pList->nAlloc = 0;
7869 + if( pList->nId>=pList->nAlloc ){
7870 + struct IdList_item *a;
7871 + pList->nAlloc = pList->nAlloc*2 + 5;
7872 + a = sqliteRealloc(pList->a, pList->nAlloc*sizeof(pList->a[0]) );
7874 + sqliteIdListDelete(pList);
7879 + memset(&pList->a[pList->nId], 0, sizeof(pList->a[0]));
7881 + char **pz = &pList->a[pList->nId].zName;
7882 + sqliteSetNString(pz, pToken->z, pToken->n, 0);
7884 + sqliteIdListDelete(pList);
7887 + sqliteDequote(*pz);
7895 +** Append a new table name to the given SrcList. Create a new SrcList if
7896 +** need be. A new entry is created in the SrcList even if pToken is NULL.
7898 +** A new SrcList is returned, or NULL if malloc() fails.
7900 +** If pDatabase is not null, it means that the table has an optional
7901 +** database name prefix. Like this: "database.table". The pDatabase
7902 +** points to the table name and the pTable points to the database name.
7903 +** The SrcList.a[].zName field is filled with the table name which might
7904 +** come from pTable (if pDatabase is NULL) or from pDatabase.
7905 +** SrcList.a[].zDatabase is filled with the database name from pTable,
7906 +** or with NULL if no database is specified.
7908 +** In other words, if call like this:
7910 +** sqliteSrcListAppend(A,B,0);
7912 +** Then B is a table name and the database name is unspecified. If called
7915 +** sqliteSrcListAppend(A,B,C);
7917 +** Then C is the table name and B is the database name.
7919 +SrcList *sqliteSrcListAppend(SrcList *pList, Token *pTable, Token *pDatabase){
7921 + pList = sqliteMalloc( sizeof(SrcList) );
7922 + if( pList==0 ) return 0;
7923 + pList->nAlloc = 1;
7925 + if( pList->nSrc>=pList->nAlloc ){
7927 + pList->nAlloc *= 2;
7928 + pNew = sqliteRealloc(pList,
7929 + sizeof(*pList) + (pList->nAlloc-1)*sizeof(pList->a[0]) );
7931 + sqliteSrcListDelete(pList);
7936 + memset(&pList->a[pList->nSrc], 0, sizeof(pList->a[0]));
7937 + if( pDatabase && pDatabase->z==0 ){
7940 + if( pDatabase && pTable ){
7941 + Token *pTemp = pDatabase;
7942 + pDatabase = pTable;
7946 + char **pz = &pList->a[pList->nSrc].zName;
7947 + sqliteSetNString(pz, pTable->z, pTable->n, 0);
7949 + sqliteSrcListDelete(pList);
7952 + sqliteDequote(*pz);
7956 + char **pz = &pList->a[pList->nSrc].zDatabase;
7957 + sqliteSetNString(pz, pDatabase->z, pDatabase->n, 0);
7959 + sqliteSrcListDelete(pList);
7962 + sqliteDequote(*pz);
7965 + pList->a[pList->nSrc].iCursor = -1;
7971 +** Assign cursors to all tables in a SrcList
7973 +void sqliteSrcListAssignCursors(Parse *pParse, SrcList *pList){
7975 + for(i=0; i<pList->nSrc; i++){
7976 + if( pList->a[i].iCursor<0 ){
7977 + pList->a[i].iCursor = pParse->nTab++;
7983 +** Add an alias to the last identifier on the given identifier list.
7985 +void sqliteSrcListAddAlias(SrcList *pList, Token *pToken){
7986 + if( pList && pList->nSrc>0 ){
7987 + int i = pList->nSrc - 1;
7988 + sqliteSetNString(&pList->a[i].zAlias, pToken->z, pToken->n, 0);
7989 + sqliteDequote(pList->a[i].zAlias);
7994 +** Delete an IdList.
7996 +void sqliteIdListDelete(IdList *pList){
7998 + if( pList==0 ) return;
7999 + for(i=0; i<pList->nId; i++){
8000 + sqliteFree(pList->a[i].zName);
8002 + sqliteFree(pList->a);
8003 + sqliteFree(pList);
8007 +** Return the index in pList of the identifier named zId. Return -1
8010 +int sqliteIdListIndex(IdList *pList, const char *zName){
8012 + if( pList==0 ) return -1;
8013 + for(i=0; i<pList->nId; i++){
8014 + if( sqliteStrICmp(pList->a[i].zName, zName)==0 ) return i;
8020 +** Delete an entire SrcList including all its substructure.
8022 +void sqliteSrcListDelete(SrcList *pList){
8024 + if( pList==0 ) return;
8025 + for(i=0; i<pList->nSrc; i++){
8026 + sqliteFree(pList->a[i].zDatabase);
8027 + sqliteFree(pList->a[i].zName);
8028 + sqliteFree(pList->a[i].zAlias);
8029 + if( pList->a[i].pTab && pList->a[i].pTab->isTransient ){
8030 + sqliteDeleteTable(0, pList->a[i].pTab);
8032 + sqliteSelectDelete(pList->a[i].pSelect);
8033 + sqliteExprDelete(pList->a[i].pOn);
8034 + sqliteIdListDelete(pList->a[i].pUsing);
8036 + sqliteFree(pList);
8040 +** Begin a transaction
8042 +void sqliteBeginTransaction(Parse *pParse, int onError){
8045 + if( pParse==0 || (db=pParse->db)==0 || db->aDb[0].pBt==0 ) return;
8046 + if( pParse->nErr || sqlite_malloc_failed ) return;
8047 + if( sqliteAuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ) return;
8048 + if( db->flags & SQLITE_InTrans ){
8049 + sqliteErrorMsg(pParse, "cannot start a transaction within a transaction");
8052 + sqliteBeginWriteOperation(pParse, 0, 0);
8053 + if( !pParse->explain ){
8054 + db->flags |= SQLITE_InTrans;
8055 + db->onError = onError;
8060 +** Commit a transaction
8062 +void sqliteCommitTransaction(Parse *pParse){
8065 + if( pParse==0 || (db=pParse->db)==0 || db->aDb[0].pBt==0 ) return;
8066 + if( pParse->nErr || sqlite_malloc_failed ) return;
8067 + if( sqliteAuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ) return;
8068 + if( (db->flags & SQLITE_InTrans)==0 ){
8069 + sqliteErrorMsg(pParse, "cannot commit - no transaction is active");
8072 + if( !pParse->explain ){
8073 + db->flags &= ~SQLITE_InTrans;
8075 + sqliteEndWriteOperation(pParse);
8076 + if( !pParse->explain ){
8077 + db->onError = OE_Default;
8082 +** Rollback a transaction
8084 +void sqliteRollbackTransaction(Parse *pParse){
8088 + if( pParse==0 || (db=pParse->db)==0 || db->aDb[0].pBt==0 ) return;
8089 + if( pParse->nErr || sqlite_malloc_failed ) return;
8090 + if( sqliteAuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ) return;
8091 + if( (db->flags & SQLITE_InTrans)==0 ){
8092 + sqliteErrorMsg(pParse, "cannot rollback - no transaction is active");
8095 + v = sqliteGetVdbe(pParse);
8097 + sqliteVdbeAddOp(v, OP_Rollback, 0, 0);
8099 + if( !pParse->explain ){
8100 + db->flags &= ~SQLITE_InTrans;
8101 + db->onError = OE_Default;
8106 +** Generate VDBE code that will verify the schema cookie for all
8107 +** named database files.
8109 +void sqliteCodeVerifySchema(Parse *pParse, int iDb){
8110 + sqlite *db = pParse->db;
8111 + Vdbe *v = sqliteGetVdbe(pParse);
8112 + assert( iDb>=0 && iDb<db->nDb );
8113 + assert( db->aDb[iDb].pBt!=0 );
8114 + if( iDb!=1 && !DbHasProperty(db, iDb, DB_Cookie) ){
8115 + sqliteVdbeAddOp(v, OP_VerifyCookie, iDb, db->aDb[iDb].schema_cookie);
8116 + DbSetProperty(db, iDb, DB_Cookie);
8121 +** Generate VDBE code that prepares for doing an operation that
8122 +** might change the database.
8124 +** This routine starts a new transaction if we are not already within
8125 +** a transaction. If we are already within a transaction, then a checkpoint
8126 +** is set if the setCheckpoint parameter is true. A checkpoint should
8127 +** be set for operations that might fail (due to a constraint) part of
8128 +** the way through and which will need to undo some writes without having to
8129 +** rollback the whole transaction. For operations where all constraints
8130 +** can be checked before any changes are made to the database, it is never
8131 +** necessary to undo a write and the checkpoint should not be set.
8133 +** Only database iDb and the temp database are made writable by this call.
8134 +** If iDb==0, then the main and temp databases are made writable. If
8135 +** iDb==1 then only the temp database is made writable. If iDb>1 then the
8136 +** specified auxiliary database and the temp database are made writable.
8138 +void sqliteBeginWriteOperation(Parse *pParse, int setCheckpoint, int iDb){
8140 + sqlite *db = pParse->db;
8141 + if( DbHasProperty(db, iDb, DB_Locked) ) return;
8142 + v = sqliteGetVdbe(pParse);
8143 + if( v==0 ) return;
8144 + if( !db->aDb[iDb].inTrans ){
8145 + sqliteVdbeAddOp(v, OP_Transaction, iDb, 0);
8146 + DbSetProperty(db, iDb, DB_Locked);
8147 + sqliteCodeVerifySchema(pParse, iDb);
8149 + sqliteBeginWriteOperation(pParse, setCheckpoint, 1);
8151 + }else if( setCheckpoint ){
8152 + sqliteVdbeAddOp(v, OP_Checkpoint, iDb, 0);
8153 + DbSetProperty(db, iDb, DB_Locked);
8158 +** Generate code that concludes an operation that may have changed
8159 +** the database. If a statement transaction was started, then emit
8160 +** an OP_Commit that will cause the changes to be committed to disk.
8162 +** Note that checkpoints are automatically committed at the end of
8163 +** a statement. Note also that there can be multiple calls to
8164 +** sqliteBeginWriteOperation() but there should only be a single
8165 +** call to sqliteEndWriteOperation() at the conclusion of the statement.
8167 +void sqliteEndWriteOperation(Parse *pParse){
8169 + sqlite *db = pParse->db;
8170 + if( pParse->trigStack ) return; /* if this is in a trigger */
8171 + v = sqliteGetVdbe(pParse);
8172 + if( v==0 ) return;
8173 + if( db->flags & SQLITE_InTrans ){
8174 + /* A BEGIN has executed. Do not commit until we see an explicit
8175 + ** COMMIT statement. */
8177 + sqliteVdbeAddOp(v, OP_Commit, 0, 0);
8181 +++ b/ext/sqlite/libsqlite/src/config_static.w32.h
8183 +#define SQLITE_PTR_SZ 4
8184 \ No newline at end of file
8186 +++ b/ext/sqlite/libsqlite/src/copy.c
8191 +** The author disclaims copyright to this source code. In place of
8192 +** a legal notice, here is a blessing:
8194 +** May you do good and not evil.
8195 +** May you find forgiveness for yourself and forgive others.
8196 +** May you share freely, never taking more than you give.
8198 +*************************************************************************
8199 +** This file contains code used to implement the COPY command.
8203 +#include "sqliteInt.h"
8206 +** The COPY command is for compatibility with PostgreSQL and specificially
8207 +** for the ability to read the output of pg_dump. The format is as
8210 +** COPY table FROM file [USING DELIMITERS string]
8212 +** "table" is an existing table name. We will read lines of code from
8213 +** file to fill this table with data. File might be "stdin". The optional
8214 +** delimiter string identifies the field separators. The default is a tab.
8217 + Parse *pParse, /* The parser context */
8218 + SrcList *pTableName, /* The name of the table into which we will insert */
8219 + Token *pFilename, /* The file from which to obtain information */
8220 + Token *pDelimiter, /* Use this as the field delimiter */
8221 + int onError /* What to do if a constraint fails */
8229 + sqlite *db = pParse->db;
8232 + if( sqlite_malloc_failed ) goto copy_cleanup;
8233 + assert( pTableName->nSrc==1 );
8234 + pTab = sqliteSrcListLookup(pParse, pTableName);
8235 + if( pTab==0 || sqliteIsReadOnly(pParse, pTab, 0) ) goto copy_cleanup;
8236 + zFile = sqliteStrNDup(pFilename->z, pFilename->n);
8237 + sqliteDequote(zFile);
8238 + assert( pTab->iDb<db->nDb );
8239 + zDb = db->aDb[pTab->iDb].zName;
8240 + if( sqliteAuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb)
8241 + || sqliteAuthCheck(pParse, SQLITE_COPY, pTab->zName, zFile, zDb) ){
8242 + goto copy_cleanup;
8244 + v = sqliteGetVdbe(pParse);
8246 + sqliteBeginWriteOperation(pParse, 1, pTab->iDb);
8247 + addr = sqliteVdbeOp3(v, OP_FileOpen, 0, 0, pFilename->z, pFilename->n);
8248 + sqliteVdbeDequoteP3(v, addr);
8249 + sqliteOpenTableAndIndices(pParse, pTab, 0);
8250 + if( db->flags & SQLITE_CountRows ){
8251 + sqliteVdbeAddOp(v, OP_Integer, 0, 0); /* Initialize the row count */
8253 + end = sqliteVdbeMakeLabel(v);
8254 + addr = sqliteVdbeAddOp(v, OP_FileRead, pTab->nCol, end);
8256 + sqliteVdbeChangeP3(v, addr, pDelimiter->z, pDelimiter->n);
8257 + sqliteVdbeDequoteP3(v, addr);
8259 + sqliteVdbeChangeP3(v, addr, "\t", 1);
8261 + if( pTab->iPKey>=0 ){
8262 + sqliteVdbeAddOp(v, OP_FileColumn, pTab->iPKey, 0);
8263 + sqliteVdbeAddOp(v, OP_MustBeInt, 0, 0);
8265 + sqliteVdbeAddOp(v, OP_NewRecno, 0, 0);
8267 + for(i=0; i<pTab->nCol; i++){
8268 + if( i==pTab->iPKey ){
8269 + /* The integer primary key column is filled with NULL since its
8270 + ** value is always pulled from the record number */
8271 + sqliteVdbeAddOp(v, OP_String, 0, 0);
8273 + sqliteVdbeAddOp(v, OP_FileColumn, i, 0);
8276 + sqliteGenerateConstraintChecks(pParse, pTab, 0, 0, pTab->iPKey>=0,
8277 + 0, onError, addr);
8278 + sqliteCompleteInsertion(pParse, pTab, 0, 0, 0, 0, -1);
8279 + if( (db->flags & SQLITE_CountRows)!=0 ){
8280 + sqliteVdbeAddOp(v, OP_AddImm, 1, 0); /* Increment row count */
8282 + sqliteVdbeAddOp(v, OP_Goto, 0, addr);
8283 + sqliteVdbeResolveLabel(v, end);
8284 + sqliteVdbeAddOp(v, OP_Noop, 0, 0);
8285 + sqliteEndWriteOperation(pParse);
8286 + if( db->flags & SQLITE_CountRows ){
8287 + sqliteVdbeAddOp(v, OP_ColumnName, 0, 1);
8288 + sqliteVdbeChangeP3(v, -1, "rows inserted", P3_STATIC);
8289 + sqliteVdbeAddOp(v, OP_Callback, 1, 0);
8294 + sqliteSrcListDelete(pTableName);
8295 + sqliteFree(zFile);
8299 +++ b/ext/sqlite/libsqlite/src/date.c
8304 +** The author disclaims copyright to this source code. In place of
8305 +** a legal notice, here is a blessing:
8307 +** May you do good and not evil.
8308 +** May you find forgiveness for yourself and forgive others.
8309 +** May you share freely, never taking more than you give.
8311 +*************************************************************************
8312 +** This file contains the C functions that implement date and time
8313 +** functions for SQLite.
8315 +** There is only one exported symbol in this file - the function
8316 +** sqliteRegisterDateTimeFunctions() found at the bottom of the file.
8317 +** All other code has file scope.
8323 +** SQLite processes all times and dates as Julian Day numbers. The
8324 +** dates and times are stored as the number of days since noon
8325 +** in Greenwich on November 24, 4714 B.C. according to the Gregorian
8326 +** calendar system.
8328 +** 1970-01-01 00:00:00 is JD 2440587.5
8329 +** 2000-01-01 00:00:00 is JD 2451544.5
8331 +** This implemention requires years to be expressed as a 4-digit number
8332 +** which means that only dates between 0000-01-01 and 9999-12-31 can
8333 +** be represented, even though julian day numbers allow a much wider
8336 +** The Gregorian calendar system is used for all dates and times,
8337 +** even those that predate the Gregorian calendar. Historians usually
8338 +** use the Julian calendar for dates prior to 1582-10-15 and for some
8339 +** dates afterwards, depending on locale. Beware of this difference.
8341 +** The conversion algorithms are implemented based on descriptions
8342 +** in the following text:
8345 +** Astronomical Algorithms, 2nd Edition, 1998
8346 +** ISBM 0-943396-61-1
8347 +** Willmann-Bell, Inc
8348 +** Richmond, Virginia (USA)
8351 +#include "sqliteInt.h"
8353 +#include <stdlib.h>
8354 +#include <assert.h>
8357 +#include "main/php_reentrancy.h"
8360 +#ifndef SQLITE_OMIT_DATETIME_FUNCS
8363 +** A structure for holding a single date and time.
8365 +typedef struct DateTime DateTime;
8367 + double rJD; /* The julian day number */
8368 + int Y, M, D; /* Year, month, and day */
8369 + int h, m; /* Hour and minutes */
8370 + int tz; /* Timezone offset in minutes */
8371 + double s; /* Seconds */
8372 + char validYMD; /* True if Y,M,D are valid */
8373 + char validHMS; /* True if h,m,s are valid */
8374 + char validJD; /* True if rJD is valid */
8375 + char validTZ; /* True if tz is valid */
8380 +** Convert zDate into one or more integers. Additional arguments
8381 +** come in groups of 5 as follows:
8383 +** N number of digits in the integer
8384 +** min minimum allowed value of the integer
8385 +** max maximum allowed value of the integer
8386 +** nextC first character after the integer
8387 +** pVal where to write the integers value.
8389 +** Conversions continue until one with nextC==0 is encountered.
8390 +** The function returns the number of successful conversions.
8392 +static int getDigits(const char *zDate, ...){
8401 + va_start(ap, zDate);
8403 + N = va_arg(ap, int);
8404 + min = va_arg(ap, int);
8405 + max = va_arg(ap, int);
8406 + nextC = va_arg(ap, int);
8407 + pVal = va_arg(ap, int*);
8410 + if( !isdigit(*zDate) ){
8413 + val = val*10 + *zDate - '0';
8416 + if( val<min || val>max || (nextC!=0 && nextC!=*zDate) ){
8427 +** Read text from z[] and convert into a floating point number. Return
8428 +** the number of digits converted.
8430 +static int getValue(const char *z, double *pR){
8432 + *pR = sqliteAtoF(z, &zEnd);
8437 +** Parse a timezone extension on the end of a date-time.
8438 +** The extension is of the form:
8442 +** If the parse is successful, write the number of minutes
8443 +** of change in *pnMin and return 0. If a parser error occurs,
8446 +** A missing specifier is not considered an error.
8448 +static int parseTimezone(const char *zDate, DateTime *p){
8451 + while( isspace(*zDate) ){ zDate++; }
8453 + if( *zDate=='-' ){
8455 + }else if( *zDate=='+' ){
8461 + if( getDigits(zDate, 2, 0, 14, ':', &nHr, 2, 0, 59, 0, &nMn)!=2 ){
8465 + p->tz = sgn*(nMn + nHr*60);
8466 + while( isspace(*zDate) ){ zDate++; }
8471 +** Parse times of the form HH:MM or HH:MM:SS or HH:MM:SS.FFFF.
8472 +** The HH, MM, and SS must each be exactly 2 digits. The
8473 +** fractional seconds FFFF can be one or more digits.
8475 +** Return 1 if there is a parsing error and 0 on success.
8477 +static int parseHhMmSs(const char *zDate, DateTime *p){
8480 + if( getDigits(zDate, 2, 0, 24, ':', &h, 2, 0, 59, 0, &m)!=2 ){
8484 + if( *zDate==':' ){
8486 + if( getDigits(zDate, 2, 0, 59, 0, &s)!=1 ){
8490 + if( *zDate=='.' && isdigit(zDate[1]) ){
8491 + double rScale = 1.0;
8493 + while( isdigit(*zDate) ){
8494 + ms = ms*10.0 + *zDate - '0';
8508 + if( parseTimezone(zDate, p) ) return 1;
8509 + p->validTZ = p->tz!=0;
8514 +** Convert from YYYY-MM-DD HH:MM:SS to julian day. We always assume
8515 +** that the YYYY-MM-DD is according to the Gregorian calendar.
8517 +** Reference: Meeus page 61
8519 +static void computeJD(DateTime *p){
8520 + int Y, M, D, A, B, X1, X2;
8522 + if( p->validJD ) return;
8523 + if( p->validYMD ){
8528 + Y = 2000; /* If no YMD specified, assume 2000-Jan-01 */
8537 + B = 2 - A + (A/4);
8538 + X1 = 365.25*(Y+4716);
8539 + X2 = 30.6001*(M+1);
8540 + p->rJD = X1 + X2 + D + B - 1524.5;
8543 + if( p->validHMS ){
8544 + p->rJD += (p->h*3600.0 + p->m*60.0 + p->s)/86400.0;
8546 + p->rJD += p->tz*60/86400.0;
8554 +** Parse dates of the form
8556 +** YYYY-MM-DD HH:MM:SS.FFF
8557 +** YYYY-MM-DD HH:MM:SS
8558 +** YYYY-MM-DD HH:MM
8561 +** Write the result into the DateTime structure and return 0
8562 +** on success and 1 if the input string is not a well-formed
8565 +static int parseYyyyMmDd(const char *zDate, DateTime *p){
8568 + if( zDate[0]=='-' ){
8574 + if( getDigits(zDate,4,0,9999,'-',&Y,2,1,12,'-',&M,2,1,31,0,&D)!=3 ){
8578 + while( isspace(*zDate) ){ zDate++; }
8579 + if( parseHhMmSs(zDate, p)==0 ){
8580 + /* We got the time */
8581 + }else if( *zDate==0 ){
8588 + p->Y = neg ? -Y : Y;
8598 +** Attempt to parse the given string into a Julian Day Number. Return
8599 +** the number of errors.
8601 +** The following are acceptable forms for the input string:
8603 +** YYYY-MM-DD HH:MM:SS.FFF +/-HH:MM
8607 +** In the first form, the +/-HH:MM is always optional. The fractional
8608 +** seconds extension (the ".FFF") is optional. The seconds portion
8609 +** (":SS.FFF") is option. The year and date can be omitted as long
8610 +** as there is a time string. The time string can be omitted as long
8611 +** as there is a year and date.
8613 +static int parseDateOrTime(const char *zDate, DateTime *p){
8614 + memset(p, 0, sizeof(*p));
8615 + if( parseYyyyMmDd(zDate,p)==0 ){
8617 + }else if( parseHhMmSs(zDate, p)==0 ){
8619 + }else if( sqliteStrICmp(zDate,"now")==0){
8621 + if( sqliteOsCurrentTime(&r)==0 ){
8627 + }else if( sqliteIsNumber(zDate) ){
8628 + p->rJD = sqliteAtoF(zDate, 0);
8636 +** Compute the Year, Month, and Day from the julian day number.
8638 +static void computeYMD(DateTime *p){
8639 + int Z, A, B, C, D, E, X1;
8640 + if( p->validYMD ) return;
8641 + if( !p->validJD ){
8647 + A = (Z - 1867216.25)/36524.25;
8648 + A = Z + 1 + A - (A/4);
8650 + C = (B - 122.1)/365.25;
8652 + E = (B-D)/30.6001;
8654 + p->D = B - D - X1;
8655 + p->M = E<14 ? E-1 : E-13;
8656 + p->Y = p->M>2 ? C - 4716 : C - 4715;
8662 +** Compute the Hour, Minute, and Seconds from the julian day number.
8664 +static void computeHMS(DateTime *p){
8666 + if( p->validHMS ) return;
8668 + s = (p->rJD + 0.5 - Z)*86400000.0 + 0.5;
8675 + p->s += s - p->m*60;
8680 +** Compute both YMD and HMS
8682 +static void computeYMD_HMS(DateTime *p){
8688 +** Clear the YMD and HMS and the TZ
8690 +static void clearYMD_HMS_TZ(DateTime *p){
8697 +** Compute the difference (in days) between localtime and UTC (a.k.a. GMT)
8698 +** for the time value p where p is in UTC.
8700 +static double localtimeOffset(DateTime *p){
8703 + struct tm *pTm, tmbuf;
8705 + computeYMD_HMS(&x);
8706 + if( x.Y<1971 || x.Y>=2038 ){
8714 + int s = x.s + 0.5;
8720 + t = (x.rJD-2440587.5)*86400.0 + 0.5;
8721 + sqliteOsEnterMutex();
8722 + pTm = php_localtime_r(&t, &tmbuf);
8726 + y.Y = pTm->tm_year + 1900;
8727 + y.M = pTm->tm_mon + 1;
8728 + y.D = pTm->tm_mday;
8729 + y.h = pTm->tm_hour;
8730 + y.m = pTm->tm_min;
8731 + y.s = pTm->tm_sec;
8732 + sqliteOsLeaveMutex();
8738 + return y.rJD - x.rJD;
8742 +** Process a modifier to a date-time stamp. The modifiers are
8748 +** NNN.NNNN seconds
8760 +** Return 0 on success and 1 if there is any kind of error.
8762 +static int parseModifier(const char *zMod, DateTime *p){
8766 + char *z, zBuf[30];
8768 + for(n=0; n<sizeof(zBuf)-1 && zMod[n]; n++){
8769 + z[n] = tolower(zMod[n]);
8776 + ** Assuming the current time value is UTC (a.k.a. GMT), shift it to
8777 + ** show local time.
8779 + if( strcmp(z, "localtime")==0 ){
8781 + p->rJD += localtimeOffset(p);
8782 + clearYMD_HMS_TZ(p);
8791 + ** Treat the current value of p->rJD as the number of
8792 + ** seconds since 1970. Convert to a real julian day number.
8794 + if( strcmp(z, "unixepoch")==0 && p->validJD ){
8795 + p->rJD = p->rJD/86400.0 + 2440587.5;
8796 + clearYMD_HMS_TZ(p);
8798 + }else if( strcmp(z, "utc")==0 ){
8801 + c1 = localtimeOffset(p);
8803 + clearYMD_HMS_TZ(p);
8804 + p->rJD += c1 - localtimeOffset(p);
8813 + ** Move the date to the same time on the next occurrance of
8814 + ** weekday N where 0==Sunday, 1==Monday, and so forth. If the
8815 + ** date is already on the appropriate weekday, this is a no-op.
8817 + if( strncmp(z, "weekday ", 8)==0 && getValue(&z[8],&r)>0
8818 + && (n=r)==r && n>=0 && r<7 ){
8820 + computeYMD_HMS(p);
8828 + clearYMD_HMS_TZ(p);
8837 + ** Move the date backwards to the beginning of the current day,
8838 + ** or month or year.
8840 + if( strncmp(z, "start of ", 9)!=0 ) break;
8848 + if( strcmp(z,"month")==0 ){
8851 + }else if( strcmp(z,"year")==0 ){
8856 + }else if( strcmp(z,"day")==0 ){
8873 + n = getValue(z, &r);
8876 + /* A modifier of the form (+|-)HH:MM:SS.FFF adds (or subtracts) the
8877 + ** specified number of hours, minutes, seconds, and fractional seconds
8878 + ** to the time. The ".FFF" may be omitted. The ":SS.FFF" may be
8881 + const char *z2 = z;
8884 + if( !isdigit(*z2) ) z2++;
8885 + memset(&tx, 0, sizeof(tx));
8886 + if( parseHhMmSs(z2, &tx) ) break;
8889 + day = (int)tx.rJD;
8891 + if( z[0]=='-' ) tx.rJD = -tx.rJD;
8893 + clearYMD_HMS_TZ(p);
8899 + while( isspace(z[0]) ) z++;
8901 + if( n>10 || n<3 ) break;
8902 + if( z[n-1]=='s' ){ z[n-1] = 0; n--; }
8905 + if( n==3 && strcmp(z,"day")==0 ){
8907 + }else if( n==4 && strcmp(z,"hour")==0 ){
8909 + }else if( n==6 && strcmp(z,"minute")==0 ){
8910 + p->rJD += r/(24.0*60.0);
8911 + }else if( n==6 && strcmp(z,"second")==0 ){
8912 + p->rJD += r/(24.0*60.0*60.0);
8913 + }else if( n==5 && strcmp(z,"month")==0 ){
8915 + computeYMD_HMS(p);
8917 + x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12;
8924 + p->rJD += (r - y)*30.0;
8926 + }else if( n==4 && strcmp(z,"year")==0 ){
8927 + computeYMD_HMS(p);
8934 + clearYMD_HMS_TZ(p);
8945 +** Process time function arguments. argv[0] is a date-time stamp.
8946 +** argv[1] and following are modifiers. Parse them all and write
8947 +** the resulting time into the DateTime structure p. Return 0
8948 +** on success and 1 if there are any errors.
8950 +static int isDate(int argc, const char **argv, DateTime *p){
8952 + if( argc==0 ) return 1;
8953 + if( argv[0]==0 || parseDateOrTime(argv[0], p) ) return 1;
8954 + for(i=1; i<argc; i++){
8955 + if( argv[i]==0 || parseModifier(argv[i], p) ) return 1;
8962 +** The following routines implement the various date and time functions
8967 +** julianday( TIMESTRING, MOD, MOD, ...)
8969 +** Return the julian day number of the date specified in the arguments
8971 +static void juliandayFunc(sqlite_func *context, int argc, const char **argv){
8973 + if( isDate(argc, argv, &x)==0 ){
8975 + sqlite_set_result_double(context, x.rJD);
8980 +** datetime( TIMESTRING, MOD, MOD, ...)
8982 +** Return YYYY-MM-DD HH:MM:SS
8984 +static void datetimeFunc(sqlite_func *context, int argc, const char **argv){
8986 + if( isDate(argc, argv, &x)==0 ){
8988 + computeYMD_HMS(&x);
8989 + sprintf(zBuf, "%04d-%02d-%02d %02d:%02d:%02d",x.Y, x.M, x.D, x.h, x.m,
8991 + sqlite_set_result_string(context, zBuf, -1);
8996 +** time( TIMESTRING, MOD, MOD, ...)
9000 +static void timeFunc(sqlite_func *context, int argc, const char **argv){
9002 + if( isDate(argc, argv, &x)==0 ){
9005 + sprintf(zBuf, "%02d:%02d:%02d", x.h, x.m, (int)x.s);
9006 + sqlite_set_result_string(context, zBuf, -1);
9011 +** date( TIMESTRING, MOD, MOD, ...)
9013 +** Return YYYY-MM-DD
9015 +static void dateFunc(sqlite_func *context, int argc, const char **argv){
9017 + if( isDate(argc, argv, &x)==0 ){
9020 + sprintf(zBuf, "%04d-%02d-%02d", x.Y, x.M, x.D);
9021 + sqlite_set_result_string(context, zBuf, -1);
9026 +** strftime( FORMAT, TIMESTRING, MOD, MOD, ...)
9028 +** Return a string described by FORMAT. Conversions as follows:
9031 +** %f ** fractional seconds SS.SSS
9033 +** %j day of year 000-366
9034 +** %J ** Julian day number
9037 +** %s seconds since 1970-01-01
9038 +** %S seconds 00-59
9039 +** %w day of week 0-6 sunday==0
9040 +** %W week of year 00-53
9041 +** %Y year 0000-9999
9044 +static void strftimeFunc(sqlite_func *context, int argc, const char **argv){
9048 + const char *zFmt = argv[0];
9050 + if( argv[0]==0 || isDate(argc-1, argv+1, &x) ) return;
9051 + for(i=0, n=1; zFmt[i]; i++, n++){
9052 + if( zFmt[i]=='%' ){
9053 + switch( zFmt[i+1] ){
9079 + return; /* ERROR. return a NULL */
9084 + if( n<sizeof(zBuf) ){
9087 + z = sqliteMalloc( n );
9088 + if( z==0 ) return;
9091 + computeYMD_HMS(&x);
9092 + for(i=j=0; zFmt[i]; i++){
9093 + if( zFmt[i]!='%' ){
9097 + switch( zFmt[i] ){
9098 + case 'd': sprintf(&z[j],"%02d",x.D); j+=2; break;
9101 + int ms = (x.s - s)*1000.0;
9102 + sprintf(&z[j],"%02d.%03d",s,ms);
9103 + j += strlen(&z[j]);
9106 + case 'H': sprintf(&z[j],"%02d",x.h); j+=2; break;
9107 + case 'W': /* Fall thru */
9109 + int n; /* Number of days since 1st day of year */
9115 + n = x.rJD - y.rJD;
9116 + if( zFmt[i]=='W' ){
9117 + int wd; /* 0=Monday, 1=Tuesday, ... 6=Sunday */
9118 + wd = ((int)(x.rJD+0.5)) % 7;
9119 + sprintf(&z[j],"%02d",(n+7-wd)/7);
9122 + sprintf(&z[j],"%03d",n+1);
9127 + case 'J': sprintf(&z[j],"%.16g",x.rJD); j+=strlen(&z[j]); break;
9128 + case 'm': sprintf(&z[j],"%02d",x.M); j+=2; break;
9129 + case 'M': sprintf(&z[j],"%02d",x.m); j+=2; break;
9131 + sprintf(&z[j],"%d",(int)((x.rJD-2440587.5)*86400.0 + 0.5));
9132 + j += strlen(&z[j]);
9135 + case 'S': sprintf(&z[j],"%02d",(int)(x.s+0.5)); j+=2; break;
9136 + case 'w': z[j++] = (((int)(x.rJD+1.5)) % 7) + '0'; break;
9137 + case 'Y': sprintf(&z[j],"%04d",x.Y); j+=strlen(&z[j]); break;
9138 + case '%': z[j++] = '%'; break;
9143 + sqlite_set_result_string(context, z, -1);
9150 +#endif /* !defined(SQLITE_OMIT_DATETIME_FUNCS) */
9153 +** This function registered all of the above C functions as SQL
9154 +** functions. This should be the only routine in this file with
9155 +** external linkage.
9157 +void sqliteRegisterDateTimeFunctions(sqlite *db){
9158 +#ifndef SQLITE_OMIT_DATETIME_FUNCS
9163 + void (*xFunc)(sqlite_func*,int,const char**);
9165 + { "julianday", -1, SQLITE_NUMERIC, juliandayFunc },
9166 + { "date", -1, SQLITE_TEXT, dateFunc },
9167 + { "time", -1, SQLITE_TEXT, timeFunc },
9168 + { "datetime", -1, SQLITE_TEXT, datetimeFunc },
9169 + { "strftime", -1, SQLITE_TEXT, strftimeFunc },
9173 + for(i=0; i<sizeof(aFuncs)/sizeof(aFuncs[0]); i++){
9174 + sqlite_create_function(db, aFuncs[i].zName,
9175 + aFuncs[i].nArg, aFuncs[i].xFunc, 0);
9176 + if( aFuncs[i].xFunc ){
9177 + sqlite_function_type(db, aFuncs[i].zName, aFuncs[i].dataType);
9183 +++ b/ext/sqlite/libsqlite/src/delete.c
9186 +** 2001 September 15
9188 +** The author disclaims copyright to this source code. In place of
9189 +** a legal notice, here is a blessing:
9191 +** May you do good and not evil.
9192 +** May you find forgiveness for yourself and forgive others.
9193 +** May you share freely, never taking more than you give.
9195 +*************************************************************************
9196 +** This file contains C code routines that are called by the parser
9197 +** to handle DELETE FROM statements.
9201 +#include "sqliteInt.h"
9204 +** Look up every table that is named in pSrc. If any table is not found,
9205 +** add an error message to pParse->zErrMsg and return NULL. If all tables
9206 +** are found, return a pointer to the last table.
9208 +Table *sqliteSrcListLookup(Parse *pParse, SrcList *pSrc){
9211 + for(i=0; i<pSrc->nSrc; i++){
9212 + const char *zTab = pSrc->a[i].zName;
9213 + const char *zDb = pSrc->a[i].zDatabase;
9214 + pTab = sqliteLocateTable(pParse, zTab, zDb);
9215 + pSrc->a[i].pTab = pTab;
9221 +** Check to make sure the given table is writable. If it is not
9222 +** writable, generate an error message and return 1. If it is
9223 +** writable return 0;
9225 +int sqliteIsReadOnly(Parse *pParse, Table *pTab, int viewOk){
9226 + if( pTab->readOnly ){
9227 + sqliteErrorMsg(pParse, "table %s may not be modified", pTab->zName);
9230 + if( !viewOk && pTab->pSelect ){
9231 + sqliteErrorMsg(pParse, "cannot modify %s because it is a view",pTab->zName);
9238 +** Process a DELETE FROM statement.
9240 +void sqliteDeleteFrom(
9241 + Parse *pParse, /* The parser context */
9242 + SrcList *pTabList, /* The table from which we should delete things */
9243 + Expr *pWhere /* The WHERE clause. May be null */
9245 + Vdbe *v; /* The virtual database engine */
9246 + Table *pTab; /* The table from which records will be deleted */
9247 + const char *zDb; /* Name of database holding pTab */
9248 + int end, addr; /* A couple addresses of generated code */
9249 + int i; /* Loop counter */
9250 + WhereInfo *pWInfo; /* Information about the WHERE clause */
9251 + Index *pIdx; /* For looping over indices of the table */
9252 + int iCur; /* VDBE Cursor number for pTab */
9253 + sqlite *db; /* Main database structure */
9254 + int isView; /* True if attempting to delete from a view */
9255 + AuthContext sContext; /* Authorization context */
9257 + int row_triggers_exist = 0; /* True if any triggers exist */
9258 + int before_triggers; /* True if there are BEFORE triggers */
9259 + int after_triggers; /* True if there are AFTER triggers */
9260 + int oldIdx = -1; /* Cursor for the OLD table of AFTER triggers */
9262 + sContext.pParse = 0;
9263 + if( pParse->nErr || sqlite_malloc_failed ){
9265 + goto delete_from_cleanup;
9268 + assert( pTabList->nSrc==1 );
9270 + /* Locate the table which we want to delete. This table has to be
9271 + ** put in an SrcList structure because some of the subroutines we
9272 + ** will be calling are designed to work with multiple tables and expect
9273 + ** an SrcList* parameter instead of just a Table* parameter.
9275 + pTab = sqliteSrcListLookup(pParse, pTabList);
9276 + if( pTab==0 ) goto delete_from_cleanup;
9277 + before_triggers = sqliteTriggersExist(pParse, pTab->pTrigger,
9278 + TK_DELETE, TK_BEFORE, TK_ROW, 0);
9279 + after_triggers = sqliteTriggersExist(pParse, pTab->pTrigger,
9280 + TK_DELETE, TK_AFTER, TK_ROW, 0);
9281 + row_triggers_exist = before_triggers || after_triggers;
9282 + isView = pTab->pSelect!=0;
9283 + if( sqliteIsReadOnly(pParse, pTab, before_triggers) ){
9284 + goto delete_from_cleanup;
9286 + assert( pTab->iDb<db->nDb );
9287 + zDb = db->aDb[pTab->iDb].zName;
9288 + if( sqliteAuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
9289 + goto delete_from_cleanup;
9292 + /* If pTab is really a view, make sure it has been initialized.
9294 + if( isView && sqliteViewGetColumnNames(pParse, pTab) ){
9295 + goto delete_from_cleanup;
9298 + /* Allocate a cursor used to store the old.* data for a trigger.
9300 + if( row_triggers_exist ){
9301 + oldIdx = pParse->nTab++;
9304 + /* Resolve the column names in all the expressions.
9306 + assert( pTabList->nSrc==1 );
9307 + iCur = pTabList->a[0].iCursor = pParse->nTab++;
9309 + if( sqliteExprResolveIds(pParse, pTabList, 0, pWhere) ){
9310 + goto delete_from_cleanup;
9312 + if( sqliteExprCheck(pParse, pWhere, 0, 0) ){
9313 + goto delete_from_cleanup;
9317 + /* Start the view context
9320 + sqliteAuthContextPush(pParse, &sContext, pTab->zName);
9323 + /* Begin generating code.
9325 + v = sqliteGetVdbe(pParse);
9327 + goto delete_from_cleanup;
9329 + sqliteBeginWriteOperation(pParse, row_triggers_exist, pTab->iDb);
9331 + /* If we are trying to delete from a view, construct that view into
9332 + ** a temporary table.
9335 + Select *pView = sqliteSelectDup(pTab->pSelect);
9336 + sqliteSelect(pParse, pView, SRT_TempTable, iCur, 0, 0, 0);
9337 + sqliteSelectDelete(pView);
9340 + /* Initialize the counter of the number of rows deleted, if
9341 + ** we are counting rows.
9343 + if( db->flags & SQLITE_CountRows ){
9344 + sqliteVdbeAddOp(v, OP_Integer, 0, 0);
9347 + /* Special case: A DELETE without a WHERE clause deletes everything.
9348 + ** It is easier just to erase the whole table. Note, however, that
9349 + ** this means that the row change count will be incorrect.
9351 + if( pWhere==0 && !row_triggers_exist ){
9352 + if( db->flags & SQLITE_CountRows ){
9353 + /* If counting rows deleted, just count the total number of
9354 + ** entries in the table. */
9355 + int endOfLoop = sqliteVdbeMakeLabel(v);
9358 + sqliteVdbeAddOp(v, OP_Integer, pTab->iDb, 0);
9359 + sqliteVdbeAddOp(v, OP_OpenRead, iCur, pTab->tnum);
9361 + sqliteVdbeAddOp(v, OP_Rewind, iCur, sqliteVdbeCurrentAddr(v)+2);
9362 + addr = sqliteVdbeAddOp(v, OP_AddImm, 1, 0);
9363 + sqliteVdbeAddOp(v, OP_Next, iCur, addr);
9364 + sqliteVdbeResolveLabel(v, endOfLoop);
9365 + sqliteVdbeAddOp(v, OP_Close, iCur, 0);
9368 + sqliteVdbeAddOp(v, OP_Clear, pTab->tnum, pTab->iDb);
9369 + for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
9370 + sqliteVdbeAddOp(v, OP_Clear, pIdx->tnum, pIdx->iDb);
9375 + /* The usual case: There is a WHERE clause so we have to scan through
9376 + ** the table and pick which records to delete.
9379 + /* Begin the database scan
9381 + pWInfo = sqliteWhereBegin(pParse, pTabList, pWhere, 1, 0);
9382 + if( pWInfo==0 ) goto delete_from_cleanup;
9384 + /* Remember the key of every item to be deleted.
9386 + sqliteVdbeAddOp(v, OP_ListWrite, 0, 0);
9387 + if( db->flags & SQLITE_CountRows ){
9388 + sqliteVdbeAddOp(v, OP_AddImm, 1, 0);
9391 + /* End the database scan loop.
9393 + sqliteWhereEnd(pWInfo);
9395 + /* Open the pseudo-table used to store OLD if there are triggers.
9397 + if( row_triggers_exist ){
9398 + sqliteVdbeAddOp(v, OP_OpenPseudo, oldIdx, 0);
9401 + /* Delete every item whose key was written to the list during the
9402 + ** database scan. We have to delete items after the scan is complete
9403 + ** because deleting an item can change the scan order.
9405 + sqliteVdbeAddOp(v, OP_ListRewind, 0, 0);
9406 + end = sqliteVdbeMakeLabel(v);
9408 + /* This is the beginning of the delete loop when there are
9411 + if( row_triggers_exist ){
9412 + addr = sqliteVdbeAddOp(v, OP_ListRead, 0, end);
9413 + sqliteVdbeAddOp(v, OP_Dup, 0, 0);
9415 + sqliteVdbeAddOp(v, OP_Integer, pTab->iDb, 0);
9416 + sqliteVdbeAddOp(v, OP_OpenRead, iCur, pTab->tnum);
9418 + sqliteVdbeAddOp(v, OP_MoveTo, iCur, 0);
9420 + sqliteVdbeAddOp(v, OP_Recno, iCur, 0);
9421 + sqliteVdbeAddOp(v, OP_RowData, iCur, 0);
9422 + sqliteVdbeAddOp(v, OP_PutIntKey, oldIdx, 0);
9424 + sqliteVdbeAddOp(v, OP_Close, iCur, 0);
9427 + sqliteCodeRowTrigger(pParse, TK_DELETE, 0, TK_BEFORE, pTab, -1,
9428 + oldIdx, (pParse->trigStack)?pParse->trigStack->orconf:OE_Default,
9433 + /* Open cursors for the table we are deleting from and all its
9434 + ** indices. If there are row triggers, this happens inside the
9435 + ** OP_ListRead loop because the cursor have to all be closed
9436 + ** before the trigger fires. If there are no row triggers, the
9437 + ** cursors are opened only once on the outside the loop.
9439 + pParse->nTab = iCur + 1;
9440 + sqliteOpenTableAndIndices(pParse, pTab, iCur);
9442 + /* This is the beginning of the delete loop when there are no
9443 + ** row triggers */
9444 + if( !row_triggers_exist ){
9445 + addr = sqliteVdbeAddOp(v, OP_ListRead, 0, end);
9448 + /* Delete the row */
9449 + sqliteGenerateRowDelete(db, v, pTab, iCur, pParse->trigStack==0);
9452 + /* If there are row triggers, close all cursors then invoke
9453 + ** the AFTER triggers
9455 + if( row_triggers_exist ){
9457 + for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
9458 + sqliteVdbeAddOp(v, OP_Close, iCur + i, pIdx->tnum);
9460 + sqliteVdbeAddOp(v, OP_Close, iCur, 0);
9462 + sqliteCodeRowTrigger(pParse, TK_DELETE, 0, TK_AFTER, pTab, -1,
9463 + oldIdx, (pParse->trigStack)?pParse->trigStack->orconf:OE_Default,
9467 + /* End of the delete loop */
9468 + sqliteVdbeAddOp(v, OP_Goto, 0, addr);
9469 + sqliteVdbeResolveLabel(v, end);
9470 + sqliteVdbeAddOp(v, OP_ListReset, 0, 0);
9472 + /* Close the cursors after the loop if there are no row triggers */
9473 + if( !row_triggers_exist ){
9474 + for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
9475 + sqliteVdbeAddOp(v, OP_Close, iCur + i, pIdx->tnum);
9477 + sqliteVdbeAddOp(v, OP_Close, iCur, 0);
9478 + pParse->nTab = iCur;
9481 + sqliteVdbeAddOp(v, OP_SetCounts, 0, 0);
9482 + sqliteEndWriteOperation(pParse);
9485 + ** Return the number of rows that were deleted.
9487 + if( db->flags & SQLITE_CountRows ){
9488 + sqliteVdbeAddOp(v, OP_ColumnName, 0, 1);
9489 + sqliteVdbeChangeP3(v, -1, "rows deleted", P3_STATIC);
9490 + sqliteVdbeAddOp(v, OP_Callback, 1, 0);
9493 +delete_from_cleanup:
9494 + sqliteAuthContextPop(&sContext);
9495 + sqliteSrcListDelete(pTabList);
9496 + sqliteExprDelete(pWhere);
9501 +** This routine generates VDBE code that causes a single row of a
9502 +** single table to be deleted.
9504 +** The VDBE must be in a particular state when this routine is called.
9505 +** These are the requirements:
9507 +** 1. A read/write cursor pointing to pTab, the table containing the row
9508 +** to be deleted, must be opened as cursor number "base".
9510 +** 2. Read/write cursors for all indices of pTab must be open as
9511 +** cursor number base+i for the i-th index.
9513 +** 3. The record number of the row to be deleted must be on the top
9516 +** This routine pops the top of the stack to remove the record number
9517 +** and then generates code to remove both the table record and all index
9518 +** entries that point to that record.
9520 +void sqliteGenerateRowDelete(
9521 + sqlite *db, /* The database containing the index */
9522 + Vdbe *v, /* Generate code into this VDBE */
9523 + Table *pTab, /* Table containing the row to be deleted */
9524 + int iCur, /* Cursor number for the table */
9525 + int count /* Increment the row change counter */
9528 + addr = sqliteVdbeAddOp(v, OP_NotExists, iCur, 0);
9529 + sqliteGenerateRowIndexDelete(db, v, pTab, iCur, 0);
9530 + sqliteVdbeAddOp(v, OP_Delete, iCur,
9531 + (count?OPFLAG_NCHANGE:0) | OPFLAG_CSCHANGE);
9532 + sqliteVdbeChangeP2(v, addr, sqliteVdbeCurrentAddr(v));
9536 +** This routine generates VDBE code that causes the deletion of all
9537 +** index entries associated with a single row of a single table.
9539 +** The VDBE must be in a particular state when this routine is called.
9540 +** These are the requirements:
9542 +** 1. A read/write cursor pointing to pTab, the table containing the row
9543 +** to be deleted, must be opened as cursor number "iCur".
9545 +** 2. Read/write cursors for all indices of pTab must be open as
9546 +** cursor number iCur+i for the i-th index.
9548 +** 3. The "iCur" cursor must be pointing to the row that is to be
9551 +void sqliteGenerateRowIndexDelete(
9552 + sqlite *db, /* The database containing the index */
9553 + Vdbe *v, /* Generate code into this VDBE */
9554 + Table *pTab, /* Table containing the row to be deleted */
9555 + int iCur, /* Cursor number for the table */
9556 + char *aIdxUsed /* Only delete if aIdxUsed!=0 && aIdxUsed[i]!=0 */
9561 + for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
9563 + if( aIdxUsed!=0 && aIdxUsed[i-1]==0 ) continue;
9564 + sqliteVdbeAddOp(v, OP_Recno, iCur, 0);
9565 + for(j=0; j<pIdx->nColumn; j++){
9566 + int idx = pIdx->aiColumn[j];
9567 + if( idx==pTab->iPKey ){
9568 + sqliteVdbeAddOp(v, OP_Dup, j, 0);
9570 + sqliteVdbeAddOp(v, OP_Column, iCur, idx);
9573 + sqliteVdbeAddOp(v, OP_MakeIdxKey, pIdx->nColumn, 0);
9574 + if( db->file_format>=4 ) sqliteAddIdxKeyType(v, pIdx);
9575 + sqliteVdbeAddOp(v, OP_IdxDelete, iCur+i, 0);
9579 +++ b/ext/sqlite/libsqlite/src/encode.c
9584 +** The author disclaims copyright to this source code. In place of
9585 +** a legal notice, here is a blessing:
9587 +** May you do good and not evil.
9588 +** May you find forgiveness for yourself and forgive others.
9589 +** May you share freely, never taking more than you give.
9591 +*************************************************************************
9592 +** This file contains helper routines used to translate binary data into
9593 +** a null-terminated string (suitable for use in SQLite) and back again.
9594 +** These are convenience routines for use by people who want to store binary
9595 +** data in an SQLite database. The code in this file is not used by any other
9596 +** part of the SQLite library.
9600 +#include <string.h>
9601 +#include <assert.h>
9604 +** How This Encoder Works
9606 +** The output is allowed to contain any character except 0x27 (') and
9607 +** 0x00. This is accomplished by using an escape character to encode
9608 +** 0x27 and 0x00 as a two-byte sequence. The escape character is always
9609 +** 0x01. An 0x00 is encoded as the two byte sequence 0x01 0x01. The
9610 +** 0x27 character is encoded as the two byte sequence 0x01 0x28. Finally,
9611 +** the escape character itself is encoded as the two-character sequence
9614 +** To summarize, the encoder works by using an escape sequences as follows:
9616 +** 0x00 -> 0x01 0x01
9617 +** 0x01 -> 0x01 0x02
9618 +** 0x27 -> 0x01 0x28
9620 +** If that were all the encoder did, it would work, but in certain cases
9621 +** it could double the size of the encoded string. For example, to
9622 +** encode a string of 100 0x27 characters would require 100 instances of
9623 +** the 0x01 0x03 escape sequence resulting in a 200-character output.
9624 +** We would prefer to keep the size of the encoded string smaller than
9627 +** To minimize the encoding size, we first add a fixed offset value to each
9628 +** byte in the sequence. The addition is modulo 256. (That is to say, if
9629 +** the sum of the original character value and the offset exceeds 256, then
9630 +** the higher order bits are truncated.) The offset is chosen to minimize
9631 +** the number of characters in the string that need to be escaped. For
9632 +** example, in the case above where the string was composed of 100 0x27
9633 +** characters, the offset might be 0x01. Each of the 0x27 characters would
9634 +** then be converted into an 0x28 character which would not need to be
9635 +** escaped at all and so the 100 character input string would be converted
9636 +** into just 100 characters of output. Actually 101 characters of output -
9637 +** we have to record the offset used as the first byte in the sequence so
9638 +** that the string can be decoded. Since the offset value is stored as
9639 +** part of the output string and the output string is not allowed to contain
9640 +** characters 0x00 or 0x27, the offset cannot be 0x00 or 0x27.
9642 +** Here, then, are the encoding steps:
9644 +** (1) Choose an offset value and make it the first character of
9647 +** (2) Copy each input character into the output buffer, one by
9648 +** one, adding the offset value as you copy.
9650 +** (3) If the value of an input character plus offset is 0x00, replace
9651 +** that one character by the two-character sequence 0x01 0x01.
9652 +** If the sum is 0x01, replace it with 0x01 0x02. If the sum
9653 +** is 0x27, replace it with 0x01 0x03.
9655 +** (4) Put a 0x00 terminator at the end of the output.
9657 +** Decoding is obvious:
9659 +** (5) Copy encoded characters except the first into the decode
9660 +** buffer. Set the first encoded character aside for use as
9661 +** the offset in step 7 below.
9663 +** (6) Convert each 0x01 0x01 sequence into a single character 0x00.
9664 +** Convert 0x01 0x02 into 0x01. Convert 0x01 0x28 into 0x27.
9666 +** (7) Subtract the offset value that was the first character of
9667 +** the encoded buffer from all characters in the output buffer.
9669 +** The only tricky part is step (1) - how to compute an offset value to
9670 +** minimize the size of the output buffer. This is accomplished by testing
9671 +** all offset values and picking the one that results in the fewest number
9672 +** of escapes. To do that, we first scan the entire input and count the
9673 +** number of occurances of each character value in the input. Suppose
9674 +** the number of 0x00 characters is N(0), the number of occurances of 0x01
9675 +** is N(1), and so forth up to the number of occurances of 0xff is N(255).
9676 +** An offset of 0 is not allowed so we don't have to test it. The number
9677 +** of escapes required for an offset of 1 is N(1)+N(2)+N(40). The number
9678 +** of escapes required for an offset of 2 is N(2)+N(3)+N(41). And so forth.
9679 +** In this way we find the offset that gives the minimum number of escapes,
9680 +** and thus minimizes the length of the output string.
9684 +** Encode a binary buffer "in" of size n bytes so that it contains
9685 +** no instances of characters '\'' or '\000'. The output is
9686 +** null-terminated and can be used as a string value in an INSERT
9687 +** or UPDATE statement. Use sqlite_decode_binary() to convert the
9688 +** string back into its original binary.
9690 +** The result is written into a preallocated output buffer "out".
9691 +** "out" must be able to hold at least 2 +(257*n)/254 bytes.
9692 +** In other words, the output will be expanded by as much as 3
9693 +** bytes for every 254 bytes of input plus 2 bytes of fixed overhead.
9694 +** (This is approximately 2 + 1.0118*n or about a 1.2% size increase.)
9696 +** The return value is the number of characters in the encoded
9697 +** string, excluding the "\000" terminator.
9699 +** If out==NULL then no output is generated but the routine still returns
9700 +** the number of characters that would have been generated if out had
9703 +int sqlite_encode_binary(const unsigned char *in, int n, unsigned char *out){
9714 + memset(cnt, 0, sizeof(cnt));
9715 + for(i=n-1; i>=0; i--){ cnt[in[i]]++; }
9717 + for(i=1; i<256; i++){
9719 + if( i=='\'' ) continue;
9720 + sum = cnt[i] + cnt[(i+1)&0xff] + cnt[(i+'\'')&0xff];
9732 + for(i=0; i<n; i++){
9734 + if( x==0 || x==1 || x=='\''){
9741 + assert( j==n+m+1 );
9746 +** Decode the string "in" into binary data and write it into "out".
9747 +** This routine reverses the encoding created by sqlite_encode_binary().
9748 +** The output will always be a few bytes less than the input. The number
9749 +** of bytes of output is returned. If the input is not a well-formed
9750 +** encoding, -1 is returned.
9752 +** The "in" and "out" parameters may point to the same buffer in order
9753 +** to decode a string in place.
9755 +int sqlite_decode_binary(const unsigned char *in, unsigned char *out){
9763 + while( (c = *(in++))!=0 ){
9772 +#ifdef ENCODER_TEST
9775 +** The subroutines above are not tested by the usual test suite. To test
9776 +** these routines, compile just this one file with a -DENCODER_TEST=1 option
9777 +** and run the result.
9779 +int main(int argc, char **argv){
9780 + int i, j, n, m, nOut, nByteIn, nByteOut;
9781 + unsigned char in[30000];
9782 + unsigned char out[33000];
9784 + nByteIn = nByteOut = 0;
9785 + for(i=0; i<sizeof(in); i++){
9786 + printf("Test %d: ", i+1);
9787 + n = rand() % (i+1);
9790 + for(j=k=0; j<n; j++){
9791 + /* if( k==0 || k=='\'' ) k++; */
9796 + for(j=0; j<n; j++) in[j] = rand() & 0xff;
9799 + nOut = sqlite_encode_binary(in, n, out);
9801 + if( nOut!=strlen(out) ){
9802 + printf(" ERROR return value is %d instead of %d\n", nOut, strlen(out));
9805 + if( nOut!=sqlite_encode_binary(in, n, 0) ){
9806 + printf(" ERROR actual output size disagrees with predicted size\n");
9809 + m = (256*n + 1262)/253;
9810 + printf("size %d->%d (max %d)", n, strlen(out)+1, m);
9811 + if( strlen(out)+1>m ){
9812 + printf(" ERROR output too big\n");
9815 + for(j=0; out[j]; j++){
9816 + if( out[j]=='\'' ){
9817 + printf(" ERROR contains (')\n");
9821 + j = sqlite_decode_binary(out, out);
9823 + printf(" ERROR decode size %d\n", j);
9826 + if( memcmp(in, out, n)!=0 ){
9827 + printf(" ERROR decode mismatch\n");
9832 + fprintf(stderr,"Finished. Total encoding: %d->%d bytes\n",
9833 + nByteIn, nByteOut);
9834 + fprintf(stderr,"Avg size increase: %.3f%%\n",
9835 + (nByteOut-nByteIn)*100.0/(double)nByteIn);
9837 +#endif /* ENCODER_TEST */
9839 +++ b/ext/sqlite/libsqlite/src/expr.c
9842 +** 2001 September 15
9844 +** The author disclaims copyright to this source code. In place of
9845 +** a legal notice, here is a blessing:
9847 +** May you do good and not evil.
9848 +** May you find forgiveness for yourself and forgive others.
9849 +** May you share freely, never taking more than you give.
9851 +*************************************************************************
9852 +** This file contains routines used for analyzing expressions and
9853 +** for generating VDBE code that evaluates expressions in SQLite.
9857 +#include "sqliteInt.h"
9861 +** Construct a new expression node and return a pointer to it. Memory
9862 +** for this node is obtained from sqliteMalloc(). The calling function
9863 +** is responsible for making sure the node eventually gets freed.
9865 +Expr *sqliteExpr(int op, Expr *pLeft, Expr *pRight, Token *pToken){
9867 + pNew = sqliteMalloc( sizeof(Expr) );
9869 + /* When malloc fails, we leak memory from pLeft and pRight */
9873 + pNew->pLeft = pLeft;
9874 + pNew->pRight = pRight;
9876 + assert( pToken->dyn==0 );
9877 + pNew->token = *pToken;
9878 + pNew->span = *pToken;
9880 + assert( pNew->token.dyn==0 );
9881 + assert( pNew->token.z==0 );
9882 + assert( pNew->token.n==0 );
9883 + if( pLeft && pRight ){
9884 + sqliteExprSpan(pNew, &pLeft->span, &pRight->span);
9886 + pNew->span = pNew->token;
9893 +** Set the Expr.span field of the given expression to span all
9894 +** text between the two given tokens.
9896 +void sqliteExprSpan(Expr *pExpr, Token *pLeft, Token *pRight){
9897 + assert( pRight!=0 );
9898 + assert( pLeft!=0 );
9899 + /* Note: pExpr might be NULL due to a prior malloc failure */
9900 + if( pExpr && pRight->z && pLeft->z ){
9901 + if( pLeft->dyn==0 && pRight->dyn==0 ){
9902 + pExpr->span.z = pLeft->z;
9903 + pExpr->span.n = pRight->n + Addr(pRight->z) - Addr(pLeft->z);
9905 + pExpr->span.z = 0;
9911 +** Construct a new expression node for a function with multiple
9914 +Expr *sqliteExprFunction(ExprList *pList, Token *pToken){
9916 + pNew = sqliteMalloc( sizeof(Expr) );
9918 + /* sqliteExprListDelete(pList); // Leak pList when malloc fails */
9921 + pNew->op = TK_FUNCTION;
9922 + pNew->pList = pList;
9924 + assert( pToken->dyn==0 );
9925 + pNew->token = *pToken;
9927 + pNew->token.z = 0;
9929 + pNew->span = pNew->token;
9934 +** Recursively delete an expression tree.
9936 +void sqliteExprDelete(Expr *p){
9937 + if( p==0 ) return;
9938 + if( p->span.dyn ) sqliteFree((char*)p->span.z);
9939 + if( p->token.dyn ) sqliteFree((char*)p->token.z);
9940 + sqliteExprDelete(p->pLeft);
9941 + sqliteExprDelete(p->pRight);
9942 + sqliteExprListDelete(p->pList);
9943 + sqliteSelectDelete(p->pSelect);
9949 +** The following group of routines make deep copies of expressions,
9950 +** expression lists, ID lists, and select statements. The copies can
9951 +** be deleted (by being passed to their respective ...Delete() routines)
9952 +** without effecting the originals.
9954 +** The expression list, ID, and source lists return by sqliteExprListDup(),
9955 +** sqliteIdListDup(), and sqliteSrcListDup() can not be further expanded
9956 +** by subsequent calls to sqlite*ListAppend() routines.
9958 +** Any tables that the SrcList might point to are not duplicated.
9960 +Expr *sqliteExprDup(Expr *p){
9962 + if( p==0 ) return 0;
9963 + pNew = sqliteMallocRaw( sizeof(*p) );
9964 + if( pNew==0 ) return 0;
9965 + memcpy(pNew, p, sizeof(*pNew));
9966 + if( p->token.z!=0 ){
9967 + pNew->token.z = sqliteStrNDup(p->token.z, p->token.n);
9968 + pNew->token.dyn = 1;
9970 + assert( pNew->token.z==0 );
9973 + pNew->pLeft = sqliteExprDup(p->pLeft);
9974 + pNew->pRight = sqliteExprDup(p->pRight);
9975 + pNew->pList = sqliteExprListDup(p->pList);
9976 + pNew->pSelect = sqliteSelectDup(p->pSelect);
9979 +void sqliteTokenCopy(Token *pTo, Token *pFrom){
9980 + if( pTo->dyn ) sqliteFree((char*)pTo->z);
9982 + pTo->n = pFrom->n;
9983 + pTo->z = sqliteStrNDup(pFrom->z, pFrom->n);
9989 +ExprList *sqliteExprListDup(ExprList *p){
9991 + struct ExprList_item *pItem;
9993 + if( p==0 ) return 0;
9994 + pNew = sqliteMalloc( sizeof(*pNew) );
9995 + if( pNew==0 ) return 0;
9996 + pNew->nExpr = pNew->nAlloc = p->nExpr;
9997 + pNew->a = pItem = sqliteMalloc( p->nExpr*sizeof(p->a[0]) );
10002 + for(i=0; i<p->nExpr; i++, pItem++){
10003 + Expr *pNewExpr, *pOldExpr;
10004 + pItem->pExpr = pNewExpr = sqliteExprDup(pOldExpr = p->a[i].pExpr);
10005 + if( pOldExpr->span.z!=0 && pNewExpr ){
10006 + /* Always make a copy of the span for top-level expressions in the
10007 + ** expression list. The logic in SELECT processing that determines
10008 + ** the names of columns in the result set needs this information */
10009 + sqliteTokenCopy(&pNewExpr->span, &pOldExpr->span);
10011 + assert( pNewExpr==0 || pNewExpr->span.z!=0
10012 + || pOldExpr->span.z==0 || sqlite_malloc_failed );
10013 + pItem->zName = sqliteStrDup(p->a[i].zName);
10014 + pItem->sortOrder = p->a[i].sortOrder;
10015 + pItem->isAgg = p->a[i].isAgg;
10020 +SrcList *sqliteSrcListDup(SrcList *p){
10024 + if( p==0 ) return 0;
10025 + nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
10026 + pNew = sqliteMallocRaw( nByte );
10027 + if( pNew==0 ) return 0;
10028 + pNew->nSrc = pNew->nAlloc = p->nSrc;
10029 + for(i=0; i<p->nSrc; i++){
10030 + struct SrcList_item *pNewItem = &pNew->a[i];
10031 + struct SrcList_item *pOldItem = &p->a[i];
10032 + pNewItem->zDatabase = sqliteStrDup(pOldItem->zDatabase);
10033 + pNewItem->zName = sqliteStrDup(pOldItem->zName);
10034 + pNewItem->zAlias = sqliteStrDup(pOldItem->zAlias);
10035 + pNewItem->jointype = pOldItem->jointype;
10036 + pNewItem->iCursor = pOldItem->iCursor;
10037 + pNewItem->pTab = 0;
10038 + pNewItem->pSelect = sqliteSelectDup(pOldItem->pSelect);
10039 + pNewItem->pOn = sqliteExprDup(pOldItem->pOn);
10040 + pNewItem->pUsing = sqliteIdListDup(pOldItem->pUsing);
10044 +IdList *sqliteIdListDup(IdList *p){
10047 + if( p==0 ) return 0;
10048 + pNew = sqliteMallocRaw( sizeof(*pNew) );
10049 + if( pNew==0 ) return 0;
10050 + pNew->nId = pNew->nAlloc = p->nId;
10051 + pNew->a = sqliteMallocRaw( p->nId*sizeof(p->a[0]) );
10052 + if( pNew->a==0 ) return 0;
10053 + for(i=0; i<p->nId; i++){
10054 + struct IdList_item *pNewItem = &pNew->a[i];
10055 + struct IdList_item *pOldItem = &p->a[i];
10056 + pNewItem->zName = sqliteStrDup(pOldItem->zName);
10057 + pNewItem->idx = pOldItem->idx;
10061 +Select *sqliteSelectDup(Select *p){
10063 + if( p==0 ) return 0;
10064 + pNew = sqliteMallocRaw( sizeof(*p) );
10065 + if( pNew==0 ) return 0;
10066 + pNew->isDistinct = p->isDistinct;
10067 + pNew->pEList = sqliteExprListDup(p->pEList);
10068 + pNew->pSrc = sqliteSrcListDup(p->pSrc);
10069 + pNew->pWhere = sqliteExprDup(p->pWhere);
10070 + pNew->pGroupBy = sqliteExprListDup(p->pGroupBy);
10071 + pNew->pHaving = sqliteExprDup(p->pHaving);
10072 + pNew->pOrderBy = sqliteExprListDup(p->pOrderBy);
10073 + pNew->op = p->op;
10074 + pNew->pPrior = sqliteSelectDup(p->pPrior);
10075 + pNew->nLimit = p->nLimit;
10076 + pNew->nOffset = p->nOffset;
10077 + pNew->zSelect = 0;
10078 + pNew->iLimit = -1;
10079 + pNew->iOffset = -1;
10085 +** Add a new element to the end of an expression list. If pList is
10086 +** initially NULL, then create a new expression list.
10088 +ExprList *sqliteExprListAppend(ExprList *pList, Expr *pExpr, Token *pName){
10090 + pList = sqliteMalloc( sizeof(ExprList) );
10092 + /* sqliteExprDelete(pExpr); // Leak memory if malloc fails */
10095 + assert( pList->nAlloc==0 );
10097 + if( pList->nAlloc<=pList->nExpr ){
10098 + pList->nAlloc = pList->nAlloc*2 + 4;
10099 + pList->a = sqliteRealloc(pList->a, pList->nAlloc*sizeof(pList->a[0]));
10100 + if( pList->a==0 ){
10101 + /* sqliteExprDelete(pExpr); // Leak memory if malloc fails */
10102 + pList->nExpr = pList->nAlloc = 0;
10106 + assert( pList->a!=0 );
10107 + if( pExpr || pName ){
10108 + struct ExprList_item *pItem = &pList->a[pList->nExpr++];
10109 + memset(pItem, 0, sizeof(*pItem));
10110 + pItem->pExpr = pExpr;
10112 + sqliteSetNString(&pItem->zName, pName->z, pName->n, 0);
10113 + sqliteDequote(pItem->zName);
10120 +** Delete an entire expression list.
10122 +void sqliteExprListDelete(ExprList *pList){
10124 + if( pList==0 ) return;
10125 + assert( pList->a!=0 || (pList->nExpr==0 && pList->nAlloc==0) );
10126 + assert( pList->nExpr<=pList->nAlloc );
10127 + for(i=0; i<pList->nExpr; i++){
10128 + sqliteExprDelete(pList->a[i].pExpr);
10129 + sqliteFree(pList->a[i].zName);
10131 + sqliteFree(pList->a);
10132 + sqliteFree(pList);
10136 +** Walk an expression tree. Return 1 if the expression is constant
10137 +** and 0 if it involves variables.
10139 +** For the purposes of this function, a double-quoted string (ex: "abc")
10140 +** is considered a variable but a single-quoted string (ex: 'abc') is
10143 +int sqliteExprIsConstant(Expr *p){
10148 + case TK_FUNCTION:
10154 + case TK_VARIABLE:
10157 + if( p->pLeft && !sqliteExprIsConstant(p->pLeft) ) return 0;
10158 + if( p->pRight && !sqliteExprIsConstant(p->pRight) ) return 0;
10161 + for(i=0; i<p->pList->nExpr; i++){
10162 + if( !sqliteExprIsConstant(p->pList->a[i].pExpr) ) return 0;
10165 + return p->pLeft!=0 || p->pRight!=0 || (p->pList && p->pList->nExpr>0);
10172 +** If the given expression codes a constant integer that is small enough
10173 +** to fit in a 32-bit integer, return 1 and put the value of the integer
10174 +** in *pValue. If the expression is not an integer or if it is too big
10175 +** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
10177 +int sqliteExprIsInteger(Expr *p, int *pValue){
10179 + case TK_INTEGER: {
10180 + if( sqliteFitsIn32Bits(p->token.z) ){
10181 + *pValue = atoi(p->token.z);
10186 + case TK_STRING: {
10187 + const char *z = p->token.z;
10188 + int n = p->token.n;
10189 + if( n>0 && z[0]=='-' ){ z++; n--; }
10190 + while( n>0 && *z && isdigit(*z) ){ z++; n--; }
10191 + if( n==0 && sqliteFitsIn32Bits(p->token.z) ){
10192 + *pValue = atoi(p->token.z);
10198 + return sqliteExprIsInteger(p->pLeft, pValue);
10200 + case TK_UMINUS: {
10202 + if( sqliteExprIsInteger(p->pLeft, &v) ){
10214 +** Return TRUE if the given string is a row-id column name.
10216 +int sqliteIsRowid(const char *z){
10217 + if( sqliteStrICmp(z, "_ROWID_")==0 ) return 1;
10218 + if( sqliteStrICmp(z, "ROWID")==0 ) return 1;
10219 + if( sqliteStrICmp(z, "OID")==0 ) return 1;
10224 +** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
10225 +** that name in the set of source tables in pSrcList and make the pExpr
10226 +** expression node refer back to that source column. The following changes
10227 +** are made to pExpr:
10229 +** pExpr->iDb Set the index in db->aDb[] of the database holding
10231 +** pExpr->iTable Set to the cursor number for the table obtained
10233 +** pExpr->iColumn Set to the column number within the table.
10234 +** pExpr->dataType Set to the appropriate data type for the column.
10235 +** pExpr->op Set to TK_COLUMN.
10236 +** pExpr->pLeft Any expression this points to is deleted
10237 +** pExpr->pRight Any expression this points to is deleted.
10239 +** The pDbToken is the name of the database (the "X"). This value may be
10240 +** NULL meaning that name is of the form Y.Z or Z. Any available database
10241 +** can be used. The pTableToken is the name of the table (the "Y"). This
10242 +** value can be NULL if pDbToken is also NULL. If pTableToken is NULL it
10243 +** means that the form of the name is Z and that columns from any table
10246 +** If the name cannot be resolved unambiguously, leave an error message
10247 +** in pParse and return non-zero. Return zero on success.
10249 +static int lookupName(
10250 + Parse *pParse, /* The parsing context */
10251 + Token *pDbToken, /* Name of the database containing table, or NULL */
10252 + Token *pTableToken, /* Name of table containing column, or NULL */
10253 + Token *pColumnToken, /* Name of the column. */
10254 + SrcList *pSrcList, /* List of tables used to resolve column names */
10255 + ExprList *pEList, /* List of expressions used to resolve "AS" */
10256 + Expr *pExpr /* Make this EXPR node point to the selected column */
10258 + char *zDb = 0; /* Name of the database. The "X" in X.Y.Z */
10259 + char *zTab = 0; /* Name of the table. The "Y" in X.Y.Z or Y.Z */
10260 + char *zCol = 0; /* Name of the column. The "Z" */
10261 + int i, j; /* Loop counters */
10262 + int cnt = 0; /* Number of matching column names */
10263 + int cntTab = 0; /* Number of matching table names */
10264 + sqlite *db = pParse->db; /* The database */
10266 + assert( pColumnToken && pColumnToken->z ); /* The Z in X.Y.Z cannot be NULL */
10267 + if( pDbToken && pDbToken->z ){
10268 + zDb = sqliteStrNDup(pDbToken->z, pDbToken->n);
10269 + sqliteDequote(zDb);
10273 + if( pTableToken && pTableToken->z ){
10274 + zTab = sqliteStrNDup(pTableToken->z, pTableToken->n);
10275 + sqliteDequote(zTab);
10277 + assert( zDb==0 );
10280 + zCol = sqliteStrNDup(pColumnToken->z, pColumnToken->n);
10281 + sqliteDequote(zCol);
10282 + if( sqlite_malloc_failed ){
10283 + return 1; /* Leak memory (zDb and zTab) if malloc fails */
10285 + assert( zTab==0 || pEList==0 );
10287 + pExpr->iTable = -1;
10288 + for(i=0; i<pSrcList->nSrc; i++){
10289 + struct SrcList_item *pItem = &pSrcList->a[i];
10290 + Table *pTab = pItem->pTab;
10293 + if( pTab==0 ) continue;
10294 + assert( pTab->nCol>0 );
10296 + if( pItem->zAlias ){
10297 + char *zTabName = pItem->zAlias;
10298 + if( sqliteStrICmp(zTabName, zTab)!=0 ) continue;
10300 + char *zTabName = pTab->zName;
10301 + if( zTabName==0 || sqliteStrICmp(zTabName, zTab)!=0 ) continue;
10302 + if( zDb!=0 && sqliteStrICmp(db->aDb[pTab->iDb].zName, zDb)!=0 ){
10307 + if( 0==(cntTab++) ){
10308 + pExpr->iTable = pItem->iCursor;
10309 + pExpr->iDb = pTab->iDb;
10311 + for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
10312 + if( sqliteStrICmp(pCol->zName, zCol)==0 ){
10314 + pExpr->iTable = pItem->iCursor;
10315 + pExpr->iDb = pTab->iDb;
10316 + /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
10317 + pExpr->iColumn = j==pTab->iPKey ? -1 : j;
10318 + pExpr->dataType = pCol->sortOrder & SQLITE_SO_TYPEMASK;
10324 + /* If we have not already resolved the name, then maybe
10325 + ** it is a new.* or old.* trigger argument reference
10327 + if( zDb==0 && zTab!=0 && cnt==0 && pParse->trigStack!=0 ){
10328 + TriggerStack *pTriggerStack = pParse->trigStack;
10330 + if( pTriggerStack->newIdx != -1 && sqliteStrICmp("new", zTab) == 0 ){
10331 + pExpr->iTable = pTriggerStack->newIdx;
10332 + assert( pTriggerStack->pTab );
10333 + pTab = pTriggerStack->pTab;
10334 + }else if( pTriggerStack->oldIdx != -1 && sqliteStrICmp("old", zTab) == 0 ){
10335 + pExpr->iTable = pTriggerStack->oldIdx;
10336 + assert( pTriggerStack->pTab );
10337 + pTab = pTriggerStack->pTab;
10342 + Column *pCol = pTab->aCol;
10344 + pExpr->iDb = pTab->iDb;
10346 + for(j=0; j < pTab->nCol; j++, pCol++) {
10347 + if( sqliteStrICmp(pCol->zName, zCol)==0 ){
10349 + pExpr->iColumn = j==pTab->iPKey ? -1 : j;
10350 + pExpr->dataType = pCol->sortOrder & SQLITE_SO_TYPEMASK;
10358 + ** Perhaps the name is a reference to the ROWID
10360 + if( cnt==0 && cntTab==1 && sqliteIsRowid(zCol) ){
10362 + pExpr->iColumn = -1;
10363 + pExpr->dataType = SQLITE_SO_NUM;
10367 + ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
10368 + ** might refer to an result-set alias. This happens, for example, when
10369 + ** we are resolving names in the WHERE clause of the following command:
10371 + ** SELECT a+b AS x FROM table WHERE x<10;
10373 + ** In cases like this, replace pExpr with a copy of the expression that
10374 + ** forms the result set entry ("a+b" in the example) and return immediately.
10375 + ** Note that the expression in the result set should have already been
10376 + ** resolved by the time the WHERE clause is resolved.
10378 + if( cnt==0 && pEList!=0 ){
10379 + for(j=0; j<pEList->nExpr; j++){
10380 + char *zAs = pEList->a[j].zName;
10381 + if( zAs!=0 && sqliteStrICmp(zAs, zCol)==0 ){
10382 + assert( pExpr->pLeft==0 && pExpr->pRight==0 );
10383 + pExpr->op = TK_AS;
10384 + pExpr->iColumn = j;
10385 + pExpr->pLeft = sqliteExprDup(pEList->a[j].pExpr);
10386 + sqliteFree(zCol);
10387 + assert( zTab==0 && zDb==0 );
10394 + ** If X and Y are NULL (in other words if only the column name Z is
10395 + ** supplied) and the value of Z is enclosed in double-quotes, then
10396 + ** Z is a string literal if it doesn't match any column names. In that
10397 + ** case, we need to return right away and not make any changes to
10400 + if( cnt==0 && zTab==0 && pColumnToken->z[0]=='"' ){
10401 + sqliteFree(zCol);
10406 + ** cnt==0 means there was not match. cnt>1 means there were two or
10407 + ** more matches. Either way, we have an error.
10412 + zErr = cnt==0 ? "no such column: %s" : "ambiguous column name: %s";
10414 + sqliteSetString(&z, zDb, ".", zTab, ".", zCol, 0);
10415 + }else if( zTab ){
10416 + sqliteSetString(&z, zTab, ".", zCol, 0);
10418 + z = sqliteStrDup(zCol);
10420 + sqliteErrorMsg(pParse, zErr, z);
10424 + /* Clean up and return
10427 + sqliteFree(zTab);
10428 + sqliteFree(zCol);
10429 + sqliteExprDelete(pExpr->pLeft);
10430 + pExpr->pLeft = 0;
10431 + sqliteExprDelete(pExpr->pRight);
10432 + pExpr->pRight = 0;
10433 + pExpr->op = TK_COLUMN;
10434 + sqliteAuthRead(pParse, pExpr, pSrcList);
10439 +** This routine walks an expression tree and resolves references to
10440 +** table columns. Nodes of the form ID.ID or ID resolve into an
10441 +** index to the table in the table list and a column offset. The
10442 +** Expr.opcode for such nodes is changed to TK_COLUMN. The Expr.iTable
10443 +** value is changed to the index of the referenced table in pTabList
10444 +** plus the "base" value. The base value will ultimately become the
10445 +** VDBE cursor number for a cursor that is pointing into the referenced
10446 +** table. The Expr.iColumn value is changed to the index of the column
10447 +** of the referenced table. The Expr.iColumn value for the special
10448 +** ROWID column is -1. Any INTEGER PRIMARY KEY column is tried as an
10449 +** alias for ROWID.
10451 +** We also check for instances of the IN operator. IN comes in two
10454 +** expr IN (exprlist)
10456 +** expr IN (SELECT ...)
10458 +** The first form is handled by creating a set holding the list
10459 +** of allowed values. The second form causes the SELECT to generate
10460 +** a temporary table.
10462 +** This routine also looks for scalar SELECTs that are part of an expression.
10463 +** If it finds any, it generates code to write the value of that select
10464 +** into a memory cell.
10466 +** Unknown columns or tables provoke an error. The function returns
10467 +** the number of errors seen and leaves an error message on pParse->zErrMsg.
10469 +int sqliteExprResolveIds(
10470 + Parse *pParse, /* The parser context */
10471 + SrcList *pSrcList, /* List of tables used to resolve column names */
10472 + ExprList *pEList, /* List of expressions used to resolve "AS" */
10473 + Expr *pExpr /* The expression to be analyzed. */
10477 + if( pExpr==0 || pSrcList==0 ) return 0;
10478 + for(i=0; i<pSrcList->nSrc; i++){
10479 + assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab );
10481 + switch( pExpr->op ){
10482 + /* Double-quoted strings (ex: "abc") are used as identifiers if
10483 + ** possible. Otherwise they remain as strings. Single-quoted
10484 + ** strings (ex: 'abc') are always string literals.
10486 + case TK_STRING: {
10487 + if( pExpr->token.z[0]=='\'' ) break;
10488 + /* Fall thru into the TK_ID case if this is a double-quoted string */
10490 + /* A lone identifier is the name of a columnd.
10493 + if( lookupName(pParse, 0, 0, &pExpr->token, pSrcList, pEList, pExpr) ){
10499 + /* A table name and column name: ID.ID
10500 + ** Or a database, table and column: ID.ID.ID
10508 + pRight = pExpr->pRight;
10509 + if( pRight->op==TK_ID ){
10511 + pTable = &pExpr->pLeft->token;
10512 + pColumn = &pRight->token;
10514 + assert( pRight->op==TK_DOT );
10515 + pDb = &pExpr->pLeft->token;
10516 + pTable = &pRight->pLeft->token;
10517 + pColumn = &pRight->pRight->token;
10519 + if( lookupName(pParse, pDb, pTable, pColumn, pSrcList, 0, pExpr) ){
10526 + Vdbe *v = sqliteGetVdbe(pParse);
10527 + if( v==0 ) return 1;
10528 + if( sqliteExprResolveIds(pParse, pSrcList, pEList, pExpr->pLeft) ){
10531 + if( pExpr->pSelect ){
10532 + /* Case 1: expr IN (SELECT ...)
10534 + ** Generate code to write the results of the select into a temporary
10535 + ** table. The cursor number of the temporary table has already
10536 + ** been put in iTable by sqliteExprResolveInSelect().
10538 + pExpr->iTable = pParse->nTab++;
10539 + sqliteVdbeAddOp(v, OP_OpenTemp, pExpr->iTable, 1);
10540 + sqliteSelect(pParse, pExpr->pSelect, SRT_Set, pExpr->iTable, 0,0,0);
10541 + }else if( pExpr->pList ){
10542 + /* Case 2: expr IN (exprlist)
10544 + ** Create a set to put the exprlist values in. The Set id is stored
10548 + for(i=0; i<pExpr->pList->nExpr; i++){
10549 + Expr *pE2 = pExpr->pList->a[i].pExpr;
10550 + if( !sqliteExprIsConstant(pE2) ){
10551 + sqliteErrorMsg(pParse,
10552 + "right-hand side of IN operator must be constant");
10555 + if( sqliteExprCheck(pParse, pE2, 0, 0) ){
10559 + iSet = pExpr->iTable = pParse->nSet++;
10560 + for(i=0; i<pExpr->pList->nExpr; i++){
10561 + Expr *pE2 = pExpr->pList->a[i].pExpr;
10562 + switch( pE2->op ){
10565 + case TK_STRING: {
10567 + assert( pE2->token.z );
10568 + addr = sqliteVdbeOp3(v, OP_SetInsert, iSet, 0,
10569 + pE2->token.z, pE2->token.n);
10570 + sqliteVdbeDequoteP3(v, addr);
10574 + sqliteExprCode(pParse, pE2);
10575 + sqliteVdbeAddOp(v, OP_SetInsert, iSet, 0);
10584 + case TK_SELECT: {
10585 + /* This has to be a scalar SELECT. Generate code to put the
10586 + ** value of this select in a memory cell and record the number
10587 + ** of the memory cell in iColumn.
10589 + pExpr->iColumn = pParse->nMem++;
10590 + if( sqliteSelect(pParse, pExpr->pSelect, SRT_Mem, pExpr->iColumn,0,0,0) ){
10596 + /* For all else, just recursively walk the tree */
10599 + && sqliteExprResolveIds(pParse, pSrcList, pEList, pExpr->pLeft) ){
10602 + if( pExpr->pRight
10603 + && sqliteExprResolveIds(pParse, pSrcList, pEList, pExpr->pRight) ){
10606 + if( pExpr->pList ){
10608 + ExprList *pList = pExpr->pList;
10609 + for(i=0; i<pList->nExpr; i++){
10610 + Expr *pArg = pList->a[i].pExpr;
10611 + if( sqliteExprResolveIds(pParse, pSrcList, pEList, pArg) ){
10622 +** pExpr is a node that defines a function of some kind. It might
10623 +** be a syntactic function like "count(x)" or it might be a function
10624 +** that implements an operator, like "a LIKE b".
10626 +** This routine makes *pzName point to the name of the function and
10627 +** *pnName hold the number of characters in the function name.
10629 +static void getFunctionName(Expr *pExpr, const char **pzName, int *pnName){
10630 + switch( pExpr->op ){
10631 + case TK_FUNCTION: {
10632 + *pzName = pExpr->token.z;
10633 + *pnName = pExpr->token.n;
10637 + *pzName = "like";
10642 + *pzName = "glob";
10647 + *pzName = "can't happen";
10655 +** Error check the functions in an expression. Make sure all
10656 +** function names are recognized and all functions have the correct
10657 +** number of arguments. Leave an error message in pParse->zErrMsg
10658 +** if anything is amiss. Return the number of errors.
10660 +** if pIsAgg is not null and this expression is an aggregate function
10661 +** (like count(*) or max(value)) then write a 1 into *pIsAgg.
10663 +int sqliteExprCheck(Parse *pParse, Expr *pExpr, int allowAgg, int *pIsAgg){
10665 + if( pExpr==0 ) return 0;
10666 + switch( pExpr->op ){
10669 + case TK_FUNCTION: {
10670 + int n = pExpr->pList ? pExpr->pList->nExpr : 0; /* Number of arguments */
10671 + int no_such_func = 0; /* True if no such function exists */
10672 + int wrong_num_args = 0; /* True if wrong number of arguments */
10673 + int is_agg = 0; /* True if is an aggregate function */
10675 + int nId; /* Number of characters in function name */
10676 + const char *zId; /* The function name. */
10679 + getFunctionName(pExpr, &zId, &nId);
10680 + pDef = sqliteFindFunction(pParse->db, zId, nId, n, 0);
10682 + pDef = sqliteFindFunction(pParse->db, zId, nId, -1, 0);
10684 + no_such_func = 1;
10686 + wrong_num_args = 1;
10689 + is_agg = pDef->xFunc==0;
10691 + if( is_agg && !allowAgg ){
10692 + sqliteErrorMsg(pParse, "misuse of aggregate function %.*s()", nId, zId);
10695 + }else if( no_such_func ){
10696 + sqliteErrorMsg(pParse, "no such function: %.*s", nId, zId);
10698 + }else if( wrong_num_args ){
10699 + sqliteErrorMsg(pParse,"wrong number of arguments to function %.*s()",
10704 + pExpr->op = TK_AGG_FUNCTION;
10705 + if( pIsAgg ) *pIsAgg = 1;
10707 + for(i=0; nErr==0 && i<n; i++){
10708 + nErr = sqliteExprCheck(pParse, pExpr->pList->a[i].pExpr,
10709 + allowAgg && !is_agg, pIsAgg);
10712 + /* Already reported an error */
10713 + }else if( pDef->dataType>=0 ){
10714 + if( pDef->dataType<n ){
10715 + pExpr->dataType =
10716 + sqliteExprType(pExpr->pList->a[pDef->dataType].pExpr);
10718 + pExpr->dataType = SQLITE_SO_NUM;
10720 + }else if( pDef->dataType==SQLITE_ARGS ){
10721 + pDef->dataType = SQLITE_SO_TEXT;
10722 + for(i=0; i<n; i++){
10723 + if( sqliteExprType(pExpr->pList->a[i].pExpr)==SQLITE_SO_NUM ){
10724 + pExpr->dataType = SQLITE_SO_NUM;
10728 + }else if( pDef->dataType==SQLITE_NUMERIC ){
10729 + pExpr->dataType = SQLITE_SO_NUM;
10731 + pExpr->dataType = SQLITE_SO_TEXT;
10735 + if( pExpr->pLeft ){
10736 + nErr = sqliteExprCheck(pParse, pExpr->pLeft, allowAgg, pIsAgg);
10738 + if( nErr==0 && pExpr->pRight ){
10739 + nErr = sqliteExprCheck(pParse, pExpr->pRight, allowAgg, pIsAgg);
10741 + if( nErr==0 && pExpr->pList ){
10742 + int n = pExpr->pList->nExpr;
10744 + for(i=0; nErr==0 && i<n; i++){
10745 + Expr *pE2 = pExpr->pList->a[i].pExpr;
10746 + nErr = sqliteExprCheck(pParse, pE2, allowAgg, pIsAgg);
10756 +** Return either SQLITE_SO_NUM or SQLITE_SO_TEXT to indicate whether the
10757 +** given expression should sort as numeric values or as text.
10759 +** The sqliteExprResolveIds() and sqliteExprCheck() routines must have
10760 +** both been called on the expression before it is passed to this routine.
10762 +int sqliteExprType(Expr *p){
10763 + if( p==0 ) return SQLITE_SO_NUM;
10764 + while( p ) switch( p->op ){
10788 + return SQLITE_SO_NUM;
10793 + case TK_VARIABLE:
10794 + return SQLITE_SO_TEXT;
10802 + if( sqliteExprType(p->pLeft)==SQLITE_SO_NUM ){
10803 + return SQLITE_SO_NUM;
10813 + case TK_FUNCTION:
10814 + case TK_AGG_FUNCTION:
10815 + return p->dataType;
10818 + assert( p->pSelect );
10819 + assert( p->pSelect->pEList );
10820 + assert( p->pSelect->pEList->nExpr>0 );
10821 + p = p->pSelect->pEList->a[0].pExpr;
10825 + if( p->pRight && sqliteExprType(p->pRight)==SQLITE_SO_NUM ){
10826 + return SQLITE_SO_NUM;
10830 + ExprList *pList = p->pList;
10831 + for(i=1; i<pList->nExpr; i+=2){
10832 + if( sqliteExprType(pList->a[i].pExpr)==SQLITE_SO_NUM ){
10833 + return SQLITE_SO_NUM;
10837 + return SQLITE_SO_TEXT;
10841 + assert( p->op==TK_ABORT ); /* Can't Happen */
10844 + return SQLITE_SO_NUM;
10848 +** Generate code into the current Vdbe to evaluate the given
10849 +** expression and leave the result on the top of stack.
10851 +void sqliteExprCode(Parse *pParse, Expr *pExpr){
10852 + Vdbe *v = pParse->pVdbe;
10854 + if( v==0 || pExpr==0 ) return;
10855 + switch( pExpr->op ){
10856 + case TK_PLUS: op = OP_Add; break;
10857 + case TK_MINUS: op = OP_Subtract; break;
10858 + case TK_STAR: op = OP_Multiply; break;
10859 + case TK_SLASH: op = OP_Divide; break;
10860 + case TK_AND: op = OP_And; break;
10861 + case TK_OR: op = OP_Or; break;
10862 + case TK_LT: op = OP_Lt; break;
10863 + case TK_LE: op = OP_Le; break;
10864 + case TK_GT: op = OP_Gt; break;
10865 + case TK_GE: op = OP_Ge; break;
10866 + case TK_NE: op = OP_Ne; break;
10867 + case TK_EQ: op = OP_Eq; break;
10868 + case TK_ISNULL: op = OP_IsNull; break;
10869 + case TK_NOTNULL: op = OP_NotNull; break;
10870 + case TK_NOT: op = OP_Not; break;
10871 + case TK_UMINUS: op = OP_Negative; break;
10872 + case TK_BITAND: op = OP_BitAnd; break;
10873 + case TK_BITOR: op = OP_BitOr; break;
10874 + case TK_BITNOT: op = OP_BitNot; break;
10875 + case TK_LSHIFT: op = OP_ShiftLeft; break;
10876 + case TK_RSHIFT: op = OP_ShiftRight; break;
10877 + case TK_REM: op = OP_Remainder; break;
10880 + switch( pExpr->op ){
10881 + case TK_COLUMN: {
10882 + if( pParse->useAgg ){
10883 + sqliteVdbeAddOp(v, OP_AggGet, 0, pExpr->iAgg);
10884 + }else if( pExpr->iColumn>=0 ){
10885 + sqliteVdbeAddOp(v, OP_Column, pExpr->iTable, pExpr->iColumn);
10887 + sqliteVdbeAddOp(v, OP_Recno, pExpr->iTable, 0);
10893 + case TK_INTEGER: {
10894 + if( pExpr->op==TK_INTEGER && sqliteFitsIn32Bits(pExpr->token.z) ){
10895 + sqliteVdbeAddOp(v, OP_Integer, atoi(pExpr->token.z), 0);
10897 + sqliteVdbeAddOp(v, OP_String, 0, 0);
10899 + assert( pExpr->token.z );
10900 + sqliteVdbeChangeP3(v, -1, pExpr->token.z, pExpr->token.n);
10901 + sqliteVdbeDequoteP3(v, -1);
10905 + sqliteVdbeAddOp(v, OP_String, 0, 0);
10908 + case TK_VARIABLE: {
10909 + sqliteVdbeAddOp(v, OP_Variable, pExpr->iTable, 0);
10918 + if( pParse->db->file_format>=4 && sqliteExprType(pExpr)==SQLITE_SO_TEXT ){
10919 + op += 6; /* Convert numeric opcodes to text opcodes */
10921 + /* Fall through into the next case */
10932 + sqliteExprCode(pParse, pExpr->pLeft);
10933 + sqliteExprCode(pParse, pExpr->pRight);
10934 + sqliteVdbeAddOp(v, op, 0, 0);
10938 + case TK_RSHIFT: {
10939 + sqliteExprCode(pParse, pExpr->pRight);
10940 + sqliteExprCode(pParse, pExpr->pLeft);
10941 + sqliteVdbeAddOp(v, op, 0, 0);
10944 + case TK_CONCAT: {
10945 + sqliteExprCode(pParse, pExpr->pLeft);
10946 + sqliteExprCode(pParse, pExpr->pRight);
10947 + sqliteVdbeAddOp(v, OP_Concat, 2, 0);
10950 + case TK_UMINUS: {
10951 + assert( pExpr->pLeft );
10952 + if( pExpr->pLeft->op==TK_FLOAT || pExpr->pLeft->op==TK_INTEGER ){
10953 + Token *p = &pExpr->pLeft->token;
10954 + char *z = sqliteMalloc( p->n + 2 );
10955 + sprintf(z, "-%.*s", p->n, p->z);
10956 + if( pExpr->pLeft->op==TK_INTEGER && sqliteFitsIn32Bits(z) ){
10957 + sqliteVdbeAddOp(v, OP_Integer, atoi(z), 0);
10959 + sqliteVdbeAddOp(v, OP_String, 0, 0);
10961 + sqliteVdbeChangeP3(v, -1, z, p->n+1);
10965 + /* Fall through into TK_NOT */
10969 + sqliteExprCode(pParse, pExpr->pLeft);
10970 + sqliteVdbeAddOp(v, op, 0, 0);
10974 + case TK_NOTNULL: {
10976 + sqliteVdbeAddOp(v, OP_Integer, 1, 0);
10977 + sqliteExprCode(pParse, pExpr->pLeft);
10978 + dest = sqliteVdbeCurrentAddr(v) + 2;
10979 + sqliteVdbeAddOp(v, op, 1, dest);
10980 + sqliteVdbeAddOp(v, OP_AddImm, -1, 0);
10983 + case TK_AGG_FUNCTION: {
10984 + sqliteVdbeAddOp(v, OP_AggGet, 0, pExpr->iAgg);
10989 + case TK_FUNCTION: {
10990 + ExprList *pList = pExpr->pList;
10991 + int nExpr = pList ? pList->nExpr : 0;
10995 + getFunctionName(pExpr, &zId, &nId);
10996 + pDef = sqliteFindFunction(pParse->db, zId, nId, nExpr, 0);
10997 + assert( pDef!=0 );
10998 + nExpr = sqliteExprCodeExprList(pParse, pList, pDef->includeTypes);
10999 + sqliteVdbeOp3(v, OP_Function, nExpr, 0, (char*)pDef, P3_POINTER);
11002 + case TK_SELECT: {
11003 + sqliteVdbeAddOp(v, OP_MemLoad, pExpr->iColumn, 0);
11008 + sqliteVdbeAddOp(v, OP_Integer, 1, 0);
11009 + sqliteExprCode(pParse, pExpr->pLeft);
11010 + addr = sqliteVdbeCurrentAddr(v);
11011 + sqliteVdbeAddOp(v, OP_NotNull, -1, addr+4);
11012 + sqliteVdbeAddOp(v, OP_Pop, 2, 0);
11013 + sqliteVdbeAddOp(v, OP_String, 0, 0);
11014 + sqliteVdbeAddOp(v, OP_Goto, 0, addr+6);
11015 + if( pExpr->pSelect ){
11016 + sqliteVdbeAddOp(v, OP_Found, pExpr->iTable, addr+6);
11018 + sqliteVdbeAddOp(v, OP_SetFound, pExpr->iTable, addr+6);
11020 + sqliteVdbeAddOp(v, OP_AddImm, -1, 0);
11023 + case TK_BETWEEN: {
11024 + sqliteExprCode(pParse, pExpr->pLeft);
11025 + sqliteVdbeAddOp(v, OP_Dup, 0, 0);
11026 + sqliteExprCode(pParse, pExpr->pList->a[0].pExpr);
11027 + sqliteVdbeAddOp(v, OP_Ge, 0, 0);
11028 + sqliteVdbeAddOp(v, OP_Pull, 1, 0);
11029 + sqliteExprCode(pParse, pExpr->pList->a[1].pExpr);
11030 + sqliteVdbeAddOp(v, OP_Le, 0, 0);
11031 + sqliteVdbeAddOp(v, OP_And, 0, 0);
11036 + sqliteExprCode(pParse, pExpr->pLeft);
11040 + int expr_end_label;
11046 + assert(pExpr->pList);
11047 + assert((pExpr->pList->nExpr % 2) == 0);
11048 + assert(pExpr->pList->nExpr > 0);
11049 + nExpr = pExpr->pList->nExpr;
11050 + expr_end_label = sqliteVdbeMakeLabel(v);
11051 + if( pExpr->pLeft ){
11052 + sqliteExprCode(pParse, pExpr->pLeft);
11054 + for(i=0; i<nExpr; i=i+2){
11055 + sqliteExprCode(pParse, pExpr->pList->a[i].pExpr);
11056 + if( pExpr->pLeft ){
11057 + sqliteVdbeAddOp(v, OP_Dup, 1, 1);
11058 + jumpInst = sqliteVdbeAddOp(v, OP_Ne, 1, 0);
11059 + sqliteVdbeAddOp(v, OP_Pop, 1, 0);
11061 + jumpInst = sqliteVdbeAddOp(v, OP_IfNot, 1, 0);
11063 + sqliteExprCode(pParse, pExpr->pList->a[i+1].pExpr);
11064 + sqliteVdbeAddOp(v, OP_Goto, 0, expr_end_label);
11065 + addr = sqliteVdbeCurrentAddr(v);
11066 + sqliteVdbeChangeP2(v, jumpInst, addr);
11068 + if( pExpr->pLeft ){
11069 + sqliteVdbeAddOp(v, OP_Pop, 1, 0);
11071 + if( pExpr->pRight ){
11072 + sqliteExprCode(pParse, pExpr->pRight);
11074 + sqliteVdbeAddOp(v, OP_String, 0, 0);
11076 + sqliteVdbeResolveLabel(v, expr_end_label);
11080 + if( !pParse->trigStack ){
11081 + sqliteErrorMsg(pParse,
11082 + "RAISE() may only be used within a trigger-program");
11086 + if( pExpr->iColumn == OE_Rollback ||
11087 + pExpr->iColumn == OE_Abort ||
11088 + pExpr->iColumn == OE_Fail ){
11089 + sqliteVdbeOp3(v, OP_Halt, SQLITE_CONSTRAINT, pExpr->iColumn,
11090 + pExpr->token.z, pExpr->token.n);
11091 + sqliteVdbeDequoteP3(v, -1);
11093 + assert( pExpr->iColumn == OE_Ignore );
11094 + sqliteVdbeOp3(v, OP_Goto, 0, pParse->trigStack->ignoreJump,
11095 + "(IGNORE jump)", 0);
11103 +** Generate code that pushes the value of every element of the given
11104 +** expression list onto the stack. If the includeTypes flag is true,
11105 +** then also push a string that is the datatype of each element onto
11106 +** the stack after the value.
11108 +** Return the number of elements pushed onto the stack.
11110 +int sqliteExprCodeExprList(
11111 + Parse *pParse, /* Parsing context */
11112 + ExprList *pList, /* The expression list to be coded */
11113 + int includeTypes /* TRUE to put datatypes on the stack too */
11115 + struct ExprList_item *pItem;
11118 + if( pList==0 ) return 0;
11119 + v = sqliteGetVdbe(pParse);
11120 + n = pList->nExpr;
11121 + for(pItem=pList->a, i=0; i<n; i++, pItem++){
11122 + sqliteExprCode(pParse, pItem->pExpr);
11123 + if( includeTypes ){
11124 + sqliteVdbeOp3(v, OP_String, 0, 0,
11125 + sqliteExprType(pItem->pExpr)==SQLITE_SO_NUM ? "numeric" : "text",
11129 + return includeTypes ? n*2 : n;
11133 +** Generate code for a boolean expression such that a jump is made
11134 +** to the label "dest" if the expression is true but execution
11135 +** continues straight thru if the expression is false.
11137 +** If the expression evaluates to NULL (neither true nor false), then
11138 +** take the jump if the jumpIfNull flag is true.
11140 +void sqliteExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
11141 + Vdbe *v = pParse->pVdbe;
11143 + if( v==0 || pExpr==0 ) return;
11144 + switch( pExpr->op ){
11145 + case TK_LT: op = OP_Lt; break;
11146 + case TK_LE: op = OP_Le; break;
11147 + case TK_GT: op = OP_Gt; break;
11148 + case TK_GE: op = OP_Ge; break;
11149 + case TK_NE: op = OP_Ne; break;
11150 + case TK_EQ: op = OP_Eq; break;
11151 + case TK_ISNULL: op = OP_IsNull; break;
11152 + case TK_NOTNULL: op = OP_NotNull; break;
11155 + switch( pExpr->op ){
11157 + int d2 = sqliteVdbeMakeLabel(v);
11158 + sqliteExprIfFalse(pParse, pExpr->pLeft, d2, !jumpIfNull);
11159 + sqliteExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
11160 + sqliteVdbeResolveLabel(v, d2);
11164 + sqliteExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
11165 + sqliteExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
11169 + sqliteExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
11178 + sqliteExprCode(pParse, pExpr->pLeft);
11179 + sqliteExprCode(pParse, pExpr->pRight);
11180 + if( pParse->db->file_format>=4 && sqliteExprType(pExpr)==SQLITE_SO_TEXT ){
11181 + op += 6; /* Convert numeric opcodes to text opcodes */
11183 + sqliteVdbeAddOp(v, op, jumpIfNull, dest);
11187 + case TK_NOTNULL: {
11188 + sqliteExprCode(pParse, pExpr->pLeft);
11189 + sqliteVdbeAddOp(v, op, 1, dest);
11194 + sqliteExprCode(pParse, pExpr->pLeft);
11195 + addr = sqliteVdbeCurrentAddr(v);
11196 + sqliteVdbeAddOp(v, OP_NotNull, -1, addr+3);
11197 + sqliteVdbeAddOp(v, OP_Pop, 1, 0);
11198 + sqliteVdbeAddOp(v, OP_Goto, 0, jumpIfNull ? dest : addr+4);
11199 + if( pExpr->pSelect ){
11200 + sqliteVdbeAddOp(v, OP_Found, pExpr->iTable, dest);
11202 + sqliteVdbeAddOp(v, OP_SetFound, pExpr->iTable, dest);
11206 + case TK_BETWEEN: {
11208 + sqliteExprCode(pParse, pExpr->pLeft);
11209 + sqliteVdbeAddOp(v, OP_Dup, 0, 0);
11210 + sqliteExprCode(pParse, pExpr->pList->a[0].pExpr);
11211 + addr = sqliteVdbeAddOp(v, OP_Lt, !jumpIfNull, 0);
11212 + sqliteExprCode(pParse, pExpr->pList->a[1].pExpr);
11213 + sqliteVdbeAddOp(v, OP_Le, jumpIfNull, dest);
11214 + sqliteVdbeAddOp(v, OP_Integer, 0, 0);
11215 + sqliteVdbeChangeP2(v, addr, sqliteVdbeCurrentAddr(v));
11216 + sqliteVdbeAddOp(v, OP_Pop, 1, 0);
11220 + sqliteExprCode(pParse, pExpr);
11221 + sqliteVdbeAddOp(v, OP_If, jumpIfNull, dest);
11228 +** Generate code for a boolean expression such that a jump is made
11229 +** to the label "dest" if the expression is false but execution
11230 +** continues straight thru if the expression is true.
11232 +** If the expression evaluates to NULL (neither true nor false) then
11233 +** jump if jumpIfNull is true or fall through if jumpIfNull is false.
11235 +void sqliteExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
11236 + Vdbe *v = pParse->pVdbe;
11238 + if( v==0 || pExpr==0 ) return;
11239 + switch( pExpr->op ){
11240 + case TK_LT: op = OP_Ge; break;
11241 + case TK_LE: op = OP_Gt; break;
11242 + case TK_GT: op = OP_Le; break;
11243 + case TK_GE: op = OP_Lt; break;
11244 + case TK_NE: op = OP_Eq; break;
11245 + case TK_EQ: op = OP_Ne; break;
11246 + case TK_ISNULL: op = OP_NotNull; break;
11247 + case TK_NOTNULL: op = OP_IsNull; break;
11250 + switch( pExpr->op ){
11252 + sqliteExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
11253 + sqliteExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
11257 + int d2 = sqliteVdbeMakeLabel(v);
11258 + sqliteExprIfTrue(pParse, pExpr->pLeft, d2, !jumpIfNull);
11259 + sqliteExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
11260 + sqliteVdbeResolveLabel(v, d2);
11264 + sqliteExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
11273 + if( pParse->db->file_format>=4 && sqliteExprType(pExpr)==SQLITE_SO_TEXT ){
11274 + /* Convert numeric comparison opcodes into text comparison opcodes.
11275 + ** This step depends on the fact that the text comparision opcodes are
11276 + ** always 6 greater than their corresponding numeric comparison
11279 + assert( OP_Eq+6 == OP_StrEq );
11282 + sqliteExprCode(pParse, pExpr->pLeft);
11283 + sqliteExprCode(pParse, pExpr->pRight);
11284 + sqliteVdbeAddOp(v, op, jumpIfNull, dest);
11288 + case TK_NOTNULL: {
11289 + sqliteExprCode(pParse, pExpr->pLeft);
11290 + sqliteVdbeAddOp(v, op, 1, dest);
11295 + sqliteExprCode(pParse, pExpr->pLeft);
11296 + addr = sqliteVdbeCurrentAddr(v);
11297 + sqliteVdbeAddOp(v, OP_NotNull, -1, addr+3);
11298 + sqliteVdbeAddOp(v, OP_Pop, 1, 0);
11299 + sqliteVdbeAddOp(v, OP_Goto, 0, jumpIfNull ? dest : addr+4);
11300 + if( pExpr->pSelect ){
11301 + sqliteVdbeAddOp(v, OP_NotFound, pExpr->iTable, dest);
11303 + sqliteVdbeAddOp(v, OP_SetNotFound, pExpr->iTable, dest);
11307 + case TK_BETWEEN: {
11309 + sqliteExprCode(pParse, pExpr->pLeft);
11310 + sqliteVdbeAddOp(v, OP_Dup, 0, 0);
11311 + sqliteExprCode(pParse, pExpr->pList->a[0].pExpr);
11312 + addr = sqliteVdbeCurrentAddr(v);
11313 + sqliteVdbeAddOp(v, OP_Ge, !jumpIfNull, addr+3);
11314 + sqliteVdbeAddOp(v, OP_Pop, 1, 0);
11315 + sqliteVdbeAddOp(v, OP_Goto, 0, dest);
11316 + sqliteExprCode(pParse, pExpr->pList->a[1].pExpr);
11317 + sqliteVdbeAddOp(v, OP_Gt, jumpIfNull, dest);
11321 + sqliteExprCode(pParse, pExpr);
11322 + sqliteVdbeAddOp(v, OP_IfNot, jumpIfNull, dest);
11329 +** Do a deep comparison of two expression trees. Return TRUE (non-zero)
11330 +** if they are identical and return FALSE if they differ in any way.
11332 +int sqliteExprCompare(Expr *pA, Expr *pB){
11336 + }else if( pB==0 ){
11339 + if( pA->op!=pB->op ) return 0;
11340 + if( !sqliteExprCompare(pA->pLeft, pB->pLeft) ) return 0;
11341 + if( !sqliteExprCompare(pA->pRight, pB->pRight) ) return 0;
11343 + if( pB->pList==0 ) return 0;
11344 + if( pA->pList->nExpr!=pB->pList->nExpr ) return 0;
11345 + for(i=0; i<pA->pList->nExpr; i++){
11346 + if( !sqliteExprCompare(pA->pList->a[i].pExpr, pB->pList->a[i].pExpr) ){
11350 + }else if( pB->pList ){
11353 + if( pA->pSelect || pB->pSelect ) return 0;
11354 + if( pA->iTable!=pB->iTable || pA->iColumn!=pB->iColumn ) return 0;
11355 + if( pA->token.z ){
11356 + if( pB->token.z==0 ) return 0;
11357 + if( pB->token.n!=pA->token.n ) return 0;
11358 + if( sqliteStrNICmp(pA->token.z, pB->token.z, pB->token.n)!=0 ) return 0;
11364 +** Add a new element to the pParse->aAgg[] array and return its index.
11366 +static int appendAggInfo(Parse *pParse){
11367 + if( (pParse->nAgg & 0x7)==0 ){
11368 + int amt = pParse->nAgg + 8;
11369 + AggExpr *aAgg = sqliteRealloc(pParse->aAgg, amt*sizeof(pParse->aAgg[0]));
11373 + pParse->aAgg = aAgg;
11375 + memset(&pParse->aAgg[pParse->nAgg], 0, sizeof(pParse->aAgg[0]));
11376 + return pParse->nAgg++;
11380 +** Analyze the given expression looking for aggregate functions and
11381 +** for variables that need to be added to the pParse->aAgg[] array.
11382 +** Make additional entries to the pParse->aAgg[] array as necessary.
11384 +** This routine should only be called after the expression has been
11385 +** analyzed by sqliteExprResolveIds() and sqliteExprCheck().
11387 +** If errors are seen, leave an error message in zErrMsg and return
11388 +** the number of errors.
11390 +int sqliteExprAnalyzeAggregates(Parse *pParse, Expr *pExpr){
11395 + if( pExpr==0 ) return 0;
11396 + switch( pExpr->op ){
11397 + case TK_COLUMN: {
11398 + aAgg = pParse->aAgg;
11399 + for(i=0; i<pParse->nAgg; i++){
11400 + if( aAgg[i].isAgg ) continue;
11401 + if( aAgg[i].pExpr->iTable==pExpr->iTable
11402 + && aAgg[i].pExpr->iColumn==pExpr->iColumn ){
11406 + if( i>=pParse->nAgg ){
11407 + i = appendAggInfo(pParse);
11408 + if( i<0 ) return 1;
11409 + pParse->aAgg[i].isAgg = 0;
11410 + pParse->aAgg[i].pExpr = pExpr;
11415 + case TK_AGG_FUNCTION: {
11416 + aAgg = pParse->aAgg;
11417 + for(i=0; i<pParse->nAgg; i++){
11418 + if( !aAgg[i].isAgg ) continue;
11419 + if( sqliteExprCompare(aAgg[i].pExpr, pExpr) ){
11423 + if( i>=pParse->nAgg ){
11424 + i = appendAggInfo(pParse);
11425 + if( i<0 ) return 1;
11426 + pParse->aAgg[i].isAgg = 1;
11427 + pParse->aAgg[i].pExpr = pExpr;
11428 + pParse->aAgg[i].pFunc = sqliteFindFunction(pParse->db,
11429 + pExpr->token.z, pExpr->token.n,
11430 + pExpr->pList ? pExpr->pList->nExpr : 0, 0);
11436 + if( pExpr->pLeft ){
11437 + nErr = sqliteExprAnalyzeAggregates(pParse, pExpr->pLeft);
11439 + if( nErr==0 && pExpr->pRight ){
11440 + nErr = sqliteExprAnalyzeAggregates(pParse, pExpr->pRight);
11442 + if( nErr==0 && pExpr->pList ){
11443 + int n = pExpr->pList->nExpr;
11445 + for(i=0; nErr==0 && i<n; i++){
11446 + nErr = sqliteExprAnalyzeAggregates(pParse, pExpr->pList->a[i].pExpr);
11456 +** Locate a user function given a name and a number of arguments.
11457 +** Return a pointer to the FuncDef structure that defines that
11458 +** function, or return NULL if the function does not exist.
11460 +** If the createFlag argument is true, then a new (blank) FuncDef
11461 +** structure is created and liked into the "db" structure if a
11462 +** no matching function previously existed. When createFlag is true
11463 +** and the nArg parameter is -1, then only a function that accepts
11464 +** any number of arguments will be returned.
11466 +** If createFlag is false and nArg is -1, then the first valid
11467 +** function found is returned. A function is valid if either xFunc
11468 +** or xStep is non-zero.
11470 +FuncDef *sqliteFindFunction(
11471 + sqlite *db, /* An open database */
11472 + const char *zName, /* Name of the function. Not null-terminated */
11473 + int nName, /* Number of characters in the name */
11474 + int nArg, /* Number of arguments. -1 means any number */
11475 + int createFlag /* Create new entry if true and does not otherwise exist */
11477 + FuncDef *pFirst, *p, *pMaybe;
11478 + pFirst = p = (FuncDef*)sqliteHashFind(&db->aFunc, zName, nName);
11479 + if( p && !createFlag && nArg<0 ){
11480 + while( p && p->xFunc==0 && p->xStep==0 ){ p = p->pNext; }
11484 + while( p && p->nArg!=nArg ){
11485 + if( p->nArg<0 && !createFlag && (p->xFunc || p->xStep) ) pMaybe = p;
11488 + if( p && !createFlag && p->xFunc==0 && p->xStep==0 ){
11491 + if( p==0 && pMaybe ){
11492 + assert( createFlag==0 );
11495 + if( p==0 && createFlag && (p = sqliteMalloc(sizeof(*p)))!=0 ){
11497 + p->pNext = pFirst;
11498 + p->dataType = pFirst ? pFirst->dataType : SQLITE_NUMERIC;
11499 + sqliteHashInsert(&db->aFunc, zName, nName, (void*)p);
11504 +++ b/ext/sqlite/libsqlite/src/func.c
11507 +** 2002 February 23
11509 +** The author disclaims copyright to this source code. In place of
11510 +** a legal notice, here is a blessing:
11512 +** May you do good and not evil.
11513 +** May you find forgiveness for yourself and forgive others.
11514 +** May you share freely, never taking more than you give.
11516 +*************************************************************************
11517 +** This file contains the C functions that implement various SQL
11518 +** functions of SQLite.
11520 +** There is only one exported symbol in this file - the function
11521 +** sqliteRegisterBuildinFunctions() found at the bottom of the file.
11522 +** All other code has file scope.
11526 +#include <ctype.h>
11528 +#include <stdlib.h>
11529 +#include <assert.h>
11530 +#include "sqliteInt.h"
11534 +** Implementation of the non-aggregate min() and max() functions
11536 +static void minmaxFunc(sqlite_func *context, int argc, const char **argv){
11537 + const char *zBest;
11539 + int (*xCompare)(const char*, const char*);
11540 + int mask; /* 0 for min() or 0xffffffff for max() */
11542 + if( argc==0 ) return;
11543 + mask = (int)sqlite_user_data(context);
11545 + if( zBest==0 ) return;
11546 + if( argv[1][0]=='n' ){
11547 + xCompare = sqliteCompare;
11549 + xCompare = strcmp;
11551 + for(i=2; i<argc; i+=2){
11552 + if( argv[i]==0 ) return;
11553 + if( (xCompare(argv[i], zBest)^mask)<0 ){
11557 + sqlite_set_result_string(context, zBest, -1);
11561 +** Return the type of the argument.
11563 +static void typeofFunc(sqlite_func *context, int argc, const char **argv){
11564 + assert( argc==2 );
11565 + sqlite_set_result_string(context, argv[1], -1);
11569 +** Implementation of the length() function
11571 +static void lengthFunc(sqlite_func *context, int argc, const char **argv){
11575 + assert( argc==1 );
11577 + if( z==0 ) return;
11578 +#ifdef SQLITE_UTF8
11579 + for(len=0; *z; z++){ if( (0xc0&*z)!=0x80 ) len++; }
11583 + sqlite_set_result_int(context, len);
11587 +** Implementation of the abs() function
11589 +static void absFunc(sqlite_func *context, int argc, const char **argv){
11591 + assert( argc==1 );
11593 + if( z==0 ) return;
11594 + if( z[0]=='-' && isdigit(z[1]) ) z++;
11595 + sqlite_set_result_string(context, z, -1);
11599 +** Implementation of the substr() function
11601 +static void substrFunc(sqlite_func *context, int argc, const char **argv){
11603 +#ifdef SQLITE_UTF8
11608 + assert( argc==3 );
11610 + if( z==0 ) return;
11611 + p1 = atoi(argv[1]?argv[1]:0);
11612 + p2 = atoi(argv[2]?argv[2]:0);
11613 +#ifdef SQLITE_UTF8
11614 + for(len=0, z2=z; *z2; z2++){ if( (0xc0&*z2)!=0x80 ) len++; }
11624 + }else if( p1>0 ){
11630 +#ifdef SQLITE_UTF8
11631 + for(i=0; i<p1 && z[i]; i++){
11632 + if( (z[i]&0xc0)==0x80 ) p1++;
11634 + while( z[i] && (z[i]&0xc0)==0x80 ){ i++; p1++; }
11635 + for(; i<p1+p2 && z[i]; i++){
11636 + if( (z[i]&0xc0)==0x80 ) p2++;
11638 + while( z[i] && (z[i]&0xc0)==0x80 ){ i++; p2++; }
11640 + if( p2<0 ) p2 = 0;
11641 + sqlite_set_result_string(context, &z[p1], p2);
11645 +** Implementation of the round() function
11647 +static void roundFunc(sqlite_func *context, int argc, const char **argv){
11651 + assert( argc==1 || argc==2 );
11652 + if( argv[0]==0 || (argc==2 && argv[1]==0) ) return;
11653 + n = argc==2 ? atoi(argv[1]) : 0;
11654 + if( n>30 ) n = 30;
11656 + r = sqliteAtoF(argv[0], 0);
11657 + sprintf(zBuf,"%.*f",n,r);
11658 + sqlite_set_result_string(context, zBuf, -1);
11662 +** Implementation of the upper() and lower() SQL functions.
11664 +static void upperFunc(sqlite_func *context, int argc, const char **argv){
11665 + unsigned char *z;
11667 + if( argc<1 || argv[0]==0 ) return;
11668 + z = (unsigned char*)sqlite_set_result_string(context, argv[0], -1);
11669 + if( z==0 ) return;
11670 + for(i=0; z[i]; i++){
11671 + if( islower(z[i]) ) z[i] = toupper(z[i]);
11674 +static void lowerFunc(sqlite_func *context, int argc, const char **argv){
11675 + unsigned char *z;
11677 + if( argc<1 || argv[0]==0 ) return;
11678 + z = (unsigned char*)sqlite_set_result_string(context, argv[0], -1);
11679 + if( z==0 ) return;
11680 + for(i=0; z[i]; i++){
11681 + if( isupper(z[i]) ) z[i] = tolower(z[i]);
11686 +** Implementation of the IFNULL(), NVL(), and COALESCE() functions.
11687 +** All three do the same thing. They return the first non-NULL
11690 +static void ifnullFunc(sqlite_func *context, int argc, const char **argv){
11692 + for(i=0; i<argc; i++){
11694 + sqlite_set_result_string(context, argv[i], -1);
11701 +** Implementation of random(). Return a random integer.
11703 +static void randomFunc(sqlite_func *context, int argc, const char **argv){
11705 + sqliteRandomness(sizeof(r), &r);
11706 + sqlite_set_result_int(context, r);
11710 +** Implementation of the last_insert_rowid() SQL function. The return
11711 +** value is the same as the sqlite_last_insert_rowid() API function.
11713 +static void last_insert_rowid(sqlite_func *context, int arg, const char **argv){
11714 + sqlite *db = sqlite_user_data(context);
11715 + sqlite_set_result_int(context, sqlite_last_insert_rowid(db));
11719 +** Implementation of the change_count() SQL function. The return
11720 +** value is the same as the sqlite_changes() API function.
11722 +static void change_count(sqlite_func *context, int arg, const char **argv){
11723 + sqlite *db = sqlite_user_data(context);
11724 + sqlite_set_result_int(context, sqlite_changes(db));
11728 +** Implementation of the last_statement_change_count() SQL function. The
11729 +** return value is the same as the sqlite_last_statement_changes() API function.
11731 +static void last_statement_change_count(sqlite_func *context, int arg,
11732 + const char **argv){
11733 + sqlite *db = sqlite_user_data(context);
11734 + sqlite_set_result_int(context, sqlite_last_statement_changes(db));
11738 +** Implementation of the like() SQL function. This function implements
11739 +** the build-in LIKE operator. The first argument to the function is the
11740 +** string and the second argument is the pattern. So, the SQL statements:
11744 +** is implemented as like(A,B).
11746 +static void likeFunc(sqlite_func *context, int arg, const char **argv){
11747 + if( argv[0]==0 || argv[1]==0 ) return;
11748 + sqlite_set_result_int(context,
11749 + sqliteLikeCompare((const unsigned char*)argv[0],
11750 + (const unsigned char*)argv[1]));
11754 +** Implementation of the glob() SQL function. This function implements
11755 +** the build-in GLOB operator. The first argument to the function is the
11756 +** string and the second argument is the pattern. So, the SQL statements:
11760 +** is implemented as glob(A,B).
11762 +static void globFunc(sqlite_func *context, int arg, const char **argv){
11763 + if( argv[0]==0 || argv[1]==0 ) return;
11764 + sqlite_set_result_int(context,
11765 + sqliteGlobCompare((const unsigned char*)argv[0],
11766 + (const unsigned char*)argv[1]));
11770 +** Implementation of the NULLIF(x,y) function. The result is the first
11771 +** argument if the arguments are different. The result is NULL if the
11772 +** arguments are equal to each other.
11774 +static void nullifFunc(sqlite_func *context, int argc, const char **argv){
11775 + if( argv[0]!=0 && sqliteCompare(argv[0],argv[1])!=0 ){
11776 + sqlite_set_result_string(context, argv[0], -1);
11781 +** Implementation of the VERSION(*) function. The result is the version
11782 +** of the SQLite library that is running.
11784 +static void versionFunc(sqlite_func *context, int argc, const char **argv){
11785 + sqlite_set_result_string(context, sqlite_version, -1);
11789 +** EXPERIMENTAL - This is not an official function. The interface may
11790 +** change. This function may disappear. Do not write code that depends
11791 +** on this function.
11793 +** Implementation of the QUOTE() function. This function takes a single
11794 +** argument. If the argument is numeric, the return value is the same as
11795 +** the argument. If the argument is NULL, the return value is the string
11796 +** "NULL". Otherwise, the argument is enclosed in single quotes with
11797 +** single-quote escapes.
11799 +static void quoteFunc(sqlite_func *context, int argc, const char **argv){
11800 + if( argc<1 ) return;
11801 + if( argv[0]==0 ){
11802 + sqlite_set_result_string(context, "NULL", 4);
11803 + }else if( sqliteIsNumber(argv[0]) ){
11804 + sqlite_set_result_string(context, argv[0], -1);
11808 + for(i=n=0; argv[0][i]; i++){ if( argv[0][i]=='\'' ) n++; }
11809 + z = sqliteMalloc( i+n+3 );
11810 + if( z==0 ) return;
11812 + for(i=0, j=1; argv[0][i]; i++){
11813 + z[j++] = argv[0][i];
11814 + if( argv[0][i]=='\'' ){
11820 + sqlite_set_result_string(context, z, j);
11825 +#ifdef SQLITE_SOUNDEX
11827 +** Compute the soundex encoding of a word.
11829 +static void soundexFunc(sqlite_func *context, int argc, const char **argv){
11833 + static const unsigned char iCode[] = {
11834 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
11835 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
11836 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
11837 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
11838 + 0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
11839 + 1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
11840 + 0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
11841 + 1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
11843 + assert( argc==1 );
11845 + for(i=0; zIn[i] && !isalpha(zIn[i]); i++){}
11847 + zResult[0] = toupper(zIn[i]);
11848 + for(j=1; j<4 && zIn[i]; i++){
11849 + int code = iCode[zIn[i]&0x7f];
11851 + zResult[j++] = code + '0';
11855 + zResult[j++] = '0';
11858 + sqlite_set_result_string(context, zResult, 4);
11860 + sqlite_set_result_string(context, "?000", 4);
11865 +#ifdef SQLITE_TEST
11867 +** This function generates a string of random characters. Used for
11868 +** generating test data.
11870 +static void randStr(sqlite_func *context, int argc, const char **argv){
11871 + static const unsigned char zSrc[] =
11872 + "abcdefghijklmnopqrstuvwxyz"
11873 + "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
11875 + ".-!,:*^+=_|?/<> ";
11876 + int iMin, iMax, n, r, i;
11877 + unsigned char zBuf[1000];
11879 + iMin = atoi(argv[0]);
11880 + if( iMin<0 ) iMin = 0;
11881 + if( iMin>=sizeof(zBuf) ) iMin = sizeof(zBuf)-1;
11886 + iMax = atoi(argv[1]);
11887 + if( iMax<iMin ) iMax = iMin;
11888 + if( iMax>=sizeof(zBuf) ) iMax = sizeof(zBuf)-1;
11894 + sqliteRandomness(sizeof(r), &r);
11896 + n += r%(iMax + 1 - iMin);
11898 + assert( n<sizeof(zBuf) );
11899 + sqliteRandomness(n, zBuf);
11900 + for(i=0; i<n; i++){
11901 + zBuf[i] = zSrc[zBuf[i]%(sizeof(zSrc)-1)];
11904 + sqlite_set_result_string(context, zBuf, n);
11909 +** An instance of the following structure holds the context of a
11910 +** sum() or avg() aggregate computation.
11912 +typedef struct SumCtx SumCtx;
11914 + double sum; /* Sum of terms */
11915 + int cnt; /* Number of elements summed */
11919 +** Routines used to compute the sum or average.
11921 +static void sumStep(sqlite_func *context, int argc, const char **argv){
11923 + if( argc<1 ) return;
11924 + p = sqlite_aggregate_context(context, sizeof(*p));
11925 + if( p && argv[0] ){
11926 + p->sum += sqliteAtoF(argv[0], 0);
11930 +static void sumFinalize(sqlite_func *context){
11932 + p = sqlite_aggregate_context(context, sizeof(*p));
11933 + sqlite_set_result_double(context, p ? p->sum : 0.0);
11935 +static void avgFinalize(sqlite_func *context){
11937 + p = sqlite_aggregate_context(context, sizeof(*p));
11938 + if( p && p->cnt>0 ){
11939 + sqlite_set_result_double(context, p->sum/(double)p->cnt);
11944 +** An instance of the following structure holds the context of a
11945 +** variance or standard deviation computation.
11947 +typedef struct StdDevCtx StdDevCtx;
11948 +struct StdDevCtx {
11949 + double sum; /* Sum of terms */
11950 + double sum2; /* Sum of the squares of terms */
11951 + int cnt; /* Number of terms counted */
11954 +#if 0 /* Omit because math library is required */
11956 +** Routines used to compute the standard deviation as an aggregate.
11958 +static void stdDevStep(sqlite_func *context, int argc, const char **argv){
11961 + if( argc<1 ) return;
11962 + p = sqlite_aggregate_context(context, sizeof(*p));
11963 + if( p && argv[0] ){
11964 + x = sqliteAtoF(argv[0], 0);
11970 +static void stdDevFinalize(sqlite_func *context){
11971 + double rN = sqlite_aggregate_count(context);
11972 + StdDevCtx *p = sqlite_aggregate_context(context, sizeof(*p));
11973 + if( p && p->cnt>1 ){
11974 + double rCnt = cnt;
11975 + sqlite_set_result_double(context,
11976 + sqrt((p->sum2 - p->sum*p->sum/rCnt)/(rCnt-1.0)));
11982 +** The following structure keeps track of state information for the
11983 +** count() aggregate function.
11985 +typedef struct CountCtx CountCtx;
11991 +** Routines to implement the count() aggregate function.
11993 +static void countStep(sqlite_func *context, int argc, const char **argv){
11995 + p = sqlite_aggregate_context(context, sizeof(*p));
11996 + if( (argc==0 || argv[0]) && p ){
12000 +static void countFinalize(sqlite_func *context){
12002 + p = sqlite_aggregate_context(context, sizeof(*p));
12003 + sqlite_set_result_int(context, p ? p->n : 0);
12007 +** This function tracks state information for the min() and max()
12008 +** aggregate functions.
12010 +typedef struct MinMaxCtx MinMaxCtx;
12011 +struct MinMaxCtx {
12012 + char *z; /* The best so far */
12013 + char zBuf[28]; /* Space that can be used for storage */
12017 +** Routines to implement min() and max() aggregate functions.
12019 +static void minmaxStep(sqlite_func *context, int argc, const char **argv){
12021 + int (*xCompare)(const char*, const char*);
12022 + int mask; /* 0 for min() or 0xffffffff for max() */
12024 + assert( argc==2 );
12025 + if( argv[0]==0 ) return; /* Ignore NULL values */
12026 + if( argv[1][0]=='n' ){
12027 + xCompare = sqliteCompare;
12029 + xCompare = strcmp;
12031 + mask = (int)sqlite_user_data(context);
12032 + assert( mask==0 || mask==-1 );
12033 + p = sqlite_aggregate_context(context, sizeof(*p));
12034 + if( p==0 || argc<1 ) return;
12035 + if( p->z==0 || (xCompare(argv[0],p->z)^mask)<0 ){
12037 + if( p->zBuf[0] ){
12038 + sqliteFree(p->z);
12040 + len = strlen(argv[0]);
12041 + if( len < sizeof(p->zBuf)-1 ){
12042 + p->z = &p->zBuf[1];
12045 + p->z = sqliteMalloc( len+1 );
12047 + if( p->z==0 ) return;
12049 + strcpy(p->z, argv[0]);
12052 +static void minMaxFinalize(sqlite_func *context){
12054 + p = sqlite_aggregate_context(context, sizeof(*p));
12055 + if( p && p->z && p->zBuf[0]<2 ){
12056 + sqlite_set_result_string(context, p->z, strlen(p->z));
12058 + if( p && p->zBuf[0] ){
12059 + sqliteFree(p->z);
12064 +** This function registered all of the above C functions as SQL
12065 +** functions. This should be the only routine in this file with
12066 +** external linkage.
12068 +void sqliteRegisterBuiltinFunctions(sqlite *db){
12071 + signed char nArg;
12072 + signed char dataType;
12073 + u8 argType; /* 0: none. 1: db 2: (-1) */
12074 + void (*xFunc)(sqlite_func*,int,const char**);
12076 + { "min", -1, SQLITE_ARGS, 0, minmaxFunc },
12077 + { "min", 0, 0, 0, 0 },
12078 + { "max", -1, SQLITE_ARGS, 2, minmaxFunc },
12079 + { "max", 0, 0, 2, 0 },
12080 + { "typeof", 1, SQLITE_TEXT, 0, typeofFunc },
12081 + { "length", 1, SQLITE_NUMERIC, 0, lengthFunc },
12082 + { "substr", 3, SQLITE_TEXT, 0, substrFunc },
12083 + { "abs", 1, SQLITE_NUMERIC, 0, absFunc },
12084 + { "round", 1, SQLITE_NUMERIC, 0, roundFunc },
12085 + { "round", 2, SQLITE_NUMERIC, 0, roundFunc },
12086 + { "upper", 1, SQLITE_TEXT, 0, upperFunc },
12087 + { "lower", 1, SQLITE_TEXT, 0, lowerFunc },
12088 + { "coalesce", -1, SQLITE_ARGS, 0, ifnullFunc },
12089 + { "coalesce", 0, 0, 0, 0 },
12090 + { "coalesce", 1, 0, 0, 0 },
12091 + { "ifnull", 2, SQLITE_ARGS, 0, ifnullFunc },
12092 + { "random", -1, SQLITE_NUMERIC, 0, randomFunc },
12093 + { "like", 2, SQLITE_NUMERIC, 0, likeFunc },
12094 + { "glob", 2, SQLITE_NUMERIC, 0, globFunc },
12095 + { "nullif", 2, SQLITE_ARGS, 0, nullifFunc },
12096 + { "sqlite_version",0,SQLITE_TEXT, 0, versionFunc},
12097 + { "quote", 1, SQLITE_ARGS, 0, quoteFunc },
12098 + { "last_insert_rowid", 0, SQLITE_NUMERIC, 1, last_insert_rowid },
12099 + { "change_count", 0, SQLITE_NUMERIC, 1, change_count },
12100 + { "last_statement_change_count",
12101 + 0, SQLITE_NUMERIC, 1, last_statement_change_count },
12102 +#ifdef SQLITE_SOUNDEX
12103 + { "soundex", 1, SQLITE_TEXT, 0, soundexFunc},
12105 +#ifdef SQLITE_TEST
12106 + { "randstr", 2, SQLITE_TEXT, 0, randStr },
12111 + signed char nArg;
12112 + signed char dataType;
12114 + void (*xStep)(sqlite_func*,int,const char**);
12115 + void (*xFinalize)(sqlite_func*);
12117 + { "min", 1, 0, 0, minmaxStep, minMaxFinalize },
12118 + { "max", 1, 0, 2, minmaxStep, minMaxFinalize },
12119 + { "sum", 1, SQLITE_NUMERIC, 0, sumStep, sumFinalize },
12120 + { "avg", 1, SQLITE_NUMERIC, 0, sumStep, avgFinalize },
12121 + { "count", 0, SQLITE_NUMERIC, 0, countStep, countFinalize },
12122 + { "count", 1, SQLITE_NUMERIC, 0, countStep, countFinalize },
12124 + { "stddev", 1, SQLITE_NUMERIC, 0, stdDevStep, stdDevFinalize },
12127 + static const char *azTypeFuncs[] = { "min", "max", "typeof" };
12130 + for(i=0; i<sizeof(aFuncs)/sizeof(aFuncs[0]); i++){
12132 + switch( aFuncs[i].argType ){
12133 + case 0: pArg = 0; break;
12134 + case 1: pArg = db; break;
12135 + case 2: pArg = (void*)(-1); break;
12137 + sqlite_create_function(db, aFuncs[i].zName,
12138 + aFuncs[i].nArg, aFuncs[i].xFunc, pArg);
12139 + if( aFuncs[i].xFunc ){
12140 + sqlite_function_type(db, aFuncs[i].zName, aFuncs[i].dataType);
12143 + for(i=0; i<sizeof(aAggs)/sizeof(aAggs[0]); i++){
12145 + switch( aAggs[i].argType ){
12146 + case 0: pArg = 0; break;
12147 + case 1: pArg = db; break;
12148 + case 2: pArg = (void*)(-1); break;
12150 + sqlite_create_aggregate(db, aAggs[i].zName,
12151 + aAggs[i].nArg, aAggs[i].xStep, aAggs[i].xFinalize, pArg);
12152 + sqlite_function_type(db, aAggs[i].zName, aAggs[i].dataType);
12154 + for(i=0; i<sizeof(azTypeFuncs)/sizeof(azTypeFuncs[0]); i++){
12155 + int n = strlen(azTypeFuncs[i]);
12156 + FuncDef *p = sqliteHashFind(&db->aFunc, azTypeFuncs[i], n);
12158 + p->includeTypes = 1;
12162 + sqliteRegisterDateTimeFunctions(db);
12165 +++ b/ext/sqlite/libsqlite/src/hash.c
12168 +** 2001 September 22
12170 +** The author disclaims copyright to this source code. In place of
12171 +** a legal notice, here is a blessing:
12173 +** May you do good and not evil.
12174 +** May you find forgiveness for yourself and forgive others.
12175 +** May you share freely, never taking more than you give.
12177 +*************************************************************************
12178 +** This is the implementation of generic hash-tables
12179 +** used in SQLite.
12183 +#include "sqliteInt.h"
12184 +#include <assert.h>
12186 +/* Turn bulk memory into a hash table object by initializing the
12187 +** fields of the Hash structure.
12189 +** "new" is a pointer to the hash table that is to be initialized.
12190 +** keyClass is one of the constants SQLITE_HASH_INT, SQLITE_HASH_POINTER,
12191 +** SQLITE_HASH_BINARY, or SQLITE_HASH_STRING. The value of keyClass
12192 +** determines what kind of key the hash table will use. "copyKey" is
12193 +** true if the hash table should make its own private copy of keys and
12194 +** false if it should just use the supplied pointer. CopyKey only makes
12195 +** sense for SQLITE_HASH_STRING and SQLITE_HASH_BINARY and is ignored
12196 +** for other key classes.
12198 +void sqliteHashInit(Hash *new, int keyClass, int copyKey){
12199 + assert( new!=0 );
12200 + assert( keyClass>=SQLITE_HASH_INT && keyClass<=SQLITE_HASH_BINARY );
12201 + new->keyClass = keyClass;
12202 + new->copyKey = copyKey &&
12203 + (keyClass==SQLITE_HASH_STRING || keyClass==SQLITE_HASH_BINARY);
12210 +/* Remove all entries from a hash table. Reclaim all memory.
12211 +** Call this routine to delete a hash table or to reset a hash table
12212 +** to the empty state.
12214 +void sqliteHashClear(Hash *pH){
12215 + HashElem *elem; /* For looping over all elements of the table */
12218 + elem = pH->first;
12220 + if( pH->ht ) sqliteFree(pH->ht);
12224 + HashElem *next_elem = elem->next;
12225 + if( pH->copyKey && elem->pKey ){
12226 + sqliteFree(elem->pKey);
12228 + sqliteFree(elem);
12229 + elem = next_elem;
12235 +** Hash and comparison functions when the mode is SQLITE_HASH_INT
12237 +static int intHash(const void *pKey, int nKey){
12238 + return nKey ^ (nKey<<8) ^ (nKey>>8);
12240 +static int intCompare(const void *pKey1, int n1, const void *pKey2, int n2){
12244 +#if 0 /* NOT USED */
12246 +** Hash and comparison functions when the mode is SQLITE_HASH_POINTER
12248 +static int ptrHash(const void *pKey, int nKey){
12249 + uptr x = Addr(pKey);
12250 + return x ^ (x<<8) ^ (x>>8);
12252 +static int ptrCompare(const void *pKey1, int n1, const void *pKey2, int n2){
12253 + if( pKey1==pKey2 ) return 0;
12254 + if( pKey1<pKey2 ) return -1;
12260 +** Hash and comparison functions when the mode is SQLITE_HASH_STRING
12262 +static int strHash(const void *pKey, int nKey){
12263 + return sqliteHashNoCase((const char*)pKey, nKey);
12265 +static int strCompare(const void *pKey1, int n1, const void *pKey2, int n2){
12266 + if( n1!=n2 ) return n2-n1;
12267 + return sqliteStrNICmp((const char*)pKey1,(const char*)pKey2,n1);
12271 +** Hash and comparison functions when the mode is SQLITE_HASH_BINARY
12273 +static int binHash(const void *pKey, int nKey){
12275 + const char *z = (const char *)pKey;
12276 + while( nKey-- > 0 ){
12277 + h = (h<<3) ^ h ^ *(z++);
12279 + return h & 0x7fffffff;
12281 +static int binCompare(const void *pKey1, int n1, const void *pKey2, int n2){
12282 + if( n1!=n2 ) return n2-n1;
12283 + return memcmp(pKey1,pKey2,n1);
12287 +** Return a pointer to the appropriate hash function given the key class.
12289 +** The C syntax in this function definition may be unfamilar to some
12290 +** programmers, so we provide the following additional explanation:
12292 +** The name of the function is "hashFunction". The function takes a
12293 +** single parameter "keyClass". The return value of hashFunction()
12294 +** is a pointer to another function. Specifically, the return value
12295 +** of hashFunction() is a pointer to a function that takes two parameters
12296 +** with types "const void*" and "int" and returns an "int".
12298 +static int (*hashFunction(int keyClass))(const void*,int){
12299 + switch( keyClass ){
12300 + case SQLITE_HASH_INT: return &intHash;
12301 + /* case SQLITE_HASH_POINTER: return &ptrHash; // NOT USED */
12302 + case SQLITE_HASH_STRING: return &strHash;
12303 + case SQLITE_HASH_BINARY: return &binHash;;
12310 +** Return a pointer to the appropriate hash function given the key class.
12312 +** For help in interpreted the obscure C code in the function definition,
12313 +** see the header comment on the previous function.
12315 +static int (*compareFunction(int keyClass))(const void*,int,const void*,int){
12316 + switch( keyClass ){
12317 + case SQLITE_HASH_INT: return &intCompare;
12318 + /* case SQLITE_HASH_POINTER: return &ptrCompare; // NOT USED */
12319 + case SQLITE_HASH_STRING: return &strCompare;
12320 + case SQLITE_HASH_BINARY: return &binCompare;
12327 +/* Resize the hash table so that it cantains "new_size" buckets.
12328 +** "new_size" must be a power of 2. The hash table might fail
12329 +** to resize if sqliteMalloc() fails.
12331 +static void rehash(Hash *pH, int new_size){
12332 + struct _ht *new_ht; /* The new hash table */
12333 + HashElem *elem, *next_elem; /* For looping over existing elements */
12334 + HashElem *x; /* Element being copied to new hash table */
12335 + int (*xHash)(const void*,int); /* The hash function */
12337 + assert( (new_size & (new_size-1))==0 );
12338 + new_ht = (struct _ht *)sqliteMalloc( new_size*sizeof(struct _ht) );
12339 + if( new_ht==0 ) return;
12340 + if( pH->ht ) sqliteFree(pH->ht);
12342 + pH->htsize = new_size;
12343 + xHash = hashFunction(pH->keyClass);
12344 + for(elem=pH->first, pH->first=0; elem; elem = next_elem){
12345 + int h = (*xHash)(elem->pKey, elem->nKey) & (new_size-1);
12346 + next_elem = elem->next;
12347 + x = new_ht[h].chain;
12350 + elem->prev = x->prev;
12351 + if( x->prev ) x->prev->next = elem;
12352 + else pH->first = elem;
12355 + elem->next = pH->first;
12356 + if( pH->first ) pH->first->prev = elem;
12358 + pH->first = elem;
12360 + new_ht[h].chain = elem;
12361 + new_ht[h].count++;
12365 +/* This function (for internal use only) locates an element in an
12366 +** hash table that matches the given key. The hash for this key has
12367 +** already been computed and is passed as the 4th parameter.
12369 +static HashElem *findElementGivenHash(
12370 + const Hash *pH, /* The pH to be searched */
12371 + const void *pKey, /* The key we are searching for */
12373 + int h /* The hash for this key. */
12375 + HashElem *elem; /* Used to loop thru the element list */
12376 + int count; /* Number of elements left to test */
12377 + int (*xCompare)(const void*,int,const void*,int); /* comparison function */
12380 + elem = pH->ht[h].chain;
12381 + count = pH->ht[h].count;
12382 + xCompare = compareFunction(pH->keyClass);
12383 + while( count-- && elem ){
12384 + if( (*xCompare)(elem->pKey,elem->nKey,pKey,nKey)==0 ){
12387 + elem = elem->next;
12393 +/* Remove a single entry from the hash table given a pointer to that
12394 +** element and a hash on the element's key.
12396 +static void removeElementGivenHash(
12397 + Hash *pH, /* The pH containing "elem" */
12398 + HashElem* elem, /* The element to be removed from the pH */
12399 + int h /* Hash value for the element */
12401 + if( elem->prev ){
12402 + elem->prev->next = elem->next;
12404 + pH->first = elem->next;
12406 + if( elem->next ){
12407 + elem->next->prev = elem->prev;
12409 + if( pH->ht[h].chain==elem ){
12410 + pH->ht[h].chain = elem->next;
12412 + pH->ht[h].count--;
12413 + if( pH->ht[h].count<=0 ){
12414 + pH->ht[h].chain = 0;
12416 + if( pH->copyKey && elem->pKey ){
12417 + sqliteFree(elem->pKey);
12419 + sqliteFree( elem );
12423 +/* Attempt to locate an element of the hash table pH with a key
12424 +** that matches pKey,nKey. Return the data for this element if it is
12425 +** found, or NULL if there is no match.
12427 +void *sqliteHashFind(const Hash *pH, const void *pKey, int nKey){
12428 + int h; /* A hash on key */
12429 + HashElem *elem; /* The element that matches key */
12430 + int (*xHash)(const void*,int); /* The hash function */
12432 + if( pH==0 || pH->ht==0 ) return 0;
12433 + xHash = hashFunction(pH->keyClass);
12434 + assert( xHash!=0 );
12435 + h = (*xHash)(pKey,nKey);
12436 + assert( (pH->htsize & (pH->htsize-1))==0 );
12437 + elem = findElementGivenHash(pH,pKey,nKey, h & (pH->htsize-1));
12438 + return elem ? elem->data : 0;
12441 +/* Insert an element into the hash table pH. The key is pKey,nKey
12442 +** and the data is "data".
12444 +** If no element exists with a matching key, then a new
12445 +** element is created. A copy of the key is made if the copyKey
12446 +** flag is set. NULL is returned.
12448 +** If another element already exists with the same key, then the
12449 +** new data replaces the old data and the old data is returned.
12450 +** The key is not copied in this instance. If a malloc fails, then
12451 +** the new data is returned and the hash table is unchanged.
12453 +** If the "data" parameter to this function is NULL, then the
12454 +** element corresponding to "key" is removed from the hash table.
12456 +void *sqliteHashInsert(Hash *pH, const void *pKey, int nKey, void *data){
12457 + int hraw; /* Raw hash value of the key */
12458 + int h; /* the hash of the key modulo hash table size */
12459 + HashElem *elem; /* Used to loop thru the element list */
12460 + HashElem *new_elem; /* New element added to the pH */
12461 + int (*xHash)(const void*,int); /* The hash function */
12464 + xHash = hashFunction(pH->keyClass);
12465 + assert( xHash!=0 );
12466 + hraw = (*xHash)(pKey, nKey);
12467 + assert( (pH->htsize & (pH->htsize-1))==0 );
12468 + h = hraw & (pH->htsize-1);
12469 + elem = findElementGivenHash(pH,pKey,nKey,h);
12471 + void *old_data = elem->data;
12473 + removeElementGivenHash(pH,elem,h);
12475 + elem->data = data;
12479 + if( data==0 ) return 0;
12480 + new_elem = (HashElem*)sqliteMalloc( sizeof(HashElem) );
12481 + if( new_elem==0 ) return data;
12482 + if( pH->copyKey && pKey!=0 ){
12483 + new_elem->pKey = sqliteMallocRaw( nKey );
12484 + if( new_elem->pKey==0 ){
12485 + sqliteFree(new_elem);
12488 + memcpy((void*)new_elem->pKey, pKey, nKey);
12490 + new_elem->pKey = (void*)pKey;
12492 + new_elem->nKey = nKey;
12494 + if( pH->htsize==0 ) rehash(pH,8);
12495 + if( pH->htsize==0 ){
12497 + sqliteFree(new_elem);
12500 + if( pH->count > pH->htsize ){
12501 + rehash(pH,pH->htsize*2);
12503 + assert( (pH->htsize & (pH->htsize-1))==0 );
12504 + h = hraw & (pH->htsize-1);
12505 + elem = pH->ht[h].chain;
12507 + new_elem->next = elem;
12508 + new_elem->prev = elem->prev;
12509 + if( elem->prev ){ elem->prev->next = new_elem; }
12510 + else { pH->first = new_elem; }
12511 + elem->prev = new_elem;
12513 + new_elem->next = pH->first;
12514 + new_elem->prev = 0;
12515 + if( pH->first ){ pH->first->prev = new_elem; }
12516 + pH->first = new_elem;
12518 + pH->ht[h].count++;
12519 + pH->ht[h].chain = new_elem;
12520 + new_elem->data = data;
12524 +++ b/ext/sqlite/libsqlite/src/hash.h
12527 +** 2001 September 22
12529 +** The author disclaims copyright to this source code. In place of
12530 +** a legal notice, here is a blessing:
12532 +** May you do good and not evil.
12533 +** May you find forgiveness for yourself and forgive others.
12534 +** May you share freely, never taking more than you give.
12536 +*************************************************************************
12537 +** This is the header file for the generic hash-table implemenation
12538 +** used in SQLite.
12542 +#ifndef _SQLITE_HASH_H_
12543 +#define _SQLITE_HASH_H_
12545 +/* Forward declarations of structures. */
12546 +typedef struct Hash Hash;
12547 +typedef struct HashElem HashElem;
12549 +/* A complete hash table is an instance of the following structure.
12550 +** The internals of this structure are intended to be opaque -- client
12551 +** code should not attempt to access or modify the fields of this structure
12552 +** directly. Change this structure only by using the routines below.
12553 +** However, many of the "procedures" and "functions" for modifying and
12554 +** accessing this structure are really macros, so we can't really make
12555 +** this structure opaque.
12558 + char keyClass; /* SQLITE_HASH_INT, _POINTER, _STRING, _BINARY */
12559 + char copyKey; /* True if copy of key made on insert */
12560 + int count; /* Number of entries in this table */
12561 + HashElem *first; /* The first element of the array */
12562 + int htsize; /* Number of buckets in the hash table */
12563 + struct _ht { /* the hash table */
12564 + int count; /* Number of entries with this hash */
12565 + HashElem *chain; /* Pointer to first entry with this hash */
12569 +/* Each element in the hash table is an instance of the following
12570 +** structure. All elements are stored on a single doubly-linked list.
12572 +** Again, this structure is intended to be opaque, but it can't really
12573 +** be opaque because it is used by macros.
12576 + HashElem *next, *prev; /* Next and previous elements in the table */
12577 + void *data; /* Data associated with this element */
12578 + void *pKey; int nKey; /* Key associated with this element */
12582 +** There are 4 different modes of operation for a hash table:
12584 +** SQLITE_HASH_INT nKey is used as the key and pKey is ignored.
12586 +** SQLITE_HASH_POINTER pKey is used as the key and nKey is ignored.
12588 +** SQLITE_HASH_STRING pKey points to a string that is nKey bytes long
12589 +** (including the null-terminator, if any). Case
12590 +** is ignored in comparisons.
12592 +** SQLITE_HASH_BINARY pKey points to binary data nKey bytes long.
12593 +** memcmp() is used to compare keys.
12595 +** A copy of the key is made for SQLITE_HASH_STRING and SQLITE_HASH_BINARY
12596 +** if the copyKey parameter to HashInit is 1.
12598 +#define SQLITE_HASH_INT 1
12599 +/* #define SQLITE_HASH_POINTER 2 // NOT USED */
12600 +#define SQLITE_HASH_STRING 3
12601 +#define SQLITE_HASH_BINARY 4
12604 +** Access routines. To delete, insert a NULL pointer.
12606 +void sqliteHashInit(Hash*, int keytype, int copyKey);
12607 +void *sqliteHashInsert(Hash*, const void *pKey, int nKey, void *pData);
12608 +void *sqliteHashFind(const Hash*, const void *pKey, int nKey);
12609 +void sqliteHashClear(Hash*);
12612 +** Macros for looping over all elements of a hash table. The idiom is
12618 +** for(p=sqliteHashFirst(&h); p; p=sqliteHashNext(p)){
12619 +** SomeStructure *pData = sqliteHashData(p);
12620 +** // do something with pData
12623 +#define sqliteHashFirst(H) ((H)->first)
12624 +#define sqliteHashNext(E) ((E)->next)
12625 +#define sqliteHashData(E) ((E)->data)
12626 +#define sqliteHashKey(E) ((E)->pKey)
12627 +#define sqliteHashKeysize(E) ((E)->nKey)
12630 +** Number of entries in a hash table
12632 +#define sqliteHashCount(H) ((H)->count)
12634 +#endif /* _SQLITE_HASH_H_ */
12636 +++ b/ext/sqlite/libsqlite/src/insert.c
12639 +** 2001 September 15
12641 +** The author disclaims copyright to this source code. In place of
12642 +** a legal notice, here is a blessing:
12644 +** May you do good and not evil.
12645 +** May you find forgiveness for yourself and forgive others.
12646 +** May you share freely, never taking more than you give.
12648 +*************************************************************************
12649 +** This file contains C code routines that are called by the parser
12650 +** to handle INSERT statements in SQLite.
12654 +#include "sqliteInt.h"
12657 +** This routine is call to handle SQL of the following forms:
12659 +** insert into TABLE (IDLIST) values(EXPRLIST)
12660 +** insert into TABLE (IDLIST) select
12662 +** The IDLIST following the table name is always optional. If omitted,
12663 +** then a list of all columns for the table is substituted. The IDLIST
12664 +** appears in the pColumn parameter. pColumn is NULL if IDLIST is omitted.
12666 +** The pList parameter holds EXPRLIST in the first form of the INSERT
12667 +** statement above, and pSelect is NULL. For the second form, pList is
12668 +** NULL and pSelect is a pointer to the select statement used to generate
12669 +** data for the insert.
12671 +** The code generated follows one of three templates. For a simple
12672 +** select with data coming from a VALUES clause, the code executes
12673 +** once straight down through. The template looks like this:
12675 +** open write cursor to <table> and its indices
12676 +** puts VALUES clause expressions onto the stack
12677 +** write the resulting record into <table>
12680 +** If the statement is of the form
12682 +** INSERT INTO <table> SELECT ...
12684 +** And the SELECT clause does not read from <table> at any time, then
12685 +** the generated code follows this template:
12688 +** A: setup for the SELECT
12689 +** loop over the tables in the SELECT
12692 +** cleanup after the SELECT
12694 +** B: open write cursor to <table> and its indices
12696 +** C: insert the select result into <table>
12700 +** The third template is used if the insert statement takes its
12701 +** values from a SELECT but the data is being inserted into a table
12702 +** that is also read as part of the SELECT. In the third form,
12703 +** we have to use a intermediate table to store the results of
12704 +** the select. The template is like this:
12707 +** A: setup for the SELECT
12708 +** loop over the tables in the SELECT
12711 +** cleanup after the SELECT
12713 +** C: insert the select result into the intermediate table
12715 +** B: open a cursor to an intermediate table
12717 +** D: open write cursor to <table> and its indices
12718 +** loop over the intermediate table
12719 +** transfer values form intermediate table into <table>
12723 +void sqliteInsert(
12724 + Parse *pParse, /* Parser context */
12725 + SrcList *pTabList, /* Name of table into which we are inserting */
12726 + ExprList *pList, /* List of values to be inserted */
12727 + Select *pSelect, /* A SELECT statement to use as the data source */
12728 + IdList *pColumn, /* Column names corresponding to IDLIST. */
12729 + int onError /* How to handle constraint errors */
12731 + Table *pTab; /* The table to insert into */
12732 + char *zTab; /* Name of the table into which we are inserting */
12733 + const char *zDb; /* Name of the database holding this table */
12734 + int i, j, idx; /* Loop counters */
12735 + Vdbe *v; /* Generate code into this virtual machine */
12736 + Index *pIdx; /* For looping over indices of the table */
12737 + int nColumn; /* Number of columns in the data */
12738 + int base; /* VDBE Cursor number for pTab */
12739 + int iCont, iBreak; /* Beginning and end of the loop over srcTab */
12740 + sqlite *db; /* The main database structure */
12741 + int keyColumn = -1; /* Column that is the INTEGER PRIMARY KEY */
12742 + int endOfLoop; /* Label for the end of the insertion loop */
12743 + int useTempTable; /* Store SELECT results in intermediate table */
12744 + int srcTab; /* Data comes from this temporary cursor if >=0 */
12745 + int iSelectLoop; /* Address of code that implements the SELECT */
12746 + int iCleanup; /* Address of the cleanup code */
12747 + int iInsertBlock; /* Address of the subroutine used to insert data */
12748 + int iCntMem; /* Memory cell used for the row counter */
12749 + int isView; /* True if attempting to insert into a view */
12751 + int row_triggers_exist = 0; /* True if there are FOR EACH ROW triggers */
12752 + int before_triggers; /* True if there are BEFORE triggers */
12753 + int after_triggers; /* True if there are AFTER triggers */
12754 + int newIdx = -1; /* Cursor for the NEW table */
12756 + if( pParse->nErr || sqlite_malloc_failed ) goto insert_cleanup;
12759 + /* Locate the table into which we will be inserting new information.
12761 + assert( pTabList->nSrc==1 );
12762 + zTab = pTabList->a[0].zName;
12763 + if( zTab==0 ) goto insert_cleanup;
12764 + pTab = sqliteSrcListLookup(pParse, pTabList);
12766 + goto insert_cleanup;
12768 + assert( pTab->iDb<db->nDb );
12769 + zDb = db->aDb[pTab->iDb].zName;
12770 + if( sqliteAuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){
12771 + goto insert_cleanup;
12775 + * (a) the table is not read-only,
12776 + * (b) that if it is a view then ON INSERT triggers exist
12778 + before_triggers = sqliteTriggersExist(pParse, pTab->pTrigger, TK_INSERT,
12779 + TK_BEFORE, TK_ROW, 0);
12780 + after_triggers = sqliteTriggersExist(pParse, pTab->pTrigger, TK_INSERT,
12781 + TK_AFTER, TK_ROW, 0);
12782 + row_triggers_exist = before_triggers || after_triggers;
12783 + isView = pTab->pSelect!=0;
12784 + if( sqliteIsReadOnly(pParse, pTab, before_triggers) ){
12785 + goto insert_cleanup;
12787 + if( pTab==0 ) goto insert_cleanup;
12789 + /* If pTab is really a view, make sure it has been initialized.
12791 + if( isView && sqliteViewGetColumnNames(pParse, pTab) ){
12792 + goto insert_cleanup;
12795 + /* Allocate a VDBE
12797 + v = sqliteGetVdbe(pParse);
12798 + if( v==0 ) goto insert_cleanup;
12799 + sqliteBeginWriteOperation(pParse, pSelect || row_triggers_exist, pTab->iDb);
12801 + /* if there are row triggers, allocate a temp table for new.* references. */
12802 + if( row_triggers_exist ){
12803 + newIdx = pParse->nTab++;
12806 + /* Figure out how many columns of data are supplied. If the data
12807 + ** is coming from a SELECT statement, then this step also generates
12808 + ** all the code to implement the SELECT statement and invoke a subroutine
12809 + ** to process each row of the result. (Template 2.) If the SELECT
12810 + ** statement uses the the table that is being inserted into, then the
12811 + ** subroutine is also coded here. That subroutine stores the SELECT
12812 + ** results in a temporary table. (Template 3.)
12815 + /* Data is coming from a SELECT. Generate code to implement that SELECT
12817 + int rc, iInitCode;
12818 + iInitCode = sqliteVdbeAddOp(v, OP_Goto, 0, 0);
12819 + iSelectLoop = sqliteVdbeCurrentAddr(v);
12820 + iInsertBlock = sqliteVdbeMakeLabel(v);
12821 + rc = sqliteSelect(pParse, pSelect, SRT_Subroutine, iInsertBlock, 0,0,0);
12822 + if( rc || pParse->nErr || sqlite_malloc_failed ) goto insert_cleanup;
12823 + iCleanup = sqliteVdbeMakeLabel(v);
12824 + sqliteVdbeAddOp(v, OP_Goto, 0, iCleanup);
12825 + assert( pSelect->pEList );
12826 + nColumn = pSelect->pEList->nExpr;
12828 + /* Set useTempTable to TRUE if the result of the SELECT statement
12829 + ** should be written into a temporary table. Set to FALSE if each
12830 + ** row of the SELECT can be written directly into the result table.
12832 + ** A temp table must be used if the table being updated is also one
12833 + ** of the tables being read by the SELECT statement. Also use a
12834 + ** temp table in the case of row triggers.
12836 + if( row_triggers_exist ){
12837 + useTempTable = 1;
12839 + int addr = sqliteVdbeFindOp(v, OP_OpenRead, pTab->tnum);
12840 + useTempTable = 0;
12842 + VdbeOp *pOp = sqliteVdbeGetOp(v, addr-2);
12843 + if( pOp->opcode==OP_Integer && pOp->p1==pTab->iDb ){
12844 + useTempTable = 1;
12849 + if( useTempTable ){
12850 + /* Generate the subroutine that SELECT calls to process each row of
12851 + ** the result. Store the result in a temporary table
12853 + srcTab = pParse->nTab++;
12854 + sqliteVdbeResolveLabel(v, iInsertBlock);
12855 + sqliteVdbeAddOp(v, OP_MakeRecord, nColumn, 0);
12856 + sqliteVdbeAddOp(v, OP_NewRecno, srcTab, 0);
12857 + sqliteVdbeAddOp(v, OP_Pull, 1, 0);
12858 + sqliteVdbeAddOp(v, OP_PutIntKey, srcTab, 0);
12859 + sqliteVdbeAddOp(v, OP_Return, 0, 0);
12861 + /* The following code runs first because the GOTO at the very top
12862 + ** of the program jumps to it. Create the temporary table, then jump
12863 + ** back up and execute the SELECT code above.
12865 + sqliteVdbeChangeP2(v, iInitCode, sqliteVdbeCurrentAddr(v));
12866 + sqliteVdbeAddOp(v, OP_OpenTemp, srcTab, 0);
12867 + sqliteVdbeAddOp(v, OP_Goto, 0, iSelectLoop);
12868 + sqliteVdbeResolveLabel(v, iCleanup);
12870 + sqliteVdbeChangeP2(v, iInitCode, sqliteVdbeCurrentAddr(v));
12873 + /* This is the case if the data for the INSERT is coming from a VALUES
12877 + assert( pList!=0 );
12879 + useTempTable = 0;
12881 + nColumn = pList->nExpr;
12883 + for(i=0; i<nColumn; i++){
12884 + if( sqliteExprResolveIds(pParse, &dummy, 0, pList->a[i].pExpr) ){
12885 + goto insert_cleanup;
12887 + if( sqliteExprCheck(pParse, pList->a[i].pExpr, 0, 0) ){
12888 + goto insert_cleanup;
12893 + /* Make sure the number of columns in the source data matches the number
12894 + ** of columns to be inserted into the table.
12896 + if( pColumn==0 && nColumn!=pTab->nCol ){
12897 + sqliteErrorMsg(pParse,
12898 + "table %S has %d columns but %d values were supplied",
12899 + pTabList, 0, pTab->nCol, nColumn);
12900 + goto insert_cleanup;
12902 + if( pColumn!=0 && nColumn!=pColumn->nId ){
12903 + sqliteErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
12904 + goto insert_cleanup;
12907 + /* If the INSERT statement included an IDLIST term, then make sure
12908 + ** all elements of the IDLIST really are columns of the table and
12909 + ** remember the column indices.
12911 + ** If the table has an INTEGER PRIMARY KEY column and that column
12912 + ** is named in the IDLIST, then record in the keyColumn variable
12913 + ** the index into IDLIST of the primary key column. keyColumn is
12914 + ** the index of the primary key as it appears in IDLIST, not as
12915 + ** is appears in the original table. (The index of the primary
12916 + ** key in the original table is pTab->iPKey.)
12919 + for(i=0; i<pColumn->nId; i++){
12920 + pColumn->a[i].idx = -1;
12922 + for(i=0; i<pColumn->nId; i++){
12923 + for(j=0; j<pTab->nCol; j++){
12924 + if( sqliteStrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
12925 + pColumn->a[i].idx = j;
12926 + if( j==pTab->iPKey ){
12932 + if( j>=pTab->nCol ){
12933 + if( sqliteIsRowid(pColumn->a[i].zName) ){
12936 + sqliteErrorMsg(pParse, "table %S has no column named %s",
12937 + pTabList, 0, pColumn->a[i].zName);
12939 + goto insert_cleanup;
12945 + /* If there is no IDLIST term but the table has an integer primary
12946 + ** key, the set the keyColumn variable to the primary key column index
12947 + ** in the original table definition.
12949 + if( pColumn==0 ){
12950 + keyColumn = pTab->iPKey;
12953 + /* Open the temp table for FOR EACH ROW triggers
12955 + if( row_triggers_exist ){
12956 + sqliteVdbeAddOp(v, OP_OpenPseudo, newIdx, 0);
12959 + /* Initialize the count of rows to be inserted
12961 + if( db->flags & SQLITE_CountRows ){
12962 + iCntMem = pParse->nMem++;
12963 + sqliteVdbeAddOp(v, OP_Integer, 0, 0);
12964 + sqliteVdbeAddOp(v, OP_MemStore, iCntMem, 1);
12967 + /* Open tables and indices if there are no row triggers */
12968 + if( !row_triggers_exist ){
12969 + base = pParse->nTab;
12970 + idx = sqliteOpenTableAndIndices(pParse, pTab, base);
12971 + pParse->nTab += idx;
12974 + /* If the data source is a temporary table, then we have to create
12975 + ** a loop because there might be multiple rows of data. If the data
12976 + ** source is a subroutine call from the SELECT statement, then we need
12977 + ** to launch the SELECT statement processing.
12979 + if( useTempTable ){
12980 + iBreak = sqliteVdbeMakeLabel(v);
12981 + sqliteVdbeAddOp(v, OP_Rewind, srcTab, iBreak);
12982 + iCont = sqliteVdbeCurrentAddr(v);
12983 + }else if( pSelect ){
12984 + sqliteVdbeAddOp(v, OP_Goto, 0, iSelectLoop);
12985 + sqliteVdbeResolveLabel(v, iInsertBlock);
12988 + /* Run the BEFORE and INSTEAD OF triggers, if there are any
12990 + endOfLoop = sqliteVdbeMakeLabel(v);
12991 + if( before_triggers ){
12993 + /* build the NEW.* reference row. Note that if there is an INTEGER
12994 + ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
12995 + ** translated into a unique ID for the row. But on a BEFORE trigger,
12996 + ** we do not know what the unique ID will be (because the insert has
12997 + ** not happened yet) so we substitute a rowid of -1
12999 + if( keyColumn<0 ){
13000 + sqliteVdbeAddOp(v, OP_Integer, -1, 0);
13001 + }else if( useTempTable ){
13002 + sqliteVdbeAddOp(v, OP_Column, srcTab, keyColumn);
13003 + }else if( pSelect ){
13004 + sqliteVdbeAddOp(v, OP_Dup, nColumn - keyColumn - 1, 1);
13006 + sqliteExprCode(pParse, pList->a[keyColumn].pExpr);
13007 + sqliteVdbeAddOp(v, OP_NotNull, -1, sqliteVdbeCurrentAddr(v)+3);
13008 + sqliteVdbeAddOp(v, OP_Pop, 1, 0);
13009 + sqliteVdbeAddOp(v, OP_Integer, -1, 0);
13010 + sqliteVdbeAddOp(v, OP_MustBeInt, 0, 0);
13013 + /* Create the new column data
13015 + for(i=0; i<pTab->nCol; i++){
13016 + if( pColumn==0 ){
13019 + for(j=0; j<pColumn->nId; j++){
13020 + if( pColumn->a[j].idx==i ) break;
13023 + if( pColumn && j>=pColumn->nId ){
13024 + sqliteVdbeOp3(v, OP_String, 0, 0, pTab->aCol[i].zDflt, P3_STATIC);
13025 + }else if( useTempTable ){
13026 + sqliteVdbeAddOp(v, OP_Column, srcTab, j);
13027 + }else if( pSelect ){
13028 + sqliteVdbeAddOp(v, OP_Dup, nColumn-j-1, 1);
13030 + sqliteExprCode(pParse, pList->a[j].pExpr);
13033 + sqliteVdbeAddOp(v, OP_MakeRecord, pTab->nCol, 0);
13034 + sqliteVdbeAddOp(v, OP_PutIntKey, newIdx, 0);
13036 + /* Fire BEFORE or INSTEAD OF triggers */
13037 + if( sqliteCodeRowTrigger(pParse, TK_INSERT, 0, TK_BEFORE, pTab,
13038 + newIdx, -1, onError, endOfLoop) ){
13039 + goto insert_cleanup;
13043 + /* If any triggers exists, the opening of tables and indices is deferred
13046 + if( row_triggers_exist && !isView ){
13047 + base = pParse->nTab;
13048 + idx = sqliteOpenTableAndIndices(pParse, pTab, base);
13049 + pParse->nTab += idx;
13052 + /* Push the record number for the new entry onto the stack. The
13053 + ** record number is a randomly generate integer created by NewRecno
13054 + ** except when the table has an INTEGER PRIMARY KEY column, in which
13055 + ** case the record number is the same as that column.
13058 + if( keyColumn>=0 ){
13059 + if( useTempTable ){
13060 + sqliteVdbeAddOp(v, OP_Column, srcTab, keyColumn);
13061 + }else if( pSelect ){
13062 + sqliteVdbeAddOp(v, OP_Dup, nColumn - keyColumn - 1, 1);
13064 + sqliteExprCode(pParse, pList->a[keyColumn].pExpr);
13066 + /* If the PRIMARY KEY expression is NULL, then use OP_NewRecno
13067 + ** to generate a unique primary key value.
13069 + sqliteVdbeAddOp(v, OP_NotNull, -1, sqliteVdbeCurrentAddr(v)+3);
13070 + sqliteVdbeAddOp(v, OP_Pop, 1, 0);
13071 + sqliteVdbeAddOp(v, OP_NewRecno, base, 0);
13072 + sqliteVdbeAddOp(v, OP_MustBeInt, 0, 0);
13074 + sqliteVdbeAddOp(v, OP_NewRecno, base, 0);
13077 + /* Push onto the stack, data for all columns of the new entry, beginning
13078 + ** with the first column.
13080 + for(i=0; i<pTab->nCol; i++){
13081 + if( i==pTab->iPKey ){
13082 + /* The value of the INTEGER PRIMARY KEY column is always a NULL.
13083 + ** Whenever this column is read, the record number will be substituted
13084 + ** in its place. So will fill this column with a NULL to avoid
13085 + ** taking up data space with information that will never be used. */
13086 + sqliteVdbeAddOp(v, OP_String, 0, 0);
13089 + if( pColumn==0 ){
13092 + for(j=0; j<pColumn->nId; j++){
13093 + if( pColumn->a[j].idx==i ) break;
13096 + if( pColumn && j>=pColumn->nId ){
13097 + sqliteVdbeOp3(v, OP_String, 0, 0, pTab->aCol[i].zDflt, P3_STATIC);
13098 + }else if( useTempTable ){
13099 + sqliteVdbeAddOp(v, OP_Column, srcTab, j);
13100 + }else if( pSelect ){
13101 + sqliteVdbeAddOp(v, OP_Dup, i+nColumn-j, 1);
13103 + sqliteExprCode(pParse, pList->a[j].pExpr);
13107 + /* Generate code to check constraints and generate index keys and
13108 + ** do the insertion.
13110 + sqliteGenerateConstraintChecks(pParse, pTab, base, 0, keyColumn>=0,
13111 + 0, onError, endOfLoop);
13112 + sqliteCompleteInsertion(pParse, pTab, base, 0,0,0,
13113 + after_triggers ? newIdx : -1);
13116 + /* Update the count of rows that are inserted
13118 + if( (db->flags & SQLITE_CountRows)!=0 ){
13119 + sqliteVdbeAddOp(v, OP_MemIncr, iCntMem, 0);
13122 + if( row_triggers_exist ){
13123 + /* Close all tables opened */
13125 + sqliteVdbeAddOp(v, OP_Close, base, 0);
13126 + for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
13127 + sqliteVdbeAddOp(v, OP_Close, idx+base, 0);
13131 + /* Code AFTER triggers */
13132 + if( sqliteCodeRowTrigger(pParse, TK_INSERT, 0, TK_AFTER, pTab, newIdx, -1,
13133 + onError, endOfLoop) ){
13134 + goto insert_cleanup;
13138 + /* The bottom of the loop, if the data source is a SELECT statement
13140 + sqliteVdbeResolveLabel(v, endOfLoop);
13141 + if( useTempTable ){
13142 + sqliteVdbeAddOp(v, OP_Next, srcTab, iCont);
13143 + sqliteVdbeResolveLabel(v, iBreak);
13144 + sqliteVdbeAddOp(v, OP_Close, srcTab, 0);
13145 + }else if( pSelect ){
13146 + sqliteVdbeAddOp(v, OP_Pop, nColumn, 0);
13147 + sqliteVdbeAddOp(v, OP_Return, 0, 0);
13148 + sqliteVdbeResolveLabel(v, iCleanup);
13151 + if( !row_triggers_exist ){
13152 + /* Close all tables opened */
13153 + sqliteVdbeAddOp(v, OP_Close, base, 0);
13154 + for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
13155 + sqliteVdbeAddOp(v, OP_Close, idx+base, 0);
13159 + sqliteVdbeAddOp(v, OP_SetCounts, 0, 0);
13160 + sqliteEndWriteOperation(pParse);
13163 + ** Return the number of rows inserted.
13165 + if( db->flags & SQLITE_CountRows ){
13166 + sqliteVdbeOp3(v, OP_ColumnName, 0, 1, "rows inserted", P3_STATIC);
13167 + sqliteVdbeAddOp(v, OP_MemLoad, iCntMem, 0);
13168 + sqliteVdbeAddOp(v, OP_Callback, 1, 0);
13172 + sqliteSrcListDelete(pTabList);
13173 + if( pList ) sqliteExprListDelete(pList);
13174 + if( pSelect ) sqliteSelectDelete(pSelect);
13175 + sqliteIdListDelete(pColumn);
13179 +** Generate code to do a constraint check prior to an INSERT or an UPDATE.
13181 +** When this routine is called, the stack contains (from bottom to top)
13182 +** the following values:
13184 +** 1. The recno of the row to be updated before the update. This
13185 +** value is omitted unless we are doing an UPDATE that involves a
13186 +** change to the record number.
13188 +** 2. The recno of the row after the update.
13190 +** 3. The data in the first column of the entry after the update.
13192 +** i. Data from middle columns...
13194 +** N. The data in the last column of the entry after the update.
13196 +** The old recno shown as entry (1) above is omitted unless both isUpdate
13197 +** and recnoChng are 1. isUpdate is true for UPDATEs and false for
13198 +** INSERTs and recnoChng is true if the record number is being changed.
13200 +** The code generated by this routine pushes additional entries onto
13201 +** the stack which are the keys for new index entries for the new record.
13202 +** The order of index keys is the same as the order of the indices on
13203 +** the pTable->pIndex list. A key is only created for index i if
13204 +** aIdxUsed!=0 and aIdxUsed[i]!=0.
13206 +** This routine also generates code to check constraints. NOT NULL,
13207 +** CHECK, and UNIQUE constraints are all checked. If a constraint fails,
13208 +** then the appropriate action is performed. There are five possible
13209 +** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
13211 +** Constraint type Action What Happens
13212 +** --------------- ---------- ----------------------------------------
13213 +** any ROLLBACK The current transaction is rolled back and
13214 +** sqlite_exec() returns immediately with a
13215 +** return code of SQLITE_CONSTRAINT.
13217 +** any ABORT Back out changes from the current command
13218 +** only (do not do a complete rollback) then
13219 +** cause sqlite_exec() to return immediately
13220 +** with SQLITE_CONSTRAINT.
13222 +** any FAIL Sqlite_exec() returns immediately with a
13223 +** return code of SQLITE_CONSTRAINT. The
13224 +** transaction is not rolled back and any
13225 +** prior changes are retained.
13227 +** any IGNORE The record number and data is popped from
13228 +** the stack and there is an immediate jump
13229 +** to label ignoreDest.
13231 +** NOT NULL REPLACE The NULL value is replace by the default
13232 +** value for that column. If the default value
13233 +** is NULL, the action is the same as ABORT.
13235 +** UNIQUE REPLACE The other row that conflicts with the row
13236 +** being inserted is removed.
13238 +** CHECK REPLACE Illegal. The results in an exception.
13240 +** Which action to take is determined by the overrideError parameter.
13241 +** Or if overrideError==OE_Default, then the pParse->onError parameter
13242 +** is used. Or if pParse->onError==OE_Default then the onError value
13243 +** for the constraint is used.
13245 +** The calling routine must open a read/write cursor for pTab with
13246 +** cursor number "base". All indices of pTab must also have open
13247 +** read/write cursors with cursor number base+i for the i-th cursor.
13248 +** Except, if there is no possibility of a REPLACE action then
13249 +** cursors do not need to be open for indices where aIdxUsed[i]==0.
13251 +** If the isUpdate flag is true, it means that the "base" cursor is
13252 +** initially pointing to an entry that is being updated. The isUpdate
13253 +** flag causes extra code to be generated so that the "base" cursor
13254 +** is still pointing at the same entry after the routine returns.
13255 +** Without the isUpdate flag, the "base" cursor might be moved.
13257 +void sqliteGenerateConstraintChecks(
13258 + Parse *pParse, /* The parser context */
13259 + Table *pTab, /* the table into which we are inserting */
13260 + int base, /* Index of a read/write cursor pointing at pTab */
13261 + char *aIdxUsed, /* Which indices are used. NULL means all are used */
13262 + int recnoChng, /* True if the record number will change */
13263 + int isUpdate, /* True for UPDATE, False for INSERT */
13264 + int overrideError, /* Override onError to this if not OE_Default */
13265 + int ignoreDest /* Jump to this label on an OE_Ignore resolution */
13275 + int seenReplace = 0;
13276 + int jumpInst1, jumpInst2;
13278 + int hasTwoRecnos = (isUpdate && recnoChng);
13280 + v = sqliteGetVdbe(pParse);
13282 + assert( pTab->pSelect==0 ); /* This table is not a VIEW */
13283 + nCol = pTab->nCol;
13285 + /* Test all NOT NULL constraints.
13287 + for(i=0; i<nCol; i++){
13288 + if( i==pTab->iPKey ){
13291 + onError = pTab->aCol[i].notNull;
13292 + if( onError==OE_None ) continue;
13293 + if( overrideError!=OE_Default ){
13294 + onError = overrideError;
13295 + }else if( pParse->db->onError!=OE_Default ){
13296 + onError = pParse->db->onError;
13297 + }else if( onError==OE_Default ){
13298 + onError = OE_Abort;
13300 + if( onError==OE_Replace && pTab->aCol[i].zDflt==0 ){
13301 + onError = OE_Abort;
13303 + sqliteVdbeAddOp(v, OP_Dup, nCol-1-i, 1);
13304 + addr = sqliteVdbeAddOp(v, OP_NotNull, 1, 0);
13305 + switch( onError ){
13306 + case OE_Rollback:
13310 + sqliteVdbeAddOp(v, OP_Halt, SQLITE_CONSTRAINT, onError);
13311 + sqliteSetString(&zMsg, pTab->zName, ".", pTab->aCol[i].zName,
13312 + " may not be NULL", (char*)0);
13313 + sqliteVdbeChangeP3(v, -1, zMsg, P3_DYNAMIC);
13316 + case OE_Ignore: {
13317 + sqliteVdbeAddOp(v, OP_Pop, nCol+1+hasTwoRecnos, 0);
13318 + sqliteVdbeAddOp(v, OP_Goto, 0, ignoreDest);
13321 + case OE_Replace: {
13322 + sqliteVdbeOp3(v, OP_String, 0, 0, pTab->aCol[i].zDflt, P3_STATIC);
13323 + sqliteVdbeAddOp(v, OP_Push, nCol-i, 0);
13326 + default: assert(0);
13328 + sqliteVdbeChangeP2(v, addr, sqliteVdbeCurrentAddr(v));
13331 + /* Test all CHECK constraints
13335 + /* If we have an INTEGER PRIMARY KEY, make sure the primary key
13336 + ** of the new record does not previously exist. Except, if this
13337 + ** is an UPDATE and the primary key is not changing, that is OK.
13340 + onError = pTab->keyConf;
13341 + if( overrideError!=OE_Default ){
13342 + onError = overrideError;
13343 + }else if( pParse->db->onError!=OE_Default ){
13344 + onError = pParse->db->onError;
13345 + }else if( onError==OE_Default ){
13346 + onError = OE_Abort;
13350 + sqliteVdbeAddOp(v, OP_Dup, nCol+1, 1);
13351 + sqliteVdbeAddOp(v, OP_Dup, nCol+1, 1);
13352 + jumpInst1 = sqliteVdbeAddOp(v, OP_Eq, 0, 0);
13354 + sqliteVdbeAddOp(v, OP_Dup, nCol, 1);
13355 + jumpInst2 = sqliteVdbeAddOp(v, OP_NotExists, base, 0);
13356 + switch( onError ){
13358 + onError = OE_Abort;
13359 + /* Fall thru into the next case */
13361 + case OE_Rollback:
13364 + sqliteVdbeOp3(v, OP_Halt, SQLITE_CONSTRAINT, onError,
13365 + "PRIMARY KEY must be unique", P3_STATIC);
13368 + case OE_Replace: {
13369 + sqliteGenerateRowIndexDelete(pParse->db, v, pTab, base, 0);
13371 + sqliteVdbeAddOp(v, OP_Dup, nCol+hasTwoRecnos, 1);
13372 + sqliteVdbeAddOp(v, OP_MoveTo, base, 0);
13377 + case OE_Ignore: {
13378 + assert( seenReplace==0 );
13379 + sqliteVdbeAddOp(v, OP_Pop, nCol+1+hasTwoRecnos, 0);
13380 + sqliteVdbeAddOp(v, OP_Goto, 0, ignoreDest);
13384 + contAddr = sqliteVdbeCurrentAddr(v);
13385 + sqliteVdbeChangeP2(v, jumpInst2, contAddr);
13387 + sqliteVdbeChangeP2(v, jumpInst1, contAddr);
13388 + sqliteVdbeAddOp(v, OP_Dup, nCol+1, 1);
13389 + sqliteVdbeAddOp(v, OP_MoveTo, base, 0);
13393 + /* Test all UNIQUE constraints by creating entries for each UNIQUE
13394 + ** index and making sure that duplicate entries do not already exist.
13395 + ** Add the new records to the indices as we go.
13398 + for(iCur=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, iCur++){
13399 + if( aIdxUsed && aIdxUsed[iCur]==0 ) continue; /* Skip unused indices */
13402 + /* Create a key for accessing the index entry */
13403 + sqliteVdbeAddOp(v, OP_Dup, nCol+extra, 1);
13404 + for(i=0; i<pIdx->nColumn; i++){
13405 + int idx = pIdx->aiColumn[i];
13406 + if( idx==pTab->iPKey ){
13407 + sqliteVdbeAddOp(v, OP_Dup, i+extra+nCol+1, 1);
13409 + sqliteVdbeAddOp(v, OP_Dup, i+extra+nCol-idx, 1);
13412 + jumpInst1 = sqliteVdbeAddOp(v, OP_MakeIdxKey, pIdx->nColumn, 0);
13413 + if( pParse->db->file_format>=4 ) sqliteAddIdxKeyType(v, pIdx);
13415 + /* Find out what action to take in case there is an indexing conflict */
13416 + onError = pIdx->onError;
13417 + if( onError==OE_None ) continue; /* pIdx is not a UNIQUE index */
13418 + if( overrideError!=OE_Default ){
13419 + onError = overrideError;
13420 + }else if( pParse->db->onError!=OE_Default ){
13421 + onError = pParse->db->onError;
13422 + }else if( onError==OE_Default ){
13423 + onError = OE_Abort;
13425 + if( seenReplace ){
13426 + if( onError==OE_Ignore ) onError = OE_Replace;
13427 + else if( onError==OE_Fail ) onError = OE_Abort;
13431 + /* Check to see if the new index entry will be unique */
13432 + sqliteVdbeAddOp(v, OP_Dup, extra+nCol+1+hasTwoRecnos, 1);
13433 + jumpInst2 = sqliteVdbeAddOp(v, OP_IsUnique, base+iCur+1, 0);
13435 + /* Generate code that executes if the new index entry is not unique */
13436 + switch( onError ){
13437 + case OE_Rollback:
13441 + char zErrMsg[200];
13442 + strcpy(zErrMsg, pIdx->nColumn>1 ? "columns " : "column ");
13443 + n1 = strlen(zErrMsg);
13444 + for(j=0; j<pIdx->nColumn && n1<sizeof(zErrMsg)-30; j++){
13445 + char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
13446 + n2 = strlen(zCol);
13448 + strcpy(&zErrMsg[n1], ", ");
13451 + if( n1+n2>sizeof(zErrMsg)-30 ){
13452 + strcpy(&zErrMsg[n1], "...");
13456 + strcpy(&zErrMsg[n1], zCol);
13460 + strcpy(&zErrMsg[n1],
13461 + pIdx->nColumn>1 ? " are not unique" : " is not unique");
13462 + sqliteVdbeOp3(v, OP_Halt, SQLITE_CONSTRAINT, onError, zErrMsg, 0);
13465 + case OE_Ignore: {
13466 + assert( seenReplace==0 );
13467 + sqliteVdbeAddOp(v, OP_Pop, nCol+extra+3+hasTwoRecnos, 0);
13468 + sqliteVdbeAddOp(v, OP_Goto, 0, ignoreDest);
13471 + case OE_Replace: {
13472 + sqliteGenerateRowDelete(pParse->db, v, pTab, base, 0);
13474 + sqliteVdbeAddOp(v, OP_Dup, nCol+extra+1+hasTwoRecnos, 1);
13475 + sqliteVdbeAddOp(v, OP_MoveTo, base, 0);
13480 + default: assert(0);
13482 + contAddr = sqliteVdbeCurrentAddr(v);
13483 +#if NULL_DISTINCT_FOR_UNIQUE
13484 + sqliteVdbeChangeP2(v, jumpInst1, contAddr);
13486 + sqliteVdbeChangeP2(v, jumpInst2, contAddr);
13491 +** This routine generates code to finish the INSERT or UPDATE operation
13492 +** that was started by a prior call to sqliteGenerateConstraintChecks.
13493 +** The stack must contain keys for all active indices followed by data
13494 +** and the recno for the new entry. This routine creates the new
13495 +** entries in all indices and in the main table.
13497 +** The arguments to this routine should be the same as the first six
13498 +** arguments to sqliteGenerateConstraintChecks.
13500 +void sqliteCompleteInsertion(
13501 + Parse *pParse, /* The parser context */
13502 + Table *pTab, /* the table into which we are inserting */
13503 + int base, /* Index of a read/write cursor pointing at pTab */
13504 + char *aIdxUsed, /* Which indices are used. NULL means all are used */
13505 + int recnoChng, /* True if the record number will change */
13506 + int isUpdate, /* True for UPDATE, False for INSERT */
13507 + int newIdx /* Index of NEW table for triggers. -1 if none */
13514 + v = sqliteGetVdbe(pParse);
13516 + assert( pTab->pSelect==0 ); /* This table is not a VIEW */
13517 + for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
13518 + for(i=nIdx-1; i>=0; i--){
13519 + if( aIdxUsed && aIdxUsed[i]==0 ) continue;
13520 + sqliteVdbeAddOp(v, OP_IdxPut, base+i+1, 0);
13522 + sqliteVdbeAddOp(v, OP_MakeRecord, pTab->nCol, 0);
13524 + sqliteVdbeAddOp(v, OP_Dup, 1, 0);
13525 + sqliteVdbeAddOp(v, OP_Dup, 1, 0);
13526 + sqliteVdbeAddOp(v, OP_PutIntKey, newIdx, 0);
13528 + sqliteVdbeAddOp(v, OP_PutIntKey, base,
13529 + (pParse->trigStack?0:OPFLAG_NCHANGE) |
13530 + (isUpdate?0:OPFLAG_LASTROWID) | OPFLAG_CSCHANGE);
13531 + if( isUpdate && recnoChng ){
13532 + sqliteVdbeAddOp(v, OP_Pop, 1, 0);
13537 +** Generate code that will open write cursors for a table and for all
13538 +** indices of that table. The "base" parameter is the cursor number used
13539 +** for the table. Indices are opened on subsequent cursors.
13541 +** Return the total number of cursors opened. This is always at least
13542 +** 1 (for the main table) plus more for each cursor.
13544 +int sqliteOpenTableAndIndices(Parse *pParse, Table *pTab, int base){
13547 + Vdbe *v = sqliteGetVdbe(pParse);
13549 + sqliteVdbeAddOp(v, OP_Integer, pTab->iDb, 0);
13550 + sqliteVdbeOp3(v, OP_OpenWrite, base, pTab->tnum, pTab->zName, P3_STATIC);
13551 + for(i=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
13552 + sqliteVdbeAddOp(v, OP_Integer, pIdx->iDb, 0);
13553 + sqliteVdbeOp3(v, OP_OpenWrite, i+base, pIdx->tnum, pIdx->zName, P3_STATIC);
13558 +++ b/ext/sqlite/libsqlite/src/libsqlite.dsp
13560 +# Microsoft Developer Studio Project File - Name="libsqlite" - Package Owner=<4>
\r
13561 +# Microsoft Developer Studio Generated Build File, Format Version 6.00
\r
13562 +# ** DO NOT EDIT **
\r
13564 +# TARGTYPE "Win32 (x86) Static Library" 0x0104
\r
13566 +CFG=libsqlite - Win32 Debug_TS
\r
13567 +!MESSAGE This is not a valid makefile. To build this project using NMAKE,
\r
13568 +!MESSAGE use the Export Makefile command and run
\r
13570 +!MESSAGE NMAKE /f "libsqlite.mak".
\r
13572 +!MESSAGE You can specify a configuration when running NMAKE
\r
13573 +!MESSAGE by defining the macro CFG on the command line. For example:
\r
13575 +!MESSAGE NMAKE /f "libsqlite.mak" CFG="libsqlite - Win32 Debug_TS"
\r
13577 +!MESSAGE Possible choices for configuration are:
\r
13579 +!MESSAGE "libsqlite - Win32 Debug_TS" (based on "Win32 (x86) Static Library")
\r
13580 +!MESSAGE "libsqlite - Win32 Release_TS" (based on "Win32 (x86) Static Library")
\r
13581 +!MESSAGE "libsqlite - Win32 Release_TSDbg" (based on "Win32 (x86) Static Library")
\r
13585 +# PROP AllowPerConfigDependencies 0
\r
13586 +# PROP Scc_ProjName ""
\r
13587 +# PROP Scc_LocalPath ""
\r
13591 +!IF "$(CFG)" == "libsqlite - Win32 Debug_TS"
\r
13593 +# PROP BASE Use_MFC 0
\r
13594 +# PROP BASE Use_Debug_Libraries 1
\r
13595 +# PROP BASE Output_Dir "Debug_TS"
\r
13596 +# PROP BASE Intermediate_Dir "Debug_TS"
\r
13597 +# PROP BASE Target_Dir ""
\r
13598 +# PROP Use_MFC 0
\r
13599 +# PROP Use_Debug_Libraries 1
\r
13600 +# PROP Output_Dir "..\..\Debug_TS"
\r
13601 +# PROP Intermediate_Dir "..\..\Debug_TS"
\r
13602 +# PROP Target_Dir ""
\r
13603 +# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_MBCS" /D "_LIB" /YX /FD /GZ /c
\r
13604 +# ADD CPP /nologo /MDd /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_MBCS" /D "_LIB" /D THREADSAFE=1 /YX /FD /GZ /c
\r
13605 +# ADD BASE RSC /l 0x406 /d "_DEBUG"
\r
13606 +# ADD RSC /l 0x406 /d "_DEBUG"
\r
13607 +BSC32=bscmake.exe
\r
13608 +# ADD BASE BSC32 /nologo
\r
13609 +# ADD BSC32 /nologo
\r
13610 +LIB32=link.exe -lib
\r
13611 +# ADD BASE LIB32 /nologo
\r
13612 +# ADD LIB32 /nologo
\r
13614 +!ELSEIF "$(CFG)" == "libsqlite - Win32 Release_TS"
\r
13616 +# PROP BASE Use_MFC 0
\r
13617 +# PROP BASE Use_Debug_Libraries 0
\r
13618 +# PROP BASE Output_Dir "Release_TS"
\r
13619 +# PROP BASE Intermediate_Dir "Release_TS"
\r
13620 +# PROP BASE Target_Dir ""
\r
13621 +# PROP Use_MFC 0
\r
13622 +# PROP Use_Debug_Libraries 0
\r
13623 +# PROP Output_Dir "..\..\Release_TS"
\r
13624 +# PROP Intermediate_Dir "..\..\Release_TS"
\r
13625 +# PROP Target_Dir ""
\r
13626 +# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_MBCS" /D "_LIB" /YX /FD /c
\r
13627 +# ADD CPP /nologo /MD /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_MBCS" /D "_LIB" /D THREADSAFE=1 /YX /FD /c
\r
13628 +# ADD BASE RSC /l 0x406 /d "NDEBUG"
\r
13629 +# ADD RSC /l 0x406 /d "NDEBUG"
\r
13630 +BSC32=bscmake.exe
\r
13631 +# ADD BASE BSC32 /nologo
\r
13632 +# ADD BSC32 /nologo
\r
13633 +LIB32=link.exe -lib
\r
13634 +# ADD BASE LIB32 /nologo
\r
13635 +# ADD LIB32 /nologo
\r
13637 +!ELSEIF "$(CFG)" == "libsqlite - Win32 Release_TSDbg"
\r
13639 +# PROP BASE Use_MFC 0
\r
13640 +# PROP BASE Use_Debug_Libraries 0
\r
13641 +# PROP BASE Output_Dir "libsqlite___Win32_Release_TSDbg"
\r
13642 +# PROP BASE Intermediate_Dir "libsqlite___Win32_Release_TSDbg"
\r
13643 +# PROP BASE Target_Dir ""
\r
13644 +# PROP Use_MFC 0
\r
13645 +# PROP Use_Debug_Libraries 0
\r
13646 +# PROP Output_Dir "..\..\Release_TSDbg"
\r
13647 +# PROP Intermediate_Dir "..\..\Release_TSDbg"
\r
13648 +# PROP Target_Dir ""
\r
13649 +# ADD BASE CPP /nologo /MD /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_MBCS" /D "_LIB" /D THREADSAFE=1 /YX /FD /c
\r
13650 +# ADD CPP /nologo /MD /W3 /GX /Zi /Od /D "WIN32" /D "NDEBUG" /D "_MBCS" /D "_LIB" /D THREADSAFE=1 /YX /FD /c
\r
13651 +# ADD BASE RSC /l 0x406 /d "NDEBUG"
\r
13652 +# ADD RSC /l 0x406 /d "NDEBUG"
\r
13653 +BSC32=bscmake.exe
\r
13654 +# ADD BASE BSC32 /nologo
\r
13655 +# ADD BSC32 /nologo
\r
13656 +LIB32=link.exe -lib
\r
13657 +# ADD BASE LIB32 /nologo /out:"Release_TS\libsqlite.lib"
\r
13658 +# ADD LIB32 /nologo
\r
13664 +# Name "libsqlite - Win32 Debug_TS"
\r
13665 +# Name "libsqlite - Win32 Release_TS"
\r
13666 +# Name "libsqlite - Win32 Release_TSDbg"
\r
13667 +# Begin Group "Source Files"
\r
13669 +# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat"
\r
13670 +# Begin Source File
\r
13673 +# End Source File
\r
13674 +# Begin Source File
\r
13677 +# End Source File
\r
13678 +# Begin Source File
\r
13681 +# End Source File
\r
13682 +# Begin Source File
\r
13684 +SOURCE=btree_rb.c
\r
13685 +# End Source File
\r
13686 +# Begin Source File
\r
13689 +# End Source File
\r
13690 +# Begin Source File
\r
13693 +# End Source File
\r
13694 +# Begin Source File
\r
13697 +# End Source File
\r
13698 +# Begin Source File
\r
13701 +# End Source File
\r
13702 +# Begin Source File
\r
13705 +# End Source File
\r
13706 +# Begin Source File
\r
13709 +# End Source File
\r
13710 +# Begin Source File
\r
13713 +# End Source File
\r
13714 +# Begin Source File
\r
13717 +# End Source File
\r
13718 +# Begin Source File
\r
13721 +# End Source File
\r
13722 +# Begin Source File
\r
13725 +# End Source File
\r
13726 +# Begin Source File
\r
13728 +SOURCE=opcodes.c
\r
13729 +# End Source File
\r
13730 +# Begin Source File
\r
13733 +# End Source File
\r
13734 +# Begin Source File
\r
13737 +# End Source File
\r
13738 +# Begin Source File
\r
13741 +# End Source File
\r
13742 +# Begin Source File
\r
13745 +# End Source File
\r
13746 +# Begin Source File
\r
13749 +# End Source File
\r
13750 +# Begin Source File
\r
13753 +# End Source File
\r
13754 +# Begin Source File
\r
13757 +# End Source File
\r
13758 +# Begin Source File
\r
13761 +# End Source File
\r
13762 +# Begin Source File
\r
13764 +SOURCE=tokenize.c
\r
13765 +# End Source File
\r
13766 +# Begin Source File
\r
13768 +SOURCE=trigger.c
\r
13769 +# End Source File
\r
13770 +# Begin Source File
\r
13773 +# End Source File
\r
13774 +# Begin Source File
\r
13777 +# End Source File
\r
13778 +# Begin Source File
\r
13781 +# End Source File
\r
13782 +# Begin Source File
\r
13785 +# End Source File
\r
13786 +# Begin Source File
\r
13788 +SOURCE=.\vdbeaux.c
\r
13789 +# End Source File
\r
13790 +# Begin Source File
\r
13793 +# End Source File
\r
13795 +# Begin Group "Header Files"
\r
13797 +# PROP Default_Filter "h;hpp;hxx;hm;inl"
\r
13798 +# Begin Source File
\r
13801 +# End Source File
\r
13802 +# Begin Source File
\r
13804 +SOURCE=config_static.w32.h
\r
13806 +!IF "$(CFG)" == "libsqlite - Win32 Debug_TS"
\r
13808 +# Begin Custom Build
\r
13810 +InputPath=config_static.w32.h
\r
13812 +"$(InputDir)\config.h" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
\r
13813 + copy $(InputPath) $(InputDir)\config.h
\r
13815 +# End Custom Build
\r
13817 +!ELSEIF "$(CFG)" == "libsqlite - Win32 Release_TS"
\r
13819 +# Begin Custom Build
\r
13821 +InputPath=config_static.w32.h
\r
13823 +"$(InputDir)\config.h" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
\r
13824 + copy $(InputPath) $(InputDir)\config.h
\r
13826 +# End Custom Build
\r
13828 +!ELSEIF "$(CFG)" == "libsqlite - Win32 Release_TSDbg"
\r
13830 +# Begin Custom Build
\r
13832 +InputPath=config_static.w32.h
\r
13834 +"$(InputDir)\config.h" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
\r
13835 + copy $(InputPath) $(InputDir)\config.h
\r
13837 +# End Custom Build
\r
13841 +# End Source File
\r
13842 +# Begin Source File
\r
13845 +# End Source File
\r
13846 +# Begin Source File
\r
13848 +SOURCE=opcodes.h
\r
13849 +# End Source File
\r
13850 +# Begin Source File
\r
13853 +# End Source File
\r
13854 +# Begin Source File
\r
13857 +# End Source File
\r
13858 +# Begin Source File
\r
13861 +# End Source File
\r
13862 +# Begin Source File
\r
13864 +SOURCE=sqlite.w32.h
\r
13866 +!IF "$(CFG)" == "libsqlite - Win32 Debug_TS"
\r
13868 +# Begin Custom Build
\r
13870 +InputPath=sqlite.w32.h
\r
13872 +"$(InputDir)\sqlite.h" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
\r
13873 + copy $(InputPath) $(InputDir)\sqlite.h
\r
13875 +# End Custom Build
\r
13877 +!ELSEIF "$(CFG)" == "libsqlite - Win32 Release_TS"
\r
13879 +# Begin Custom Build
\r
13881 +InputPath=sqlite.w32.h
\r
13883 +"$(InputDir)\sqlite.h" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
\r
13884 + copy $(InputPath) $(InputDir)\sqlite.h
\r
13886 +# End Custom Build
\r
13888 +!ELSEIF "$(CFG)" == "libsqlite - Win32 Release_TSDbg"
\r
13890 +# Begin Custom Build
\r
13892 +InputPath=sqlite.w32.h
\r
13894 +"$(InputDir)\sqlite.h" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
\r
13895 + copy $(InputPath) $(InputDir)\sqlite.h
\r
13897 +# End Custom Build
\r
13901 +# End Source File
\r
13902 +# Begin Source File
\r
13904 +SOURCE=sqliteInt.h
\r
13905 +# End Source File
\r
13906 +# Begin Source File
\r
13909 +# End Source File
\r
13914 +++ b/ext/sqlite/libsqlite/src/main.c
13917 +** 2001 September 15
13919 +** The author disclaims copyright to this source code. In place of
13920 +** a legal notice, here is a blessing:
13922 +** May you do good and not evil.
13923 +** May you find forgiveness for yourself and forgive others.
13924 +** May you share freely, never taking more than you give.
13926 +*************************************************************************
13927 +** Main file for the SQLite library. The routines in this file
13928 +** implement the programmer interface to the library. Routines in
13929 +** other files are for internal use by SQLite and should not be
13930 +** accessed by users of the library.
13934 +#include "sqliteInt.h"
13936 +#include <ctype.h>
13939 +** A pointer to this structure is used to communicate information
13940 +** from sqliteInit into the sqliteInitCallback.
13943 + sqlite *db; /* The database being initialized */
13944 + char **pzErrMsg; /* Error message stored here */
13948 +** Fill the InitData structure with an error message that indicates
13949 +** that the database is corrupt.
13951 +static void corruptSchema(InitData *pData, const char *zExtra){
13952 + sqliteSetString(pData->pzErrMsg, "malformed database schema",
13953 + zExtra!=0 && zExtra[0]!=0 ? " - " : (char*)0, zExtra, (char*)0);
13957 +** This is the callback routine for the code that initializes the
13958 +** database. See sqliteInit() below for additional information.
13960 +** Each callback contains the following information:
13962 +** argv[0] = "file-format" or "schema-cookie" or "table" or "index"
13963 +** argv[1] = table or index name or meta statement type.
13964 +** argv[2] = root page number for table or index. NULL for meta.
13965 +** argv[3] = SQL text for a CREATE TABLE or CREATE INDEX statement.
13966 +** argv[4] = "1" for temporary files, "0" for main database, "2" or more
13967 +** for auxiliary database files.
13971 +int sqliteInitCallback(void *pInit, int argc, char **argv, char **azColName){
13972 + InitData *pData = (InitData*)pInit;
13975 + assert( argc==5 );
13976 + if( argv==0 ) return 0; /* Might happen if EMPTY_RESULT_CALLBACKS are on */
13977 + if( argv[0]==0 ){
13978 + corruptSchema(pData, 0);
13981 + switch( argv[0][0] ){
13984 + case 't': { /* CREATE TABLE, CREATE INDEX, or CREATE VIEW statements */
13985 + sqlite *db = pData->db;
13986 + if( argv[2]==0 || argv[4]==0 ){
13987 + corruptSchema(pData, 0);
13990 + if( argv[3] && argv[3][0] ){
13991 + /* Call the parser to process a CREATE TABLE, INDEX or VIEW.
13992 + ** But because db->init.busy is set to 1, no VDBE code is generated
13993 + ** or executed. All the parser does is build the internal data
13994 + ** structures that describe the table, index, or view.
13997 + assert( db->init.busy );
13998 + db->init.iDb = atoi(argv[4]);
13999 + assert( db->init.iDb>=0 && db->init.iDb<db->nDb );
14000 + db->init.newTnum = atoi(argv[2]);
14001 + if( sqlite_exec(db, argv[3], 0, 0, &zErr) ){
14002 + corruptSchema(pData, zErr);
14003 + sqlite_freemem(zErr);
14005 + db->init.iDb = 0;
14007 + /* If the SQL column is blank it means this is an index that
14008 + ** was created to be the PRIMARY KEY or to fulfill a UNIQUE
14009 + ** constraint for a CREATE TABLE. The index should have already
14010 + ** been created when we processed the CREATE TABLE. All we have
14011 + ** to do here is record the root page number for that index.
14016 + iDb = atoi(argv[4]);
14017 + assert( iDb>=0 && iDb<db->nDb );
14018 + pIndex = sqliteFindIndex(db, argv[1], db->aDb[iDb].zName);
14019 + if( pIndex==0 || pIndex->tnum!=0 ){
14020 + /* This can occur if there exists an index on a TEMP table which
14021 + ** has the same name as another index on a permanent index. Since
14022 + ** the permanent table is hidden by the TEMP table, we can also
14023 + ** safely ignore the index on the permanent table.
14025 + /* Do Nothing */;
14027 + pIndex->tnum = atoi(argv[2]);
14033 + /* This can not happen! */
14035 + assert( nErr==0 );
14042 +** This is a callback procedure used to reconstruct a table. The
14043 +** name of the table to be reconstructed is passed in as argv[0].
14045 +** This routine is used to automatically upgrade a database from
14046 +** format version 1 or 2 to version 3. The correct operation of
14047 +** this routine relys on the fact that no indices are used when
14048 +** copying a table out to a temporary file.
14050 +** The change from version 2 to version 3 occurred between SQLite
14051 +** version 2.5.6 and 2.6.0 on 2002-July-18.
14054 +int upgrade_3_callback(void *pInit, int argc, char **argv, char **NotUsed){
14055 + InitData *pData = (InitData*)pInit;
14061 + pTab = sqliteFindTable(pData->db, argv[0], 0);
14062 + assert( pTab!=0 );
14063 + assert( sqliteStrICmp(pTab->zName, argv[0])==0 );
14065 + pTrig = pTab->pTrigger;
14066 + pTab->pTrigger = 0; /* Disable all triggers before rebuilding the table */
14068 + rc = sqlite_exec_printf(pData->db,
14069 + "CREATE TEMP TABLE sqlite_x AS SELECT * FROM '%q'; "
14070 + "DELETE FROM '%q'; "
14071 + "INSERT INTO '%q' SELECT * FROM sqlite_x; "
14072 + "DROP TABLE sqlite_x;",
14073 + 0, 0, &zErr, argv[0], argv[0], argv[0]);
14075 + if( *pData->pzErrMsg ) sqlite_freemem(*pData->pzErrMsg);
14076 + *pData->pzErrMsg = zErr;
14079 + /* If an error occurred in the SQL above, then the transaction will
14080 + ** rollback which will delete the internal symbol tables. This will
14081 + ** cause the structure that pTab points to be deleted. In case that
14082 + ** happened, we need to refetch pTab.
14084 + pTab = sqliteFindTable(pData->db, argv[0], 0);
14086 + assert( sqliteStrICmp(pTab->zName, argv[0])==0 );
14087 + pTab->pTrigger = pTrig; /* Re-enable triggers */
14089 + return rc!=SQLITE_OK;
14095 +** Attempt to read the database schema and initialize internal
14096 +** data structures for a single database file. The index of the
14097 +** database file is given by iDb. iDb==0 is used for the main
14098 +** database. iDb==1 should never be used. iDb>=2 is used for
14099 +** auxiliary databases. Return one of the SQLITE_ error codes to
14100 +** indicate success or failure.
14102 +static int sqliteInitOne(sqlite *db, int iDb, char **pzErrMsg){
14104 + BtCursor *curMain;
14107 + char const *azArg[6];
14109 + int meta[SQLITE_N_BTREE_META];
14110 + InitData initData;
14111 + char const *zMasterSchema;
14112 + char const *zMasterName;
14116 + ** The master database table has a structure like this
14118 + static char master_schema[] =
14119 + "CREATE TABLE sqlite_master(\n"
14122 + " tbl_name text,\n"
14123 + " rootpage integer,\n"
14127 + static char temp_master_schema[] =
14128 + "CREATE TEMP TABLE sqlite_temp_master(\n"
14131 + " tbl_name text,\n"
14132 + " rootpage integer,\n"
14137 + assert( iDb>=0 && iDb<db->nDb );
14139 + /* zMasterSchema and zInitScript are set to point at the master schema
14140 + ** and initialisation script appropriate for the database being
14141 + ** initialised. zMasterName is the name of the master table.
14144 + zMasterSchema = temp_master_schema;
14145 + zMasterName = TEMP_MASTER_NAME;
14147 + zMasterSchema = master_schema;
14148 + zMasterName = MASTER_NAME;
14151 + /* Construct the schema table.
14153 + sqliteSafetyOff(db);
14154 + azArg[0] = "table";
14155 + azArg[1] = zMasterName;
14157 + azArg[3] = zMasterSchema;
14158 + sprintf(zDbNum, "%d", iDb);
14159 + azArg[4] = zDbNum;
14161 + initData.db = db;
14162 + initData.pzErrMsg = pzErrMsg;
14163 + sqliteInitCallback(&initData, 5, (char **)azArg, 0);
14164 + pTab = sqliteFindTable(db, zMasterName, db->aDb[iDb].zName);
14166 + pTab->readOnly = 1;
14168 + return SQLITE_NOMEM;
14170 + sqliteSafetyOn(db);
14172 + /* Create a cursor to hold the database open
14174 + if( db->aDb[iDb].pBt==0 ) return SQLITE_OK;
14175 + rc = sqliteBtreeCursor(db->aDb[iDb].pBt, 2, 0, &curMain);
14177 + sqliteSetString(pzErrMsg, sqlite_error_string(rc), (char*)0);
14181 + /* Get the database meta information
14183 + rc = sqliteBtreeGetMeta(db->aDb[iDb].pBt, meta);
14185 + sqliteSetString(pzErrMsg, sqlite_error_string(rc), (char*)0);
14186 + sqliteBtreeCloseCursor(curMain);
14189 + db->aDb[iDb].schema_cookie = meta[1];
14191 + db->next_cookie = meta[1];
14192 + db->file_format = meta[2];
14194 + if( size==0 ){ size = MAX_PAGES; }
14195 + db->cache_size = size;
14196 + db->safety_level = meta[4];
14197 + if( meta[6]>0 && meta[6]<=2 && db->temp_store==0 ){
14198 + db->temp_store = meta[6];
14200 + if( db->safety_level==0 ) db->safety_level = 2;
14203 + ** file_format==1 Version 2.1.0.
14204 + ** file_format==2 Version 2.2.0. Add support for INTEGER PRIMARY KEY.
14205 + ** file_format==3 Version 2.6.0. Fix empty-string index bug.
14206 + ** file_format==4 Version 2.7.0. Add support for separate numeric and
14207 + ** text datatypes.
14209 + if( db->file_format==0 ){
14210 + /* This happens if the database was initially empty */
14211 + db->file_format = 4;
14212 + }else if( db->file_format>4 ){
14213 + sqliteBtreeCloseCursor(curMain);
14214 + sqliteSetString(pzErrMsg, "unsupported file format", (char*)0);
14215 + return SQLITE_ERROR;
14217 + }else if( iDb!=1 && (db->file_format!=meta[2] || db->file_format<4) ){
14218 + assert( db->file_format>=4 );
14219 + if( meta[2]==0 ){
14220 + sqliteSetString(pzErrMsg, "cannot attach empty database: ",
14221 + db->aDb[iDb].zName, (char*)0);
14223 + sqliteSetString(pzErrMsg, "incompatible file format in auxiliary "
14224 + "database: ", db->aDb[iDb].zName, (char*)0);
14226 + sqliteBtreeClose(db->aDb[iDb].pBt);
14227 + db->aDb[iDb].pBt = 0;
14228 + return SQLITE_FORMAT;
14230 + sqliteBtreeSetCacheSize(db->aDb[iDb].pBt, db->cache_size);
14231 + sqliteBtreeSetSafetyLevel(db->aDb[iDb].pBt, meta[4]==0 ? 2 : meta[4]);
14233 + /* Read the schema information out of the schema tables
14235 + assert( db->init.busy );
14236 + sqliteSafetyOff(db);
14238 + /* The following SQL will read the schema from the master tables.
14239 + ** The first version works with SQLite file formats 2 or greater.
14240 + ** The second version is for format 1 files.
14242 + ** Beginning with file format 2, the rowid for new table entries
14243 + ** (including entries in sqlite_master) is an increasing integer.
14244 + ** So for file format 2 and later, we can play back sqlite_master
14245 + ** and all the CREATE statements will appear in the right order.
14246 + ** But with file format 1, table entries were random and so we
14247 + ** have to make sure the CREATE TABLEs occur before their corresponding
14248 + ** CREATE INDEXs. (We don't have to deal with CREATE VIEW or
14249 + ** CREATE TRIGGER in file format 1 because those constructs did
14250 + ** not exist then.)
14252 + if( db->file_format>=2 ){
14253 + sqliteSetString(&zSql,
14254 + "SELECT type, name, rootpage, sql, ", zDbNum, " FROM \"",
14255 + db->aDb[iDb].zName, "\".", zMasterName, (char*)0);
14257 + sqliteSetString(&zSql,
14258 + "SELECT type, name, rootpage, sql, ", zDbNum, " FROM \"",
14259 + db->aDb[iDb].zName, "\".", zMasterName,
14260 + " WHERE type IN ('table', 'index')"
14261 + " ORDER BY CASE type WHEN 'table' THEN 0 ELSE 1 END", (char*)0);
14263 + rc = sqlite_exec(db, zSql, sqliteInitCallback, &initData, 0);
14265 + sqliteFree(zSql);
14266 + sqliteSafetyOn(db);
14267 + sqliteBtreeCloseCursor(curMain);
14268 + if( sqlite_malloc_failed ){
14269 + sqliteSetString(pzErrMsg, "out of memory", (char*)0);
14270 + rc = SQLITE_NOMEM;
14271 + sqliteResetInternalSchema(db, 0);
14273 + if( rc==SQLITE_OK ){
14274 + DbSetProperty(db, iDb, DB_SchemaLoaded);
14276 + sqliteResetInternalSchema(db, iDb);
14282 +** Initialize all database files - the main database file, the file
14283 +** used to store temporary tables, and any additional database files
14284 +** created using ATTACH statements. Return a success code. If an
14285 +** error occurs, write an error message into *pzErrMsg.
14287 +** After the database is initialized, the SQLITE_Initialized
14288 +** bit is set in the flags field of the sqlite structure. An
14289 +** attempt is made to initialize the database as soon as it
14290 +** is opened. If that fails (perhaps because another process
14291 +** has the sqlite_master table locked) than another attempt
14292 +** is made the first time the database is accessed.
14294 +int sqliteInit(sqlite *db, char **pzErrMsg){
14297 + if( db->init.busy ) return SQLITE_OK;
14298 + assert( (db->flags & SQLITE_Initialized)==0 );
14300 + db->init.busy = 1;
14301 + for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
14302 + if( DbHasProperty(db, i, DB_SchemaLoaded) || i==1 ) continue;
14303 + rc = sqliteInitOne(db, i, pzErrMsg);
14305 + sqliteResetInternalSchema(db, i);
14309 + /* Once all the other databases have been initialised, load the schema
14310 + ** for the TEMP database. This is loaded last, as the TEMP database
14311 + ** schema may contain references to objects in other databases.
14313 + if( rc==SQLITE_OK && db->nDb>1 && !DbHasProperty(db, 1, DB_SchemaLoaded) ){
14314 + rc = sqliteInitOne(db, 1, pzErrMsg);
14316 + sqliteResetInternalSchema(db, 1);
14320 + db->init.busy = 0;
14321 + if( rc==SQLITE_OK ){
14322 + db->flags |= SQLITE_Initialized;
14323 + sqliteCommitInternalChanges(db);
14326 + /* If the database is in formats 1 or 2, then upgrade it to
14327 + ** version 3. This will reconstruct all indices. If the
14328 + ** upgrade fails for any reason (ex: out of disk space, database
14329 + ** is read only, interrupt received, etc.) then fail the init.
14331 + if( rc==SQLITE_OK && db->file_format<3 ){
14333 + InitData initData;
14334 + int meta[SQLITE_N_BTREE_META];
14336 + db->magic = SQLITE_MAGIC_OPEN;
14337 + initData.db = db;
14338 + initData.pzErrMsg = &zErr;
14339 + db->file_format = 3;
14340 + rc = sqlite_exec(db,
14341 + "BEGIN; SELECT name FROM sqlite_master WHERE type='table';",
14342 + upgrade_3_callback,
14345 + if( rc==SQLITE_OK ){
14346 + sqliteBtreeGetMeta(db->aDb[0].pBt, meta);
14348 + sqliteBtreeUpdateMeta(db->aDb[0].pBt, meta);
14349 + sqlite_exec(db, "COMMIT", 0, 0, 0);
14351 + if( rc!=SQLITE_OK ){
14352 + sqliteSetString(pzErrMsg,
14353 + "unable to upgrade database to the version 2.6 format",
14354 + zErr ? ": " : 0, zErr, (char*)0);
14356 + sqlite_freemem(zErr);
14359 + if( rc!=SQLITE_OK ){
14360 + db->flags &= ~SQLITE_Initialized;
14366 +** The version of the library
14368 +const char rcsid[] = "@(#) \044Id: SQLite version " SQLITE_VERSION " $";
14369 +const char sqlite_version[] = SQLITE_VERSION;
14372 +** Does the library expect data to be encoded as UTF-8 or iso8859? The
14373 +** following global constant always lets us know.
14375 +#ifdef SQLITE_UTF8
14376 +const char sqlite_encoding[] = "UTF-8";
14378 +const char sqlite_encoding[] = "iso8859";
14382 +** Open a new SQLite database. Construct an "sqlite" structure to define
14383 +** the state of this database and return a pointer to that structure.
14385 +** An attempt is made to initialize the in-memory data structures that
14386 +** hold the database schema. But if this fails (because the schema file
14387 +** is locked) then that step is deferred until the first call to
14390 +sqlite *sqlite_open(const char *zFilename, int mode, char **pzErrMsg){
14394 + /* Allocate the sqlite data structure */
14395 + db = sqliteMalloc( sizeof(sqlite) );
14396 + if( pzErrMsg ) *pzErrMsg = 0;
14397 + if( db==0 ) goto no_mem_on_open;
14398 + db->onError = OE_Default;
14399 + db->priorNewRowid = 0;
14400 + db->magic = SQLITE_MAGIC_BUSY;
14402 + db->aDb = db->aDbStatic;
14403 + /* db->flags |= SQLITE_ShortColNames; */
14404 + sqliteHashInit(&db->aFunc, SQLITE_HASH_STRING, 1);
14405 + for(i=0; i<db->nDb; i++){
14406 + sqliteHashInit(&db->aDb[i].tblHash, SQLITE_HASH_STRING, 0);
14407 + sqliteHashInit(&db->aDb[i].idxHash, SQLITE_HASH_STRING, 0);
14408 + sqliteHashInit(&db->aDb[i].trigHash, SQLITE_HASH_STRING, 0);
14409 + sqliteHashInit(&db->aDb[i].aFKey, SQLITE_HASH_STRING, 1);
14412 + /* Open the backend database driver */
14413 + if( zFilename[0]==':' && strcmp(zFilename,":memory:")==0 ){
14414 + db->temp_store = 2;
14416 + rc = sqliteBtreeFactory(db, zFilename, 0, MAX_PAGES, &db->aDb[0].pBt);
14417 + if( rc!=SQLITE_OK ){
14420 + sqliteSetString(pzErrMsg, "unable to open database: ",
14421 + zFilename, (char*)0);
14425 + sqliteStrRealloc(pzErrMsg);
14428 + db->aDb[0].zName = "main";
14429 + db->aDb[1].zName = "temp";
14431 + /* Attempt to read the schema */
14432 + sqliteRegisterBuiltinFunctions(db);
14433 + rc = sqliteInit(db, pzErrMsg);
14434 + db->magic = SQLITE_MAGIC_OPEN;
14435 + if( sqlite_malloc_failed ){
14436 + sqlite_close(db);
14437 + goto no_mem_on_open;
14438 + }else if( rc!=SQLITE_OK && rc!=SQLITE_BUSY ){
14439 + sqlite_close(db);
14440 + sqliteStrRealloc(pzErrMsg);
14442 + }else if( pzErrMsg ){
14443 + sqliteFree(*pzErrMsg);
14447 + /* Return a pointer to the newly opened database structure */
14451 + sqliteSetString(pzErrMsg, "out of memory", (char*)0);
14452 + sqliteStrRealloc(pzErrMsg);
14457 +** Return the ROWID of the most recent insert
14459 +int sqlite_last_insert_rowid(sqlite *db){
14460 + return db->lastRowid;
14464 +** Return the number of changes in the most recent call to sqlite_exec().
14466 +int sqlite_changes(sqlite *db){
14467 + return db->nChange;
14471 +** Return the number of changes produced by the last INSERT, UPDATE, or
14472 +** DELETE statement to complete execution. The count does not include
14473 +** changes due to SQL statements executed in trigger programs that were
14474 +** triggered by that statement
14476 +int sqlite_last_statement_changes(sqlite *db){
14477 + return db->lsChange;
14481 +** Close an existing SQLite database
14483 +void sqlite_close(sqlite *db){
14486 + db->want_to_close = 1;
14487 + if( sqliteSafetyCheck(db) || sqliteSafetyOn(db) ){
14488 + /* printf("DID NOT CLOSE\n"); fflush(stdout); */
14491 + db->magic = SQLITE_MAGIC_CLOSED;
14492 + for(j=0; j<db->nDb; j++){
14493 + struct Db *pDb = &db->aDb[j];
14495 + sqliteBtreeClose(pDb->pBt);
14499 + sqliteResetInternalSchema(db, 0);
14500 + assert( db->nDb<=2 );
14501 + assert( db->aDb==db->aDbStatic );
14502 + for(i=sqliteHashFirst(&db->aFunc); i; i=sqliteHashNext(i)){
14503 + FuncDef *pFunc, *pNext;
14504 + for(pFunc = (FuncDef*)sqliteHashData(i); pFunc; pFunc=pNext){
14505 + pNext = pFunc->pNext;
14506 + sqliteFree(pFunc);
14509 + sqliteHashClear(&db->aFunc);
14514 +** Rollback all database files.
14516 +void sqliteRollbackAll(sqlite *db){
14518 + for(i=0; i<db->nDb; i++){
14519 + if( db->aDb[i].pBt ){
14520 + sqliteBtreeRollback(db->aDb[i].pBt);
14521 + db->aDb[i].inTrans = 0;
14524 + sqliteResetInternalSchema(db, 0);
14525 + /* sqliteRollbackInternalChanges(db); */
14529 +** Execute SQL code. Return one of the SQLITE_ success/failure
14530 +** codes. Also write an error message into memory obtained from
14531 +** malloc() and make *pzErrMsg point to that message.
14533 +** If the SQL is a query, then for each row in the query result
14534 +** the xCallback() function is called. pArg becomes the first
14535 +** argument to xCallback(). If xCallback=NULL then no callback
14536 +** is invoked, even for queries.
14539 + sqlite *db, /* The database on which the SQL executes */
14540 + const char *zSql, /* The SQL to be executed */
14541 + sqlite_callback xCallback, /* Invoke this callback routine */
14542 + void *pArg, /* First argument to xCallback() */
14543 + char **pzErrMsg /* Write error messages here */
14545 + int rc = SQLITE_OK;
14546 + const char *zLeftover;
14552 + if( zSql==0 ) return SQLITE_OK;
14553 + while( rc==SQLITE_OK && zSql[0] ){
14555 + rc = sqlite_compile(db, zSql, &zLeftover, &pVm, pzErrMsg);
14556 + if( rc!=SQLITE_OK ){
14557 + assert( pVm==0 || sqlite_malloc_failed );
14561 + /* This happens if the zSql input contained only whitespace */
14564 + db->nChange += nChange;
14568 + char **azArg, **azCol;
14569 + rc = sqlite_step(pVm, &nArg, (const char***)&azArg,(const char***)&azCol);
14570 + if( rc==SQLITE_ROW ){
14571 + if( xCallback!=0 && xCallback(pArg, nArg, azArg, azCol) ){
14572 + sqlite_finalize(pVm, 0);
14573 + return SQLITE_ABORT;
14577 + if( rc==SQLITE_DONE && nCallback==0
14578 + && (db->flags & SQLITE_NullCallback)!=0 && xCallback!=0 ){
14579 + xCallback(pArg, nArg, azArg, azCol);
14581 + rc = sqlite_finalize(pVm, pzErrMsg);
14582 + if( rc==SQLITE_SCHEMA && nRetry<2 ){
14587 + if( db->pVdbe==0 ){
14588 + nChange = db->nChange;
14591 + zSql = zLeftover;
14592 + while( isspace(zSql[0]) ) zSql++;
14602 +** Compile a single statement of SQL into a virtual machine. Return one
14603 +** of the SQLITE_ success/failure codes. Also write an error message into
14604 +** memory obtained from malloc() and make *pzErrMsg point to that message.
14606 +int sqlite_compile(
14607 + sqlite *db, /* The database on which the SQL executes */
14608 + const char *zSql, /* The SQL to be executed */
14609 + const char **pzTail, /* OUT: Next statement after the first */
14610 + sqlite_vm **ppVm, /* OUT: The virtual machine */
14611 + char **pzErrMsg /* OUT: Write error messages here */
14615 + if( pzErrMsg ) *pzErrMsg = 0;
14616 + if( sqliteSafetyOn(db) ) goto exec_misuse;
14617 + if( !db->init.busy ){
14618 + if( (db->flags & SQLITE_Initialized)==0 ){
14620 + while( (rc = sqliteInit(db, pzErrMsg))==SQLITE_BUSY
14621 + && db->xBusyCallback
14622 + && db->xBusyCallback(db->pBusyArg, "", cnt++)!=0 ){}
14623 + if( rc!=SQLITE_OK ){
14624 + sqliteStrRealloc(pzErrMsg);
14625 + sqliteSafetyOff(db);
14629 + sqliteFree(*pzErrMsg);
14633 + if( db->file_format<3 ){
14634 + sqliteSafetyOff(db);
14635 + sqliteSetString(pzErrMsg, "obsolete database file format", (char*)0);
14636 + return SQLITE_ERROR;
14639 + assert( (db->flags & SQLITE_Initialized)!=0 || db->init.busy );
14640 + if( db->pVdbe==0 ){ db->nChange = 0; }
14641 + memset(&sParse, 0, sizeof(sParse));
14643 + sqliteRunParser(&sParse, zSql, pzErrMsg);
14644 + if( db->xTrace && !db->init.busy ){
14645 + /* Trace only the statment that was compiled.
14646 + ** Make a copy of that part of the SQL string since zSQL is const
14647 + ** and we must pass a zero terminated string to the trace function
14648 + ** The copy is unnecessary if the tail pointer is pointing at the
14649 + ** beginnig or end of the SQL string.
14651 + if( sParse.zTail && sParse.zTail!=zSql && *sParse.zTail ){
14652 + char *tmpSql = sqliteStrNDup(zSql, sParse.zTail - zSql);
14654 + db->xTrace(db->pTraceArg, tmpSql);
14657 + /* If a memory error occurred during the copy,
14658 + ** trace entire SQL string and fall through to the
14659 + ** sqlite_malloc_failed test to report the error.
14661 + db->xTrace(db->pTraceArg, zSql);
14664 + db->xTrace(db->pTraceArg, zSql);
14667 + if( sqlite_malloc_failed ){
14668 + sqliteSetString(pzErrMsg, "out of memory", (char*)0);
14669 + sParse.rc = SQLITE_NOMEM;
14670 + sqliteRollbackAll(db);
14671 + sqliteResetInternalSchema(db, 0);
14672 + db->flags &= ~SQLITE_InTrans;
14674 + if( sParse.rc==SQLITE_DONE ) sParse.rc = SQLITE_OK;
14675 + if( sParse.rc!=SQLITE_OK && pzErrMsg && *pzErrMsg==0 ){
14676 + sqliteSetString(pzErrMsg, sqlite_error_string(sParse.rc), (char*)0);
14678 + sqliteStrRealloc(pzErrMsg);
14679 + if( sParse.rc==SQLITE_SCHEMA ){
14680 + sqliteResetInternalSchema(db, 0);
14683 + *ppVm = (sqlite_vm*)sParse.pVdbe;
14684 + if( pzTail ) *pzTail = sParse.zTail;
14685 + if( sqliteSafetyOff(db) ) goto exec_misuse;
14686 + return sParse.rc;
14691 + sqliteSetString(pzErrMsg, sqlite_error_string(SQLITE_MISUSE), (char*)0);
14692 + sqliteStrRealloc(pzErrMsg);
14694 + return SQLITE_MISUSE;
14699 +** The following routine destroys a virtual machine that is created by
14700 +** the sqlite_compile() routine.
14702 +** The integer returned is an SQLITE_ success/failure code that describes
14703 +** the result of executing the virtual machine. An error message is
14704 +** written into memory obtained from malloc and *pzErrMsg is made to
14705 +** point to that error if pzErrMsg is not NULL. The calling routine
14706 +** should use sqlite_freemem() to delete the message when it has finished
14709 +int sqlite_finalize(
14710 + sqlite_vm *pVm, /* The virtual machine to be destroyed */
14711 + char **pzErrMsg /* OUT: Write error messages here */
14713 + int rc = sqliteVdbeFinalize((Vdbe*)pVm, pzErrMsg);
14714 + sqliteStrRealloc(pzErrMsg);
14719 +** Terminate the current execution of a virtual machine then
14720 +** reset the virtual machine back to its starting state so that it
14721 +** can be reused. Any error message resulting from the prior execution
14722 +** is written into *pzErrMsg. A success code from the prior execution
14726 + sqlite_vm *pVm, /* The virtual machine to be destroyed */
14727 + char **pzErrMsg /* OUT: Write error messages here */
14729 + int rc = sqliteVdbeReset((Vdbe*)pVm, pzErrMsg);
14730 + sqliteVdbeMakeReady((Vdbe*)pVm, -1, 0);
14731 + sqliteStrRealloc(pzErrMsg);
14736 +** Return a static string that describes the kind of error specified in the
14739 +const char *sqlite_error_string(int rc){
14742 + case SQLITE_OK: z = "not an error"; break;
14743 + case SQLITE_ERROR: z = "SQL logic error or missing database"; break;
14744 + case SQLITE_INTERNAL: z = "internal SQLite implementation flaw"; break;
14745 + case SQLITE_PERM: z = "access permission denied"; break;
14746 + case SQLITE_ABORT: z = "callback requested query abort"; break;
14747 + case SQLITE_BUSY: z = "database is locked"; break;
14748 + case SQLITE_LOCKED: z = "database table is locked"; break;
14749 + case SQLITE_NOMEM: z = "out of memory"; break;
14750 + case SQLITE_READONLY: z = "attempt to write a readonly database"; break;
14751 + case SQLITE_INTERRUPT: z = "interrupted"; break;
14752 + case SQLITE_IOERR: z = "disk I/O error"; break;
14753 + case SQLITE_CORRUPT: z = "database disk image is malformed"; break;
14754 + case SQLITE_NOTFOUND: z = "table or record not found"; break;
14755 + case SQLITE_FULL: z = "database is full"; break;
14756 + case SQLITE_CANTOPEN: z = "unable to open database file"; break;
14757 + case SQLITE_PROTOCOL: z = "database locking protocol failure"; break;
14758 + case SQLITE_EMPTY: z = "table contains no data"; break;
14759 + case SQLITE_SCHEMA: z = "database schema has changed"; break;
14760 + case SQLITE_TOOBIG: z = "too much data for one table row"; break;
14761 + case SQLITE_CONSTRAINT: z = "constraint failed"; break;
14762 + case SQLITE_MISMATCH: z = "datatype mismatch"; break;
14763 + case SQLITE_MISUSE: z = "library routine called out of sequence";break;
14764 + case SQLITE_NOLFS: z = "kernel lacks large file support"; break;
14765 + case SQLITE_AUTH: z = "authorization denied"; break;
14766 + case SQLITE_FORMAT: z = "auxiliary database format error"; break;
14767 + case SQLITE_RANGE: z = "bind index out of range"; break;
14768 + case SQLITE_NOTADB: z = "file is encrypted or is not a database";break;
14769 + default: z = "unknown error"; break;
14775 +** This routine implements a busy callback that sleeps and tries
14776 +** again until a timeout value is reached. The timeout value is
14777 +** an integer number of milliseconds passed in as the first
14780 +static int sqliteDefaultBusyCallback(
14781 + void *Timeout, /* Maximum amount of time to wait */
14782 + const char *NotUsed, /* The name of the table that is busy */
14783 + int count /* Number of times table has been busy */
14785 +#if SQLITE_MIN_SLEEP_MS==1
14786 + static const char delays[] =
14787 + { 1, 2, 5, 10, 15, 20, 25, 25, 25, 50, 50, 50, 100};
14788 + static const short int totals[] =
14789 + { 0, 1, 3, 8, 18, 33, 53, 78, 103, 128, 178, 228, 287};
14790 +# define NDELAY (sizeof(delays)/sizeof(delays[0]))
14791 + int timeout = (int)(long)Timeout;
14792 + int delay, prior;
14794 + if( count <= NDELAY ){
14795 + delay = delays[count-1];
14796 + prior = totals[count-1];
14798 + delay = delays[NDELAY-1];
14799 + prior = totals[NDELAY-1] + delay*(count-NDELAY-1);
14801 + if( prior + delay > timeout ){
14802 + delay = timeout - prior;
14803 + if( delay<=0 ) return 0;
14805 + sqliteOsSleep(delay);
14808 + int timeout = (int)(long)Timeout;
14809 + if( (count+1)*1000 > timeout ){
14812 + sqliteOsSleep(1000);
14818 +** This routine sets the busy callback for an Sqlite database to the
14819 +** given callback function with the given argument.
14821 +void sqlite_busy_handler(
14823 + int (*xBusy)(void*,const char*,int),
14826 + db->xBusyCallback = xBusy;
14827 + db->pBusyArg = pArg;
14830 +#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
14832 +** This routine sets the progress callback for an Sqlite database to the
14833 +** given callback function with the given argument. The progress callback will
14834 +** be invoked every nOps opcodes.
14836 +void sqlite_progress_handler(
14839 + int (*xProgress)(void*),
14843 + db->xProgress = xProgress;
14844 + db->nProgressOps = nOps;
14845 + db->pProgressArg = pArg;
14847 + db->xProgress = 0;
14848 + db->nProgressOps = 0;
14849 + db->pProgressArg = 0;
14856 +** This routine installs a default busy handler that waits for the
14857 +** specified number of milliseconds before returning 0.
14859 +void sqlite_busy_timeout(sqlite *db, int ms){
14861 + sqlite_busy_handler(db, sqliteDefaultBusyCallback, (void*)(long)ms);
14863 + sqlite_busy_handler(db, 0, 0);
14868 +** Cause any pending operation to stop at its earliest opportunity.
14870 +void sqlite_interrupt(sqlite *db){
14871 + db->flags |= SQLITE_Interrupt;
14875 +** Windows systems should call this routine to free memory that
14876 +** is returned in the in the errmsg parameter of sqlite_open() when
14877 +** SQLite is a DLL. For some reason, it does not work to call free()
14880 +** Note that we need to call free() not sqliteFree() here, since every
14881 +** string that is exported from SQLite should have already passed through
14882 +** sqliteStrRealloc().
14884 +void sqlite_freemem(void *p){ free(p); }
14887 +** Windows systems need functions to call to return the sqlite_version
14888 +** and sqlite_encoding strings since they are unable to access constants
14891 +const char *sqlite_libversion(void){ return sqlite_version; }
14892 +const char *sqlite_libencoding(void){ return sqlite_encoding; }
14895 +** Create new user-defined functions. The sqlite_create_function()
14896 +** routine creates a regular function and sqlite_create_aggregate()
14897 +** creates an aggregate function.
14899 +** Passing a NULL xFunc argument or NULL xStep and xFinalize arguments
14900 +** disables the function. Calling sqlite_create_function() with the
14901 +** same name and number of arguments as a prior call to
14902 +** sqlite_create_aggregate() disables the prior call to
14903 +** sqlite_create_aggregate(), and vice versa.
14905 +** If nArg is -1 it means that this function will accept any number
14906 +** of arguments, including 0. The maximum allowed value of nArg is 127.
14908 +int sqlite_create_function(
14909 + sqlite *db, /* Add the function to this database connection */
14910 + const char *zName, /* Name of the function to add */
14911 + int nArg, /* Number of arguments */
14912 + void (*xFunc)(sqlite_func*,int,const char**), /* The implementation */
14913 + void *pUserData /* User data */
14917 + if( db==0 || zName==0 || sqliteSafetyCheck(db) ) return 1;
14918 + if( nArg<-1 || nArg>127 ) return 1;
14919 + nName = strlen(zName);
14920 + if( nName>255 ) return 1;
14921 + p = sqliteFindFunction(db, zName, nName, nArg, 1);
14922 + if( p==0 ) return 1;
14923 + p->xFunc = xFunc;
14925 + p->xFinalize = 0;
14926 + p->pUserData = pUserData;
14929 +int sqlite_create_aggregate(
14930 + sqlite *db, /* Add the function to this database connection */
14931 + const char *zName, /* Name of the function to add */
14932 + int nArg, /* Number of arguments */
14933 + void (*xStep)(sqlite_func*,int,const char**), /* The step function */
14934 + void (*xFinalize)(sqlite_func*), /* The finalizer */
14935 + void *pUserData /* User data */
14939 + if( db==0 || zName==0 || sqliteSafetyCheck(db) ) return 1;
14940 + if( nArg<-1 || nArg>127 ) return 1;
14941 + nName = strlen(zName);
14942 + if( nName>255 ) return 1;
14943 + p = sqliteFindFunction(db, zName, nName, nArg, 1);
14944 + if( p==0 ) return 1;
14946 + p->xStep = xStep;
14947 + p->xFinalize = xFinalize;
14948 + p->pUserData = pUserData;
14953 +** Change the datatype for all functions with a given name. See the
14954 +** header comment for the prototype of this function in sqlite.h for
14955 +** additional information.
14957 +int sqlite_function_type(sqlite *db, const char *zName, int dataType){
14958 + FuncDef *p = (FuncDef*)sqliteHashFind(&db->aFunc, zName, strlen(zName));
14960 + p->dataType = dataType;
14963 + return SQLITE_OK;
14967 +** Register a trace function. The pArg from the previously registered trace
14970 +** A NULL trace function means that no tracing is executes. A non-NULL
14971 +** trace is a pointer to a function that is invoked at the start of each
14974 +void *sqlite_trace(sqlite *db, void (*xTrace)(void*,const char*), void *pArg){
14975 + void *pOld = db->pTraceArg;
14976 + db->xTrace = xTrace;
14977 + db->pTraceArg = pArg;
14981 +/*** EXPERIMENTAL ***
14983 +** Register a function to be invoked when a transaction comments.
14984 +** If either function returns non-zero, then the commit becomes a
14987 +void *sqlite_commit_hook(
14988 + sqlite *db, /* Attach the hook to this database */
14989 + int (*xCallback)(void*), /* Function to invoke on each commit */
14990 + void *pArg /* Argument to the function */
14992 + void *pOld = db->pCommitArg;
14993 + db->xCommitCallback = xCallback;
14994 + db->pCommitArg = pArg;
15000 +** This routine is called to create a connection to a database BTree
15001 +** driver. If zFilename is the name of a file, then that file is
15002 +** opened and used. If zFilename is the magic name ":memory:" then
15003 +** the database is stored in memory (and is thus forgotten as soon as
15004 +** the connection is closed.) If zFilename is NULL then the database
15005 +** is for temporary use only and is deleted as soon as the connection
15008 +** A temporary database can be either a disk file (that is automatically
15009 +** deleted when the file is closed) or a set of red-black trees held in memory,
15010 +** depending on the values of the TEMP_STORE compile-time macro and the
15011 +** db->temp_store variable, according to the following chart:
15013 +** TEMP_STORE db->temp_store Location of temporary database
15014 +** ---------- -------------- ------------------------------
15024 +int sqliteBtreeFactory(
15025 + const sqlite *db, /* Main database when opening aux otherwise 0 */
15026 + const char *zFilename, /* Name of the file containing the BTree database */
15027 + int omitJournal, /* if TRUE then do not journal this file */
15028 + int nCache, /* How many pages in the page cache */
15029 + Btree **ppBtree){ /* Pointer to new Btree object written here */
15031 + assert( ppBtree != 0);
15033 +#ifndef SQLITE_OMIT_INMEMORYDB
15034 + if( zFilename==0 ){
15035 + if (TEMP_STORE == 0) {
15036 + /* Always use file based temporary DB */
15037 + return sqliteBtreeOpen(0, omitJournal, nCache, ppBtree);
15038 + } else if (TEMP_STORE == 1 || TEMP_STORE == 2) {
15039 + /* Switch depending on compile-time and/or runtime settings. */
15040 + int location = db->temp_store==0 ? TEMP_STORE : db->temp_store;
15042 + if (location == 1) {
15043 + return sqliteBtreeOpen(zFilename, omitJournal, nCache, ppBtree);
15045 + return sqliteRbtreeOpen(0, 0, 0, ppBtree);
15048 + /* Always use in-core DB */
15049 + return sqliteRbtreeOpen(0, 0, 0, ppBtree);
15051 + }else if( zFilename[0]==':' && strcmp(zFilename,":memory:")==0 ){
15052 + return sqliteRbtreeOpen(0, 0, 0, ppBtree);
15056 + return sqliteBtreeOpen(zFilename, omitJournal, nCache, ppBtree);
15060 +++ b/ext/sqlite/libsqlite/src/opcodes.c
15062 +/* Automatically generated file. Do not edit */
15063 +char *sqliteOpcodeNames[] = { "???",
15203 +++ b/ext/sqlite/libsqlite/src/opcodes.h
15205 +/* Automatically generated file. Do not edit */
15207 +#define OP_Gosub 2
15208 +#define OP_Return 3
15210 +#define OP_Integer 5
15211 +#define OP_String 6
15212 +#define OP_Variable 7
15215 +#define OP_Pull 10
15216 +#define OP_Push 11
15217 +#define OP_ColumnName 12
15218 +#define OP_Callback 13
15219 +#define OP_Concat 14
15221 +#define OP_Subtract 16
15222 +#define OP_Multiply 17
15223 +#define OP_Divide 18
15224 +#define OP_Remainder 19
15225 +#define OP_Function 20
15226 +#define OP_BitAnd 21
15227 +#define OP_BitOr 22
15228 +#define OP_ShiftLeft 23
15229 +#define OP_ShiftRight 24
15230 +#define OP_AddImm 25
15231 +#define OP_ForceInt 26
15232 +#define OP_MustBeInt 27
15239 +#define OP_StrEq 34
15240 +#define OP_StrNe 35
15241 +#define OP_StrLt 36
15242 +#define OP_StrLe 37
15243 +#define OP_StrGt 38
15244 +#define OP_StrGe 39
15247 +#define OP_Negative 42
15248 +#define OP_AbsValue 43
15250 +#define OP_BitNot 45
15251 +#define OP_Noop 46
15253 +#define OP_IfNot 48
15254 +#define OP_IsNull 49
15255 +#define OP_NotNull 50
15256 +#define OP_MakeRecord 51
15257 +#define OP_MakeIdxKey 52
15258 +#define OP_MakeKey 53
15259 +#define OP_IncrKey 54
15260 +#define OP_Checkpoint 55
15261 +#define OP_Transaction 56
15262 +#define OP_Commit 57
15263 +#define OP_Rollback 58
15264 +#define OP_ReadCookie 59
15265 +#define OP_SetCookie 60
15266 +#define OP_VerifyCookie 61
15267 +#define OP_OpenRead 62
15268 +#define OP_OpenWrite 63
15269 +#define OP_OpenTemp 64
15270 +#define OP_OpenPseudo 65
15271 +#define OP_Close 66
15272 +#define OP_MoveLt 67
15273 +#define OP_MoveTo 68
15274 +#define OP_Distinct 69
15275 +#define OP_NotFound 70
15276 +#define OP_Found 71
15277 +#define OP_IsUnique 72
15278 +#define OP_NotExists 73
15279 +#define OP_NewRecno 74
15280 +#define OP_PutIntKey 75
15281 +#define OP_PutStrKey 76
15282 +#define OP_Delete 77
15283 +#define OP_SetCounts 78
15284 +#define OP_KeyAsData 79
15285 +#define OP_RowKey 80
15286 +#define OP_RowData 81
15287 +#define OP_Column 82
15288 +#define OP_Recno 83
15289 +#define OP_FullKey 84
15290 +#define OP_NullRow 85
15291 +#define OP_Last 86
15292 +#define OP_Rewind 87
15293 +#define OP_Prev 88
15294 +#define OP_Next 89
15295 +#define OP_IdxPut 90
15296 +#define OP_IdxDelete 91
15297 +#define OP_IdxRecno 92
15298 +#define OP_IdxLT 93
15299 +#define OP_IdxGT 94
15300 +#define OP_IdxGE 95
15301 +#define OP_IdxIsNull 96
15302 +#define OP_Destroy 97
15303 +#define OP_Clear 98
15304 +#define OP_CreateIndex 99
15305 +#define OP_CreateTable 100
15306 +#define OP_IntegrityCk 101
15307 +#define OP_ListWrite 102
15308 +#define OP_ListRewind 103
15309 +#define OP_ListRead 104
15310 +#define OP_ListReset 105
15311 +#define OP_ListPush 106
15312 +#define OP_ListPop 107
15313 +#define OP_ContextPush 108
15314 +#define OP_ContextPop 109
15315 +#define OP_SortPut 110
15316 +#define OP_SortMakeRec 111
15317 +#define OP_SortMakeKey 112
15318 +#define OP_Sort 113
15319 +#define OP_SortNext 114
15320 +#define OP_SortCallback 115
15321 +#define OP_SortReset 116
15322 +#define OP_FileOpen 117
15323 +#define OP_FileRead 118
15324 +#define OP_FileColumn 119
15325 +#define OP_MemStore 120
15326 +#define OP_MemLoad 121
15327 +#define OP_MemIncr 122
15328 +#define OP_AggReset 123
15329 +#define OP_AggInit 124
15330 +#define OP_AggFunc 125
15331 +#define OP_AggFocus 126
15332 +#define OP_AggSet 127
15333 +#define OP_AggGet 128
15334 +#define OP_AggNext 129
15335 +#define OP_SetInsert 130
15336 +#define OP_SetFound 131
15337 +#define OP_SetNotFound 132
15338 +#define OP_SetFirst 133
15339 +#define OP_SetNext 134
15340 +#define OP_Vacuum 135
15341 +#define OP_StackDepth 136
15342 +#define OP_StackReset 137
15344 +++ b/ext/sqlite/libsqlite/src/os.c
15347 +** 2001 September 16
15349 +** The author disclaims copyright to this source code. In place of
15350 +** a legal notice, here is a blessing:
15352 +** May you do good and not evil.
15353 +** May you find forgiveness for yourself and forgive others.
15354 +** May you share freely, never taking more than you give.
15356 +******************************************************************************
15358 +** This file contains code that is specific to particular operating
15359 +** systems. The purpose of this file is to provide a uniform abstraction
15360 +** on which the rest of SQLite can operate.
15362 +#include "os.h" /* Must be first to enable large file support */
15363 +#include "sqliteInt.h"
15366 +# include <time.h>
15367 +# include <errno.h>
15368 +# include <unistd.h>
15369 +# ifndef O_LARGEFILE
15370 +# define O_LARGEFILE 0
15372 +# ifdef SQLITE_DISABLE_LFS
15373 +# undef O_LARGEFILE
15374 +# define O_LARGEFILE 0
15376 +# ifndef O_NOFOLLOW
15377 +# define O_NOFOLLOW 0
15380 +# define O_BINARY 0
15386 +# include <winbase.h>
15390 +# include <extras.h>
15391 +# include <path2fss.h>
15392 +# include <TextUtils.h>
15393 +# include <FinderRegistry.h>
15394 +# include <Folders.h>
15395 +# include <Timer.h>
15396 +# include <OSUtils.h>
15400 +** The DJGPP compiler environment looks mostly like Unix, but it
15401 +** lacks the fcntl() system call. So redefine fcntl() to be something
15402 +** that always succeeds. This means that locking does not occur under
15403 +** DJGPP. But its DOS - what did you expect?
15406 +# define fcntl(A,B,C) 0
15410 +** Macros used to determine whether or not to use threads. The
15411 +** SQLITE_UNIX_THREADS macro is defined if we are synchronizing for
15412 +** Posix threads and SQLITE_W32_THREADS is defined if we are
15413 +** synchronizing using Win32 threads.
15415 +#if OS_UNIX && defined(THREADSAFE) && THREADSAFE
15416 +# include <pthread.h>
15417 +# define SQLITE_UNIX_THREADS 1
15419 +#if OS_WIN && defined(THREADSAFE) && THREADSAFE
15420 +# define SQLITE_W32_THREADS 1
15422 +#if OS_MAC && defined(THREADSAFE) && THREADSAFE
15423 +# include <Multiprocessing.h>
15424 +# define SQLITE_MACOS_MULTITASKING 1
15428 +** Macros for performance tracing. Normally turned off
15431 +static int last_page = 0;
15432 +__inline__ unsigned long long int hwtime(void){
15433 + unsigned long long int x;
15434 + __asm__("rdtsc\n\t"
15435 + "mov %%edx, %%ecx\n\t"
15439 +static unsigned long long int g_start;
15440 +static unsigned int elapse;
15441 +#define TIMER_START g_start=hwtime()
15442 +#define TIMER_END elapse=hwtime()-g_start
15443 +#define SEEK(X) last_page=(X)
15444 +#define TRACE1(X) fprintf(stderr,X)
15445 +#define TRACE2(X,Y) fprintf(stderr,X,Y)
15446 +#define TRACE3(X,Y,Z) fprintf(stderr,X,Y,Z)
15447 +#define TRACE4(X,Y,Z,A) fprintf(stderr,X,Y,Z,A)
15448 +#define TRACE5(X,Y,Z,A,B) fprintf(stderr,X,Y,Z,A,B)
15450 +#define TIMER_START
15454 +#define TRACE2(X,Y)
15455 +#define TRACE3(X,Y,Z)
15456 +#define TRACE4(X,Y,Z,A)
15457 +#define TRACE5(X,Y,Z,A,B)
15463 +** Here is the dirt on POSIX advisory locks: ANSI STD 1003.1 (1996)
15464 +** section 6.5.2.2 lines 483 through 490 specify that when a process
15465 +** sets or clears a lock, that operation overrides any prior locks set
15466 +** by the same process. It does not explicitly say so, but this implies
15467 +** that it overrides locks set by the same process using a different
15468 +** file descriptor. Consider this test case:
15470 +** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
15471 +** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
15473 +** Suppose ./file1 and ./file2 are really the same file (because
15474 +** one is a hard or symbolic link to the other) then if you set
15475 +** an exclusive lock on fd1, then try to get an exclusive lock
15476 +** on fd2, it works. I would have expected the second lock to
15477 +** fail since there was already a lock on the file due to fd1.
15478 +** But not so. Since both locks came from the same process, the
15479 +** second overrides the first, even though they were on different
15480 +** file descriptors opened on different file names.
15482 +** Bummer. If you ask me, this is broken. Badly broken. It means
15483 +** that we cannot use POSIX locks to synchronize file access among
15484 +** competing threads of the same process. POSIX locks will work fine
15485 +** to synchronize access for threads in separate processes, but not
15486 +** threads within the same process.
15488 +** To work around the problem, SQLite has to manage file locks internally
15489 +** on its own. Whenever a new database is opened, we have to find the
15490 +** specific inode of the database file (the inode is determined by the
15491 +** st_dev and st_ino fields of the stat structure that fstat() fills in)
15492 +** and check for locks already existing on that inode. When locks are
15493 +** created or removed, we have to look at our own internal record of the
15494 +** locks to see if another thread has previously set a lock on that same
15497 +** The OsFile structure for POSIX is no longer just an integer file
15498 +** descriptor. It is now a structure that holds the integer file
15499 +** descriptor and a pointer to a structure that describes the internal
15500 +** locks on the corresponding inode. There is one locking structure
15501 +** per inode, so if the same inode is opened twice, both OsFile structures
15502 +** point to the same locking structure. The locking structure keeps
15503 +** a reference count (so we will know when to delete it) and a "cnt"
15504 +** field that tells us its internal lock status. cnt==0 means the
15505 +** file is unlocked. cnt==-1 means the file has an exclusive lock.
15506 +** cnt>0 means there are cnt shared locks on the file.
15508 +** Any attempt to lock or unlock a file first checks the locking
15509 +** structure. The fcntl() system call is only invoked to set a
15510 +** POSIX lock if the internal lock structure transitions between
15511 +** a locked and an unlocked state.
15514 +** More recent discoveries about POSIX advisory locks. (The more
15515 +** I discover, the more I realize the a POSIX advisory locks are
15516 +** an abomination.)
15518 +** If you close a file descriptor that points to a file that has locks,
15519 +** all locks on that file that are owned by the current process are
15520 +** released. To work around this problem, each OsFile structure contains
15521 +** a pointer to an openCnt structure. There is one openCnt structure
15522 +** per open inode, which means that multiple OsFiles can point to a single
15523 +** openCnt. When an attempt is made to close an OsFile, if there are
15524 +** other OsFiles open on the same inode that are holding locks, the call
15525 +** to close() the file descriptor is deferred until all of the locks clear.
15526 +** The openCnt structure keeps a list of file descriptors that need to
15527 +** be closed and that list is walked (and cleared) when the last lock
15530 +** First, under Linux threads, because each thread has a separate
15531 +** process ID, lock operations in one thread do not override locks
15532 +** to the same file in other threads. Linux threads behave like
15533 +** separate processes in this respect. But, if you close a file
15534 +** descriptor in linux threads, all locks are cleared, even locks
15535 +** on other threads and even though the other threads have different
15536 +** process IDs. Linux threads is inconsistent in this respect.
15537 +** (I'm beginning to think that linux threads is an abomination too.)
15538 +** The consequence of this all is that the hash table for the lockInfo
15539 +** structure has to include the process id as part of its key because
15540 +** locks in different threads are treated as distinct. But the
15541 +** openCnt structure should not include the process id in its
15542 +** key because close() clears lock on all threads, not just the current
15543 +** thread. Were it not for this goofiness in linux threads, we could
15544 +** combine the lockInfo and openCnt structures into a single structure.
15548 +** An instance of the following structure serves as the key used
15549 +** to locate a particular lockInfo structure given its inode. Note
15550 +** that we have to include the process ID as part of the key. On some
15551 +** threading implementations (ex: linux), each thread has a separate
15555 + dev_t dev; /* Device number */
15556 + ino_t ino; /* Inode number */
15557 + pid_t pid; /* Process ID */
15561 +** An instance of the following structure is allocated for each open
15562 +** inode on each thread with a different process ID. (Threads have
15563 +** different process IDs on linux, but not on most other unixes.)
15565 +** A single inode can have multiple file descriptors, so each OsFile
15566 +** structure contains a pointer to an instance of this object and this
15567 +** object keeps a count of the number of OsFiles pointing to it.
15570 + struct lockKey key; /* The lookup key */
15571 + int cnt; /* 0: unlocked. -1: write lock. 1...: read lock. */
15572 + int nRef; /* Number of pointers to this structure */
15576 +** An instance of the following structure serves as the key used
15577 +** to locate a particular openCnt structure given its inode. This
15578 +** is the same as the lockKey except that the process ID is omitted.
15581 + dev_t dev; /* Device number */
15582 + ino_t ino; /* Inode number */
15586 +** An instance of the following structure is allocated for each open
15587 +** inode. This structure keeps track of the number of locks on that
15588 +** inode. If a close is attempted against an inode that is holding
15589 +** locks, the close is deferred until all locks clear by adding the
15590 +** file descriptor to be closed to the pending list.
15593 + struct openKey key; /* The lookup key */
15594 + int nRef; /* Number of pointers to this structure */
15595 + int nLock; /* Number of outstanding locks */
15596 + int nPending; /* Number of pending close() operations */
15597 + int *aPending; /* Malloced space holding fd's awaiting a close() */
15601 +** These hash table maps inodes and process IDs into lockInfo and openCnt
15602 +** structures. Access to these hash tables must be protected by a mutex.
15604 +static Hash lockHash = { SQLITE_HASH_BINARY, 0, 0, 0, 0, 0 };
15605 +static Hash openHash = { SQLITE_HASH_BINARY, 0, 0, 0, 0, 0 };
15608 +** Release a lockInfo structure previously allocated by findLockInfo().
15610 +static void releaseLockInfo(struct lockInfo *pLock){
15612 + if( pLock->nRef==0 ){
15613 + sqliteHashInsert(&lockHash, &pLock->key, sizeof(pLock->key), 0);
15614 + sqliteFree(pLock);
15619 +** Release a openCnt structure previously allocated by findLockInfo().
15621 +static void releaseOpenCnt(struct openCnt *pOpen){
15623 + if( pOpen->nRef==0 ){
15624 + sqliteHashInsert(&openHash, &pOpen->key, sizeof(pOpen->key), 0);
15625 + sqliteFree(pOpen->aPending);
15626 + sqliteFree(pOpen);
15631 +** Given a file descriptor, locate lockInfo and openCnt structures that
15632 +** describes that file descriptor. Create a new ones if necessary. The
15633 +** return values might be unset if an error occurs.
15635 +** Return the number of errors.
15638 + int fd, /* The file descriptor used in the key */
15639 + struct lockInfo **ppLock, /* Return the lockInfo structure here */
15640 + struct openCnt **ppOpen /* Return the openCnt structure here */
15643 + struct lockKey key1;
15644 + struct openKey key2;
15645 + struct stat statbuf;
15646 + struct lockInfo *pLock;
15647 + struct openCnt *pOpen;
15648 + rc = fstat(fd, &statbuf);
15649 + if( rc!=0 ) return 1;
15650 + memset(&key1, 0, sizeof(key1));
15651 + key1.dev = statbuf.st_dev;
15652 + key1.ino = statbuf.st_ino;
15653 + key1.pid = getpid();
15654 + memset(&key2, 0, sizeof(key2));
15655 + key2.dev = statbuf.st_dev;
15656 + key2.ino = statbuf.st_ino;
15657 + pLock = (struct lockInfo*)sqliteHashFind(&lockHash, &key1, sizeof(key1));
15659 + struct lockInfo *pOld;
15660 + pLock = sqliteMallocRaw( sizeof(*pLock) );
15661 + if( pLock==0 ) return 1;
15662 + pLock->key = key1;
15665 + pOld = sqliteHashInsert(&lockHash, &pLock->key, sizeof(key1), pLock);
15667 + assert( pOld==pLock );
15668 + sqliteFree(pLock);
15675 + pOpen = (struct openCnt*)sqliteHashFind(&openHash, &key2, sizeof(key2));
15677 + struct openCnt *pOld;
15678 + pOpen = sqliteMallocRaw( sizeof(*pOpen) );
15680 + releaseLockInfo(pLock);
15683 + pOpen->key = key2;
15685 + pOpen->nLock = 0;
15686 + pOpen->nPending = 0;
15687 + pOpen->aPending = 0;
15688 + pOld = sqliteHashInsert(&openHash, &pOpen->key, sizeof(key2), pOpen);
15690 + assert( pOld==pOpen );
15691 + sqliteFree(pOpen);
15692 + releaseLockInfo(pLock);
15702 +#endif /** POSIX advisory lock work-around **/
15705 +** If we compile with the SQLITE_TEST macro set, then the following block
15706 +** of code will give us the ability to simulate a disk I/O error. This
15707 +** is used for testing the I/O recovery logic.
15709 +#ifdef SQLITE_TEST
15710 +int sqlite_io_error_pending = 0;
15711 +#define SimulateIOError(A) \
15712 + if( sqlite_io_error_pending ) \
15713 + if( sqlite_io_error_pending-- == 1 ){ local_ioerr(); return A; }
15714 +static void local_ioerr(){
15715 + sqlite_io_error_pending = 0; /* Really just a place to set a breakpoint */
15718 +#define SimulateIOError(A)
15722 +** When testing, keep a count of the number of open files.
15724 +#ifdef SQLITE_TEST
15725 +int sqlite_open_file_count = 0;
15726 +#define OpenCounter(X) sqlite_open_file_count+=(X)
15728 +#define OpenCounter(X)
15733 +** Delete the named file
15735 +int sqliteOsDelete(const char *zFilename){
15737 + unlink(zFilename);
15740 + DeleteFile(zFilename);
15743 + unlink(zFilename);
15745 + return SQLITE_OK;
15749 +** Return TRUE if the named file exists.
15751 +int sqliteOsFileExists(const char *zFilename){
15753 + return access(zFilename, 0)==0;
15756 + return GetFileAttributes(zFilename) != 0xffffffff;
15759 + return access(zFilename, 0)==0;
15764 +#if 0 /* NOT USED */
15766 +** Change the name of an existing file.
15768 +int sqliteOsFileRename(const char *zOldName, const char *zNewName){
15770 + if( link(zOldName, zNewName) ){
15771 + return SQLITE_ERROR;
15773 + unlink(zOldName);
15774 + return SQLITE_OK;
15777 + if( !MoveFile(zOldName, zNewName) ){
15778 + return SQLITE_ERROR;
15780 + return SQLITE_OK;
15783 + /**** FIX ME ***/
15784 + return SQLITE_ERROR;
15787 +#endif /* NOT USED */
15790 +** Attempt to open a file for both reading and writing. If that
15791 +** fails, try opening it read-only. If the file does not exist,
15792 +** try to create it.
15794 +** On success, a handle for the open file is written to *id
15795 +** and *pReadonly is set to 0 if the file was opened for reading and
15796 +** writing or 1 if the file was opened read-only. The function returns
15799 +** On failure, the function returns SQLITE_CANTOPEN and leaves
15800 +** *id and *pReadonly unchanged.
15802 +int sqliteOsOpenReadWrite(
15803 + const char *zFilename,
15810 + id->fd = open(zFilename, O_RDWR|O_CREAT|O_LARGEFILE|O_BINARY, 0644);
15813 + if( errno==EISDIR ){
15814 + return SQLITE_CANTOPEN;
15817 + id->fd = open(zFilename, O_RDONLY|O_LARGEFILE|O_BINARY);
15819 + return SQLITE_CANTOPEN;
15825 + sqliteOsEnterMutex();
15826 + rc = findLockInfo(id->fd, &id->pLock, &id->pOpen);
15827 + sqliteOsLeaveMutex();
15830 + return SQLITE_NOMEM;
15833 + TRACE3("OPEN %-3d %s\n", id->fd, zFilename);
15835 + return SQLITE_OK;
15838 + HANDLE h = CreateFile(zFilename,
15839 + GENERIC_READ | GENERIC_WRITE,
15840 + FILE_SHARE_READ | FILE_SHARE_WRITE,
15843 + FILE_ATTRIBUTE_NORMAL | FILE_FLAG_RANDOM_ACCESS,
15846 + if( h==INVALID_HANDLE_VALUE ){
15847 + h = CreateFile(zFilename,
15852 + FILE_ATTRIBUTE_NORMAL | FILE_FLAG_RANDOM_ACCESS,
15855 + if( h==INVALID_HANDLE_VALUE ){
15856 + return SQLITE_CANTOPEN;
15865 + return SQLITE_OK;
15869 +# ifdef _LARGE_FILE
15870 + HFSUniStr255 dfName;
15872 + if( __path2fss(zFilename, &fsSpec) != noErr ){
15873 + if( HCreate(fsSpec.vRefNum, fsSpec.parID, fsSpec.name, 'SQLI', cDocumentFile) != noErr )
15874 + return SQLITE_CANTOPEN;
15876 + if( FSpMakeFSRef(&fsSpec, &fsRef) != noErr )
15877 + return SQLITE_CANTOPEN;
15878 + FSGetDataForkName(&dfName);
15879 + if( FSOpenFork(&fsRef, dfName.length, dfName.unicode,
15880 + fsRdWrShPerm, &(id->refNum)) != noErr ){
15881 + if( FSOpenFork(&fsRef, dfName.length, dfName.unicode,
15882 + fsRdWrPerm, &(id->refNum)) != noErr ){
15883 + if (FSOpenFork(&fsRef, dfName.length, dfName.unicode,
15884 + fsRdPerm, &(id->refNum)) != noErr )
15885 + return SQLITE_CANTOPEN;
15893 + __path2fss(zFilename, &fsSpec);
15894 + if( !sqliteOsFileExists(zFilename) ){
15895 + if( HCreate(fsSpec.vRefNum, fsSpec.parID, fsSpec.name, 'SQLI', cDocumentFile) != noErr )
15896 + return SQLITE_CANTOPEN;
15898 + if( HOpenDF(fsSpec.vRefNum, fsSpec.parID, fsSpec.name, fsRdWrShPerm, &(id->refNum)) != noErr ){
15899 + if( HOpenDF(fsSpec.vRefNum, fsSpec.parID, fsSpec.name, fsRdWrPerm, &(id->refNum)) != noErr ){
15900 + if( HOpenDF(fsSpec.vRefNum, fsSpec.parID, fsSpec.name, fsRdPerm, &(id->refNum)) != noErr )
15901 + return SQLITE_CANTOPEN;
15909 + if( HOpenRF(fsSpec.vRefNum, fsSpec.parID, fsSpec.name, fsRdWrShPerm, &(id->refNumRF)) != noErr){
15910 + id->refNumRF = -1;
15913 + id->delOnClose = 0;
15915 + return SQLITE_OK;
15921 +** Attempt to open a new file for exclusive access by this process.
15922 +** The file will be opened for both reading and writing. To avoid
15923 +** a potential security problem, we do not allow the file to have
15924 +** previously existed. Nor do we allow the file to be a symbolic
15927 +** If delFlag is true, then make arrangements to automatically delete
15928 +** the file when it is closed.
15930 +** On success, write the file handle into *id and return SQLITE_OK.
15932 +** On failure, return SQLITE_CANTOPEN.
15934 +int sqliteOsOpenExclusive(const char *zFilename, OsFile *id, int delFlag){
15937 + if( access(zFilename, 0)==0 ){
15938 + return SQLITE_CANTOPEN;
15941 + id->fd = open(zFilename,
15942 + O_RDWR|O_CREAT|O_EXCL|O_NOFOLLOW|O_LARGEFILE|O_BINARY, 0600);
15944 + return SQLITE_CANTOPEN;
15946 + sqliteOsEnterMutex();
15947 + rc = findLockInfo(id->fd, &id->pLock, &id->pOpen);
15948 + sqliteOsLeaveMutex();
15951 + unlink(zFilename);
15952 + return SQLITE_NOMEM;
15956 + unlink(zFilename);
15958 + TRACE3("OPEN-EX %-3d %s\n", id->fd, zFilename);
15960 + return SQLITE_OK;
15966 + fileflags = FILE_ATTRIBUTE_TEMPORARY | FILE_FLAG_RANDOM_ACCESS
15967 + | FILE_FLAG_DELETE_ON_CLOSE;
15969 + fileflags = FILE_FLAG_RANDOM_ACCESS;
15971 + h = CreateFile(zFilename,
15972 + GENERIC_READ | GENERIC_WRITE,
15979 + if( h==INVALID_HANDLE_VALUE ){
15980 + return SQLITE_CANTOPEN;
15985 + return SQLITE_OK;
15989 +# ifdef _LARGE_FILE
15990 + HFSUniStr255 dfName;
15992 + __path2fss(zFilename, &fsSpec);
15993 + if( HCreate(fsSpec.vRefNum, fsSpec.parID, fsSpec.name, 'SQLI', cDocumentFile) != noErr )
15994 + return SQLITE_CANTOPEN;
15995 + if( FSpMakeFSRef(&fsSpec, &fsRef) != noErr )
15996 + return SQLITE_CANTOPEN;
15997 + FSGetDataForkName(&dfName);
15998 + if( FSOpenFork(&fsRef, dfName.length, dfName.unicode,
15999 + fsRdWrPerm, &(id->refNum)) != noErr )
16000 + return SQLITE_CANTOPEN;
16002 + __path2fss(zFilename, &fsSpec);
16003 + if( HCreate(fsSpec.vRefNum, fsSpec.parID, fsSpec.name, 'SQLI', cDocumentFile) != noErr )
16004 + return SQLITE_CANTOPEN;
16005 + if( HOpenDF(fsSpec.vRefNum, fsSpec.parID, fsSpec.name, fsRdWrPerm, &(id->refNum)) != noErr )
16006 + return SQLITE_CANTOPEN;
16008 + id->refNumRF = -1;
16010 + id->delOnClose = delFlag;
16012 + id->pathToDel = sqliteOsFullPathname(zFilename);
16014 + return SQLITE_OK;
16019 +** Attempt to open a new file for read-only access.
16021 +** On success, write the file handle into *id and return SQLITE_OK.
16023 +** On failure, return SQLITE_CANTOPEN.
16025 +int sqliteOsOpenReadOnly(const char *zFilename, OsFile *id){
16029 + id->fd = open(zFilename, O_RDONLY|O_LARGEFILE|O_BINARY);
16031 + return SQLITE_CANTOPEN;
16033 + sqliteOsEnterMutex();
16034 + rc = findLockInfo(id->fd, &id->pLock, &id->pOpen);
16035 + sqliteOsLeaveMutex();
16038 + return SQLITE_NOMEM;
16041 + TRACE3("OPEN-RO %-3d %s\n", id->fd, zFilename);
16043 + return SQLITE_OK;
16046 + HANDLE h = CreateFile(zFilename,
16051 + FILE_ATTRIBUTE_NORMAL | FILE_FLAG_RANDOM_ACCESS,
16054 + if( h==INVALID_HANDLE_VALUE ){
16055 + return SQLITE_CANTOPEN;
16060 + return SQLITE_OK;
16064 +# ifdef _LARGE_FILE
16065 + HFSUniStr255 dfName;
16067 + if( __path2fss(zFilename, &fsSpec) != noErr )
16068 + return SQLITE_CANTOPEN;
16069 + if( FSpMakeFSRef(&fsSpec, &fsRef) != noErr )
16070 + return SQLITE_CANTOPEN;
16071 + FSGetDataForkName(&dfName);
16072 + if( FSOpenFork(&fsRef, dfName.length, dfName.unicode,
16073 + fsRdPerm, &(id->refNum)) != noErr )
16074 + return SQLITE_CANTOPEN;
16076 + __path2fss(zFilename, &fsSpec);
16077 + if( HOpenDF(fsSpec.vRefNum, fsSpec.parID, fsSpec.name, fsRdPerm, &(id->refNum)) != noErr )
16078 + return SQLITE_CANTOPEN;
16080 + if( HOpenRF(fsSpec.vRefNum, fsSpec.parID, fsSpec.name, fsRdWrShPerm, &(id->refNumRF)) != noErr){
16081 + id->refNumRF = -1;
16084 + id->delOnClose = 0;
16086 + return SQLITE_OK;
16091 +** Attempt to open a file descriptor for the directory that contains a
16092 +** file. This file descriptor can be used to fsync() the directory
16093 +** in order to make sure the creation of a new file is actually written
16096 +** This routine is only meaningful for Unix. It is a no-op under
16097 +** windows since windows does not support hard links.
16099 +** On success, a handle for a previously open file is at *id is
16100 +** updated with the new directory file descriptor and SQLITE_OK is
16103 +** On failure, the function returns SQLITE_CANTOPEN and leaves
16106 +int sqliteOsOpenDirectory(
16107 + const char *zDirname,
16112 + /* Do not open the directory if the corresponding file is not already
16114 + return SQLITE_CANTOPEN;
16116 + assert( id->dirfd<0 );
16117 + id->dirfd = open(zDirname, O_RDONLY|O_BINARY, 0644);
16118 + if( id->dirfd<0 ){
16119 + return SQLITE_CANTOPEN;
16121 + TRACE3("OPENDIR %-3d %s\n", id->dirfd, zDirname);
16123 + return SQLITE_OK;
16127 +** If the following global variable points to a string which is the
16128 +** name of a directory, then that directory will be used to store
16129 +** temporary files.
16131 +const char *sqlite_temp_directory = 0;
16134 +** Create a temporary file name in zBuf. zBuf must be big enough to
16135 +** hold at least SQLITE_TEMPNAME_SIZE characters.
16137 +int sqliteOsTempFileName(char *zBuf){
16139 + static const char *azDirs[] = {
16146 + static unsigned char zChars[] =
16147 + "abcdefghijklmnopqrstuvwxyz"
16148 + "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
16152 + const char *zDir = ".";
16153 + azDirs[0] = sqlite_temp_directory;
16154 + for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); i++){
16155 + if( azDirs[i]==0 ) continue;
16156 + if( stat(azDirs[i], &buf) ) continue;
16157 + if( !S_ISDIR(buf.st_mode) ) continue;
16158 + if( access(azDirs[i], 07) ) continue;
16159 + zDir = azDirs[i];
16163 + sprintf(zBuf, "%s/"TEMP_FILE_PREFIX, zDir);
16164 + j = strlen(zBuf);
16165 + sqliteRandomness(15, &zBuf[j]);
16166 + for(i=0; i<15; i++, j++){
16167 + zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
16170 + }while( access(zBuf,0)==0 );
16173 + static char zChars[] =
16174 + "abcdefghijklmnopqrstuvwxyz"
16175 + "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
16178 + const char *zDir;
16179 + char zTempPath[SQLITE_TEMPNAME_SIZE];
16180 + if( sqlite_temp_directory==0 ){
16181 + GetTempPath(SQLITE_TEMPNAME_SIZE-30, zTempPath);
16182 + for(i=strlen(zTempPath); i>0 && zTempPath[i-1]=='\\'; i--){}
16183 + zTempPath[i] = 0;
16184 + zDir = zTempPath;
16186 + zDir = sqlite_temp_directory;
16189 + sprintf(zBuf, "%s\\"TEMP_FILE_PREFIX, zDir);
16190 + j = strlen(zBuf);
16191 + sqliteRandomness(15, &zBuf[j]);
16192 + for(i=0; i<15; i++, j++){
16193 + zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
16196 + if( !sqliteOsFileExists(zBuf) ) break;
16200 + static char zChars[] =
16201 + "abcdefghijklmnopqrstuvwxyz"
16202 + "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
16206 + char zTempPath[SQLITE_TEMPNAME_SIZE];
16207 + char zdirName[32];
16208 + CInfoPBRec infoRec;
16210 + memset(&infoRec, 0, sizeof(infoRec));
16211 + memset(zTempPath, 0, SQLITE_TEMPNAME_SIZE);
16212 + if( sqlite_temp_directory!=0 ){
16213 + zDir = sqlite_temp_directory;
16214 + }else if( FindFolder(kOnSystemDisk, kTemporaryFolderType, kCreateFolder,
16215 + &(infoRec.dirInfo.ioVRefNum), &(infoRec.dirInfo.ioDrParID)) == noErr ){
16216 + infoRec.dirInfo.ioNamePtr = dirName;
16218 + infoRec.dirInfo.ioFDirIndex = -1;
16219 + infoRec.dirInfo.ioDrDirID = infoRec.dirInfo.ioDrParID;
16220 + if( PBGetCatInfoSync(&infoRec) == noErr ){
16221 + CopyPascalStringToC(dirName, zdirName);
16222 + i = strlen(zdirName);
16223 + memmove(&(zTempPath[i+1]), zTempPath, strlen(zTempPath));
16224 + strcpy(zTempPath, zdirName);
16225 + zTempPath[i] = ':';
16230 + } while( infoRec.dirInfo.ioDrDirID != fsRtDirID );
16231 + zDir = zTempPath;
16233 + if( zDir[0]==0 ){
16234 + getcwd(zTempPath, SQLITE_TEMPNAME_SIZE-24);
16235 + zDir = zTempPath;
16238 + sprintf(zBuf, "%s"TEMP_FILE_PREFIX, zDir);
16239 + j = strlen(zBuf);
16240 + sqliteRandomness(15, &zBuf[j]);
16241 + for(i=0; i<15; i++, j++){
16242 + zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
16245 + if( !sqliteOsFileExists(zBuf) ) break;
16248 + return SQLITE_OK;
16254 +int sqliteOsClose(OsFile *id){
16256 + sqliteOsUnlock(id);
16257 + if( id->dirfd>=0 ) close(id->dirfd);
16259 + sqliteOsEnterMutex();
16260 + if( id->pOpen->nLock ){
16261 + /* If there are outstanding locks, do not actually close the file just
16262 + ** yet because that would clear those locks. Instead, add the file
16263 + ** descriptor to pOpen->aPending. It will be automatically closed when
16264 + ** the last lock is cleared.
16267 + struct openCnt *pOpen = id->pOpen;
16268 + pOpen->nPending++;
16269 + aNew = sqliteRealloc( pOpen->aPending, pOpen->nPending*sizeof(int) );
16271 + /* If a malloc fails, just leak the file descriptor */
16273 + pOpen->aPending = aNew;
16274 + pOpen->aPending[pOpen->nPending-1] = id->fd;
16277 + /* There are no outstanding locks so we can close the file immediately */
16280 + releaseLockInfo(id->pLock);
16281 + releaseOpenCnt(id->pOpen);
16282 + sqliteOsLeaveMutex();
16283 + TRACE2("CLOSE %-3d\n", id->fd);
16285 + return SQLITE_OK;
16288 + CloseHandle(id->h);
16290 + return SQLITE_OK;
16293 + if( id->refNumRF!=-1 )
16294 + FSClose(id->refNumRF);
16295 +# ifdef _LARGE_FILE
16296 + FSCloseFork(id->refNum);
16298 + FSClose(id->refNum);
16300 + if( id->delOnClose ){
16301 + unlink(id->pathToDel);
16302 + sqliteFree(id->pathToDel);
16305 + return SQLITE_OK;
16310 +** Read data from a file into a buffer. Return SQLITE_OK if all
16311 +** bytes were read successfully and SQLITE_IOERR if anything goes
16314 +int sqliteOsRead(OsFile *id, void *pBuf, int amt){
16317 + SimulateIOError(SQLITE_IOERR);
16319 + got = read(id->fd, pBuf, amt);
16321 + TRACE4("READ %-3d %7d %d\n", id->fd, last_page, elapse);
16323 + /* if( got<0 ) got = 0; */
16325 + return SQLITE_OK;
16327 + return SQLITE_IOERR;
16332 + SimulateIOError(SQLITE_IOERR);
16333 + TRACE2("READ %d\n", last_page);
16334 + if( !ReadFile(id->h, pBuf, amt, &got, 0) ){
16337 + if( got==(DWORD)amt ){
16338 + return SQLITE_OK;
16340 + return SQLITE_IOERR;
16345 + SimulateIOError(SQLITE_IOERR);
16346 + TRACE2("READ %d\n", last_page);
16347 +# ifdef _LARGE_FILE
16348 + FSReadFork(id->refNum, fsAtMark, 0, (ByteCount)amt, pBuf, (ByteCount*)&got);
16351 + FSRead(id->refNum, &got, pBuf);
16354 + return SQLITE_OK;
16356 + return SQLITE_IOERR;
16362 +** Write data from a buffer into a file. Return SQLITE_OK on success
16363 +** or some other error code on failure.
16365 +int sqliteOsWrite(OsFile *id, const void *pBuf, int amt){
16368 + SimulateIOError(SQLITE_IOERR);
16370 + while( amt>0 && (wrote = write(id->fd, pBuf, amt))>0 ){
16372 + pBuf = &((char*)pBuf)[wrote];
16375 + TRACE4("WRITE %-3d %7d %d\n", id->fd, last_page, elapse);
16378 + return SQLITE_FULL;
16380 + return SQLITE_OK;
16385 + SimulateIOError(SQLITE_IOERR);
16386 + TRACE2("WRITE %d\n", last_page);
16387 + while( amt>0 && (rc = WriteFile(id->h, pBuf, amt, &wrote, 0))!=0 && wrote>0 ){
16389 + pBuf = &((char*)pBuf)[wrote];
16391 + if( !rc || amt>(int)wrote ){
16392 + return SQLITE_FULL;
16394 + return SQLITE_OK;
16399 + SimulateIOError(SQLITE_IOERR);
16400 + TRACE2("WRITE %d\n", last_page);
16402 +# ifdef _LARGE_FILE
16403 + oserr = FSWriteFork(id->refNum, fsAtMark, 0,
16404 + (ByteCount)amt, pBuf, (ByteCount*)&wrote);
16407 + oserr = FSWrite(id->refNum, &wrote, pBuf);
16409 + if( wrote == 0 || oserr != noErr)
16412 + pBuf = &((char*)pBuf)[wrote];
16414 + if( oserr != noErr || amt>wrote ){
16415 + return SQLITE_FULL;
16417 + return SQLITE_OK;
16422 +** Move the read/write pointer in a file.
16424 +int sqliteOsSeek(OsFile *id, off_t offset){
16425 + SEEK(offset/1024 + 1);
16427 + lseek(id->fd, offset, SEEK_SET);
16428 + return SQLITE_OK;
16432 + LONG upperBits = offset>>32;
16433 + LONG lowerBits = offset & 0xffffffff;
16435 + rc = SetFilePointer(id->h, lowerBits, &upperBits, FILE_BEGIN);
16436 + /* TRACE3("SEEK rc=0x%x upper=0x%x\n", rc, upperBits); */
16438 + return SQLITE_OK;
16443 + if( sqliteOsFileSize(id, &curSize) != SQLITE_OK ){
16444 + return SQLITE_IOERR;
16446 + if( offset >= curSize ){
16447 + if( sqliteOsTruncate(id, offset+1) != SQLITE_OK ){
16448 + return SQLITE_IOERR;
16451 +# ifdef _LARGE_FILE
16452 + if( FSSetForkPosition(id->refNum, fsFromStart, offset) != noErr ){
16454 + if( SetFPos(id->refNum, fsFromStart, offset) != noErr ){
16456 + return SQLITE_IOERR;
16458 + return SQLITE_OK;
16464 +#ifdef SQLITE_NOSYNC
16465 +# define fsync(X) 0
16469 +** Make sure all writes to a particular file are committed to disk.
16471 +** Under Unix, also make sure that the directory entry for the file
16472 +** has been created by fsync-ing the directory that contains the file.
16473 +** If we do not do this and we encounter a power failure, the directory
16474 +** entry for the journal might not exist after we reboot. The next
16475 +** SQLite to access the file will not know that the journal exists (because
16476 +** the directory entry for the journal was never created) and the transaction
16477 +** will not roll back - possibly leading to database corruption.
16479 +int sqliteOsSync(OsFile *id){
16481 + SimulateIOError(SQLITE_IOERR);
16482 + TRACE2("SYNC %-3d\n", id->fd);
16483 + if( fsync(id->fd) ){
16484 + return SQLITE_IOERR;
16486 + if( id->dirfd>=0 ){
16487 + TRACE2("DIRSYNC %-3d\n", id->dirfd);
16488 + fsync(id->dirfd);
16489 + close(id->dirfd); /* Only need to sync once, so close the directory */
16490 + id->dirfd = -1; /* when we are done. */
16492 + return SQLITE_OK;
16496 + if( FlushFileBuffers(id->h) ){
16497 + return SQLITE_OK;
16499 + return SQLITE_IOERR;
16503 +# ifdef _LARGE_FILE
16504 + if( FSFlushFork(id->refNum) != noErr ){
16506 + ParamBlockRec params;
16507 + memset(¶ms, 0, sizeof(ParamBlockRec));
16508 + params.ioParam.ioRefNum = id->refNum;
16509 + if( PBFlushFileSync(¶ms) != noErr ){
16511 + return SQLITE_IOERR;
16513 + return SQLITE_OK;
16519 +** Truncate an open file to a specified size
16521 +int sqliteOsTruncate(OsFile *id, off_t nByte){
16522 + SimulateIOError(SQLITE_IOERR);
16524 + return ftruncate(id->fd, nByte)==0 ? SQLITE_OK : SQLITE_IOERR;
16528 + LONG upperBits = nByte>>32;
16529 + SetFilePointer(id->h, nByte, &upperBits, FILE_BEGIN);
16530 + SetEndOfFile(id->h);
16532 + return SQLITE_OK;
16535 +# ifdef _LARGE_FILE
16536 + if( FSSetForkSize(id->refNum, fsFromStart, nByte) != noErr){
16538 + if( SetEOF(id->refNum, nByte) != noErr ){
16540 + return SQLITE_IOERR;
16542 + return SQLITE_OK;
16548 +** Determine the current size of a file in bytes
16550 +int sqliteOsFileSize(OsFile *id, off_t *pSize){
16553 + SimulateIOError(SQLITE_IOERR);
16554 + if( fstat(id->fd, &buf)!=0 ){
16555 + return SQLITE_IOERR;
16557 + *pSize = buf.st_size;
16558 + return SQLITE_OK;
16561 + DWORD upperBits, lowerBits;
16562 + SimulateIOError(SQLITE_IOERR);
16563 + lowerBits = GetFileSize(id->h, &upperBits);
16564 + *pSize = (((off_t)upperBits)<<32) + lowerBits;
16565 + return SQLITE_OK;
16568 +# ifdef _LARGE_FILE
16569 + if( FSGetForkSize(id->refNum, pSize) != noErr){
16571 + if( GetEOF(id->refNum, pSize) != noErr ){
16573 + return SQLITE_IOERR;
16575 + return SQLITE_OK;
16582 +** Return true (non-zero) if we are running under WinNT, Win2K or WinXP.
16583 +** Return false (zero) for Win95, Win98, or WinME.
16585 +** Here is an interesting observation: Win95, Win98, and WinME lack
16586 +** the LockFileEx() API. But we can still statically link against that
16587 +** API as long as we don't call it win running Win95/98/ME. A call to
16588 +** this routine is used to determine if the host is Win95/98/ME or
16589 +** WinNT/2K/XP so that we will know whether or not we can safely call
16590 +** the LockFileEx() API.
16593 + static int osType = 0; /* 0=unknown 1=win95 2=winNT */
16595 + OSVERSIONINFO sInfo;
16596 + sInfo.dwOSVersionInfoSize = sizeof(sInfo);
16597 + GetVersionEx(&sInfo);
16598 + osType = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1;
16600 + return osType==2;
16605 +** Windows file locking notes: [similar issues apply to MacOS]
16607 +** We cannot use LockFileEx() or UnlockFileEx() on Win95/98/ME because
16608 +** those functions are not available. So we use only LockFile() and
16611 +** LockFile() prevents not just writing but also reading by other processes.
16612 +** (This is a design error on the part of Windows, but there is nothing
16613 +** we can do about that.) So the region used for locking is at the
16614 +** end of the file where it is unlikely to ever interfere with an
16615 +** actual read attempt.
16617 +** A database read lock is obtained by locking a single randomly-chosen
16618 +** byte out of a specific range of bytes. The lock byte is obtained at
16619 +** random so two separate readers can probably access the file at the
16620 +** same time, unless they are unlucky and choose the same lock byte.
16621 +** A database write lock is obtained by locking all bytes in the range.
16622 +** There can only be one writer.
16624 +** A lock is obtained on the first byte of the lock range before acquiring
16625 +** either a read lock or a write lock. This prevents two processes from
16626 +** attempting to get a lock at a same time. The semantics of
16627 +** sqliteOsReadLock() require that if there is already a write lock, that
16628 +** lock is converted into a read lock atomically. The lock on the first
16629 +** byte allows us to drop the old write lock and get the read lock without
16630 +** another process jumping into the middle and messing us up. The same
16631 +** argument applies to sqliteOsWriteLock().
16633 +** On WinNT/2K/XP systems, LockFileEx() and UnlockFileEx() are available,
16634 +** which means we can use reader/writer locks. When reader writer locks
16635 +** are used, the lock is placed on the same range of bytes that is used
16636 +** for probabilistic locking in Win95/98/ME. Hence, the locking scheme
16637 +** will support two or more Win95 readers or two or more WinNT readers.
16638 +** But a single Win95 reader will lock out all WinNT readers and a single
16639 +** WinNT reader will lock out all other Win95 readers.
16641 +** Note: On MacOS we use the resource fork for locking.
16643 +** The following #defines specify the range of bytes used for locking.
16644 +** N_LOCKBYTE is the number of bytes available for doing the locking.
16645 +** The first byte used to hold the lock while the lock is changing does
16646 +** not count toward this number. FIRST_LOCKBYTE is the address of
16647 +** the first byte in the range of bytes used for locking.
16649 +#define N_LOCKBYTE 10239
16651 +# define FIRST_LOCKBYTE (0x000fffff - N_LOCKBYTE)
16653 +# define FIRST_LOCKBYTE (0xffffffff - N_LOCKBYTE)
16657 +** Change the status of the lock on the file "id" to be a readlock.
16658 +** If the file was write locked, then this reduces the lock to a read.
16659 +** If the file was read locked, then this acquires a new read lock.
16661 +** Return SQLITE_OK on success and SQLITE_BUSY on failure. If this
16662 +** library was compiled with large file support (LFS) but LFS is not
16663 +** available on the host, then an SQLITE_NOLFS is returned.
16665 +int sqliteOsReadLock(OsFile *id){
16668 + sqliteOsEnterMutex();
16669 + if( id->pLock->cnt>0 ){
16670 + if( !id->locked ){
16671 + id->pLock->cnt++;
16673 + id->pOpen->nLock++;
16676 + }else if( id->locked || id->pLock->cnt==0 ){
16677 + struct flock lock;
16679 + lock.l_type = F_RDLCK;
16680 + lock.l_whence = SEEK_SET;
16681 + lock.l_start = lock.l_len = 0L;
16682 + s = fcntl(id->fd, F_SETLK, &lock);
16684 + rc = (errno==EINVAL) ? SQLITE_NOLFS : SQLITE_BUSY;
16687 + if( !id->locked ){
16688 + id->pOpen->nLock++;
16691 + id->pLock->cnt = 1;
16694 + rc = SQLITE_BUSY;
16696 + sqliteOsLeaveMutex();
16701 + if( id->locked>0 ){
16707 + sqliteRandomness(sizeof(lk), &lk);
16708 + lk = (lk & 0x7fffffff)%N_LOCKBYTE + 1;
16709 + while( cnt-->0 && (res = LockFile(id->h, FIRST_LOCKBYTE, 0, 1, 0))==0 ){
16713 + UnlockFile(id->h, FIRST_LOCKBYTE+1, 0, N_LOCKBYTE, 0);
16716 + ovlp.Offset = FIRST_LOCKBYTE+1;
16717 + ovlp.OffsetHigh = 0;
16719 + res = LockFileEx(id->h, LOCKFILE_FAIL_IMMEDIATELY,
16720 + 0, N_LOCKBYTE, 0, &ovlp);
16722 + res = LockFile(id->h, FIRST_LOCKBYTE+lk, 0, 1, 0);
16724 + UnlockFile(id->h, FIRST_LOCKBYTE, 0, 1, 0);
16730 + rc = SQLITE_BUSY;
16737 + if( id->locked>0 || id->refNumRF == -1 ){
16743 + ParamBlockRec params;
16744 + sqliteRandomness(sizeof(lk), &lk);
16745 + lk = (lk & 0x7fffffff)%N_LOCKBYTE + 1;
16746 + memset(¶ms, 0, sizeof(params));
16747 + params.ioParam.ioRefNum = id->refNumRF;
16748 + params.ioParam.ioPosMode = fsFromStart;
16749 + params.ioParam.ioPosOffset = FIRST_LOCKBYTE;
16750 + params.ioParam.ioReqCount = 1;
16751 + while( cnt-->0 && (res = PBLockRangeSync(¶ms))!=noErr ){
16752 + UInt32 finalTicks;
16753 + Delay(1, &finalTicks); /* 1/60 sec */
16755 + if( res == noErr ){
16756 + params.ioParam.ioPosOffset = FIRST_LOCKBYTE+1;
16757 + params.ioParam.ioReqCount = N_LOCKBYTE;
16758 + PBUnlockRangeSync(¶ms);
16759 + params.ioParam.ioPosOffset = FIRST_LOCKBYTE+lk;
16760 + params.ioParam.ioReqCount = 1;
16761 + res = PBLockRangeSync(¶ms);
16762 + params.ioParam.ioPosOffset = FIRST_LOCKBYTE;
16763 + params.ioParam.ioReqCount = 1;
16764 + PBUnlockRangeSync(¶ms);
16766 + if( res == noErr ){
16770 + rc = SQLITE_BUSY;
16778 +** Change the lock status to be an exclusive or write lock. Return
16779 +** SQLITE_OK on success and SQLITE_BUSY on a failure. If this
16780 +** library was compiled with large file support (LFS) but LFS is not
16781 +** available on the host, then an SQLITE_NOLFS is returned.
16783 +int sqliteOsWriteLock(OsFile *id){
16786 + sqliteOsEnterMutex();
16787 + if( id->pLock->cnt==0 || (id->pLock->cnt==1 && id->locked==1) ){
16788 + struct flock lock;
16790 + lock.l_type = F_WRLCK;
16791 + lock.l_whence = SEEK_SET;
16792 + lock.l_start = lock.l_len = 0L;
16793 + s = fcntl(id->fd, F_SETLK, &lock);
16795 + rc = (errno==EINVAL) ? SQLITE_NOLFS : SQLITE_BUSY;
16798 + if( !id->locked ){
16799 + id->pOpen->nLock++;
16802 + id->pLock->cnt = -1;
16805 + rc = SQLITE_BUSY;
16807 + sqliteOsLeaveMutex();
16812 + if( id->locked<0 ){
16817 + while( cnt-->0 && (res = LockFile(id->h, FIRST_LOCKBYTE, 0, 1, 0))==0 ){
16821 + if( id->locked>0 ){
16823 + UnlockFile(id->h, FIRST_LOCKBYTE+1, 0, N_LOCKBYTE, 0);
16825 + res = UnlockFile(id->h, FIRST_LOCKBYTE + id->locked, 0, 1, 0);
16829 + res = LockFile(id->h, FIRST_LOCKBYTE+1, 0, N_LOCKBYTE, 0);
16833 + UnlockFile(id->h, FIRST_LOCKBYTE, 0, 1, 0);
16839 + rc = SQLITE_BUSY;
16846 + if( id->locked<0 || id->refNumRF == -1 ){
16851 + ParamBlockRec params;
16852 + memset(¶ms, 0, sizeof(params));
16853 + params.ioParam.ioRefNum = id->refNumRF;
16854 + params.ioParam.ioPosMode = fsFromStart;
16855 + params.ioParam.ioPosOffset = FIRST_LOCKBYTE;
16856 + params.ioParam.ioReqCount = 1;
16857 + while( cnt-->0 && (res = PBLockRangeSync(¶ms))!=noErr ){
16858 + UInt32 finalTicks;
16859 + Delay(1, &finalTicks); /* 1/60 sec */
16861 + if( res == noErr ){
16862 + params.ioParam.ioPosOffset = FIRST_LOCKBYTE + id->locked;
16863 + params.ioParam.ioReqCount = 1;
16864 + if( id->locked==0
16865 + || PBUnlockRangeSync(¶ms)==noErr ){
16866 + params.ioParam.ioPosOffset = FIRST_LOCKBYTE+1;
16867 + params.ioParam.ioReqCount = N_LOCKBYTE;
16868 + res = PBLockRangeSync(¶ms);
16870 + res = afpRangeNotLocked;
16872 + params.ioParam.ioPosOffset = FIRST_LOCKBYTE;
16873 + params.ioParam.ioReqCount = 1;
16874 + PBUnlockRangeSync(¶ms);
16876 + if( res == noErr ){
16880 + rc = SQLITE_BUSY;
16888 +** Unlock the given file descriptor. If the file descriptor was
16889 +** not previously locked, then this routine is a no-op. If this
16890 +** library was compiled with large file support (LFS) but LFS is not
16891 +** available on the host, then an SQLITE_NOLFS is returned.
16893 +int sqliteOsUnlock(OsFile *id){
16896 + if( !id->locked ) return SQLITE_OK;
16897 + sqliteOsEnterMutex();
16898 + assert( id->pLock->cnt!=0 );
16899 + if( id->pLock->cnt>1 ){
16900 + id->pLock->cnt--;
16903 + struct flock lock;
16905 + lock.l_type = F_UNLCK;
16906 + lock.l_whence = SEEK_SET;
16907 + lock.l_start = lock.l_len = 0L;
16908 + s = fcntl(id->fd, F_SETLK, &lock);
16910 + rc = (errno==EINVAL) ? SQLITE_NOLFS : SQLITE_BUSY;
16913 + id->pLock->cnt = 0;
16916 + if( rc==SQLITE_OK ){
16917 + /* Decrement the count of locks against this same file. When the
16918 + ** count reaches zero, close any other file descriptors whose close
16919 + ** was deferred because of outstanding locks.
16921 + struct openCnt *pOpen = id->pOpen;
16923 + assert( pOpen->nLock>=0 );
16924 + if( pOpen->nLock==0 && pOpen->nPending>0 ){
16926 + for(i=0; i<pOpen->nPending; i++){
16927 + close(pOpen->aPending[i]);
16929 + sqliteFree(pOpen->aPending);
16930 + pOpen->nPending = 0;
16931 + pOpen->aPending = 0;
16934 + sqliteOsLeaveMutex();
16940 + if( id->locked==0 ){
16942 + }else if( isNT() || id->locked<0 ){
16943 + UnlockFile(id->h, FIRST_LOCKBYTE+1, 0, N_LOCKBYTE, 0);
16947 + UnlockFile(id->h, FIRST_LOCKBYTE+id->locked, 0, 1, 0);
16955 + ParamBlockRec params;
16956 + memset(¶ms, 0, sizeof(params));
16957 + params.ioParam.ioRefNum = id->refNumRF;
16958 + params.ioParam.ioPosMode = fsFromStart;
16959 + if( id->locked==0 || id->refNumRF == -1 ){
16961 + }else if( id->locked<0 ){
16962 + params.ioParam.ioPosOffset = FIRST_LOCKBYTE+1;
16963 + params.ioParam.ioReqCount = N_LOCKBYTE;
16964 + PBUnlockRangeSync(¶ms);
16968 + params.ioParam.ioPosOffset = FIRST_LOCKBYTE+id->locked;
16969 + params.ioParam.ioReqCount = 1;
16970 + PBUnlockRangeSync(¶ms);
16979 +** Get information to seed the random number generator. The seed
16980 +** is written into the buffer zBuf[256]. The calling function must
16981 +** supply a sufficiently large buffer.
16983 +int sqliteOsRandomSeed(char *zBuf){
16984 + /* We have to initialize zBuf to prevent valgrind from reporting
16985 + ** errors. The reports issued by valgrind are incorrect - we would
16986 + ** prefer that the randomness be increased by making use of the
16987 + ** uninitialized space in zBuf - but valgrind errors tend to worry
16988 + ** some users. Rather than argue, it seems easier just to initialize
16989 + ** the whole array and silence valgrind, even if that means less randomness
16990 + ** in the random seed.
16992 + ** When testing, initializing zBuf[] to zero is all we do. That means
16993 + ** that we always use the same random number sequence.* This makes the
16994 + ** tests repeatable.
16996 + memset(zBuf, 0, 256);
16997 +#if OS_UNIX && !defined(SQLITE_TEST)
17000 + time((time_t*)zBuf);
17002 + memcpy(&zBuf[sizeof(time_t)], &pid, sizeof(pid));
17005 +#if OS_WIN && !defined(SQLITE_TEST)
17006 + GetSystemTime((LPSYSTEMTIME)zBuf);
17011 + Microseconds((UnsignedWide*)zBuf);
17013 + memcpy(&zBuf[sizeof(UnsignedWide)], &pid, sizeof(pid));
17016 + return SQLITE_OK;
17020 +** Sleep for a little while. Return the amount of time slept.
17022 +int sqliteOsSleep(int ms){
17024 +#if defined(HAVE_USLEEP) && HAVE_USLEEP
17028 + sleep((ms+999)/1000);
17029 + return 1000*((ms+999)/1000);
17037 + UInt32 finalTicks;
17038 + UInt32 ticks = (((UInt32)ms+16)*3)/50; /* 1/60 sec per tick */
17039 + Delay(ticks, &finalTicks);
17040 + return (int)((ticks*50)/3);
17045 +** Static variables used for thread synchronization
17047 +static int inMutex = 0;
17048 +#ifdef SQLITE_UNIX_THREADS
17049 + static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
17051 +#ifdef SQLITE_W32_THREADS
17052 + static CRITICAL_SECTION cs;
17054 +#ifdef SQLITE_MACOS_MULTITASKING
17055 + static MPCriticalRegionID criticalRegion;
17059 +** The following pair of routine implement mutual exclusion for
17060 +** multi-threaded processes. Only a single thread is allowed to
17061 +** executed code that is surrounded by EnterMutex() and LeaveMutex().
17063 +** SQLite uses only a single Mutex. There is not much critical
17064 +** code and what little there is executes quickly and without blocking.
17066 +void sqliteOsEnterMutex(){
17067 +#ifdef SQLITE_UNIX_THREADS
17068 + pthread_mutex_lock(&mutex);
17070 +#ifdef SQLITE_W32_THREADS
17071 + static int isInit = 0;
17072 + while( !isInit ){
17073 + static long lock = 0;
17074 + if( InterlockedIncrement(&lock)==1 ){
17075 + InitializeCriticalSection(&cs);
17081 + EnterCriticalSection(&cs);
17083 +#ifdef SQLITE_MACOS_MULTITASKING
17084 + static volatile int notInit = 1;
17086 + if( notInit == 2 ) /* as close as you can get to thread safe init */
17090 + MPCreateCriticalRegion(&criticalRegion);
17094 + MPEnterCriticalRegion(criticalRegion, kDurationForever);
17096 + assert( !inMutex );
17099 +void sqliteOsLeaveMutex(){
17100 + assert( inMutex );
17102 +#ifdef SQLITE_UNIX_THREADS
17103 + pthread_mutex_unlock(&mutex);
17105 +#ifdef SQLITE_W32_THREADS
17106 + LeaveCriticalSection(&cs);
17108 +#ifdef SQLITE_MACOS_MULTITASKING
17109 + MPExitCriticalRegion(criticalRegion);
17114 +** Turn a relative pathname into a full pathname. Return a pointer
17115 +** to the full pathname stored in space obtained from sqliteMalloc().
17116 +** The calling function is responsible for freeing this space once it
17117 +** is no longer needed.
17119 +char *sqliteOsFullPathname(const char *zRelative){
17122 + if( zRelative[0]=='/' ){
17123 + sqliteSetString(&zFull, zRelative, (char*)0);
17127 + sqliteSetString(&zFull, getcwd(zBuf, sizeof(zBuf)), "/", zRelative,
17136 + nByte = GetFullPathName(zRelative, 0, 0, &zNotUsed) + 1;
17137 + zFull = sqliteMalloc( nByte );
17138 + if( zFull==0 ) return 0;
17139 + GetFullPathName(zRelative, nByte, zFull, &zNotUsed);
17144 + if( zRelative[0]==':' ){
17145 + char zBuf[_MAX_PATH+1];
17146 + sqliteSetString(&zFull, getcwd(zBuf, sizeof(zBuf)), &(zRelative[1]),
17149 + if( strchr(zRelative, ':') ){
17150 + sqliteSetString(&zFull, zRelative, (char*)0);
17152 + char zBuf[_MAX_PATH+1];
17153 + sqliteSetString(&zFull, getcwd(zBuf, sizeof(zBuf)), zRelative, (char*)0);
17161 +** The following variable, if set to a non-zero value, becomes the result
17162 +** returned from sqliteOsCurrentTime(). This is used for testing.
17164 +#ifdef SQLITE_TEST
17165 +int sqlite_current_time = 0;
17169 +** Find the current time (in Universal Coordinated Time). Write the
17170 +** current time and date as a Julian Day number into *prNow and
17171 +** return 0. Return 1 if the time and date cannot be found.
17173 +int sqliteOsCurrentTime(double *prNow){
17177 + *prNow = t/86400.0 + 2440587.5;
17181 + /* FILETIME structure is a 64-bit value representing the number of
17182 + 100-nanosecond intervals since January 1, 1601 (= JD 2305813.5).
17185 + GetSystemTimeAsFileTime( &ft );
17186 + now = ((double)ft.dwHighDateTime) * 4294967296.0;
17187 + *prNow = (now + ft.dwLowDateTime)/864000000000.0 + 2305813.5;
17189 +#ifdef SQLITE_TEST
17190 + if( sqlite_current_time ){
17191 + *prNow = sqlite_current_time/86400.0 + 2440587.5;
17197 +++ b/ext/sqlite/libsqlite/src/os.h
17200 +** 2001 September 16
17202 +** The author disclaims copyright to this source code. In place of
17203 +** a legal notice, here is a blessing:
17205 +** May you do good and not evil.
17206 +** May you find forgiveness for yourself and forgive others.
17207 +** May you share freely, never taking more than you give.
17209 +******************************************************************************
17211 +** This header file (together with is companion C source-code file
17212 +** "os.c") attempt to abstract the underlying operating system so that
17213 +** the SQLite library will work on both POSIX and windows systems.
17215 +#ifndef _SQLITE_OS_H_
17216 +#define _SQLITE_OS_H_
17219 +** Helpful hint: To get this to compile on HP/UX, add -D_INCLUDE_POSIX_SOURCE
17220 +** to the compiler command line.
17224 +** These #defines should enable >2GB file support on Posix if the
17225 +** underlying operating system supports it. If the OS lacks
17226 +** large file support, or if the OS is windows, these should be no-ops.
17228 +** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
17229 +** on the compiler command line. This is necessary if you are compiling
17230 +** on a recent machine (ex: RedHat 7.2) but you want your code to work
17231 +** on an older machine (ex: RedHat 6.0). If you compile on RedHat 7.2
17232 +** without this option, LFS is enable. But LFS does not exist in the kernel
17233 +** in RedHat 6.0, so the code won't work. Hence, for maximum binary
17234 +** portability you should omit LFS.
17236 +** Similar is true for MacOS. LFS is only supported on MacOS 9 and later.
17238 +#ifndef SQLITE_DISABLE_LFS
17239 +# define _LARGE_FILE 1
17240 +# ifndef _FILE_OFFSET_BITS
17241 +# define _FILE_OFFSET_BITS 64
17243 +# define _LARGEFILE_SOURCE 1
17247 +** Temporary files are named starting with this prefix followed by 16 random
17248 +** alphanumeric characters, and no file extension. They are stored in the
17249 +** OS's standard temporary file directory, and are deleted prior to exit.
17250 +** If sqlite is being embedded in another program, you may wish to change the
17251 +** prefix to reflect your program's name, so that if your program exits
17252 +** prematurely, old temporary files can be easily identified. This can be done
17253 +** using -DTEMP_FILE_PREFIX=myprefix_ on the compiler command line.
17255 +#ifndef TEMP_FILE_PREFIX
17256 +# define TEMP_FILE_PREFIX "sqlite_"
17260 +** Figure out if we are dealing with Unix, Windows or MacOS.
17262 +** N.B. MacOS means Mac Classic (or Carbon). Treat Darwin (OS X) as Unix.
17263 +** The MacOS build is designed to use CodeWarrior (tested with v8)
17268 +# if defined(__MACOS__)
17271 +# define OS_UNIX 0
17272 +# elif defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || defined(__MINGW32__) || defined(__BORLANDC__)
17275 +# define OS_UNIX 0
17279 +# define OS_UNIX 1
17283 +# define OS_UNIX 0
17287 +# define OS_UNIX 0
17297 +** A handle for an open file is stored in an OsFile object.
17300 +# include <sys/types.h>
17301 +# include <sys/stat.h>
17302 +# include <fcntl.h>
17303 +# include <unistd.h>
17304 + typedef struct OsFile OsFile;
17306 + struct openCnt *pOpen; /* Info about all open fd's on this inode */
17307 + struct lockInfo *pLock; /* Info about locks on this inode */
17308 + int fd; /* The file descriptor */
17309 + int locked; /* True if this instance holds the lock */
17310 + int dirfd; /* File descriptor for the directory */
17312 +# define SQLITE_TEMPNAME_SIZE 200
17313 +# if defined(HAVE_USLEEP) && HAVE_USLEEP
17314 +# define SQLITE_MIN_SLEEP_MS 1
17316 +# define SQLITE_MIN_SLEEP_MS 1000
17321 +#include <windows.h>
17322 +#include <winbase.h>
17323 + typedef struct OsFile OsFile;
17325 + HANDLE h; /* Handle for accessing the file */
17326 + int locked; /* 0: unlocked, <0: write lock, >0: read lock */
17328 +# if defined(_MSC_VER) || defined(__BORLANDC__)
17329 + typedef __int64 off_t;
17331 +# if !defined(_CYGWIN_TYPES_H)
17332 + typedef long long off_t;
17333 +# if defined(__MINGW32__)
17338 +# define SQLITE_TEMPNAME_SIZE (MAX_PATH+50)
17339 +# define SQLITE_MIN_SLEEP_MS 1
17343 +# include <unistd.h>
17344 +# include <Files.h>
17345 + typedef struct OsFile OsFile;
17347 + SInt16 refNum; /* Data fork/file reference number */
17348 + SInt16 refNumRF; /* Resource fork reference number (for locking) */
17349 + int locked; /* 0: unlocked, <0: write lock, >0: read lock */
17350 + int delOnClose; /* True if file is to be deleted on close */
17351 + char *pathToDel; /* Name of file to delete on close */
17353 +# ifdef _LARGE_FILE
17354 + typedef SInt64 off_t;
17356 + typedef SInt32 off_t;
17358 +# define SQLITE_TEMPNAME_SIZE _MAX_PATH
17359 +# define SQLITE_MIN_SLEEP_MS 17
17362 +int sqliteOsDelete(const char*);
17363 +int sqliteOsFileExists(const char*);
17364 +int sqliteOsFileRename(const char*, const char*);
17365 +int sqliteOsOpenReadWrite(const char*, OsFile*, int*);
17366 +int sqliteOsOpenExclusive(const char*, OsFile*, int);
17367 +int sqliteOsOpenReadOnly(const char*, OsFile*);
17368 +int sqliteOsOpenDirectory(const char*, OsFile*);
17369 +int sqliteOsTempFileName(char*);
17370 +int sqliteOsClose(OsFile*);
17371 +int sqliteOsRead(OsFile*, void*, int amt);
17372 +int sqliteOsWrite(OsFile*, const void*, int amt);
17373 +int sqliteOsSeek(OsFile*, off_t offset);
17374 +int sqliteOsSync(OsFile*);
17375 +int sqliteOsTruncate(OsFile*, off_t size);
17376 +int sqliteOsFileSize(OsFile*, off_t *pSize);
17377 +int sqliteOsReadLock(OsFile*);
17378 +int sqliteOsWriteLock(OsFile*);
17379 +int sqliteOsUnlock(OsFile*);
17380 +int sqliteOsRandomSeed(char*);
17381 +int sqliteOsSleep(int ms);
17382 +int sqliteOsCurrentTime(double*);
17383 +void sqliteOsEnterMutex(void);
17384 +void sqliteOsLeaveMutex(void);
17385 +char *sqliteOsFullPathname(const char*);
17389 +#endif /* _SQLITE_OS_H_ */
17391 +++ b/ext/sqlite/libsqlite/src/pager.c
17394 +** 2001 September 15
17396 +** The author disclaims copyright to this source code. In place of
17397 +** a legal notice, here is a blessing:
17399 +** May you do good and not evil.
17400 +** May you find forgiveness for yourself and forgive others.
17401 +** May you share freely, never taking more than you give.
17403 +*************************************************************************
17404 +** This is the implementation of the page cache subsystem or "pager".
17406 +** The pager is used to access a database disk file. It implements
17407 +** atomic commit and rollback through the use of a journal file that
17408 +** is separate from the database file. The pager also implements file
17409 +** locking to prevent two processes from writing the same database
17410 +** file simultaneously, or one process from reading the database while
17411 +** another is writing.
17415 +#include "os.h" /* Must be first to enable large file support */
17416 +#include "sqliteInt.h"
17417 +#include "pager.h"
17418 +#include <assert.h>
17419 +#include <string.h>
17422 +** Macros for troubleshooting. Normally turned off
17425 +static Pager *mainPager = 0;
17426 +#define SET_PAGER(X) if( mainPager==0 ) mainPager = (X)
17427 +#define CLR_PAGER(X) if( mainPager==(X) ) mainPager = 0
17428 +#define TRACE1(X) if( pPager==mainPager ) fprintf(stderr,X)
17429 +#define TRACE2(X,Y) if( pPager==mainPager ) fprintf(stderr,X,Y)
17430 +#define TRACE3(X,Y,Z) if( pPager==mainPager ) fprintf(stderr,X,Y,Z)
17432 +#define SET_PAGER(X)
17433 +#define CLR_PAGER(X)
17435 +#define TRACE2(X,Y)
17436 +#define TRACE3(X,Y,Z)
17441 +** The page cache as a whole is always in one of the following
17444 +** SQLITE_UNLOCK The page cache is not currently reading or
17445 +** writing the database file. There is no
17446 +** data held in memory. This is the initial
17449 +** SQLITE_READLOCK The page cache is reading the database.
17450 +** Writing is not permitted. There can be
17451 +** multiple readers accessing the same database
17452 +** file at the same time.
17454 +** SQLITE_WRITELOCK The page cache is writing the database.
17455 +** Access is exclusive. No other processes or
17456 +** threads can be reading or writing while one
17457 +** process is writing.
17459 +** The page cache comes up in SQLITE_UNLOCK. The first time a
17460 +** sqlite_page_get() occurs, the state transitions to SQLITE_READLOCK.
17461 +** After all pages have been released using sqlite_page_unref(),
17462 +** the state transitions back to SQLITE_UNLOCK. The first time
17463 +** that sqlite_page_write() is called, the state transitions to
17464 +** SQLITE_WRITELOCK. (Note that sqlite_page_write() can only be
17465 +** called on an outstanding page which means that the pager must
17466 +** be in SQLITE_READLOCK before it transitions to SQLITE_WRITELOCK.)
17467 +** The sqlite_page_rollback() and sqlite_page_commit() functions
17468 +** transition the state from SQLITE_WRITELOCK back to SQLITE_READLOCK.
17470 +#define SQLITE_UNLOCK 0
17471 +#define SQLITE_READLOCK 1
17472 +#define SQLITE_WRITELOCK 2
17476 +** Each in-memory image of a page begins with the following header.
17477 +** This header is only visible to this pager module. The client
17478 +** code that calls pager sees only the data that follows the header.
17480 +** Client code should call sqlitepager_write() on a page prior to making
17481 +** any modifications to that page. The first time sqlitepager_write()
17482 +** is called, the original page contents are written into the rollback
17483 +** journal and PgHdr.inJournal and PgHdr.needSync are set. Later, once
17484 +** the journal page has made it onto the disk surface, PgHdr.needSync
17485 +** is cleared. The modified page cannot be written back into the original
17486 +** database file until the journal pages has been synced to disk and the
17487 +** PgHdr.needSync has been cleared.
17489 +** The PgHdr.dirty flag is set when sqlitepager_write() is called and
17490 +** is cleared again when the page content is written back to the original
17493 +typedef struct PgHdr PgHdr;
17495 + Pager *pPager; /* The pager to which this page belongs */
17496 + Pgno pgno; /* The page number for this page */
17497 + PgHdr *pNextHash, *pPrevHash; /* Hash collision chain for PgHdr.pgno */
17498 + int nRef; /* Number of users of this page */
17499 + PgHdr *pNextFree, *pPrevFree; /* Freelist of pages where nRef==0 */
17500 + PgHdr *pNextAll, *pPrevAll; /* A list of all pages */
17501 + PgHdr *pNextCkpt, *pPrevCkpt; /* List of pages in the checkpoint journal */
17502 + u8 inJournal; /* TRUE if has been written to journal */
17503 + u8 inCkpt; /* TRUE if written to the checkpoint journal */
17504 + u8 dirty; /* TRUE if we need to write back changes */
17505 + u8 needSync; /* Sync journal before writing this page */
17506 + u8 alwaysRollback; /* Disable dont_rollback() for this page */
17507 + PgHdr *pDirty; /* Dirty pages sorted by PgHdr.pgno */
17508 + /* SQLITE_PAGE_SIZE bytes of page data follow this header */
17509 + /* Pager.nExtra bytes of local data follow the page data */
17514 +** A macro used for invoking the codec if there is one
17516 +#ifdef SQLITE_HAS_CODEC
17517 +# define CODEC(P,D,N,X) if( P->xCodec ){ P->xCodec(P->pCodecArg,D,N,X); }
17519 +# define CODEC(P,D,N,X)
17523 +** Convert a pointer to a PgHdr into a pointer to its data
17524 +** and back again.
17526 +#define PGHDR_TO_DATA(P) ((void*)(&(P)[1]))
17527 +#define DATA_TO_PGHDR(D) (&((PgHdr*)(D))[-1])
17528 +#define PGHDR_TO_EXTRA(P) ((void*)&((char*)(&(P)[1]))[SQLITE_PAGE_SIZE])
17531 +** How big to make the hash table used for locating in-memory pages
17532 +** by page number.
17534 +#define N_PG_HASH 2048
17537 +** Hash a page number
17539 +#define pager_hash(PN) ((PN)&(N_PG_HASH-1))
17542 +** A open page cache is an instance of the following structure.
17545 + char *zFilename; /* Name of the database file */
17546 + char *zJournal; /* Name of the journal file */
17547 + char *zDirectory; /* Directory hold database and journal files */
17548 + OsFile fd, jfd; /* File descriptors for database and journal */
17549 + OsFile cpfd; /* File descriptor for the checkpoint journal */
17550 + int dbSize; /* Number of pages in the file */
17551 + int origDbSize; /* dbSize before the current change */
17552 + int ckptSize; /* Size of database (in pages) at ckpt_begin() */
17553 + off_t ckptJSize; /* Size of journal at ckpt_begin() */
17554 + int nRec; /* Number of pages written to the journal */
17555 + u32 cksumInit; /* Quasi-random value added to every checksum */
17556 + int ckptNRec; /* Number of records in the checkpoint journal */
17557 + int nExtra; /* Add this many bytes to each in-memory page */
17558 + void (*xDestructor)(void*); /* Call this routine when freeing pages */
17559 + int nPage; /* Total number of in-memory pages */
17560 + int nRef; /* Number of in-memory pages with PgHdr.nRef>0 */
17561 + int mxPage; /* Maximum number of pages to hold in cache */
17562 + int nHit, nMiss, nOvfl; /* Cache hits, missing, and LRU overflows */
17563 + void (*xCodec)(void*,void*,Pgno,int); /* Routine for en/decoding data */
17564 + void *pCodecArg; /* First argument to xCodec() */
17565 + u8 journalOpen; /* True if journal file descriptors is valid */
17566 + u8 journalStarted; /* True if header of journal is synced */
17567 + u8 useJournal; /* Use a rollback journal on this file */
17568 + u8 ckptOpen; /* True if the checkpoint journal is open */
17569 + u8 ckptInUse; /* True we are in a checkpoint */
17570 + u8 ckptAutoopen; /* Open ckpt journal when main journal is opened*/
17571 + u8 noSync; /* Do not sync the journal if true */
17572 + u8 fullSync; /* Do extra syncs of the journal for robustness */
17573 + u8 state; /* SQLITE_UNLOCK, _READLOCK or _WRITELOCK */
17574 + u8 errMask; /* One of several kinds of errors */
17575 + u8 tempFile; /* zFilename is a temporary file */
17576 + u8 readOnly; /* True for a read-only database */
17577 + u8 needSync; /* True if an fsync() is needed on the journal */
17578 + u8 dirtyFile; /* True if database file has changed in any way */
17579 + u8 alwaysRollback; /* Disable dont_rollback() for all pages */
17580 + u8 *aInJournal; /* One bit for each page in the database file */
17581 + u8 *aInCkpt; /* One bit for each page in the database */
17582 + PgHdr *pFirst, *pLast; /* List of free pages */
17583 + PgHdr *pFirstSynced; /* First free page with PgHdr.needSync==0 */
17584 + PgHdr *pAll; /* List of all pages */
17585 + PgHdr *pCkpt; /* List of pages in the checkpoint journal */
17586 + PgHdr *aHash[N_PG_HASH]; /* Hash table to map page number of PgHdr */
17590 +** These are bits that can be set in Pager.errMask.
17592 +#define PAGER_ERR_FULL 0x01 /* a write() failed */
17593 +#define PAGER_ERR_MEM 0x02 /* malloc() failed */
17594 +#define PAGER_ERR_LOCK 0x04 /* error in the locking protocol */
17595 +#define PAGER_ERR_CORRUPT 0x08 /* database or journal corruption */
17596 +#define PAGER_ERR_DISK 0x10 /* general disk I/O error - bad hard drive? */
17599 +** The journal file contains page records in the following
17602 +** Actually, this structure is the complete page record for pager
17603 +** formats less than 3. Beginning with format 3, this record is surrounded
17604 +** by two checksums.
17606 +typedef struct PageRecord PageRecord;
17607 +struct PageRecord {
17608 + Pgno pgno; /* The page number */
17609 + char aData[SQLITE_PAGE_SIZE]; /* Original data for page pgno */
17613 +** Journal files begin with the following magic string. The data
17614 +** was obtained from /dev/random. It is used only as a sanity check.
17616 +** There are three journal formats (so far). The 1st journal format writes
17617 +** 32-bit integers in the byte-order of the host machine. New
17618 +** formats writes integers as big-endian. All new journals use the
17619 +** new format, but we have to be able to read an older journal in order
17620 +** to rollback journals created by older versions of the library.
17622 +** The 3rd journal format (added for 2.8.0) adds additional sanity
17623 +** checking information to the journal. If the power fails while the
17624 +** journal is being written, semi-random garbage data might appear in
17625 +** the journal file after power is restored. If an attempt is then made
17626 +** to roll the journal back, the database could be corrupted. The additional
17627 +** sanity checking data is an attempt to discover the garbage in the
17628 +** journal and ignore it.
17630 +** The sanity checking information for the 3rd journal format consists
17631 +** of a 32-bit checksum on each page of data. The checksum covers both
17632 +** the page number and the SQLITE_PAGE_SIZE bytes of data for the page.
17633 +** This cksum is initialized to a 32-bit random value that appears in the
17634 +** journal file right after the header. The random initializer is important,
17635 +** because garbage data that appears at the end of a journal is likely
17636 +** data that was once in other files that have now been deleted. If the
17637 +** garbage data came from an obsolete journal file, the checksums might
17638 +** be correct. But by initializing the checksum to random value which
17639 +** is different for every journal, we minimize that risk.
17641 +static const unsigned char aJournalMagic1[] = {
17642 + 0xd9, 0xd5, 0x05, 0xf9, 0x20, 0xa1, 0x63, 0xd4,
17644 +static const unsigned char aJournalMagic2[] = {
17645 + 0xd9, 0xd5, 0x05, 0xf9, 0x20, 0xa1, 0x63, 0xd5,
17647 +static const unsigned char aJournalMagic3[] = {
17648 + 0xd9, 0xd5, 0x05, 0xf9, 0x20, 0xa1, 0x63, 0xd6,
17650 +#define JOURNAL_FORMAT_1 1
17651 +#define JOURNAL_FORMAT_2 2
17652 +#define JOURNAL_FORMAT_3 3
17655 +** The following integer determines what format to use when creating
17656 +** new primary journal files. By default we always use format 3.
17657 +** When testing, we can set this value to older journal formats in order to
17658 +** make sure that newer versions of the library are able to rollback older
17661 +** Note that checkpoint journals always use format 2 and omit the header.
17663 +#ifdef SQLITE_TEST
17664 +int journal_format = 3;
17666 +# define journal_format 3
17670 +** The size of the header and of each page in the journal varies according
17671 +** to which journal format is being used. The following macros figure out
17672 +** the sizes based on format numbers.
17674 +#define JOURNAL_HDR_SZ(X) \
17675 + (sizeof(aJournalMagic1) + sizeof(Pgno) + ((X)>=3)*2*sizeof(u32))
17676 +#define JOURNAL_PG_SZ(X) \
17677 + (SQLITE_PAGE_SIZE + sizeof(Pgno) + ((X)>=3)*sizeof(u32))
17680 +** Enable reference count tracking here:
17682 +#ifdef SQLITE_TEST
17683 + int pager_refinfo_enable = 0;
17684 + static void pager_refinfo(PgHdr *p){
17685 + static int cnt = 0;
17686 + if( !pager_refinfo_enable ) return;
17688 + "REFCNT: %4d addr=0x%08x nRef=%d\n",
17689 + p->pgno, (int)PGHDR_TO_DATA(p), p->nRef
17691 + cnt++; /* Something to set a breakpoint on */
17693 +# define REFINFO(X) pager_refinfo(X)
17695 +# define REFINFO(X)
17699 +** Read a 32-bit integer from the given file descriptor. Store the integer
17700 +** that is read in *pRes. Return SQLITE_OK if everything worked, or an
17701 +** error code is something goes wrong.
17703 +** If the journal format is 2 or 3, read a big-endian integer. If the
17704 +** journal format is 1, read an integer in the native byte-order of the
17707 +static int read32bits(int format, OsFile *fd, u32 *pRes){
17710 + rc = sqliteOsRead(fd, &res, sizeof(res));
17711 + if( rc==SQLITE_OK && format>JOURNAL_FORMAT_1 ){
17712 + unsigned char ac[4];
17713 + memcpy(ac, &res, 4);
17714 + res = (ac[0]<<24) | (ac[1]<<16) | (ac[2]<<8) | ac[3];
17721 +** Write a 32-bit integer into the given file descriptor. Return SQLITE_OK
17722 +** on success or an error code is something goes wrong.
17724 +** If the journal format is 2 or 3, write the integer as 4 big-endian
17725 +** bytes. If the journal format is 1, write the integer in the native
17726 +** byte order. In normal operation, only formats 2 and 3 are used.
17727 +** Journal format 1 is only used for testing.
17729 +static int write32bits(OsFile *fd, u32 val){
17730 + unsigned char ac[4];
17731 + if( journal_format<=1 ){
17732 + return sqliteOsWrite(fd, &val, 4);
17734 + ac[0] = (val>>24) & 0xff;
17735 + ac[1] = (val>>16) & 0xff;
17736 + ac[2] = (val>>8) & 0xff;
17737 + ac[3] = val & 0xff;
17738 + return sqliteOsWrite(fd, ac, 4);
17742 +** Write a 32-bit integer into a page header right before the
17743 +** page data. This will overwrite the PgHdr.pDirty pointer.
17745 +** The integer is big-endian for formats 2 and 3 and native byte order
17746 +** for journal format 1.
17748 +static void store32bits(u32 val, PgHdr *p, int offset){
17749 + unsigned char *ac;
17750 + ac = &((unsigned char*)PGHDR_TO_DATA(p))[offset];
17751 + if( journal_format<=1 ){
17752 + memcpy(ac, &val, 4);
17754 + ac[0] = (val>>24) & 0xff;
17755 + ac[1] = (val>>16) & 0xff;
17756 + ac[2] = (val>>8) & 0xff;
17757 + ac[3] = val & 0xff;
17763 +** Convert the bits in the pPager->errMask into an approprate
17766 +static int pager_errcode(Pager *pPager){
17767 + int rc = SQLITE_OK;
17768 + if( pPager->errMask & PAGER_ERR_LOCK ) rc = SQLITE_PROTOCOL;
17769 + if( pPager->errMask & PAGER_ERR_DISK ) rc = SQLITE_IOERR;
17770 + if( pPager->errMask & PAGER_ERR_FULL ) rc = SQLITE_FULL;
17771 + if( pPager->errMask & PAGER_ERR_MEM ) rc = SQLITE_NOMEM;
17772 + if( pPager->errMask & PAGER_ERR_CORRUPT ) rc = SQLITE_CORRUPT;
17777 +** Add or remove a page from the list of all pages that are in the
17778 +** checkpoint journal.
17780 +** The Pager keeps a separate list of pages that are currently in
17781 +** the checkpoint journal. This helps the sqlitepager_ckpt_commit()
17782 +** routine run MUCH faster for the common case where there are many
17783 +** pages in memory but only a few are in the checkpoint journal.
17785 +static void page_add_to_ckpt_list(PgHdr *pPg){
17786 + Pager *pPager = pPg->pPager;
17787 + if( pPg->inCkpt ) return;
17788 + assert( pPg->pPrevCkpt==0 && pPg->pNextCkpt==0 );
17789 + pPg->pPrevCkpt = 0;
17790 + if( pPager->pCkpt ){
17791 + pPager->pCkpt->pPrevCkpt = pPg;
17793 + pPg->pNextCkpt = pPager->pCkpt;
17794 + pPager->pCkpt = pPg;
17797 +static void page_remove_from_ckpt_list(PgHdr *pPg){
17798 + if( !pPg->inCkpt ) return;
17799 + if( pPg->pPrevCkpt ){
17800 + assert( pPg->pPrevCkpt->pNextCkpt==pPg );
17801 + pPg->pPrevCkpt->pNextCkpt = pPg->pNextCkpt;
17803 + assert( pPg->pPager->pCkpt==pPg );
17804 + pPg->pPager->pCkpt = pPg->pNextCkpt;
17806 + if( pPg->pNextCkpt ){
17807 + assert( pPg->pNextCkpt->pPrevCkpt==pPg );
17808 + pPg->pNextCkpt->pPrevCkpt = pPg->pPrevCkpt;
17810 + pPg->pNextCkpt = 0;
17811 + pPg->pPrevCkpt = 0;
17816 +** Find a page in the hash table given its page number. Return
17817 +** a pointer to the page or NULL if not found.
17819 +static PgHdr *pager_lookup(Pager *pPager, Pgno pgno){
17820 + PgHdr *p = pPager->aHash[pager_hash(pgno)];
17821 + while( p && p->pgno!=pgno ){
17822 + p = p->pNextHash;
17828 +** Unlock the database and clear the in-memory cache. This routine
17829 +** sets the state of the pager back to what it was when it was first
17830 +** opened. Any outstanding pages are invalidated and subsequent attempts
17831 +** to access those pages will likely result in a coredump.
17833 +static void pager_reset(Pager *pPager){
17834 + PgHdr *pPg, *pNext;
17835 + for(pPg=pPager->pAll; pPg; pPg=pNext){
17836 + pNext = pPg->pNextAll;
17839 + pPager->pFirst = 0;
17840 + pPager->pFirstSynced = 0;
17841 + pPager->pLast = 0;
17842 + pPager->pAll = 0;
17843 + memset(pPager->aHash, 0, sizeof(pPager->aHash));
17844 + pPager->nPage = 0;
17845 + if( pPager->state>=SQLITE_WRITELOCK ){
17846 + sqlitepager_rollback(pPager);
17848 + sqliteOsUnlock(&pPager->fd);
17849 + pPager->state = SQLITE_UNLOCK;
17850 + pPager->dbSize = -1;
17851 + pPager->nRef = 0;
17852 + assert( pPager->journalOpen==0 );
17856 +** When this routine is called, the pager has the journal file open and
17857 +** a write lock on the database. This routine releases the database
17858 +** write lock and acquires a read lock in its place. The journal file
17859 +** is deleted and closed.
17861 +** TODO: Consider keeping the journal file open for temporary databases.
17862 +** This might give a performance improvement on windows where opening
17863 +** a file is an expensive operation.
17865 +static int pager_unwritelock(Pager *pPager){
17868 + if( pPager->state<SQLITE_WRITELOCK ) return SQLITE_OK;
17869 + sqlitepager_ckpt_commit(pPager);
17870 + if( pPager->ckptOpen ){
17871 + sqliteOsClose(&pPager->cpfd);
17872 + pPager->ckptOpen = 0;
17874 + if( pPager->journalOpen ){
17875 + sqliteOsClose(&pPager->jfd);
17876 + pPager->journalOpen = 0;
17877 + sqliteOsDelete(pPager->zJournal);
17878 + sqliteFree( pPager->aInJournal );
17879 + pPager->aInJournal = 0;
17880 + for(pPg=pPager->pAll; pPg; pPg=pPg->pNextAll){
17881 + pPg->inJournal = 0;
17883 + pPg->needSync = 0;
17886 + assert( pPager->dirtyFile==0 || pPager->useJournal==0 );
17888 + rc = sqliteOsReadLock(&pPager->fd);
17889 + if( rc==SQLITE_OK ){
17890 + pPager->state = SQLITE_READLOCK;
17892 + /* This can only happen if a process does a BEGIN, then forks and the
17893 + ** child process does the COMMIT. Because of the semantics of unix
17894 + ** file locking, the unlock will fail.
17896 + pPager->state = SQLITE_UNLOCK;
17902 +** Compute and return a checksum for the page of data.
17904 +** This is not a real checksum. It is really just the sum of the
17905 +** random initial value and the page number. We considered do a checksum
17906 +** of the database, but that was found to be too slow.
17908 +static u32 pager_cksum(Pager *pPager, Pgno pgno, const char *aData){
17909 + u32 cksum = pPager->cksumInit + pgno;
17914 +** Read a single page from the journal file opened on file descriptor
17915 +** jfd. Playback this one page.
17917 +** There are three different journal formats. The format parameter determines
17918 +** which format is used by the journal that is played back.
17920 +static int pager_playback_one_page(Pager *pPager, OsFile *jfd, int format){
17922 + PgHdr *pPg; /* An existing page in the cache */
17923 + PageRecord pgRec;
17926 + rc = read32bits(format, jfd, &pgRec.pgno);
17927 + if( rc!=SQLITE_OK ) return rc;
17928 + rc = sqliteOsRead(jfd, &pgRec.aData, sizeof(pgRec.aData));
17929 + if( rc!=SQLITE_OK ) return rc;
17931 + /* Sanity checking on the page. This is more important that I originally
17932 + ** thought. If a power failure occurs while the journal is being written,
17933 + ** it could cause invalid data to be written into the journal. We need to
17934 + ** detect this invalid data (with high probability) and ignore it.
17936 + if( pgRec.pgno==0 ){
17937 + return SQLITE_DONE;
17939 + if( pgRec.pgno>(unsigned)pPager->dbSize ){
17940 + return SQLITE_OK;
17942 + if( format>=JOURNAL_FORMAT_3 ){
17943 + rc = read32bits(format, jfd, &cksum);
17944 + if( rc ) return rc;
17945 + if( pager_cksum(pPager, pgRec.pgno, pgRec.aData)!=cksum ){
17946 + return SQLITE_DONE;
17950 + /* Playback the page. Update the in-memory copy of the page
17951 + ** at the same time, if there is one.
17953 + pPg = pager_lookup(pPager, pgRec.pgno);
17954 + TRACE2("PLAYBACK %d\n", pgRec.pgno);
17955 + sqliteOsSeek(&pPager->fd, (pgRec.pgno-1)*(off_t)SQLITE_PAGE_SIZE);
17956 + rc = sqliteOsWrite(&pPager->fd, pgRec.aData, SQLITE_PAGE_SIZE);
17958 + /* No page should ever be rolled back that is in use, except for page
17959 + ** 1 which is held in use in order to keep the lock on the database
17962 + assert( pPg->nRef==0 || pPg->pgno==1 );
17963 + memcpy(PGHDR_TO_DATA(pPg), pgRec.aData, SQLITE_PAGE_SIZE);
17964 + memset(PGHDR_TO_EXTRA(pPg), 0, pPager->nExtra);
17966 + pPg->needSync = 0;
17967 + CODEC(pPager, PGHDR_TO_DATA(pPg), pPg->pgno, 3);
17973 +** Playback the journal and thus restore the database file to
17974 +** the state it was in before we started making changes.
17976 +** The journal file format is as follows:
17978 +** * 8 byte prefix. One of the aJournalMagic123 vectors defined
17979 +** above. The format of the journal file is determined by which
17980 +** of the three prefix vectors is seen.
17981 +** * 4 byte big-endian integer which is the number of valid page records
17982 +** in the journal. If this value is 0xffffffff, then compute the
17983 +** number of page records from the journal size. This field appears
17984 +** in format 3 only.
17985 +** * 4 byte big-endian integer which is the initial value for the
17986 +** sanity checksum. This field appears in format 3 only.
17987 +** * 4 byte integer which is the number of pages to truncate the
17988 +** database to during a rollback.
17989 +** * Zero or more pages instances, each as follows:
17990 +** + 4 byte page number.
17991 +** + SQLITE_PAGE_SIZE bytes of data.
17992 +** + 4 byte checksum (format 3 only)
17994 +** When we speak of the journal header, we mean the first 4 bullets above.
17995 +** Each entry in the journal is an instance of the 5th bullet. Note that
17996 +** bullets 2 and 3 only appear in format-3 journals.
17998 +** Call the value from the second bullet "nRec". nRec is the number of
17999 +** valid page entries in the journal. In most cases, you can compute the
18000 +** value of nRec from the size of the journal file. But if a power
18001 +** failure occurred while the journal was being written, it could be the
18002 +** case that the size of the journal file had already been increased but
18003 +** the extra entries had not yet made it safely to disk. In such a case,
18004 +** the value of nRec computed from the file size would be too large. For
18005 +** that reason, we always use the nRec value in the header.
18007 +** If the nRec value is 0xffffffff it means that nRec should be computed
18008 +** from the file size. This value is used when the user selects the
18009 +** no-sync option for the journal. A power failure could lead to corruption
18010 +** in this case. But for things like temporary table (which will be
18011 +** deleted when the power is restored) we don't care.
18013 +** Journal formats 1 and 2 do not have an nRec value in the header so we
18014 +** have to compute nRec from the file size. This has risks (as described
18015 +** above) which is why all persistent tables have been changed to use
18018 +** If the file opened as the journal file is not a well-formed
18019 +** journal file then the database will likely already be
18020 +** corrupted, so the PAGER_ERR_CORRUPT bit is set in pPager->errMask
18021 +** and SQLITE_CORRUPT is returned. If it all works, then this routine
18022 +** returns SQLITE_OK.
18024 +static int pager_playback(Pager *pPager, int useJournalSize){
18025 + off_t szJ; /* Size of the journal file in bytes */
18026 + int nRec; /* Number of Records in the journal */
18027 + int i; /* Loop counter */
18028 + Pgno mxPg = 0; /* Size of the original file in pages */
18029 + int format; /* Format of the journal file. */
18030 + unsigned char aMagic[sizeof(aJournalMagic1)];
18033 + /* Figure out how many records are in the journal. Abort early if
18034 + ** the journal is empty.
18036 + assert( pPager->journalOpen );
18037 + sqliteOsSeek(&pPager->jfd, 0);
18038 + rc = sqliteOsFileSize(&pPager->jfd, &szJ);
18039 + if( rc!=SQLITE_OK ){
18040 + goto end_playback;
18043 + /* If the journal file is too small to contain a complete header,
18044 + ** it must mean that the process that created the journal was just
18045 + ** beginning to write the journal file when it died. In that case,
18046 + ** the database file should have still been completely unchanged.
18047 + ** Nothing needs to be rolled back. We can safely ignore this journal.
18049 + if( szJ < sizeof(aMagic)+sizeof(Pgno) ){
18050 + goto end_playback;
18053 + /* Read the beginning of the journal and truncate the
18054 + ** database file back to its original size.
18056 + rc = sqliteOsRead(&pPager->jfd, aMagic, sizeof(aMagic));
18057 + if( rc!=SQLITE_OK ){
18058 + rc = SQLITE_PROTOCOL;
18059 + goto end_playback;
18061 + if( memcmp(aMagic, aJournalMagic3, sizeof(aMagic))==0 ){
18062 + format = JOURNAL_FORMAT_3;
18063 + }else if( memcmp(aMagic, aJournalMagic2, sizeof(aMagic))==0 ){
18064 + format = JOURNAL_FORMAT_2;
18065 + }else if( memcmp(aMagic, aJournalMagic1, sizeof(aMagic))==0 ){
18066 + format = JOURNAL_FORMAT_1;
18068 + rc = SQLITE_PROTOCOL;
18069 + goto end_playback;
18071 + if( format>=JOURNAL_FORMAT_3 ){
18072 + if( szJ < sizeof(aMagic) + 3*sizeof(u32) ){
18073 + /* Ignore the journal if it is too small to contain a complete
18074 + ** header. We already did this test once above, but at the prior
18075 + ** test, we did not know the journal format and so we had to assume
18076 + ** the smallest possible header. Now we know the header is bigger
18077 + ** than the minimum so we test again.
18079 + goto end_playback;
18081 + rc = read32bits(format, &pPager->jfd, (u32*)&nRec);
18082 + if( rc ) goto end_playback;
18083 + rc = read32bits(format, &pPager->jfd, &pPager->cksumInit);
18084 + if( rc ) goto end_playback;
18085 + if( nRec==0xffffffff || useJournalSize ){
18086 + nRec = (szJ - JOURNAL_HDR_SZ(3))/JOURNAL_PG_SZ(3);
18089 + nRec = (szJ - JOURNAL_HDR_SZ(2))/JOURNAL_PG_SZ(2);
18090 + assert( nRec*JOURNAL_PG_SZ(2)+JOURNAL_HDR_SZ(2)==szJ );
18092 + rc = read32bits(format, &pPager->jfd, &mxPg);
18093 + if( rc!=SQLITE_OK ){
18094 + goto end_playback;
18096 + assert( pPager->origDbSize==0 || pPager->origDbSize==mxPg );
18097 + rc = sqliteOsTruncate(&pPager->fd, SQLITE_PAGE_SIZE*(off_t)mxPg);
18098 + if( rc!=SQLITE_OK ){
18099 + goto end_playback;
18101 + pPager->dbSize = mxPg;
18103 + /* Copy original pages out of the journal and back into the database file.
18105 + for(i=0; i<nRec; i++){
18106 + rc = pager_playback_one_page(pPager, &pPager->jfd, format);
18107 + if( rc!=SQLITE_OK ){
18108 + if( rc==SQLITE_DONE ){
18115 + /* Pages that have been written to the journal but never synced
18116 + ** where not restored by the loop above. We have to restore those
18117 + ** pages by reading them back from the original database.
18119 + if( rc==SQLITE_OK ){
18121 + for(pPg=pPager->pAll; pPg; pPg=pPg->pNextAll){
18122 + char zBuf[SQLITE_PAGE_SIZE];
18123 + if( !pPg->dirty ) continue;
18124 + if( (int)pPg->pgno <= pPager->origDbSize ){
18125 + sqliteOsSeek(&pPager->fd, SQLITE_PAGE_SIZE*(off_t)(pPg->pgno-1));
18126 + rc = sqliteOsRead(&pPager->fd, zBuf, SQLITE_PAGE_SIZE);
18127 + TRACE2("REFETCH %d\n", pPg->pgno);
18128 + CODEC(pPager, zBuf, pPg->pgno, 2);
18131 + memset(zBuf, 0, SQLITE_PAGE_SIZE);
18133 + if( pPg->nRef==0 || memcmp(zBuf, PGHDR_TO_DATA(pPg), SQLITE_PAGE_SIZE) ){
18134 + memcpy(PGHDR_TO_DATA(pPg), zBuf, SQLITE_PAGE_SIZE);
18135 + memset(PGHDR_TO_EXTRA(pPg), 0, pPager->nExtra);
18137 + pPg->needSync = 0;
18143 + if( rc!=SQLITE_OK ){
18144 + pager_unwritelock(pPager);
18145 + pPager->errMask |= PAGER_ERR_CORRUPT;
18146 + rc = SQLITE_CORRUPT;
18148 + rc = pager_unwritelock(pPager);
18154 +** Playback the checkpoint journal.
18156 +** This is similar to playing back the transaction journal but with
18157 +** a few extra twists.
18159 +** (1) The number of pages in the database file at the start of
18160 +** the checkpoint is stored in pPager->ckptSize, not in the
18161 +** journal file itself.
18163 +** (2) In addition to playing back the checkpoint journal, also
18164 +** playback all pages of the transaction journal beginning
18165 +** at offset pPager->ckptJSize.
18167 +static int pager_ckpt_playback(Pager *pPager){
18168 + off_t szJ; /* Size of the full journal */
18169 + int nRec; /* Number of Records */
18170 + int i; /* Loop counter */
18173 + /* Truncate the database back to its original size.
18175 + rc = sqliteOsTruncate(&pPager->fd, SQLITE_PAGE_SIZE*(off_t)pPager->ckptSize);
18176 + pPager->dbSize = pPager->ckptSize;
18178 + /* Figure out how many records are in the checkpoint journal.
18180 + assert( pPager->ckptInUse && pPager->journalOpen );
18181 + sqliteOsSeek(&pPager->cpfd, 0);
18182 + nRec = pPager->ckptNRec;
18184 + /* Copy original pages out of the checkpoint journal and back into the
18185 + ** database file. Note that the checkpoint journal always uses format
18186 + ** 2 instead of format 3 since it does not need to be concerned with
18187 + ** power failures corrupting the journal and can thus omit the checksums.
18189 + for(i=nRec-1; i>=0; i--){
18190 + rc = pager_playback_one_page(pPager, &pPager->cpfd, 2);
18191 + assert( rc!=SQLITE_DONE );
18192 + if( rc!=SQLITE_OK ) goto end_ckpt_playback;
18195 + /* Figure out how many pages need to be copied out of the transaction
18198 + rc = sqliteOsSeek(&pPager->jfd, pPager->ckptJSize);
18199 + if( rc!=SQLITE_OK ){
18200 + goto end_ckpt_playback;
18202 + rc = sqliteOsFileSize(&pPager->jfd, &szJ);
18203 + if( rc!=SQLITE_OK ){
18204 + goto end_ckpt_playback;
18206 + nRec = (szJ - pPager->ckptJSize)/JOURNAL_PG_SZ(journal_format);
18207 + for(i=nRec-1; i>=0; i--){
18208 + rc = pager_playback_one_page(pPager, &pPager->jfd, journal_format);
18209 + if( rc!=SQLITE_OK ){
18210 + assert( rc!=SQLITE_DONE );
18211 + goto end_ckpt_playback;
18215 +end_ckpt_playback:
18216 + if( rc!=SQLITE_OK ){
18217 + pPager->errMask |= PAGER_ERR_CORRUPT;
18218 + rc = SQLITE_CORRUPT;
18224 +** Change the maximum number of in-memory pages that are allowed.
18226 +** The maximum number is the absolute value of the mxPage parameter.
18227 +** If mxPage is negative, the noSync flag is also set. noSync bypasses
18228 +** calls to sqliteOsSync(). The pager runs much faster with noSync on,
18229 +** but if the operating system crashes or there is an abrupt power
18230 +** failure, the database file might be left in an inconsistent and
18231 +** unrepairable state.
18233 +void sqlitepager_set_cachesize(Pager *pPager, int mxPage){
18235 + pPager->noSync = pPager->tempFile;
18236 + if( pPager->noSync==0 ) pPager->needSync = 0;
18238 + pPager->noSync = 1;
18239 + mxPage = -mxPage;
18242 + pPager->mxPage = mxPage;
18247 +** Adjust the robustness of the database to damage due to OS crashes
18248 +** or power failures by changing the number of syncs()s when writing
18249 +** the rollback journal. There are three levels:
18251 +** OFF sqliteOsSync() is never called. This is the default
18252 +** for temporary and transient files.
18254 +** NORMAL The journal is synced once before writes begin on the
18255 +** database. This is normally adequate protection, but
18256 +** it is theoretically possible, though very unlikely,
18257 +** that an inopertune power failure could leave the journal
18258 +** in a state which would cause damage to the database
18259 +** when it is rolled back.
18261 +** FULL The journal is synced twice before writes begin on the
18262 +** database (with some additional information - the nRec field
18263 +** of the journal header - being written in between the two
18264 +** syncs). If we assume that writing a
18265 +** single disk sector is atomic, then this mode provides
18266 +** assurance that the journal will not be corrupted to the
18267 +** point of causing damage to the database during rollback.
18269 +** Numeric values associated with these states are OFF==1, NORMAL=2,
18272 +void sqlitepager_set_safety_level(Pager *pPager, int level){
18273 + pPager->noSync = level==1 || pPager->tempFile;
18274 + pPager->fullSync = level==3 && !pPager->tempFile;
18275 + if( pPager->noSync==0 ) pPager->needSync = 0;
18279 +** Open a temporary file. Write the name of the file into zName
18280 +** (zName must be at least SQLITE_TEMPNAME_SIZE bytes long.) Write
18281 +** the file descriptor into *fd. Return SQLITE_OK on success or some
18282 +** other error code if we fail.
18284 +** The OS will automatically delete the temporary file when it is
18287 +static int sqlitepager_opentemp(char *zFile, OsFile *fd){
18292 + sqliteOsTempFileName(zFile);
18293 + rc = sqliteOsOpenExclusive(zFile, fd, 1);
18294 + }while( cnt>0 && rc!=SQLITE_OK );
18299 +** Create a new page cache and put a pointer to the page cache in *ppPager.
18300 +** The file to be cached need not exist. The file is not locked until
18301 +** the first call to sqlitepager_get() and is only held open until the
18302 +** last page is released using sqlitepager_unref().
18304 +** If zFilename is NULL then a randomly-named temporary file is created
18305 +** and used as the file to be cached. The file will be deleted
18306 +** automatically when it is closed.
18308 +int sqlitepager_open(
18309 + Pager **ppPager, /* Return the Pager structure here */
18310 + const char *zFilename, /* Name of the database file to open */
18311 + int mxPage, /* Max number of in-memory cache pages */
18312 + int nExtra, /* Extra bytes append to each in-memory page */
18313 + int useJournal /* TRUE to use a rollback journal on this file */
18316 + char *zFullPathname;
18321 + int readOnly = 0;
18322 + char zTemp[SQLITE_TEMPNAME_SIZE];
18325 + if( sqlite_malloc_failed ){
18326 + return SQLITE_NOMEM;
18328 + if( zFilename && zFilename[0] ){
18329 + zFullPathname = sqliteOsFullPathname(zFilename);
18330 + rc = sqliteOsOpenReadWrite(zFullPathname, &fd, &readOnly);
18333 + rc = sqlitepager_opentemp(zTemp, &fd);
18334 + zFilename = zTemp;
18335 + zFullPathname = sqliteOsFullPathname(zFilename);
18338 + if( sqlite_malloc_failed ){
18339 + return SQLITE_NOMEM;
18341 + if( rc!=SQLITE_OK ){
18342 + sqliteFree(zFullPathname);
18343 + return SQLITE_CANTOPEN;
18345 + nameLen = strlen(zFullPathname);
18346 + pPager = sqliteMalloc( sizeof(*pPager) + nameLen*3 + 30 );
18348 + sqliteOsClose(&fd);
18349 + sqliteFree(zFullPathname);
18350 + return SQLITE_NOMEM;
18352 + SET_PAGER(pPager);
18353 + pPager->zFilename = (char*)&pPager[1];
18354 + pPager->zDirectory = &pPager->zFilename[nameLen+1];
18355 + pPager->zJournal = &pPager->zDirectory[nameLen+1];
18356 + strcpy(pPager->zFilename, zFullPathname);
18357 + strcpy(pPager->zDirectory, zFullPathname);
18358 + for(i=nameLen; i>0 && pPager->zDirectory[i-1]!='/'; i--){}
18359 + if( i>0 ) pPager->zDirectory[i-1] = 0;
18360 + strcpy(pPager->zJournal, zFullPathname);
18361 + sqliteFree(zFullPathname);
18362 + strcpy(&pPager->zJournal[nameLen], "-journal");
18364 + pPager->journalOpen = 0;
18365 + pPager->useJournal = useJournal;
18366 + pPager->ckptOpen = 0;
18367 + pPager->ckptInUse = 0;
18368 + pPager->nRef = 0;
18369 + pPager->dbSize = -1;
18370 + pPager->ckptSize = 0;
18371 + pPager->ckptJSize = 0;
18372 + pPager->nPage = 0;
18373 + pPager->mxPage = mxPage>5 ? mxPage : 10;
18374 + pPager->state = SQLITE_UNLOCK;
18375 + pPager->errMask = 0;
18376 + pPager->tempFile = tempFile;
18377 + pPager->readOnly = readOnly;
18378 + pPager->needSync = 0;
18379 + pPager->noSync = pPager->tempFile || !useJournal;
18380 + pPager->pFirst = 0;
18381 + pPager->pFirstSynced = 0;
18382 + pPager->pLast = 0;
18383 + pPager->nExtra = nExtra;
18384 + memset(pPager->aHash, 0, sizeof(pPager->aHash));
18385 + *ppPager = pPager;
18386 + return SQLITE_OK;
18390 +** Set the destructor for this pager. If not NULL, the destructor is called
18391 +** when the reference count on each page reaches zero. The destructor can
18392 +** be used to clean up information in the extra segment appended to each page.
18394 +** The destructor is not called as a result sqlitepager_close().
18395 +** Destructors are only called by sqlitepager_unref().
18397 +void sqlitepager_set_destructor(Pager *pPager, void (*xDesc)(void*)){
18398 + pPager->xDestructor = xDesc;
18402 +** Return the total number of pages in the disk file associated with
18405 +int sqlitepager_pagecount(Pager *pPager){
18407 + assert( pPager!=0 );
18408 + if( pPager->dbSize>=0 ){
18409 + return pPager->dbSize;
18411 + if( sqliteOsFileSize(&pPager->fd, &n)!=SQLITE_OK ){
18412 + pPager->errMask |= PAGER_ERR_DISK;
18415 + n /= SQLITE_PAGE_SIZE;
18416 + if( pPager->state!=SQLITE_UNLOCK ){
18417 + pPager->dbSize = n;
18423 +** Forward declaration
18425 +static int syncJournal(Pager*);
18428 +** Truncate the file to the number of pages specified.
18430 +int sqlitepager_truncate(Pager *pPager, Pgno nPage){
18432 + if( pPager->dbSize<0 ){
18433 + sqlitepager_pagecount(pPager);
18435 + if( pPager->errMask!=0 ){
18436 + rc = pager_errcode(pPager);
18439 + if( nPage>=(unsigned)pPager->dbSize ){
18440 + return SQLITE_OK;
18442 + syncJournal(pPager);
18443 + rc = sqliteOsTruncate(&pPager->fd, SQLITE_PAGE_SIZE*(off_t)nPage);
18444 + if( rc==SQLITE_OK ){
18445 + pPager->dbSize = nPage;
18451 +** Shutdown the page cache. Free all memory and close all files.
18453 +** If a transaction was in progress when this routine is called, that
18454 +** transaction is rolled back. All outstanding pages are invalidated
18455 +** and their memory is freed. Any attempt to use a page associated
18456 +** with this page cache after this function returns will likely
18457 +** result in a coredump.
18459 +int sqlitepager_close(Pager *pPager){
18460 + PgHdr *pPg, *pNext;
18461 + switch( pPager->state ){
18462 + case SQLITE_WRITELOCK: {
18463 + sqlitepager_rollback(pPager);
18464 + sqliteOsUnlock(&pPager->fd);
18465 + assert( pPager->journalOpen==0 );
18468 + case SQLITE_READLOCK: {
18469 + sqliteOsUnlock(&pPager->fd);
18477 + for(pPg=pPager->pAll; pPg; pPg=pNext){
18478 + pNext = pPg->pNextAll;
18481 + sqliteOsClose(&pPager->fd);
18482 + assert( pPager->journalOpen==0 );
18483 + /* Temp files are automatically deleted by the OS
18484 + ** if( pPager->tempFile ){
18485 + ** sqliteOsDelete(pPager->zFilename);
18488 + CLR_PAGER(pPager);
18489 + if( pPager->zFilename!=(char*)&pPager[1] ){
18490 + assert( 0 ); /* Cannot happen */
18491 + sqliteFree(pPager->zFilename);
18492 + sqliteFree(pPager->zJournal);
18493 + sqliteFree(pPager->zDirectory);
18495 + sqliteFree(pPager);
18496 + return SQLITE_OK;
18500 +** Return the page number for the given page data.
18502 +Pgno sqlitepager_pagenumber(void *pData){
18503 + PgHdr *p = DATA_TO_PGHDR(pData);
18508 +** Increment the reference count for a page. If the page is
18509 +** currently on the freelist (the reference count is zero) then
18510 +** remove it from the freelist.
18512 +#define page_ref(P) ((P)->nRef==0?_page_ref(P):(void)(P)->nRef++)
18513 +static void _page_ref(PgHdr *pPg){
18514 + if( pPg->nRef==0 ){
18515 + /* The page is currently on the freelist. Remove it. */
18516 + if( pPg==pPg->pPager->pFirstSynced ){
18517 + PgHdr *p = pPg->pNextFree;
18518 + while( p && p->needSync ){ p = p->pNextFree; }
18519 + pPg->pPager->pFirstSynced = p;
18521 + if( pPg->pPrevFree ){
18522 + pPg->pPrevFree->pNextFree = pPg->pNextFree;
18524 + pPg->pPager->pFirst = pPg->pNextFree;
18526 + if( pPg->pNextFree ){
18527 + pPg->pNextFree->pPrevFree = pPg->pPrevFree;
18529 + pPg->pPager->pLast = pPg->pPrevFree;
18531 + pPg->pPager->nRef++;
18538 +** Increment the reference count for a page. The input pointer is
18539 +** a reference to the page data.
18541 +int sqlitepager_ref(void *pData){
18542 + PgHdr *pPg = DATA_TO_PGHDR(pData);
18544 + return SQLITE_OK;
18548 +** Sync the journal. In other words, make sure all the pages that have
18549 +** been written to the journal have actually reached the surface of the
18550 +** disk. It is not safe to modify the original database file until after
18551 +** the journal has been synced. If the original database is modified before
18552 +** the journal is synced and a power failure occurs, the unsynced journal
18553 +** data would be lost and we would be unable to completely rollback the
18554 +** database changes. Database corruption would occur.
18556 +** This routine also updates the nRec field in the header of the journal.
18557 +** (See comments on the pager_playback() routine for additional information.)
18558 +** If the sync mode is FULL, two syncs will occur. First the whole journal
18559 +** is synced, then the nRec field is updated, then a second sync occurs.
18561 +** For temporary databases, we do not care if we are able to rollback
18562 +** after a power failure, so sync occurs.
18564 +** This routine clears the needSync field of every page current held in
18567 +static int syncJournal(Pager *pPager){
18569 + int rc = SQLITE_OK;
18571 + /* Sync the journal before modifying the main database
18572 + ** (assuming there is a journal and it needs to be synced.)
18574 + if( pPager->needSync ){
18575 + if( !pPager->tempFile ){
18576 + assert( pPager->journalOpen );
18577 + /* assert( !pPager->noSync ); // noSync might be set if synchronous
18578 + ** was turned off after the transaction was started. Ticket #615 */
18581 + /* Make sure the pPager->nRec counter we are keeping agrees
18582 + ** with the nRec computed from the size of the journal file.
18584 + off_t hdrSz, pgSz, jSz;
18585 + hdrSz = JOURNAL_HDR_SZ(journal_format);
18586 + pgSz = JOURNAL_PG_SZ(journal_format);
18587 + rc = sqliteOsFileSize(&pPager->jfd, &jSz);
18588 + if( rc!=0 ) return rc;
18589 + assert( pPager->nRec*pgSz+hdrSz==jSz );
18592 + if( journal_format>=3 ){
18593 + /* Write the nRec value into the journal file header */
18595 + if( pPager->fullSync ){
18596 + TRACE1("SYNC\n");
18597 + rc = sqliteOsSync(&pPager->jfd);
18598 + if( rc!=0 ) return rc;
18600 + sqliteOsSeek(&pPager->jfd, sizeof(aJournalMagic1));
18601 + rc = write32bits(&pPager->jfd, pPager->nRec);
18602 + if( rc ) return rc;
18603 + szJ = JOURNAL_HDR_SZ(journal_format) +
18604 + pPager->nRec*JOURNAL_PG_SZ(journal_format);
18605 + sqliteOsSeek(&pPager->jfd, szJ);
18607 + TRACE1("SYNC\n");
18608 + rc = sqliteOsSync(&pPager->jfd);
18609 + if( rc!=0 ) return rc;
18610 + pPager->journalStarted = 1;
18612 + pPager->needSync = 0;
18614 + /* Erase the needSync flag from every page.
18616 + for(pPg=pPager->pAll; pPg; pPg=pPg->pNextAll){
18617 + pPg->needSync = 0;
18619 + pPager->pFirstSynced = pPager->pFirst;
18623 + /* If the Pager.needSync flag is clear then the PgHdr.needSync
18624 + ** flag must also be clear for all pages. Verify that this
18625 + ** invariant is true.
18628 + for(pPg=pPager->pAll; pPg; pPg=pPg->pNextAll){
18629 + assert( pPg->needSync==0 );
18631 + assert( pPager->pFirstSynced==pPager->pFirst );
18639 +** Given a list of pages (connected by the PgHdr.pDirty pointer) write
18640 +** every one of those pages out to the database file and mark them all
18643 +static int pager_write_pagelist(PgHdr *pList){
18647 + if( pList==0 ) return SQLITE_OK;
18648 + pPager = pList->pPager;
18650 + assert( pList->dirty );
18651 + sqliteOsSeek(&pPager->fd, (pList->pgno-1)*(off_t)SQLITE_PAGE_SIZE);
18652 + CODEC(pPager, PGHDR_TO_DATA(pList), pList->pgno, 6);
18653 + TRACE2("STORE %d\n", pList->pgno);
18654 + rc = sqliteOsWrite(&pPager->fd, PGHDR_TO_DATA(pList), SQLITE_PAGE_SIZE);
18655 + CODEC(pPager, PGHDR_TO_DATA(pList), pList->pgno, 0);
18656 + if( rc ) return rc;
18657 + pList->dirty = 0;
18658 + pList = pList->pDirty;
18660 + return SQLITE_OK;
18664 +** Collect every dirty page into a dirty list and
18665 +** return a pointer to the head of that list. All pages are
18666 +** collected even if they are still in use.
18668 +static PgHdr *pager_get_all_dirty_pages(Pager *pPager){
18669 + PgHdr *p, *pList;
18671 + for(p=pPager->pAll; p; p=p->pNextAll){
18673 + p->pDirty = pList;
18681 +** Acquire a page.
18683 +** A read lock on the disk file is obtained when the first page is acquired.
18684 +** This read lock is dropped when the last page is released.
18686 +** A _get works for any page number greater than 0. If the database
18687 +** file is smaller than the requested page, then no actual disk
18688 +** read occurs and the memory image of the page is initialized to
18689 +** all zeros. The extra data appended to a page is always initialized
18690 +** to zeros the first time a page is loaded into memory.
18692 +** The acquisition might fail for several reasons. In all cases,
18693 +** an appropriate error code is returned and *ppPage is set to NULL.
18695 +** See also sqlitepager_lookup(). Both this routine and _lookup() attempt
18696 +** to find a page in the in-memory cache first. If the page is not already
18697 +** in memory, this routine goes to disk to read it in whereas _lookup()
18698 +** just returns 0. This routine acquires a read-lock the first time it
18699 +** has to go to disk, and could also playback an old journal if necessary.
18700 +** Since _lookup() never goes to disk, it never has to deal with locks
18701 +** or journal files.
18703 +int sqlitepager_get(Pager *pPager, Pgno pgno, void **ppPage){
18707 + /* Make sure we have not hit any critical errors.
18709 + assert( pPager!=0 );
18710 + assert( pgno!=0 );
18712 + if( pPager->errMask & ~(PAGER_ERR_FULL) ){
18713 + return pager_errcode(pPager);
18716 + /* If this is the first page accessed, then get a read lock
18717 + ** on the database file.
18719 + if( pPager->nRef==0 ){
18720 + rc = sqliteOsReadLock(&pPager->fd);
18721 + if( rc!=SQLITE_OK ){
18724 + pPager->state = SQLITE_READLOCK;
18726 + /* If a journal file exists, try to play it back.
18728 + if( pPager->useJournal && sqliteOsFileExists(pPager->zJournal) ){
18731 + /* Get a write lock on the database
18733 + rc = sqliteOsWriteLock(&pPager->fd);
18734 + if( rc!=SQLITE_OK ){
18735 + if( sqliteOsUnlock(&pPager->fd)!=SQLITE_OK ){
18736 + /* This should never happen! */
18737 + rc = SQLITE_INTERNAL;
18741 + pPager->state = SQLITE_WRITELOCK;
18743 + /* Open the journal for reading only. Return SQLITE_BUSY if
18744 + ** we are unable to open the journal file.
18746 + ** The journal file does not need to be locked itself. The
18747 + ** journal file is never open unless the main database file holds
18748 + ** a write lock, so there is never any chance of two or more
18749 + ** processes opening the journal at the same time.
18751 + rc = sqliteOsOpenReadOnly(pPager->zJournal, &pPager->jfd);
18752 + if( rc!=SQLITE_OK ){
18753 + rc = sqliteOsUnlock(&pPager->fd);
18754 + assert( rc==SQLITE_OK );
18755 + return SQLITE_BUSY;
18757 + pPager->journalOpen = 1;
18758 + pPager->journalStarted = 0;
18760 + /* Playback and delete the journal. Drop the database write
18761 + ** lock and reacquire the read lock.
18763 + rc = pager_playback(pPager, 0);
18764 + if( rc!=SQLITE_OK ){
18770 + /* Search for page in cache */
18771 + pPg = pager_lookup(pPager, pgno);
18774 + /* The requested page is not in the page cache. */
18777 + if( pPager->nPage<pPager->mxPage || pPager->pFirst==0 ){
18778 + /* Create a new page */
18779 + pPg = sqliteMallocRaw( sizeof(*pPg) + SQLITE_PAGE_SIZE
18780 + + sizeof(u32) + pPager->nExtra );
18782 + pager_unwritelock(pPager);
18783 + pPager->errMask |= PAGER_ERR_MEM;
18784 + return SQLITE_NOMEM;
18786 + memset(pPg, 0, sizeof(*pPg));
18787 + pPg->pPager = pPager;
18788 + pPg->pNextAll = pPager->pAll;
18789 + if( pPager->pAll ){
18790 + pPager->pAll->pPrevAll = pPg;
18792 + pPg->pPrevAll = 0;
18793 + pPager->pAll = pPg;
18796 + /* Find a page to recycle. Try to locate a page that does not
18797 + ** require us to do an fsync() on the journal.
18799 + pPg = pPager->pFirstSynced;
18801 + /* If we could not find a page that does not require an fsync()
18802 + ** on the journal file then fsync the journal file. This is a
18803 + ** very slow operation, so we work hard to avoid it. But sometimes
18804 + ** it can't be helped.
18807 + int rc = syncJournal(pPager);
18809 + sqlitepager_rollback(pPager);
18810 + return SQLITE_IOERR;
18812 + pPg = pPager->pFirst;
18814 + assert( pPg->nRef==0 );
18816 + /* Write the page to the database file if it is dirty.
18818 + if( pPg->dirty ){
18819 + assert( pPg->needSync==0 );
18821 + rc = pager_write_pagelist( pPg );
18822 + if( rc!=SQLITE_OK ){
18823 + sqlitepager_rollback(pPager);
18824 + return SQLITE_IOERR;
18827 + assert( pPg->dirty==0 );
18829 + /* If the page we are recycling is marked as alwaysRollback, then
18830 + ** set the global alwaysRollback flag, thus disabling the
18831 + ** sqlite_dont_rollback() optimization for the rest of this transaction.
18832 + ** It is necessary to do this because the page marked alwaysRollback
18833 + ** might be reloaded at a later time but at that point we won't remember
18834 + ** that is was marked alwaysRollback. This means that all pages must
18835 + ** be marked as alwaysRollback from here on out.
18837 + if( pPg->alwaysRollback ){
18838 + pPager->alwaysRollback = 1;
18841 + /* Unlink the old page from the free list and the hash table
18843 + if( pPg==pPager->pFirstSynced ){
18844 + PgHdr *p = pPg->pNextFree;
18845 + while( p && p->needSync ){ p = p->pNextFree; }
18846 + pPager->pFirstSynced = p;
18848 + if( pPg->pPrevFree ){
18849 + pPg->pPrevFree->pNextFree = pPg->pNextFree;
18851 + assert( pPager->pFirst==pPg );
18852 + pPager->pFirst = pPg->pNextFree;
18854 + if( pPg->pNextFree ){
18855 + pPg->pNextFree->pPrevFree = pPg->pPrevFree;
18857 + assert( pPager->pLast==pPg );
18858 + pPager->pLast = pPg->pPrevFree;
18860 + pPg->pNextFree = pPg->pPrevFree = 0;
18861 + if( pPg->pNextHash ){
18862 + pPg->pNextHash->pPrevHash = pPg->pPrevHash;
18864 + if( pPg->pPrevHash ){
18865 + pPg->pPrevHash->pNextHash = pPg->pNextHash;
18867 + h = pager_hash(pPg->pgno);
18868 + assert( pPager->aHash[h]==pPg );
18869 + pPager->aHash[h] = pPg->pNextHash;
18871 + pPg->pNextHash = pPg->pPrevHash = 0;
18874 + pPg->pgno = pgno;
18875 + if( pPager->aInJournal && (int)pgno<=pPager->origDbSize ){
18876 + sqliteCheckMemory(pPager->aInJournal, pgno/8);
18877 + assert( pPager->journalOpen );
18878 + pPg->inJournal = (pPager->aInJournal[pgno/8] & (1<<(pgno&7)))!=0;
18879 + pPg->needSync = 0;
18881 + pPg->inJournal = 0;
18882 + pPg->needSync = 0;
18884 + if( pPager->aInCkpt && (int)pgno<=pPager->ckptSize
18885 + && (pPager->aInCkpt[pgno/8] & (1<<(pgno&7)))!=0 ){
18886 + page_add_to_ckpt_list(pPg);
18888 + page_remove_from_ckpt_list(pPg);
18894 + h = pager_hash(pgno);
18895 + pPg->pNextHash = pPager->aHash[h];
18896 + pPager->aHash[h] = pPg;
18897 + if( pPg->pNextHash ){
18898 + assert( pPg->pNextHash->pPrevHash==0 );
18899 + pPg->pNextHash->pPrevHash = pPg;
18901 + if( pPager->nExtra>0 ){
18902 + memset(PGHDR_TO_EXTRA(pPg), 0, pPager->nExtra);
18904 + if( pPager->dbSize<0 ) sqlitepager_pagecount(pPager);
18905 + if( pPager->errMask!=0 ){
18906 + sqlitepager_unref(PGHDR_TO_DATA(pPg));
18907 + rc = pager_errcode(pPager);
18910 + if( pPager->dbSize<(int)pgno ){
18911 + memset(PGHDR_TO_DATA(pPg), 0, SQLITE_PAGE_SIZE);
18914 + sqliteOsSeek(&pPager->fd, (pgno-1)*(off_t)SQLITE_PAGE_SIZE);
18915 + rc = sqliteOsRead(&pPager->fd, PGHDR_TO_DATA(pPg), SQLITE_PAGE_SIZE);
18916 + TRACE2("FETCH %d\n", pPg->pgno);
18917 + CODEC(pPager, PGHDR_TO_DATA(pPg), pPg->pgno, 3);
18918 + if( rc!=SQLITE_OK ){
18920 + if( sqliteOsFileSize(&pPager->fd,&fileSize)!=SQLITE_OK
18921 + || fileSize>=pgno*SQLITE_PAGE_SIZE ){
18922 + sqlitepager_unref(PGHDR_TO_DATA(pPg));
18925 + memset(PGHDR_TO_DATA(pPg), 0, SQLITE_PAGE_SIZE);
18930 + /* The requested page is in the page cache. */
18934 + *ppPage = PGHDR_TO_DATA(pPg);
18935 + return SQLITE_OK;
18939 +** Acquire a page if it is already in the in-memory cache. Do
18940 +** not read the page from disk. Return a pointer to the page,
18941 +** or 0 if the page is not in cache.
18943 +** See also sqlitepager_get(). The difference between this routine
18944 +** and sqlitepager_get() is that _get() will go to the disk and read
18945 +** in the page if the page is not already in cache. This routine
18946 +** returns NULL if the page is not in cache or if a disk I/O error
18947 +** has ever happened.
18949 +void *sqlitepager_lookup(Pager *pPager, Pgno pgno){
18952 + assert( pPager!=0 );
18953 + assert( pgno!=0 );
18954 + if( pPager->errMask & ~(PAGER_ERR_FULL) ){
18957 + /* if( pPager->nRef==0 ){
18961 + pPg = pager_lookup(pPager, pgno);
18962 + if( pPg==0 ) return 0;
18964 + return PGHDR_TO_DATA(pPg);
18968 +** Release a page.
18970 +** If the number of references to the page drop to zero, then the
18971 +** page is added to the LRU list. When all references to all pages
18972 +** are released, a rollback occurs and the lock on the database is
18975 +int sqlitepager_unref(void *pData){
18978 + /* Decrement the reference count for this page
18980 + pPg = DATA_TO_PGHDR(pData);
18981 + assert( pPg->nRef>0 );
18985 + /* When the number of references to a page reach 0, call the
18986 + ** destructor and add the page to the freelist.
18988 + if( pPg->nRef==0 ){
18990 + pPager = pPg->pPager;
18991 + pPg->pNextFree = 0;
18992 + pPg->pPrevFree = pPager->pLast;
18993 + pPager->pLast = pPg;
18994 + if( pPg->pPrevFree ){
18995 + pPg->pPrevFree->pNextFree = pPg;
18997 + pPager->pFirst = pPg;
18999 + if( pPg->needSync==0 && pPager->pFirstSynced==0 ){
19000 + pPager->pFirstSynced = pPg;
19002 + if( pPager->xDestructor ){
19003 + pPager->xDestructor(pData);
19006 + /* When all pages reach the freelist, drop the read lock from
19007 + ** the database file.
19010 + assert( pPager->nRef>=0 );
19011 + if( pPager->nRef==0 ){
19012 + pager_reset(pPager);
19015 + return SQLITE_OK;
19019 +** Create a journal file for pPager. There should already be a write
19020 +** lock on the database file when this routine is called.
19022 +** Return SQLITE_OK if everything. Return an error code and release the
19023 +** write lock if anything goes wrong.
19025 +static int pager_open_journal(Pager *pPager){
19027 + assert( pPager->state==SQLITE_WRITELOCK );
19028 + assert( pPager->journalOpen==0 );
19029 + assert( pPager->useJournal );
19030 + sqlitepager_pagecount(pPager);
19031 + pPager->aInJournal = sqliteMalloc( pPager->dbSize/8 + 1 );
19032 + if( pPager->aInJournal==0 ){
19033 + sqliteOsReadLock(&pPager->fd);
19034 + pPager->state = SQLITE_READLOCK;
19035 + return SQLITE_NOMEM;
19037 + rc = sqliteOsOpenExclusive(pPager->zJournal, &pPager->jfd,pPager->tempFile);
19038 + if( rc!=SQLITE_OK ){
19039 + sqliteFree(pPager->aInJournal);
19040 + pPager->aInJournal = 0;
19041 + sqliteOsReadLock(&pPager->fd);
19042 + pPager->state = SQLITE_READLOCK;
19043 + return SQLITE_CANTOPEN;
19045 + sqliteOsOpenDirectory(pPager->zDirectory, &pPager->jfd);
19046 + pPager->journalOpen = 1;
19047 + pPager->journalStarted = 0;
19048 + pPager->needSync = 0;
19049 + pPager->alwaysRollback = 0;
19050 + pPager->nRec = 0;
19051 + if( pPager->errMask!=0 ){
19052 + rc = pager_errcode(pPager);
19055 + pPager->origDbSize = pPager->dbSize;
19056 + if( journal_format==JOURNAL_FORMAT_3 ){
19057 + rc = sqliteOsWrite(&pPager->jfd, aJournalMagic3, sizeof(aJournalMagic3));
19058 + if( rc==SQLITE_OK ){
19059 + rc = write32bits(&pPager->jfd, pPager->noSync ? 0xffffffff : 0);
19061 + if( rc==SQLITE_OK ){
19062 + sqliteRandomness(sizeof(pPager->cksumInit), &pPager->cksumInit);
19063 + rc = write32bits(&pPager->jfd, pPager->cksumInit);
19065 + }else if( journal_format==JOURNAL_FORMAT_2 ){
19066 + rc = sqliteOsWrite(&pPager->jfd, aJournalMagic2, sizeof(aJournalMagic2));
19068 + assert( journal_format==JOURNAL_FORMAT_1 );
19069 + rc = sqliteOsWrite(&pPager->jfd, aJournalMagic1, sizeof(aJournalMagic1));
19071 + if( rc==SQLITE_OK ){
19072 + rc = write32bits(&pPager->jfd, pPager->dbSize);
19074 + if( pPager->ckptAutoopen && rc==SQLITE_OK ){
19075 + rc = sqlitepager_ckpt_begin(pPager);
19077 + if( rc!=SQLITE_OK ){
19078 + rc = pager_unwritelock(pPager);
19079 + if( rc==SQLITE_OK ){
19080 + rc = SQLITE_FULL;
19087 +** Acquire a write-lock on the database. The lock is removed when
19088 +** the any of the following happen:
19090 +** * sqlitepager_commit() is called.
19091 +** * sqlitepager_rollback() is called.
19092 +** * sqlitepager_close() is called.
19093 +** * sqlitepager_unref() is called to on every outstanding page.
19095 +** The parameter to this routine is a pointer to any open page of the
19096 +** database file. Nothing changes about the page - it is used merely
19097 +** to acquire a pointer to the Pager structure and as proof that there
19098 +** is already a read-lock on the database.
19100 +** A journal file is opened if this is not a temporary file. For
19101 +** temporary files, the opening of the journal file is deferred until
19102 +** there is an actual need to write to the journal.
19104 +** If the database is already write-locked, this routine is a no-op.
19106 +int sqlitepager_begin(void *pData){
19107 + PgHdr *pPg = DATA_TO_PGHDR(pData);
19108 + Pager *pPager = pPg->pPager;
19109 + int rc = SQLITE_OK;
19110 + assert( pPg->nRef>0 );
19111 + assert( pPager->state!=SQLITE_UNLOCK );
19112 + if( pPager->state==SQLITE_READLOCK ){
19113 + assert( pPager->aInJournal==0 );
19114 + rc = sqliteOsWriteLock(&pPager->fd);
19115 + if( rc!=SQLITE_OK ){
19118 + pPager->state = SQLITE_WRITELOCK;
19119 + pPager->dirtyFile = 0;
19120 + TRACE1("TRANSACTION\n");
19121 + if( pPager->useJournal && !pPager->tempFile ){
19122 + rc = pager_open_journal(pPager);
19129 +** Mark a data page as writeable. The page is written into the journal
19130 +** if it is not there already. This routine must be called before making
19131 +** changes to a page.
19133 +** The first time this routine is called, the pager creates a new
19134 +** journal and acquires a write lock on the database. If the write
19135 +** lock could not be acquired, this routine returns SQLITE_BUSY. The
19136 +** calling routine must check for that return value and be careful not to
19137 +** change any page data until this routine returns SQLITE_OK.
19139 +** If the journal file could not be written because the disk is full,
19140 +** then this routine returns SQLITE_FULL and does an immediate rollback.
19141 +** All subsequent write attempts also return SQLITE_FULL until there
19142 +** is a call to sqlitepager_commit() or sqlitepager_rollback() to
19145 +int sqlitepager_write(void *pData){
19146 + PgHdr *pPg = DATA_TO_PGHDR(pData);
19147 + Pager *pPager = pPg->pPager;
19148 + int rc = SQLITE_OK;
19150 + /* Check for errors
19152 + if( pPager->errMask ){
19153 + return pager_errcode(pPager);
19155 + if( pPager->readOnly ){
19156 + return SQLITE_PERM;
19159 + /* Mark the page as dirty. If the page has already been written
19160 + ** to the journal then we can return right away.
19163 + if( pPg->inJournal && (pPg->inCkpt || pPager->ckptInUse==0) ){
19164 + pPager->dirtyFile = 1;
19165 + return SQLITE_OK;
19168 + /* If we get this far, it means that the page needs to be
19169 + ** written to the transaction journal or the ckeckpoint journal
19172 + ** First check to see that the transaction journal exists and
19173 + ** create it if it does not.
19175 + assert( pPager->state!=SQLITE_UNLOCK );
19176 + rc = sqlitepager_begin(pData);
19177 + if( rc!=SQLITE_OK ){
19180 + assert( pPager->state==SQLITE_WRITELOCK );
19181 + if( !pPager->journalOpen && pPager->useJournal ){
19182 + rc = pager_open_journal(pPager);
19183 + if( rc!=SQLITE_OK ) return rc;
19185 + assert( pPager->journalOpen || !pPager->useJournal );
19186 + pPager->dirtyFile = 1;
19188 + /* The transaction journal now exists and we have a write lock on the
19189 + ** main database file. Write the current page to the transaction
19190 + ** journal if it is not there already.
19192 + if( !pPg->inJournal && pPager->useJournal ){
19193 + if( (int)pPg->pgno <= pPager->origDbSize ){
19196 + if( journal_format>=JOURNAL_FORMAT_3 ){
19197 + u32 cksum = pager_cksum(pPager, pPg->pgno, pData);
19198 + saved = *(u32*)PGHDR_TO_EXTRA(pPg);
19199 + store32bits(cksum, pPg, SQLITE_PAGE_SIZE);
19200 + szPg = SQLITE_PAGE_SIZE+8;
19202 + szPg = SQLITE_PAGE_SIZE+4;
19204 + store32bits(pPg->pgno, pPg, -4);
19205 + CODEC(pPager, pData, pPg->pgno, 7);
19206 + rc = sqliteOsWrite(&pPager->jfd, &((char*)pData)[-4], szPg);
19207 + TRACE3("JOURNAL %d %d\n", pPg->pgno, pPg->needSync);
19208 + CODEC(pPager, pData, pPg->pgno, 0);
19209 + if( journal_format>=JOURNAL_FORMAT_3 ){
19210 + *(u32*)PGHDR_TO_EXTRA(pPg) = saved;
19212 + if( rc!=SQLITE_OK ){
19213 + sqlitepager_rollback(pPager);
19214 + pPager->errMask |= PAGER_ERR_FULL;
19218 + assert( pPager->aInJournal!=0 );
19219 + pPager->aInJournal[pPg->pgno/8] |= 1<<(pPg->pgno&7);
19220 + pPg->needSync = !pPager->noSync;
19221 + pPg->inJournal = 1;
19222 + if( pPager->ckptInUse ){
19223 + pPager->aInCkpt[pPg->pgno/8] |= 1<<(pPg->pgno&7);
19224 + page_add_to_ckpt_list(pPg);
19227 + pPg->needSync = !pPager->journalStarted && !pPager->noSync;
19228 + TRACE3("APPEND %d %d\n", pPg->pgno, pPg->needSync);
19230 + if( pPg->needSync ){
19231 + pPager->needSync = 1;
19235 + /* If the checkpoint journal is open and the page is not in it,
19236 + ** then write the current page to the checkpoint journal. Note that
19237 + ** the checkpoint journal always uses the simplier format 2 that lacks
19238 + ** checksums. The header is also omitted from the checkpoint journal.
19240 + if( pPager->ckptInUse && !pPg->inCkpt && (int)pPg->pgno<=pPager->ckptSize ){
19241 + assert( pPg->inJournal || (int)pPg->pgno>pPager->origDbSize );
19242 + store32bits(pPg->pgno, pPg, -4);
19243 + CODEC(pPager, pData, pPg->pgno, 7);
19244 + rc = sqliteOsWrite(&pPager->cpfd, &((char*)pData)[-4], SQLITE_PAGE_SIZE+4);
19245 + TRACE2("CKPT-JOURNAL %d\n", pPg->pgno);
19246 + CODEC(pPager, pData, pPg->pgno, 0);
19247 + if( rc!=SQLITE_OK ){
19248 + sqlitepager_rollback(pPager);
19249 + pPager->errMask |= PAGER_ERR_FULL;
19252 + pPager->ckptNRec++;
19253 + assert( pPager->aInCkpt!=0 );
19254 + pPager->aInCkpt[pPg->pgno/8] |= 1<<(pPg->pgno&7);
19255 + page_add_to_ckpt_list(pPg);
19258 + /* Update the database size and return.
19260 + if( pPager->dbSize<(int)pPg->pgno ){
19261 + pPager->dbSize = pPg->pgno;
19267 +** Return TRUE if the page given in the argument was previously passed
19268 +** to sqlitepager_write(). In other words, return TRUE if it is ok
19269 +** to change the content of the page.
19271 +int sqlitepager_iswriteable(void *pData){
19272 + PgHdr *pPg = DATA_TO_PGHDR(pData);
19273 + return pPg->dirty;
19277 +** Replace the content of a single page with the information in the third
19280 +int sqlitepager_overwrite(Pager *pPager, Pgno pgno, void *pData){
19284 + rc = sqlitepager_get(pPager, pgno, &pPage);
19285 + if( rc==SQLITE_OK ){
19286 + rc = sqlitepager_write(pPage);
19287 + if( rc==SQLITE_OK ){
19288 + memcpy(pPage, pData, SQLITE_PAGE_SIZE);
19290 + sqlitepager_unref(pPage);
19296 +** A call to this routine tells the pager that it is not necessary to
19297 +** write the information on page "pgno" back to the disk, even though
19298 +** that page might be marked as dirty.
19300 +** The overlying software layer calls this routine when all of the data
19301 +** on the given page is unused. The pager marks the page as clean so
19302 +** that it does not get written to disk.
19304 +** Tests show that this optimization, together with the
19305 +** sqlitepager_dont_rollback() below, more than double the speed
19306 +** of large INSERT operations and quadruple the speed of large DELETEs.
19308 +** When this routine is called, set the alwaysRollback flag to true.
19309 +** Subsequent calls to sqlitepager_dont_rollback() for the same page
19310 +** will thereafter be ignored. This is necessary to avoid a problem
19311 +** where a page with data is added to the freelist during one part of
19312 +** a transaction then removed from the freelist during a later part
19313 +** of the same transaction and reused for some other purpose. When it
19314 +** is first added to the freelist, this routine is called. When reused,
19315 +** the dont_rollback() routine is called. But because the page contains
19316 +** critical data, we still need to be sure it gets rolled back in spite
19317 +** of the dont_rollback() call.
19319 +void sqlitepager_dont_write(Pager *pPager, Pgno pgno){
19322 + pPg = pager_lookup(pPager, pgno);
19323 + pPg->alwaysRollback = 1;
19324 + if( pPg && pPg->dirty && !pPager->ckptInUse ){
19325 + if( pPager->dbSize==(int)pPg->pgno && pPager->origDbSize<pPager->dbSize ){
19326 + /* If this pages is the last page in the file and the file has grown
19327 + ** during the current transaction, then do NOT mark the page as clean.
19328 + ** When the database file grows, we must make sure that the last page
19329 + ** gets written at least once so that the disk file will be the correct
19330 + ** size. If you do not write this page and the size of the file
19331 + ** on the disk ends up being too small, that can lead to database
19332 + ** corruption during the next transaction.
19335 + TRACE2("DONT_WRITE %d\n", pgno);
19342 +** A call to this routine tells the pager that if a rollback occurs,
19343 +** it is not necessary to restore the data on the given page. This
19344 +** means that the pager does not have to record the given page in the
19345 +** rollback journal.
19347 +void sqlitepager_dont_rollback(void *pData){
19348 + PgHdr *pPg = DATA_TO_PGHDR(pData);
19349 + Pager *pPager = pPg->pPager;
19351 + if( pPager->state!=SQLITE_WRITELOCK || pPager->journalOpen==0 ) return;
19352 + if( pPg->alwaysRollback || pPager->alwaysRollback ) return;
19353 + if( !pPg->inJournal && (int)pPg->pgno <= pPager->origDbSize ){
19354 + assert( pPager->aInJournal!=0 );
19355 + pPager->aInJournal[pPg->pgno/8] |= 1<<(pPg->pgno&7);
19356 + pPg->inJournal = 1;
19357 + if( pPager->ckptInUse ){
19358 + pPager->aInCkpt[pPg->pgno/8] |= 1<<(pPg->pgno&7);
19359 + page_add_to_ckpt_list(pPg);
19361 + TRACE2("DONT_ROLLBACK %d\n", pPg->pgno);
19363 + if( pPager->ckptInUse && !pPg->inCkpt && (int)pPg->pgno<=pPager->ckptSize ){
19364 + assert( pPg->inJournal || (int)pPg->pgno>pPager->origDbSize );
19365 + assert( pPager->aInCkpt!=0 );
19366 + pPager->aInCkpt[pPg->pgno/8] |= 1<<(pPg->pgno&7);
19367 + page_add_to_ckpt_list(pPg);
19372 +** Commit all changes to the database and release the write lock.
19374 +** If the commit fails for any reason, a rollback attempt is made
19375 +** and an error code is returned. If the commit worked, SQLITE_OK
19378 +int sqlitepager_commit(Pager *pPager){
19382 + if( pPager->errMask==PAGER_ERR_FULL ){
19383 + rc = sqlitepager_rollback(pPager);
19384 + if( rc==SQLITE_OK ){
19385 + rc = SQLITE_FULL;
19389 + if( pPager->errMask!=0 ){
19390 + rc = pager_errcode(pPager);
19393 + if( pPager->state!=SQLITE_WRITELOCK ){
19394 + return SQLITE_ERROR;
19396 + TRACE1("COMMIT\n");
19397 + if( pPager->dirtyFile==0 ){
19398 + /* Exit early (without doing the time-consuming sqliteOsSync() calls)
19399 + ** if there have been no changes to the database file. */
19400 + assert( pPager->needSync==0 );
19401 + rc = pager_unwritelock(pPager);
19402 + pPager->dbSize = -1;
19405 + assert( pPager->journalOpen );
19406 + rc = syncJournal(pPager);
19407 + if( rc!=SQLITE_OK ){
19408 + goto commit_abort;
19410 + pPg = pager_get_all_dirty_pages(pPager);
19412 + rc = pager_write_pagelist(pPg);
19413 + if( rc || (!pPager->noSync && sqliteOsSync(&pPager->fd)!=SQLITE_OK) ){
19414 + goto commit_abort;
19417 + rc = pager_unwritelock(pPager);
19418 + pPager->dbSize = -1;
19421 + /* Jump here if anything goes wrong during the commit process.
19424 + rc = sqlitepager_rollback(pPager);
19425 + if( rc==SQLITE_OK ){
19426 + rc = SQLITE_FULL;
19432 +** Rollback all changes. The database falls back to read-only mode.
19433 +** All in-memory cache pages revert to their original data contents.
19434 +** The journal is deleted.
19436 +** This routine cannot fail unless some other process is not following
19437 +** the correct locking protocol (SQLITE_PROTOCOL) or unless some other
19438 +** process is writing trash into the journal file (SQLITE_CORRUPT) or
19439 +** unless a prior malloc() failed (SQLITE_NOMEM). Appropriate error
19440 +** codes are returned for all these occasions. Otherwise,
19441 +** SQLITE_OK is returned.
19443 +int sqlitepager_rollback(Pager *pPager){
19445 + TRACE1("ROLLBACK\n");
19446 + if( !pPager->dirtyFile || !pPager->journalOpen ){
19447 + rc = pager_unwritelock(pPager);
19448 + pPager->dbSize = -1;
19452 + if( pPager->errMask!=0 && pPager->errMask!=PAGER_ERR_FULL ){
19453 + if( pPager->state>=SQLITE_WRITELOCK ){
19454 + pager_playback(pPager, 1);
19456 + return pager_errcode(pPager);
19458 + if( pPager->state!=SQLITE_WRITELOCK ){
19459 + return SQLITE_OK;
19461 + rc = pager_playback(pPager, 1);
19462 + if( rc!=SQLITE_OK ){
19463 + rc = SQLITE_CORRUPT;
19464 + pPager->errMask |= PAGER_ERR_CORRUPT;
19466 + pPager->dbSize = -1;
19471 +** Return TRUE if the database file is opened read-only. Return FALSE
19472 +** if the database is (in theory) writable.
19474 +int sqlitepager_isreadonly(Pager *pPager){
19475 + return pPager->readOnly;
19479 +** This routine is used for testing and analysis only.
19481 +int *sqlitepager_stats(Pager *pPager){
19483 + a[0] = pPager->nRef;
19484 + a[1] = pPager->nPage;
19485 + a[2] = pPager->mxPage;
19486 + a[3] = pPager->dbSize;
19487 + a[4] = pPager->state;
19488 + a[5] = pPager->errMask;
19489 + a[6] = pPager->nHit;
19490 + a[7] = pPager->nMiss;
19491 + a[8] = pPager->nOvfl;
19496 +** Set the checkpoint.
19498 +** This routine should be called with the transaction journal already
19499 +** open. A new checkpoint journal is created that can be used to rollback
19500 +** changes of a single SQL command within a larger transaction.
19502 +int sqlitepager_ckpt_begin(Pager *pPager){
19504 + char zTemp[SQLITE_TEMPNAME_SIZE];
19505 + if( !pPager->journalOpen ){
19506 + pPager->ckptAutoopen = 1;
19507 + return SQLITE_OK;
19509 + assert( pPager->journalOpen );
19510 + assert( !pPager->ckptInUse );
19511 + pPager->aInCkpt = sqliteMalloc( pPager->dbSize/8 + 1 );
19512 + if( pPager->aInCkpt==0 ){
19513 + sqliteOsReadLock(&pPager->fd);
19514 + return SQLITE_NOMEM;
19517 + rc = sqliteOsFileSize(&pPager->jfd, &pPager->ckptJSize);
19518 + if( rc ) goto ckpt_begin_failed;
19519 + assert( pPager->ckptJSize ==
19520 + pPager->nRec*JOURNAL_PG_SZ(journal_format)+JOURNAL_HDR_SZ(journal_format) );
19522 + pPager->ckptJSize = pPager->nRec*JOURNAL_PG_SZ(journal_format)
19523 + + JOURNAL_HDR_SZ(journal_format);
19524 + pPager->ckptSize = pPager->dbSize;
19525 + if( !pPager->ckptOpen ){
19526 + rc = sqlitepager_opentemp(zTemp, &pPager->cpfd);
19527 + if( rc ) goto ckpt_begin_failed;
19528 + pPager->ckptOpen = 1;
19529 + pPager->ckptNRec = 0;
19531 + pPager->ckptInUse = 1;
19532 + return SQLITE_OK;
19534 +ckpt_begin_failed:
19535 + if( pPager->aInCkpt ){
19536 + sqliteFree(pPager->aInCkpt);
19537 + pPager->aInCkpt = 0;
19543 +** Commit a checkpoint.
19545 +int sqlitepager_ckpt_commit(Pager *pPager){
19546 + if( pPager->ckptInUse ){
19547 + PgHdr *pPg, *pNext;
19548 + sqliteOsSeek(&pPager->cpfd, 0);
19549 + /* sqliteOsTruncate(&pPager->cpfd, 0); */
19550 + pPager->ckptNRec = 0;
19551 + pPager->ckptInUse = 0;
19552 + sqliteFree( pPager->aInCkpt );
19553 + pPager->aInCkpt = 0;
19554 + for(pPg=pPager->pCkpt; pPg; pPg=pNext){
19555 + pNext = pPg->pNextCkpt;
19556 + assert( pPg->inCkpt );
19558 + pPg->pPrevCkpt = pPg->pNextCkpt = 0;
19560 + pPager->pCkpt = 0;
19562 + pPager->ckptAutoopen = 0;
19563 + return SQLITE_OK;
19567 +** Rollback a checkpoint.
19569 +int sqlitepager_ckpt_rollback(Pager *pPager){
19571 + if( pPager->ckptInUse ){
19572 + rc = pager_ckpt_playback(pPager);
19573 + sqlitepager_ckpt_commit(pPager);
19577 + pPager->ckptAutoopen = 0;
19582 +** Return the full pathname of the database file.
19584 +const char *sqlitepager_filename(Pager *pPager){
19585 + return pPager->zFilename;
19589 +** Set the codec for this pager
19591 +void sqlitepager_set_codec(
19593 + void (*xCodec)(void*,void*,Pgno,int),
19596 + pPager->xCodec = xCodec;
19597 + pPager->pCodecArg = pCodecArg;
19600 +#ifdef SQLITE_TEST
19602 +** Print a listing of all referenced pages and their ref count.
19604 +void sqlitepager_refdump(Pager *pPager){
19606 + for(pPg=pPager->pAll; pPg; pPg=pPg->pNextAll){
19607 + if( pPg->nRef<=0 ) continue;
19608 + printf("PAGE %3d addr=0x%08x nRef=%d\n",
19609 + pPg->pgno, (int)PGHDR_TO_DATA(pPg), pPg->nRef);
19614 +++ b/ext/sqlite/libsqlite/src/pager.h
19617 +** 2001 September 15
19619 +** The author disclaims copyright to this source code. In place of
19620 +** a legal notice, here is a blessing:
19622 +** May you do good and not evil.
19623 +** May you find forgiveness for yourself and forgive others.
19624 +** May you share freely, never taking more than you give.
19626 +*************************************************************************
19627 +** This header file defines the interface that the sqlite page cache
19628 +** subsystem. The page cache subsystem reads and writes a file a page
19629 +** at a time and provides a journal for rollback.
19635 +** The size of one page
19637 +** You can change this value to another (reasonable) value you want.
19638 +** It need not be a power of two, though the interface to the disk
19639 +** will likely be faster if it is.
19641 +** Experiments show that a page size of 1024 gives the best speed
19642 +** for common usages. The speed differences for different sizes
19643 +** such as 512, 2048, 4096, an so forth, is minimal. Note, however,
19644 +** that changing the page size results in a completely imcompatible
19647 +#ifndef SQLITE_PAGE_SIZE
19648 +#define SQLITE_PAGE_SIZE 1024
19652 +** Number of extra bytes of data allocated at the end of each page and
19653 +** stored on disk but not used by the higher level btree layer. Changing
19654 +** this value results in a completely incompatible file format.
19656 +#ifndef SQLITE_PAGE_RESERVE
19657 +#define SQLITE_PAGE_RESERVE 0
19661 +** The total number of usable bytes stored on disk for each page.
19662 +** The usable bytes come at the beginning of the page and the reserve
19663 +** bytes come at the end.
19665 +#define SQLITE_USABLE_SIZE (SQLITE_PAGE_SIZE-SQLITE_PAGE_RESERVE)
19668 +** Maximum number of pages in one database. (This is a limitation of
19669 +** imposed by 4GB files size limits.)
19671 +#define SQLITE_MAX_PAGE 1073741823
19674 +** The type used to represent a page number. The first page in a file
19675 +** is called page 1. 0 is used to represent "not a page".
19677 +typedef unsigned int Pgno;
19680 +** Each open file is managed by a separate instance of the "Pager" structure.
19682 +typedef struct Pager Pager;
19685 +** See source code comments for a detailed description of the following
19688 +int sqlitepager_open(Pager **ppPager, const char *zFilename,
19689 + int nPage, int nExtra, int useJournal);
19690 +void sqlitepager_set_destructor(Pager*, void(*)(void*));
19691 +void sqlitepager_set_cachesize(Pager*, int);
19692 +int sqlitepager_close(Pager *pPager);
19693 +int sqlitepager_get(Pager *pPager, Pgno pgno, void **ppPage);
19694 +void *sqlitepager_lookup(Pager *pPager, Pgno pgno);
19695 +int sqlitepager_ref(void*);
19696 +int sqlitepager_unref(void*);
19697 +Pgno sqlitepager_pagenumber(void*);
19698 +int sqlitepager_write(void*);
19699 +int sqlitepager_iswriteable(void*);
19700 +int sqlitepager_overwrite(Pager *pPager, Pgno pgno, void*);
19701 +int sqlitepager_pagecount(Pager*);
19702 +int sqlitepager_truncate(Pager*,Pgno);
19703 +int sqlitepager_begin(void*);
19704 +int sqlitepager_commit(Pager*);
19705 +int sqlitepager_rollback(Pager*);
19706 +int sqlitepager_isreadonly(Pager*);
19707 +int sqlitepager_ckpt_begin(Pager*);
19708 +int sqlitepager_ckpt_commit(Pager*);
19709 +int sqlitepager_ckpt_rollback(Pager*);
19710 +void sqlitepager_dont_rollback(void*);
19711 +void sqlitepager_dont_write(Pager*, Pgno);
19712 +int *sqlitepager_stats(Pager*);
19713 +void sqlitepager_set_safety_level(Pager*,int);
19714 +const char *sqlitepager_filename(Pager*);
19715 +int sqlitepager_rename(Pager*, const char *zNewName);
19716 +void sqlitepager_set_codec(Pager*,void(*)(void*,void*,Pgno,int),void*);
19718 +#ifdef SQLITE_TEST
19719 +void sqlitepager_refdump(Pager*);
19720 +int pager_refinfo_enable;
19721 +int journal_format;
19724 +++ b/ext/sqlite/libsqlite/src/parse.c
19726 +/* Driver template for the LEMON parser generator.
19727 +** The author disclaims copyright to this source code.
19729 +/* First off, code is included that follows the "include" declaration
19730 +** in the input grammar file. */
19731 +#include <stdio.h>
19732 +#line 33 "ext/sqlite/libsqlite/src/parse.y"
19734 +#include "sqliteInt.h"
19735 +#include "parse.h"
19738 +** An instance of this structure holds information about the
19739 +** LIMIT clause of a SELECT statement.
19742 + int limit; /* The LIMIT value. -1 if there is no limit */
19743 + int offset; /* The OFFSET. 0 if there is none */
19747 +** An instance of the following structure describes the event of a
19748 +** TRIGGER. "a" is the event type, one of TK_UPDATE, TK_INSERT,
19749 +** TK_DELETE, or TK_INSTEAD. If the event is of the form
19751 +** UPDATE ON (a,b,c)
19753 +** Then the "b" IdList records the list "a,b,c".
19755 +struct TrigEvent { int a; IdList * b; };
19757 +#line 33 "ext/sqlite/libsqlite/src/parse.c"
19758 +/* Next is all token values, in a form suitable for use by makeheaders.
19759 +** This section will be null unless lemon is run with the -m switch.
19762 +** These constants (all generated automatically by the parser generator)
19763 +** specify the various kinds of tokens (terminals) that the parser
19766 +** Each symbol here is a terminal symbol in the grammar.
19768 +/* Make sure the INTERFACE macro is defined.
19771 +# define INTERFACE 1
19773 +/* The next thing included is series of defines which control
19774 +** various aspects of the generated parser.
19775 +** YYCODETYPE is the data type used for storing terminal
19776 +** and nonterminal numbers. "unsigned char" is
19777 +** used if there are fewer than 250 terminals
19778 +** and nonterminals. "int" is used otherwise.
19779 +** YYNOCODE is a number of type YYCODETYPE which corresponds
19780 +** to no legal terminal or nonterminal number. This
19781 +** number is used to fill in empty slots of the hash
19783 +** YYFALLBACK If defined, this indicates that one or more tokens
19784 +** have fall-back values which should be used if the
19785 +** original value of the token will not parse.
19786 +** YYACTIONTYPE is the data type used for storing terminal
19787 +** and nonterminal numbers. "unsigned char" is
19788 +** used if there are fewer than 250 rules and
19789 +** states combined. "int" is used otherwise.
19790 +** sqliteParserTOKENTYPE is the data type used for minor tokens given
19791 +** directly to the parser from the tokenizer.
19792 +** YYMINORTYPE is the data type used for all minor tokens.
19793 +** This is typically a union of many types, one of
19794 +** which is sqliteParserTOKENTYPE. The entry in the union
19795 +** for base tokens is called "yy0".
19796 +** YYSTACKDEPTH is the maximum depth of the parser's stack. If
19797 +** zero the stack is dynamically sized using realloc()
19798 +** sqliteParserARG_SDECL A static variable declaration for the %extra_argument
19799 +** sqliteParserARG_PDECL A parameter declaration for the %extra_argument
19800 +** sqliteParserARG_STORE Code to store %extra_argument into yypParser
19801 +** sqliteParserARG_FETCH Code to extract %extra_argument from yypParser
19802 +** YYNSTATE the combined number of states.
19803 +** YYNRULE the number of rules in the grammar
19804 +** YYERRORSYMBOL is the code number of the error symbol. If not
19805 +** defined, then do no error processing.
19807 +#define YYCODETYPE unsigned char
19808 +#define YYNOCODE 221
19809 +#define YYACTIONTYPE unsigned short int
19810 +#define sqliteParserTOKENTYPE Token
19813 + sqliteParserTOKENTYPE yy0;
19814 + TriggerStep * yy19;
19815 + struct LimitVal yy124;
19819 + struct TrigEvent yy290;
19824 + struct {int value; int mask;} yy407;
19826 +#ifndef YYSTACKDEPTH
19827 +#define YYSTACKDEPTH 100
19829 +#define sqliteParserARG_SDECL Parse *pParse;
19830 +#define sqliteParserARG_PDECL ,Parse *pParse
19831 +#define sqliteParserARG_FETCH Parse *pParse = yypParser->pParse
19832 +#define sqliteParserARG_STORE yypParser->pParse = pParse
19833 +#define YYNSTATE 563
19834 +#define YYNRULE 293
19835 +#define YYFALLBACK 1
19836 +#define YY_NO_ACTION (YYNSTATE+YYNRULE+2)
19837 +#define YY_ACCEPT_ACTION (YYNSTATE+YYNRULE+1)
19838 +#define YY_ERROR_ACTION (YYNSTATE+YYNRULE)
19840 +/* The yyzerominor constant is used to initialize instances of
19841 +** YYMINORTYPE objects to zero. */
19842 +static const YYMINORTYPE yyzerominor = { 0 };
19844 +/* Define the yytestcase() macro to be a no-op if is not already defined
19847 +** Applications can choose to define yytestcase() in the %include section
19848 +** to a macro that can assist in verifying code coverage. For production
19849 +** code the yytestcase() macro should be turned off. But it is useful
19852 +#ifndef yytestcase
19853 +# define yytestcase(X)
19857 +/* Next are the tables used to determine what action to take based on the
19858 +** current state and lookahead token. These tables are used to implement
19859 +** functions that take a state number and lookahead value and return an
19860 +** action integer.
19862 +** Suppose the action integer is N. Then the action is determined as
19865 +** 0 <= N < YYNSTATE Shift N. That is, push the lookahead
19866 +** token onto the stack and goto state N.
19868 +** YYNSTATE <= N < YYNSTATE+YYNRULE Reduce by rule N-YYNSTATE.
19870 +** N == YYNSTATE+YYNRULE A syntax error has occurred.
19872 +** N == YYNSTATE+YYNRULE+1 The parser accepts its input.
19874 +** N == YYNSTATE+YYNRULE+2 No such action. Denotes unused
19875 +** slots in the yy_action[] table.
19877 +** The action table is constructed as a single large table named yy_action[].
19878 +** Given state S and lookahead X, the action is computed as
19880 +** yy_action[ yy_shift_ofst[S] + X ]
19882 +** If the index value yy_shift_ofst[S]+X is out of range or if the value
19883 +** yy_lookahead[yy_shift_ofst[S]+X] is not equal to X or if yy_shift_ofst[S]
19884 +** is equal to YY_SHIFT_USE_DFLT, it means that the action is not in the table
19885 +** and that yy_default[S] should be used instead.
19887 +** The formula above is for computing the action when the lookahead is
19888 +** a terminal symbol. If the lookahead is a non-terminal (as occurs after
19889 +** a reduce action) then the yy_reduce_ofst[] array is used in place of
19890 +** the yy_shift_ofst[] array and YY_REDUCE_USE_DFLT is used in place of
19891 +** YY_SHIFT_USE_DFLT.
19893 +** The following are the tables generated in this section:
19895 +** yy_action[] A single table containing all actions.
19896 +** yy_lookahead[] A table containing the lookahead for each entry in
19897 +** yy_action. Used to detect hash collisions.
19898 +** yy_shift_ofst[] For each state, the offset into yy_action for
19899 +** shifting terminals.
19900 +** yy_reduce_ofst[] For each state, the offset into yy_action for
19901 +** shifting non-terminals after a reduce.
19902 +** yy_default[] Default action for each state.
19904 +#define YY_ACTTAB_COUNT (1090)
19905 +static const YYACTIONTYPE yy_action[] = {
19906 + /* 0 */ 186, 561, 483, 69, 67, 70, 68, 64, 63, 62,
19907 + /* 10 */ 61, 58, 57, 56, 55, 54, 53, 181, 180, 179,
19908 + /* 20 */ 514, 421, 334, 420, 468, 515, 64, 63, 62, 61,
19909 + /* 30 */ 58, 57, 56, 55, 54, 53, 9, 423, 422, 71,
19910 + /* 40 */ 72, 129, 65, 66, 513, 510, 305, 52, 138, 69,
19911 + /* 50 */ 67, 70, 68, 64, 63, 62, 61, 58, 57, 56,
19912 + /* 60 */ 55, 54, 53, 448, 469, 175, 482, 514, 470, 344,
19913 + /* 70 */ 342, 36, 515, 58, 57, 56, 55, 54, 53, 8,
19914 + /* 80 */ 341, 281, 285, 307, 437, 178, 71, 72, 129, 65,
19915 + /* 90 */ 66, 513, 510, 305, 52, 138, 69, 67, 70, 68,
19916 + /* 100 */ 64, 63, 62, 61, 58, 57, 56, 55, 54, 53,
19917 + /* 110 */ 130, 362, 360, 508, 507, 267, 551, 436, 298, 297,
19918 + /* 120 */ 369, 368, 50, 128, 543, 29, 266, 449, 537, 447,
19919 + /* 130 */ 591, 528, 442, 441, 187, 132, 514, 536, 47, 48,
19920 + /* 140 */ 472, 515, 122, 427, 331, 409, 49, 371, 370, 518,
19921 + /* 150 */ 328, 363, 517, 520, 45, 71, 72, 129, 65, 66,
19922 + /* 160 */ 513, 510, 305, 52, 138, 69, 67, 70, 68, 64,
19923 + /* 170 */ 63, 62, 61, 58, 57, 56, 55, 54, 53, 185,
19924 + /* 180 */ 550, 549, 512, 175, 467, 516, 18, 344, 342, 36,
19925 + /* 190 */ 544, 175, 320, 230, 231, 344, 342, 36, 341, 56,
19926 + /* 200 */ 55, 54, 53, 212, 531, 514, 341, 551, 3, 213,
19927 + /* 210 */ 515, 2, 551, 73, 7, 551, 184, 132, 551, 172,
19928 + /* 220 */ 551, 309, 348, 42, 71, 72, 129, 65, 66, 513,
19929 + /* 230 */ 510, 305, 52, 138, 69, 67, 70, 68, 64, 63,
19930 + /* 240 */ 62, 61, 58, 57, 56, 55, 54, 53, 243, 197,
19931 + /* 250 */ 282, 358, 268, 373, 264, 372, 183, 241, 436, 169,
19932 + /* 260 */ 356, 171, 269, 240, 471, 426, 29, 446, 506, 514,
19933 + /* 270 */ 445, 550, 549, 494, 515, 354, 550, 549, 359, 550,
19934 + /* 280 */ 549, 144, 550, 549, 550, 549, 592, 309, 71, 72,
19935 + /* 290 */ 129, 65, 66, 513, 510, 305, 52, 138, 69, 67,
19936 + /* 300 */ 70, 68, 64, 63, 62, 61, 58, 57, 56, 55,
19937 + /* 310 */ 54, 53, 514, 857, 82, 377, 1, 515, 268, 373,
19938 + /* 320 */ 264, 372, 183, 241, 362, 12, 508, 507, 500, 240,
19939 + /* 330 */ 17, 71, 72, 129, 65, 66, 513, 510, 305, 52,
19940 + /* 340 */ 138, 69, 67, 70, 68, 64, 63, 62, 61, 58,
19941 + /* 350 */ 57, 56, 55, 54, 53, 362, 182, 508, 507, 514,
19942 + /* 360 */ 362, 527, 508, 507, 515, 563, 429, 463, 182, 444,
19943 + /* 370 */ 375, 338, 443, 430, 379, 378, 593, 156, 71, 72,
19944 + /* 380 */ 129, 65, 66, 513, 510, 305, 52, 138, 69, 67,
19945 + /* 390 */ 70, 68, 64, 63, 62, 61, 58, 57, 56, 55,
19946 + /* 400 */ 54, 53, 514, 526, 542, 450, 534, 515, 286, 493,
19947 + /* 410 */ 453, 17, 478, 240, 80, 11, 533, 153, 194, 155,
19948 + /* 420 */ 286, 71, 51, 129, 65, 66, 513, 510, 305, 52,
19949 + /* 430 */ 138, 69, 67, 70, 68, 64, 63, 62, 61, 58,
19950 + /* 440 */ 57, 56, 55, 54, 53, 514, 195, 466, 160, 17,
19951 + /* 450 */ 515, 454, 490, 80, 459, 440, 460, 176, 239, 238,
19952 + /* 460 */ 80, 80, 562, 1, 71, 40, 129, 65, 66, 513,
19953 + /* 470 */ 510, 305, 52, 138, 69, 67, 70, 68, 64, 63,
19954 + /* 480 */ 62, 61, 58, 57, 56, 55, 54, 53, 514, 365,
19955 + /* 490 */ 154, 19, 339, 515, 80, 232, 405, 80, 165, 404,
19956 + /* 500 */ 193, 32, 396, 13, 32, 86, 414, 108, 72, 129,
19957 + /* 510 */ 65, 66, 513, 510, 305, 52, 138, 69, 67, 70,
19958 + /* 520 */ 68, 64, 63, 62, 61, 58, 57, 56, 55, 54,
19959 + /* 530 */ 53, 514, 551, 365, 483, 192, 515, 488, 323, 207,
19960 + /* 540 */ 366, 249, 177, 186, 87, 483, 483, 46, 38, 44,
19961 + /* 550 */ 458, 108, 129, 65, 66, 513, 510, 305, 52, 138,
19962 + /* 560 */ 69, 67, 70, 68, 64, 63, 62, 61, 58, 57,
19963 + /* 570 */ 56, 55, 54, 53, 274, 457, 272, 271, 270, 23,
19964 + /* 580 */ 8, 551, 211, 412, 307, 257, 365, 385, 201, 31,
19965 + /* 590 */ 217, 388, 141, 205, 387, 219, 550, 549, 482, 511,
19966 + /* 600 */ 215, 376, 560, 134, 90, 477, 214, 514, 392, 482,
19967 + /* 610 */ 482, 152, 515, 360, 203, 212, 409, 531, 800, 284,
19968 + /* 620 */ 365, 145, 505, 50, 300, 365, 365, 173, 321, 212,
19969 + /* 630 */ 487, 137, 135, 8, 41, 136, 531, 307, 93, 47,
19970 + /* 640 */ 48, 346, 316, 106, 106, 550, 549, 49, 371, 370,
19971 + /* 650 */ 518, 509, 531, 517, 520, 504, 531, 531, 162, 495,
19972 + /* 660 */ 170, 317, 503, 319, 223, 231, 360, 551, 502, 283,
19973 + /* 670 */ 162, 207, 557, 486, 212, 191, 50, 10, 289, 304,
19974 + /* 680 */ 303, 556, 207, 531, 8, 531, 516, 18, 307, 498,
19975 + /* 690 */ 498, 189, 47, 48, 393, 531, 555, 28, 302, 554,
19976 + /* 700 */ 49, 371, 370, 518, 484, 480, 517, 520, 322, 299,
19977 + /* 710 */ 553, 418, 365, 323, 17, 365, 365, 360, 416, 207,
19978 + /* 720 */ 322, 417, 207, 418, 327, 212, 480, 50, 207, 326,
19979 + /* 730 */ 106, 550, 549, 106, 105, 247, 407, 475, 332, 516,
19980 + /* 740 */ 18, 326, 365, 47, 48, 207, 295, 365, 475, 294,
19981 + /* 750 */ 158, 49, 371, 370, 518, 293, 473, 517, 520, 485,
19982 + /* 760 */ 106, 391, 390, 202, 148, 93, 351, 480, 204, 301,
19983 + /* 770 */ 333, 190, 291, 541, 60, 531, 498, 252, 453, 498,
19984 + /* 780 */ 365, 365, 290, 365, 501, 475, 365, 79, 475, 531,
19985 + /* 790 */ 516, 18, 379, 378, 475, 365, 465, 245, 89, 112,
19986 + /* 800 */ 365, 109, 365, 131, 121, 288, 499, 365, 365, 439,
19987 + /* 810 */ 365, 475, 365, 120, 365, 365, 343, 365, 119, 365,
19988 + /* 820 */ 118, 365, 365, 365, 365, 117, 116, 365, 126, 365,
19989 + /* 830 */ 125, 365, 124, 123, 365, 115, 365, 114, 431, 140,
19990 + /* 840 */ 139, 255, 254, 365, 365, 253, 365, 280, 365, 107,
19991 + /* 850 */ 365, 365, 113, 365, 111, 26, 365, 365, 365, 365,
19992 + /* 860 */ 365, 279, 278, 365, 277, 365, 92, 365, 104, 103,
19993 + /* 870 */ 365, 91, 365, 365, 102, 101, 110, 100, 99, 347,
19994 + /* 880 */ 25, 98, 340, 30, 24, 97, 266, 174, 96, 85,
19995 + /* 890 */ 95, 94, 166, 292, 78, 165, 415, 14, 163, 60,
19996 + /* 900 */ 164, 22, 6, 408, 5, 77, 34, 33, 159, 16,
19997 + /* 910 */ 157, 151, 75, 149, 15, 146, 313, 312, 395, 384,
19998 + /* 920 */ 143, 20, 60, 206, 21, 273, 198, 559, 375, 548,
19999 + /* 930 */ 547, 546, 374, 4, 540, 539, 538, 308, 535, 532,
20000 + /* 940 */ 530, 212, 261, 38, 260, 352, 259, 39, 258, 367,
20001 + /* 950 */ 529, 196, 210, 256, 521, 522, 53, 53, 209, 43,
20002 + /* 960 */ 496, 188, 492, 208, 256, 81, 246, 37, 479, 349,
20003 + /* 970 */ 244, 37, 474, 464, 276, 27, 452, 451, 433, 432,
20004 + /* 980 */ 275, 235, 234, 335, 424, 35, 329, 413, 410, 127,
20005 + /* 990 */ 161, 84, 76, 403, 38, 400, 188, 399, 224, 398,
20006 + /* 1000 */ 38, 150, 318, 220, 83, 147, 315, 200, 381, 383,
20007 + /* 1010 */ 199, 142, 545, 265, 88, 262, 523, 361, 491, 476,
20008 + /* 1020 */ 463, 406, 397, 287, 389, 386, 310, 382, 552, 74,
20009 + /* 1030 */ 306, 525, 524, 364, 519, 357, 355, 353, 497, 489,
20010 + /* 1040 */ 481, 263, 242, 462, 461, 456, 455, 438, 296, 345,
20011 + /* 1050 */ 434, 237, 425, 337, 168, 167, 336, 236, 419, 330,
20012 + /* 1060 */ 233, 325, 324, 229, 228, 402, 401, 227, 226, 225,
20013 + /* 1070 */ 222, 221, 218, 314, 394, 311, 216, 380, 251, 250,
20014 + /* 1080 */ 133, 350, 248, 364, 558, 59, 435, 411, 428, 212,
20016 +static const YYCODETYPE yy_lookahead[] = {
20017 + /* 0 */ 21, 9, 23, 70, 71, 72, 73, 74, 75, 76,
20018 + /* 10 */ 77, 78, 79, 80, 81, 82, 83, 100, 101, 102,
20019 + /* 20 */ 41, 100, 101, 102, 20, 46, 74, 75, 76, 77,
20020 + /* 30 */ 78, 79, 80, 81, 82, 83, 19, 55, 56, 60,
20021 + /* 40 */ 61, 62, 63, 64, 65, 66, 67, 68, 69, 70,
20022 + /* 50 */ 71, 72, 73, 74, 75, 76, 77, 78, 79, 80,
20023 + /* 60 */ 81, 82, 83, 23, 108, 90, 87, 41, 112, 94,
20024 + /* 70 */ 95, 96, 46, 78, 79, 80, 81, 82, 83, 19,
20025 + /* 80 */ 105, 149, 143, 23, 152, 153, 60, 61, 62, 63,
20026 + /* 90 */ 64, 65, 66, 67, 68, 69, 70, 71, 72, 73,
20027 + /* 100 */ 74, 75, 76, 77, 78, 79, 80, 81, 82, 83,
20028 + /* 110 */ 31, 107, 52, 109, 110, 93, 23, 140, 78, 79,
20029 + /* 120 */ 78, 79, 62, 22, 147, 148, 104, 87, 34, 89,
20030 + /* 130 */ 113, 89, 92, 93, 183, 184, 41, 43, 78, 79,
20031 + /* 140 */ 80, 46, 165, 166, 205, 53, 86, 87, 88, 89,
20032 + /* 150 */ 211, 62, 92, 93, 128, 60, 61, 62, 63, 64,
20033 + /* 160 */ 65, 66, 67, 68, 69, 70, 71, 72, 73, 74,
20034 + /* 170 */ 75, 76, 77, 78, 79, 80, 81, 82, 83, 146,
20035 + /* 180 */ 87, 88, 93, 90, 20, 125, 126, 94, 95, 96,
20036 + /* 190 */ 20, 90, 100, 101, 102, 94, 95, 96, 105, 80,
20037 + /* 200 */ 81, 82, 83, 111, 171, 41, 105, 23, 19, 48,
20038 + /* 210 */ 46, 19, 23, 19, 19, 23, 183, 184, 23, 17,
20039 + /* 220 */ 23, 62, 189, 128, 60, 61, 62, 63, 64, 65,
20040 + /* 230 */ 66, 67, 68, 69, 70, 71, 72, 73, 74, 75,
20041 + /* 240 */ 76, 77, 78, 79, 80, 81, 82, 83, 20, 90,
20042 + /* 250 */ 91, 15, 93, 94, 95, 96, 97, 98, 140, 57,
20043 + /* 260 */ 24, 59, 144, 104, 80, 147, 148, 89, 20, 41,
20044 + /* 270 */ 92, 87, 88, 20, 46, 39, 87, 88, 42, 87,
20045 + /* 280 */ 88, 19, 87, 88, 87, 88, 113, 62, 60, 61,
20046 + /* 290 */ 62, 63, 64, 65, 66, 67, 68, 69, 70, 71,
20047 + /* 300 */ 72, 73, 74, 75, 76, 77, 78, 79, 80, 81,
20048 + /* 310 */ 82, 83, 41, 132, 133, 134, 135, 46, 93, 94,
20049 + /* 320 */ 95, 96, 97, 98, 107, 63, 109, 110, 20, 104,
20050 + /* 330 */ 22, 60, 61, 62, 63, 64, 65, 66, 67, 68,
20051 + /* 340 */ 69, 70, 71, 72, 73, 74, 75, 76, 77, 78,
20052 + /* 350 */ 79, 80, 81, 82, 83, 107, 47, 109, 110, 41,
20053 + /* 360 */ 107, 89, 109, 110, 46, 0, 161, 162, 47, 89,
20054 + /* 370 */ 99, 62, 92, 168, 9, 10, 113, 17, 60, 61,
20055 + /* 380 */ 62, 63, 64, 65, 66, 67, 68, 69, 70, 71,
20056 + /* 390 */ 72, 73, 74, 75, 76, 77, 78, 79, 80, 81,
20057 + /* 400 */ 82, 83, 41, 89, 155, 156, 26, 46, 99, 20,
20058 + /* 410 */ 161, 22, 20, 104, 22, 118, 36, 57, 22, 59,
20059 + /* 420 */ 99, 60, 61, 62, 63, 64, 65, 66, 67, 68,
20060 + /* 430 */ 69, 70, 71, 72, 73, 74, 75, 76, 77, 78,
20061 + /* 440 */ 79, 80, 81, 82, 83, 41, 50, 20, 22, 22,
20062 + /* 450 */ 46, 20, 22, 22, 91, 20, 93, 22, 20, 20,
20063 + /* 460 */ 22, 22, 134, 135, 60, 61, 62, 63, 64, 65,
20064 + /* 470 */ 66, 67, 68, 69, 70, 71, 72, 73, 74, 75,
20065 + /* 480 */ 76, 77, 78, 79, 80, 81, 82, 83, 41, 140,
20066 + /* 490 */ 130, 22, 20, 46, 22, 20, 20, 22, 22, 20,
20067 + /* 500 */ 113, 22, 20, 19, 22, 21, 18, 158, 61, 62,
20068 + /* 510 */ 63, 64, 65, 66, 67, 68, 69, 70, 71, 72,
20069 + /* 520 */ 73, 74, 75, 76, 77, 78, 79, 80, 81, 82,
20070 + /* 530 */ 83, 41, 23, 140, 23, 113, 46, 22, 140, 140,
20071 + /* 540 */ 191, 192, 19, 21, 114, 23, 23, 127, 122, 129,
20072 + /* 550 */ 29, 158, 62, 63, 64, 65, 66, 67, 68, 69,
20073 + /* 560 */ 70, 71, 72, 73, 74, 75, 76, 77, 78, 79,
20074 + /* 570 */ 80, 81, 82, 83, 11, 54, 13, 14, 15, 16,
20075 + /* 580 */ 19, 23, 174, 95, 23, 192, 140, 78, 79, 181,
20076 + /* 590 */ 27, 89, 146, 195, 92, 32, 87, 88, 87, 93,
20077 + /* 600 */ 37, 136, 137, 88, 158, 206, 141, 41, 99, 87,
20078 + /* 610 */ 87, 146, 46, 52, 51, 111, 53, 171, 130, 19,
20079 + /* 620 */ 140, 58, 14, 62, 103, 140, 140, 146, 124, 111,
20080 + /* 630 */ 115, 146, 146, 19, 68, 69, 171, 23, 158, 78,
20081 + /* 640 */ 79, 80, 124, 158, 158, 87, 88, 86, 87, 88,
20082 + /* 650 */ 89, 108, 171, 92, 93, 20, 171, 171, 146, 93,
20083 + /* 660 */ 146, 196, 20, 100, 101, 102, 52, 23, 20, 106,
20084 + /* 670 */ 146, 140, 15, 115, 111, 22, 62, 118, 198, 194,
20085 + /* 680 */ 194, 24, 140, 171, 19, 171, 125, 126, 23, 204,
20086 + /* 690 */ 204, 22, 78, 79, 140, 171, 39, 19, 167, 42,
20087 + /* 700 */ 86, 87, 88, 89, 115, 152, 92, 93, 196, 167,
20088 + /* 710 */ 53, 140, 140, 140, 22, 140, 140, 52, 25, 140,
20089 + /* 720 */ 196, 28, 140, 140, 212, 111, 152, 62, 140, 217,
20090 + /* 730 */ 158, 87, 88, 158, 158, 182, 212, 206, 45, 125,
20091 + /* 740 */ 126, 217, 140, 78, 79, 140, 167, 140, 206, 167,
20092 + /* 750 */ 146, 86, 87, 88, 89, 167, 182, 92, 93, 115,
20093 + /* 760 */ 158, 207, 208, 209, 146, 158, 194, 152, 195, 194,
20094 + /* 770 */ 199, 22, 167, 156, 200, 171, 204, 201, 161, 204,
20095 + /* 780 */ 140, 140, 199, 140, 20, 206, 140, 20, 206, 171,
20096 + /* 790 */ 125, 126, 9, 10, 206, 140, 20, 182, 158, 158,
20097 + /* 800 */ 140, 158, 140, 113, 158, 198, 204, 140, 140, 20,
20098 + /* 810 */ 140, 206, 140, 158, 140, 140, 48, 140, 158, 140,
20099 + /* 820 */ 158, 140, 140, 140, 140, 158, 158, 140, 158, 140,
20100 + /* 830 */ 158, 140, 158, 158, 140, 158, 140, 158, 139, 158,
20101 + /* 840 */ 158, 158, 158, 140, 140, 158, 140, 158, 140, 158,
20102 + /* 850 */ 140, 140, 158, 140, 158, 19, 140, 140, 140, 140,
20103 + /* 860 */ 140, 158, 158, 140, 158, 140, 158, 140, 158, 158,
20104 + /* 870 */ 140, 158, 140, 140, 158, 158, 158, 158, 158, 140,
20105 + /* 880 */ 19, 158, 48, 158, 19, 158, 104, 97, 158, 21,
20106 + /* 890 */ 158, 158, 99, 38, 49, 22, 49, 158, 99, 200,
20107 + /* 900 */ 130, 19, 11, 14, 9, 103, 63, 63, 123, 19,
20108 + /* 910 */ 114, 114, 103, 123, 19, 114, 116, 35, 87, 20,
20109 + /* 920 */ 21, 150, 200, 160, 160, 138, 12, 139, 99, 138,
20110 + /* 930 */ 138, 138, 145, 22, 139, 139, 164, 44, 139, 139,
20111 + /* 940 */ 171, 111, 176, 122, 177, 119, 178, 120, 179, 117,
20112 + /* 950 */ 180, 121, 193, 98, 151, 23, 83, 83, 202, 127,
20113 + /* 960 */ 186, 113, 186, 193, 98, 186, 187, 99, 188, 116,
20114 + /* 970 */ 187, 99, 188, 139, 159, 19, 151, 164, 139, 139,
20115 + /* 980 */ 159, 186, 215, 40, 216, 127, 186, 139, 169, 60,
20116 + /* 990 */ 169, 197, 19, 176, 122, 186, 113, 186, 186, 176,
20117 + /* 1000 */ 122, 169, 186, 186, 197, 169, 186, 218, 33, 219,
20118 + /* 1010 */ 116, 218, 142, 157, 173, 175, 157, 203, 157, 157,
20119 + /* 1020 */ 162, 176, 176, 152, 210, 210, 152, 152, 140, 140,
20120 + /* 1030 */ 154, 154, 154, 140, 140, 140, 140, 140, 140, 185,
20121 + /* 1040 */ 140, 172, 140, 140, 163, 163, 163, 152, 154, 154,
20122 + /* 1050 */ 140, 140, 140, 140, 140, 213, 214, 140, 140, 140,
20123 + /* 1060 */ 140, 140, 140, 140, 140, 140, 140, 140, 140, 140,
20124 + /* 1070 */ 140, 140, 140, 140, 140, 140, 140, 140, 140, 140,
20125 + /* 1080 */ 140, 140, 140, 140, 170, 200, 166, 170, 166, 111,
20127 +#define YY_SHIFT_USE_DFLT (-84)
20128 +#define YY_SHIFT_COUNT (376)
20129 +#define YY_SHIFT_MIN (-83)
20130 +#define YY_SHIFT_MAX (978)
20131 +static const short yy_shift_ofst[] = {
20132 + /* 0 */ 783, 563, 614, 614, 93, 92, 92, 978, 614, 561,
20133 + /* 10 */ 665, 665, 509, 197, -21, 665, 665, 665, 665, 665,
20134 + /* 20 */ 159, 309, 197, 488, 197, 197, 197, 197, 197, 511,
20135 + /* 30 */ 271, 60, 665, 665, 665, 665, 665, 665, 665, 665,
20136 + /* 40 */ 665, 665, 665, 665, 665, 665, 665, 665, 665, 665,
20137 + /* 50 */ 665, 665, 665, 665, 665, 665, 665, 665, 665, 665,
20138 + /* 60 */ 665, 665, 665, 665, 665, 665, 665, 665, 665, 665,
20139 + /* 70 */ 665, 665, 665, 665, 225, 197, 197, 197, 197, 522,
20140 + /* 80 */ 197, 522, 365, 518, 504, 978, 978, -84, -84, 228,
20141 + /* 90 */ 164, 95, 26, 318, 318, 318, 318, 318, 318, 318,
20142 + /* 100 */ 318, 404, 318, 318, 318, 318, 318, 361, 318, 447,
20143 + /* 110 */ 490, 490, 490, -67, -67, -67, -67, -67, -48, -48,
20144 + /* 120 */ -48, -48, 101, -5, -5, -5, -5, 657, -25, 566,
20145 + /* 130 */ 657, 184, 195, 644, 558, 253, 192, 248, 189, 119,
20146 + /* 140 */ 119, 4, 197, 197, 197, 197, 197, 197, 217, 197,
20147 + /* 150 */ 197, 197, 217, 197, 197, 197, 197, 197, 217, 197,
20148 + /* 160 */ 197, 197, 217, 197, 197, 197, 197, -79, 693, 197,
20149 + /* 170 */ 217, 197, 197, 217, 197, 197, 42, 42, 523, 521,
20150 + /* 180 */ 521, 521, 197, 197, 515, 217, 197, 515, 197, 197,
20151 + /* 190 */ 197, 197, 197, 197, 42, 42, 42, 197, 197, 511,
20152 + /* 200 */ 511, 502, 502, 511, 426, 426, 321, 380, 380, 420,
20153 + /* 210 */ 380, 430, -44, 380, 484, 975, 894, 975, 883, 929,
20154 + /* 220 */ 973, 883, 883, 929, 878, 883, 883, 883, 872, 973,
20155 + /* 230 */ 929, 929, 829, 848, 858, 943, 848, 956, 829, 829,
20156 + /* 240 */ 893, 932, 956, 829, 853, 872, 853, 868, 848, 866,
20157 + /* 250 */ 848, 848, 832, 874, 874, 873, 932, 855, 830, 832,
20158 + /* 260 */ 827, 826, 821, 830, 829, 829, 893, 829, 829, 911,
20159 + /* 270 */ 914, 914, 914, 829, 914, -84, -84, -84, -84, -84,
20160 + /* 280 */ -84, -84, 40, 360, 236, 202, -83, 262, 482, 479,
20161 + /* 290 */ 476, 475, -18, 472, 439, 438, 435, 280, 178, 431,
20162 + /* 300 */ 363, 427, 392, 389, 308, 89, 396, 17, 94, 22,
20163 + /* 310 */ 899, 899, 831, 882, 800, 801, 895, 790, 809, 797,
20164 + /* 320 */ 796, 890, 785, 844, 843, 802, 895, 889, 891, 882,
20165 + /* 330 */ 799, 770, 847, 873, 845, 855, 793, 868, 782, 790,
20166 + /* 340 */ 865, 834, 861, 836, 768, 789, 776, 690, 767, 678,
20167 + /* 350 */ 589, 692, 559, 764, 669, 648, 749, 642, 653, 635,
20168 + /* 360 */ 600, 608, 543, 506, 422, 387, 469, 297, 314, 272,
20169 + /* 370 */ 263, 173, 194, 161, 170, 79, -8,
20171 +#define YY_REDUCE_USE_DFLT (-69)
20172 +#define YY_REDUCE_COUNT (281)
20173 +#define YY_REDUCE_MIN (-68)
20174 +#define YY_REDUCE_MAX (943)
20175 +static const short yy_reduce_ofst[] = {
20176 + /* 0 */ 181, 465, 486, 485, -23, 524, 512, 33, 446, 575,
20177 + /* 10 */ 572, 349, 554, 118, 574, 607, 480, 602, 576, 393,
20178 + /* 20 */ 249, 205, 605, -61, 588, 582, 579, 542, 531, -68,
20179 + /* 30 */ 699, 739, 733, 732, 730, 727, 725, 723, 720, 719,
20180 + /* 40 */ 718, 717, 716, 713, 711, 710, 708, 706, 704, 703,
20181 + /* 50 */ 696, 694, 691, 689, 687, 684, 683, 682, 681, 679,
20182 + /* 60 */ 677, 675, 674, 672, 670, 668, 667, 662, 660, 655,
20183 + /* 70 */ 646, 643, 641, 640, 617, 573, 583, 398, 571, 615,
20184 + /* 80 */ 399, 553, 328, 618, 604, 514, 481, -49, 408, 722,
20185 + /* 90 */ 722, 722, 722, 722, 722, 722, 722, 722, 722, 722,
20186 + /* 100 */ 722, 722, 722, 722, 722, 722, 722, 722, 722, 722,
20187 + /* 110 */ 722, 722, 722, 722, 722, 722, 722, 722, 722, 722,
20188 + /* 120 */ 722, 722, 922, 722, 722, 722, 722, 917, 920, 885,
20189 + /* 130 */ 914, 943, 942, 941, 940, 869, 939, 869, 938, 722,
20190 + /* 140 */ 722, 869, 937, 936, 935, 934, 933, 932, 869, 931,
20191 + /* 150 */ 930, 929, 869, 928, 927, 926, 925, 924, 869, 923,
20192 + /* 160 */ 922, 921, 869, 920, 919, 918, 917, 842, 842, 914,
20193 + /* 170 */ 869, 913, 912, 869, 911, 910, 895, 894, 895, 883,
20194 + /* 180 */ 882, 881, 903, 902, 854, 869, 900, 854, 898, 897,
20195 + /* 190 */ 896, 895, 894, 893, 878, 877, 876, 889, 888, 875,
20196 + /* 200 */ 874, 815, 814, 871, 846, 845, 858, 862, 861, 814,
20197 + /* 210 */ 859, 840, 841, 856, 870, 793, 790, 789, 820, 836,
20198 + /* 220 */ 807, 817, 816, 832, 823, 812, 811, 809, 817, 794,
20199 + /* 230 */ 821, 819, 848, 800, 768, 767, 795, 821, 840, 839,
20200 + /* 240 */ 813, 825, 815, 834, 784, 783, 780, 779, 779, 770,
20201 + /* 250 */ 776, 774, 756, 722, 722, 722, 803, 759, 770, 769,
20202 + /* 260 */ 768, 767, 766, 769, 800, 799, 772, 796, 795, 787,
20203 + /* 270 */ 793, 792, 791, 788, 787, 764, 763, 722, 722, 722,
20204 + /* 280 */ 722, 771,
20206 +static const YYACTIONTYPE yy_default[] = {
20207 + /* 0 */ 570, 856, 797, 797, 856, 839, 839, 685, 856, 797,
20208 + /* 10 */ 797, 856, 822, 856, 681, 856, 856, 797, 793, 856,
20209 + /* 20 */ 586, 649, 856, 581, 856, 856, 856, 856, 856, 594,
20210 + /* 30 */ 651, 856, 856, 856, 856, 856, 856, 856, 856, 856,
20211 + /* 40 */ 856, 856, 856, 856, 856, 856, 856, 856, 856, 856,
20212 + /* 50 */ 856, 856, 856, 856, 856, 856, 856, 856, 856, 856,
20213 + /* 60 */ 856, 856, 856, 856, 856, 856, 856, 856, 856, 856,
20214 + /* 70 */ 856, 856, 856, 856, 856, 856, 856, 856, 856, 681,
20215 + /* 80 */ 856, 681, 570, 856, 856, 856, 856, 685, 675, 856,
20216 + /* 90 */ 856, 856, 856, 730, 729, 724, 723, 837, 697, 721,
20217 + /* 100 */ 714, 856, 789, 790, 788, 792, 796, 856, 705, 748,
20218 + /* 110 */ 780, 774, 747, 779, 760, 759, 754, 753, 752, 751,
20219 + /* 120 */ 750, 749, 640, 758, 757, 756, 755, 856, 856, 856,
20220 + /* 130 */ 856, 856, 856, 856, 856, 856, 856, 856, 856, 764,
20221 + /* 140 */ 763, 856, 856, 856, 856, 809, 856, 856, 726, 856,
20222 + /* 150 */ 856, 856, 663, 856, 856, 856, 856, 856, 842, 856,
20223 + /* 160 */ 856, 856, 844, 856, 856, 856, 856, 856, 828, 856,
20224 + /* 170 */ 661, 856, 856, 583, 856, 856, 856, 856, 595, 856,
20225 + /* 180 */ 856, 856, 856, 856, 689, 688, 856, 683, 856, 856,
20226 + /* 190 */ 856, 856, 856, 856, 856, 856, 856, 856, 573, 856,
20227 + /* 200 */ 856, 856, 856, 856, 720, 720, 621, 708, 708, 791,
20228 + /* 210 */ 708, 682, 673, 708, 856, 854, 852, 854, 690, 653,
20229 + /* 220 */ 731, 690, 690, 653, 720, 690, 690, 690, 720, 731,
20230 + /* 230 */ 653, 653, 651, 690, 836, 833, 690, 801, 651, 651,
20231 + /* 240 */ 636, 856, 801, 651, 700, 698, 700, 698, 690, 709,
20232 + /* 250 */ 690, 690, 856, 767, 766, 765, 856, 709, 715, 701,
20233 + /* 260 */ 713, 711, 720, 856, 651, 651, 636, 651, 651, 639,
20234 + /* 270 */ 572, 572, 572, 651, 572, 624, 624, 777, 776, 775,
20235 + /* 280 */ 768, 604, 856, 856, 856, 856, 856, 816, 856, 856,
20236 + /* 290 */ 856, 856, 856, 856, 856, 856, 856, 856, 856, 856,
20237 + /* 300 */ 856, 856, 856, 856, 856, 856, 716, 737, 856, 856,
20238 + /* 310 */ 856, 856, 856, 856, 808, 856, 856, 856, 856, 856,
20239 + /* 320 */ 856, 856, 856, 856, 856, 856, 856, 856, 856, 856,
20240 + /* 330 */ 856, 856, 856, 832, 831, 856, 856, 856, 856, 856,
20241 + /* 340 */ 856, 856, 856, 856, 856, 856, 856, 856, 856, 856,
20242 + /* 350 */ 856, 712, 856, 856, 856, 856, 856, 856, 856, 856,
20243 + /* 360 */ 856, 856, 666, 856, 739, 856, 702, 856, 856, 856,
20244 + /* 370 */ 738, 743, 856, 856, 856, 856, 856, 565, 569, 567,
20245 + /* 380 */ 855, 853, 851, 850, 815, 821, 818, 820, 819, 817,
20246 + /* 390 */ 814, 813, 812, 811, 810, 807, 725, 722, 719, 849,
20247 + /* 400 */ 806, 662, 660, 843, 841, 732, 840, 838, 823, 728,
20248 + /* 410 */ 727, 654, 799, 798, 580, 827, 826, 825, 734, 733,
20249 + /* 420 */ 830, 829, 835, 834, 824, 579, 585, 643, 642, 650,
20250 + /* 430 */ 648, 647, 646, 645, 644, 641, 587, 598, 599, 597,
20251 + /* 440 */ 596, 615, 612, 614, 611, 613, 610, 609, 608, 607,
20252 + /* 450 */ 606, 635, 623, 622, 802, 629, 628, 633, 632, 631,
20253 + /* 460 */ 630, 627, 626, 625, 620, 746, 745, 735, 778, 672,
20254 + /* 470 */ 671, 678, 677, 676, 687, 804, 805, 803, 699, 686,
20255 + /* 480 */ 680, 679, 590, 589, 696, 695, 694, 693, 692, 684,
20256 + /* 490 */ 674, 704, 786, 783, 784, 772, 785, 691, 795, 794,
20257 + /* 500 */ 781, 848, 847, 846, 845, 787, 782, 669, 668, 667,
20258 + /* 510 */ 771, 773, 770, 769, 762, 761, 744, 742, 741, 740,
20259 + /* 520 */ 736, 710, 588, 703, 718, 717, 602, 601, 600, 670,
20260 + /* 530 */ 665, 664, 619, 707, 706, 618, 638, 637, 634, 617,
20261 + /* 540 */ 616, 605, 603, 584, 582, 578, 577, 576, 575, 593,
20262 + /* 550 */ 592, 591, 574, 659, 658, 657, 656, 655, 652, 571,
20263 + /* 560 */ 568, 566, 564,
20266 +/* The next table maps tokens into fallback tokens. If a construct
20267 +** like the following:
20269 +** %fallback ID X Y Z.
20271 +** appears in the grammar, then ID becomes a fallback token for X, Y,
20272 +** and Z. Whenever one of the tokens X, Y, or Z is input to the parser
20273 +** but it does not parse, the type of the token is changed to ID and
20274 +** the parse is retried before an error is thrown.
20277 +static const YYCODETYPE yyFallback[] = {
20278 + 0, /* $ => nothing */
20279 + 0, /* END_OF_FILE => nothing */
20280 + 0, /* ILLEGAL => nothing */
20281 + 0, /* SPACE => nothing */
20282 + 0, /* UNCLOSED_STRING => nothing */
20283 + 0, /* COMMENT => nothing */
20284 + 0, /* FUNCTION => nothing */
20285 + 0, /* COLUMN => nothing */
20286 + 0, /* AGG_FUNCTION => nothing */
20287 + 0, /* SEMI => nothing */
20288 + 23, /* EXPLAIN => ID */
20289 + 23, /* BEGIN => ID */
20290 + 0, /* TRANSACTION => nothing */
20291 + 0, /* COMMIT => nothing */
20292 + 23, /* END => ID */
20293 + 0, /* ROLLBACK => nothing */
20294 + 0, /* CREATE => nothing */
20295 + 0, /* TABLE => nothing */
20296 + 23, /* TEMP => ID */
20297 + 0, /* LP => nothing */
20298 + 0, /* RP => nothing */
20299 + 0, /* AS => nothing */
20300 + 0, /* COMMA => nothing */
20301 + 0, /* ID => nothing */
20302 + 23, /* ABORT => ID */
20303 + 23, /* AFTER => ID */
20304 + 23, /* ASC => ID */
20305 + 23, /* ATTACH => ID */
20306 + 23, /* BEFORE => ID */
20307 + 23, /* CASCADE => ID */
20308 + 23, /* CLUSTER => ID */
20309 + 23, /* CONFLICT => ID */
20310 + 23, /* COPY => ID */
20311 + 23, /* DATABASE => ID */
20312 + 23, /* DEFERRED => ID */
20313 + 23, /* DELIMITERS => ID */
20314 + 23, /* DESC => ID */
20315 + 23, /* DETACH => ID */
20316 + 23, /* EACH => ID */
20317 + 23, /* FAIL => ID */
20318 + 23, /* FOR => ID */
20319 + 23, /* GLOB => ID */
20320 + 23, /* IGNORE => ID */
20321 + 23, /* IMMEDIATE => ID */
20322 + 23, /* INITIALLY => ID */
20323 + 23, /* INSTEAD => ID */
20324 + 23, /* LIKE => ID */
20325 + 23, /* MATCH => ID */
20326 + 23, /* KEY => ID */
20327 + 23, /* OF => ID */
20328 + 23, /* OFFSET => ID */
20329 + 23, /* PRAGMA => ID */
20330 + 23, /* RAISE => ID */
20331 + 23, /* REPLACE => ID */
20332 + 23, /* RESTRICT => ID */
20333 + 23, /* ROW => ID */
20334 + 23, /* STATEMENT => ID */
20335 + 23, /* TRIGGER => ID */
20336 + 23, /* VACUUM => ID */
20337 + 23, /* VIEW => ID */
20339 +#endif /* YYFALLBACK */
20341 +/* The following structure represents a single element of the
20342 +** parser's stack. Information stored includes:
20344 +** + The state number for the parser at this level of the stack.
20346 +** + The value of the token stored at this level of the stack.
20347 +** (In other words, the "major" token.)
20349 +** + The semantic value stored at this level of the stack. This is
20350 +** the information used by the action routines in the grammar.
20351 +** It is sometimes called the "minor" token.
20353 +struct yyStackEntry {
20354 + YYACTIONTYPE stateno; /* The state-number */
20355 + YYCODETYPE major; /* The major token value. This is the code
20356 + ** number for the token at this stack level */
20357 + YYMINORTYPE minor; /* The user-supplied minor token value. This
20358 + ** is the value of the token */
20360 +typedef struct yyStackEntry yyStackEntry;
20362 +/* The state of the parser is completely contained in an instance of
20363 +** the following structure */
20365 + int yyidx; /* Index of top element in stack */
20366 +#ifdef YYTRACKMAXSTACKDEPTH
20367 + int yyidxMax; /* Maximum value of yyidx */
20369 + int yyerrcnt; /* Shifts left before out of the error */
20370 + sqliteParserARG_SDECL /* A place to hold %extra_argument */
20371 +#if YYSTACKDEPTH<=0
20372 + int yystksz; /* Current side of the stack */
20373 + yyStackEntry *yystack; /* The parser's stack */
20375 + yyStackEntry yystack[YYSTACKDEPTH]; /* The parser's stack */
20378 +typedef struct yyParser yyParser;
20381 +#include <stdio.h>
20382 +static FILE *yyTraceFILE = 0;
20383 +static char *yyTracePrompt = 0;
20384 +#endif /* NDEBUG */
20388 +** Turn parser tracing on by giving a stream to which to write the trace
20389 +** and a prompt to preface each trace message. Tracing is turned off
20390 +** by making either argument NULL
20394 +** <li> A FILE* to which trace output should be written.
20395 +** If NULL, then tracing is turned off.
20396 +** <li> A prefix string written at the beginning of every
20397 +** line of trace output. If NULL, then tracing is
20404 +void sqliteParserTrace(FILE *TraceFILE, char *zTracePrompt){
20405 + yyTraceFILE = TraceFILE;
20406 + yyTracePrompt = zTracePrompt;
20407 + if( yyTraceFILE==0 ) yyTracePrompt = 0;
20408 + else if( yyTracePrompt==0 ) yyTraceFILE = 0;
20410 +#endif /* NDEBUG */
20413 +/* For tracing shifts, the names of all terminals and nonterminals
20414 +** are required. The following table supplies these names */
20415 +static const char *const yyTokenName[] = {
20416 + "$", "END_OF_FILE", "ILLEGAL", "SPACE",
20417 + "UNCLOSED_STRING", "COMMENT", "FUNCTION", "COLUMN",
20418 + "AGG_FUNCTION", "SEMI", "EXPLAIN", "BEGIN",
20419 + "TRANSACTION", "COMMIT", "END", "ROLLBACK",
20420 + "CREATE", "TABLE", "TEMP", "LP",
20421 + "RP", "AS", "COMMA", "ID",
20422 + "ABORT", "AFTER", "ASC", "ATTACH",
20423 + "BEFORE", "CASCADE", "CLUSTER", "CONFLICT",
20424 + "COPY", "DATABASE", "DEFERRED", "DELIMITERS",
20425 + "DESC", "DETACH", "EACH", "FAIL",
20426 + "FOR", "GLOB", "IGNORE", "IMMEDIATE",
20427 + "INITIALLY", "INSTEAD", "LIKE", "MATCH",
20428 + "KEY", "OF", "OFFSET", "PRAGMA",
20429 + "RAISE", "REPLACE", "RESTRICT", "ROW",
20430 + "STATEMENT", "TRIGGER", "VACUUM", "VIEW",
20431 + "OR", "AND", "NOT", "EQ",
20432 + "NE", "ISNULL", "NOTNULL", "IS",
20433 + "BETWEEN", "IN", "GT", "GE",
20434 + "LT", "LE", "BITAND", "BITOR",
20435 + "LSHIFT", "RSHIFT", "PLUS", "MINUS",
20436 + "STAR", "SLASH", "REM", "CONCAT",
20437 + "UMINUS", "UPLUS", "BITNOT", "STRING",
20438 + "JOIN_KW", "INTEGER", "CONSTRAINT", "DEFAULT",
20439 + "FLOAT", "NULL", "PRIMARY", "UNIQUE",
20440 + "CHECK", "REFERENCES", "COLLATE", "ON",
20441 + "DELETE", "UPDATE", "INSERT", "SET",
20442 + "DEFERRABLE", "FOREIGN", "DROP", "UNION",
20443 + "ALL", "INTERSECT", "EXCEPT", "SELECT",
20444 + "DISTINCT", "DOT", "FROM", "JOIN",
20445 + "USING", "ORDER", "BY", "GROUP",
20446 + "HAVING", "LIMIT", "WHERE", "INTO",
20447 + "VALUES", "VARIABLE", "CASE", "WHEN",
20448 + "THEN", "ELSE", "INDEX", "error",
20449 + "input", "cmdlist", "ecmd", "explain",
20450 + "cmdx", "cmd", "trans_opt", "onconf",
20451 + "nm", "create_table", "create_table_args", "temp",
20452 + "columnlist", "conslist_opt", "select", "column",
20453 + "columnid", "type", "carglist", "id",
20454 + "ids", "typename", "signed", "carg",
20455 + "ccons", "sortorder", "expr", "idxlist_opt",
20456 + "refargs", "defer_subclause", "refarg", "refact",
20457 + "init_deferred_pred_opt", "conslist", "tcons", "idxlist",
20458 + "defer_subclause_opt", "orconf", "resolvetype", "oneselect",
20459 + "multiselect_op", "distinct", "selcollist", "from",
20460 + "where_opt", "groupby_opt", "having_opt", "orderby_opt",
20461 + "limit_opt", "sclp", "as", "seltablist",
20462 + "stl_prefix", "joinop", "dbnm", "on_opt",
20463 + "using_opt", "seltablist_paren", "joinop2", "sortlist",
20464 + "sortitem", "collate", "exprlist", "setlist",
20465 + "insert_cmd", "inscollist_opt", "itemlist", "inscollist",
20466 + "likeop", "case_operand", "case_exprlist", "case_else",
20467 + "expritem", "uniqueflag", "idxitem", "plus_num",
20468 + "minus_num", "plus_opt", "number", "trigger_decl",
20469 + "trigger_cmd_list", "trigger_time", "trigger_event", "foreach_clause",
20470 + "when_clause", "trigger_cmd", "database_kw_opt", "key_opt",
20472 +#endif /* NDEBUG */
20475 +/* For tracing reduce actions, the names of all rules are required.
20477 +static const char *const yyRuleName[] = {
20478 + /* 0 */ "input ::= cmdlist",
20479 + /* 1 */ "cmdlist ::= cmdlist ecmd",
20480 + /* 2 */ "cmdlist ::= ecmd",
20481 + /* 3 */ "ecmd ::= explain cmdx SEMI",
20482 + /* 4 */ "ecmd ::= SEMI",
20483 + /* 5 */ "cmdx ::= cmd",
20484 + /* 6 */ "explain ::= EXPLAIN",
20485 + /* 7 */ "explain ::=",
20486 + /* 8 */ "cmd ::= BEGIN trans_opt onconf",
20487 + /* 9 */ "trans_opt ::=",
20488 + /* 10 */ "trans_opt ::= TRANSACTION",
20489 + /* 11 */ "trans_opt ::= TRANSACTION nm",
20490 + /* 12 */ "cmd ::= COMMIT trans_opt",
20491 + /* 13 */ "cmd ::= END trans_opt",
20492 + /* 14 */ "cmd ::= ROLLBACK trans_opt",
20493 + /* 15 */ "cmd ::= create_table create_table_args",
20494 + /* 16 */ "create_table ::= CREATE temp TABLE nm",
20495 + /* 17 */ "temp ::= TEMP",
20496 + /* 18 */ "temp ::=",
20497 + /* 19 */ "create_table_args ::= LP columnlist conslist_opt RP",
20498 + /* 20 */ "create_table_args ::= AS select",
20499 + /* 21 */ "columnlist ::= columnlist COMMA column",
20500 + /* 22 */ "columnlist ::= column",
20501 + /* 23 */ "column ::= columnid type carglist",
20502 + /* 24 */ "columnid ::= nm",
20503 + /* 25 */ "id ::= ID",
20504 + /* 26 */ "ids ::= ID",
20505 + /* 27 */ "ids ::= STRING",
20506 + /* 28 */ "nm ::= ID",
20507 + /* 29 */ "nm ::= STRING",
20508 + /* 30 */ "nm ::= JOIN_KW",
20509 + /* 31 */ "type ::=",
20510 + /* 32 */ "type ::= typename",
20511 + /* 33 */ "type ::= typename LP signed RP",
20512 + /* 34 */ "type ::= typename LP signed COMMA signed RP",
20513 + /* 35 */ "typename ::= ids",
20514 + /* 36 */ "typename ::= typename ids",
20515 + /* 37 */ "signed ::= INTEGER",
20516 + /* 38 */ "signed ::= PLUS INTEGER",
20517 + /* 39 */ "signed ::= MINUS INTEGER",
20518 + /* 40 */ "carglist ::= carglist carg",
20519 + /* 41 */ "carglist ::=",
20520 + /* 42 */ "carg ::= CONSTRAINT nm ccons",
20521 + /* 43 */ "carg ::= ccons",
20522 + /* 44 */ "carg ::= DEFAULT STRING",
20523 + /* 45 */ "carg ::= DEFAULT ID",
20524 + /* 46 */ "carg ::= DEFAULT INTEGER",
20525 + /* 47 */ "carg ::= DEFAULT PLUS INTEGER",
20526 + /* 48 */ "carg ::= DEFAULT MINUS INTEGER",
20527 + /* 49 */ "carg ::= DEFAULT FLOAT",
20528 + /* 50 */ "carg ::= DEFAULT PLUS FLOAT",
20529 + /* 51 */ "carg ::= DEFAULT MINUS FLOAT",
20530 + /* 52 */ "carg ::= DEFAULT NULL",
20531 + /* 53 */ "ccons ::= NULL onconf",
20532 + /* 54 */ "ccons ::= NOT NULL onconf",
20533 + /* 55 */ "ccons ::= PRIMARY KEY sortorder onconf",
20534 + /* 56 */ "ccons ::= UNIQUE onconf",
20535 + /* 57 */ "ccons ::= CHECK LP expr RP onconf",
20536 + /* 58 */ "ccons ::= REFERENCES nm idxlist_opt refargs",
20537 + /* 59 */ "ccons ::= defer_subclause",
20538 + /* 60 */ "ccons ::= COLLATE id",
20539 + /* 61 */ "refargs ::=",
20540 + /* 62 */ "refargs ::= refargs refarg",
20541 + /* 63 */ "refarg ::= MATCH nm",
20542 + /* 64 */ "refarg ::= ON DELETE refact",
20543 + /* 65 */ "refarg ::= ON UPDATE refact",
20544 + /* 66 */ "refarg ::= ON INSERT refact",
20545 + /* 67 */ "refact ::= SET NULL",
20546 + /* 68 */ "refact ::= SET DEFAULT",
20547 + /* 69 */ "refact ::= CASCADE",
20548 + /* 70 */ "refact ::= RESTRICT",
20549 + /* 71 */ "defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt",
20550 + /* 72 */ "defer_subclause ::= DEFERRABLE init_deferred_pred_opt",
20551 + /* 73 */ "init_deferred_pred_opt ::=",
20552 + /* 74 */ "init_deferred_pred_opt ::= INITIALLY DEFERRED",
20553 + /* 75 */ "init_deferred_pred_opt ::= INITIALLY IMMEDIATE",
20554 + /* 76 */ "conslist_opt ::=",
20555 + /* 77 */ "conslist_opt ::= COMMA conslist",
20556 + /* 78 */ "conslist ::= conslist COMMA tcons",
20557 + /* 79 */ "conslist ::= conslist tcons",
20558 + /* 80 */ "conslist ::= tcons",
20559 + /* 81 */ "tcons ::= CONSTRAINT nm",
20560 + /* 82 */ "tcons ::= PRIMARY KEY LP idxlist RP onconf",
20561 + /* 83 */ "tcons ::= UNIQUE LP idxlist RP onconf",
20562 + /* 84 */ "tcons ::= CHECK expr onconf",
20563 + /* 85 */ "tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt",
20564 + /* 86 */ "defer_subclause_opt ::=",
20565 + /* 87 */ "defer_subclause_opt ::= defer_subclause",
20566 + /* 88 */ "onconf ::=",
20567 + /* 89 */ "onconf ::= ON CONFLICT resolvetype",
20568 + /* 90 */ "orconf ::=",
20569 + /* 91 */ "orconf ::= OR resolvetype",
20570 + /* 92 */ "resolvetype ::= ROLLBACK",
20571 + /* 93 */ "resolvetype ::= ABORT",
20572 + /* 94 */ "resolvetype ::= FAIL",
20573 + /* 95 */ "resolvetype ::= IGNORE",
20574 + /* 96 */ "resolvetype ::= REPLACE",
20575 + /* 97 */ "cmd ::= DROP TABLE nm",
20576 + /* 98 */ "cmd ::= CREATE temp VIEW nm AS select",
20577 + /* 99 */ "cmd ::= DROP VIEW nm",
20578 + /* 100 */ "cmd ::= select",
20579 + /* 101 */ "select ::= oneselect",
20580 + /* 102 */ "select ::= select multiselect_op oneselect",
20581 + /* 103 */ "multiselect_op ::= UNION",
20582 + /* 104 */ "multiselect_op ::= UNION ALL",
20583 + /* 105 */ "multiselect_op ::= INTERSECT",
20584 + /* 106 */ "multiselect_op ::= EXCEPT",
20585 + /* 107 */ "oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt",
20586 + /* 108 */ "distinct ::= DISTINCT",
20587 + /* 109 */ "distinct ::= ALL",
20588 + /* 110 */ "distinct ::=",
20589 + /* 111 */ "sclp ::= selcollist COMMA",
20590 + /* 112 */ "sclp ::=",
20591 + /* 113 */ "selcollist ::= sclp expr as",
20592 + /* 114 */ "selcollist ::= sclp STAR",
20593 + /* 115 */ "selcollist ::= sclp nm DOT STAR",
20594 + /* 116 */ "as ::= AS nm",
20595 + /* 117 */ "as ::= ids",
20596 + /* 118 */ "as ::=",
20597 + /* 119 */ "from ::=",
20598 + /* 120 */ "from ::= FROM seltablist",
20599 + /* 121 */ "stl_prefix ::= seltablist joinop",
20600 + /* 122 */ "stl_prefix ::=",
20601 + /* 123 */ "seltablist ::= stl_prefix nm dbnm as on_opt using_opt",
20602 + /* 124 */ "seltablist ::= stl_prefix LP seltablist_paren RP as on_opt using_opt",
20603 + /* 125 */ "seltablist_paren ::= select",
20604 + /* 126 */ "seltablist_paren ::= seltablist",
20605 + /* 127 */ "dbnm ::=",
20606 + /* 128 */ "dbnm ::= DOT nm",
20607 + /* 129 */ "joinop ::= COMMA",
20608 + /* 130 */ "joinop ::= JOIN",
20609 + /* 131 */ "joinop ::= JOIN_KW JOIN",
20610 + /* 132 */ "joinop ::= JOIN_KW nm JOIN",
20611 + /* 133 */ "joinop ::= JOIN_KW nm nm JOIN",
20612 + /* 134 */ "on_opt ::= ON expr",
20613 + /* 135 */ "on_opt ::=",
20614 + /* 136 */ "using_opt ::= USING LP idxlist RP",
20615 + /* 137 */ "using_opt ::=",
20616 + /* 138 */ "orderby_opt ::=",
20617 + /* 139 */ "orderby_opt ::= ORDER BY sortlist",
20618 + /* 140 */ "sortlist ::= sortlist COMMA sortitem collate sortorder",
20619 + /* 141 */ "sortlist ::= sortitem collate sortorder",
20620 + /* 142 */ "sortitem ::= expr",
20621 + /* 143 */ "sortorder ::= ASC",
20622 + /* 144 */ "sortorder ::= DESC",
20623 + /* 145 */ "sortorder ::=",
20624 + /* 146 */ "collate ::=",
20625 + /* 147 */ "collate ::= COLLATE id",
20626 + /* 148 */ "groupby_opt ::=",
20627 + /* 149 */ "groupby_opt ::= GROUP BY exprlist",
20628 + /* 150 */ "having_opt ::=",
20629 + /* 151 */ "having_opt ::= HAVING expr",
20630 + /* 152 */ "limit_opt ::=",
20631 + /* 153 */ "limit_opt ::= LIMIT signed",
20632 + /* 154 */ "limit_opt ::= LIMIT signed OFFSET signed",
20633 + /* 155 */ "limit_opt ::= LIMIT signed COMMA signed",
20634 + /* 156 */ "cmd ::= DELETE FROM nm dbnm where_opt",
20635 + /* 157 */ "where_opt ::=",
20636 + /* 158 */ "where_opt ::= WHERE expr",
20637 + /* 159 */ "cmd ::= UPDATE orconf nm dbnm SET setlist where_opt",
20638 + /* 160 */ "setlist ::= setlist COMMA nm EQ expr",
20639 + /* 161 */ "setlist ::= nm EQ expr",
20640 + /* 162 */ "cmd ::= insert_cmd INTO nm dbnm inscollist_opt VALUES LP itemlist RP",
20641 + /* 163 */ "cmd ::= insert_cmd INTO nm dbnm inscollist_opt select",
20642 + /* 164 */ "insert_cmd ::= INSERT orconf",
20643 + /* 165 */ "insert_cmd ::= REPLACE",
20644 + /* 166 */ "itemlist ::= itemlist COMMA expr",
20645 + /* 167 */ "itemlist ::= expr",
20646 + /* 168 */ "inscollist_opt ::=",
20647 + /* 169 */ "inscollist_opt ::= LP inscollist RP",
20648 + /* 170 */ "inscollist ::= inscollist COMMA nm",
20649 + /* 171 */ "inscollist ::= nm",
20650 + /* 172 */ "expr ::= LP expr RP",
20651 + /* 173 */ "expr ::= NULL",
20652 + /* 174 */ "expr ::= ID",
20653 + /* 175 */ "expr ::= JOIN_KW",
20654 + /* 176 */ "expr ::= nm DOT nm",
20655 + /* 177 */ "expr ::= nm DOT nm DOT nm",
20656 + /* 178 */ "expr ::= INTEGER",
20657 + /* 179 */ "expr ::= FLOAT",
20658 + /* 180 */ "expr ::= STRING",
20659 + /* 181 */ "expr ::= VARIABLE",
20660 + /* 182 */ "expr ::= ID LP exprlist RP",
20661 + /* 183 */ "expr ::= ID LP STAR RP",
20662 + /* 184 */ "expr ::= expr AND expr",
20663 + /* 185 */ "expr ::= expr OR expr",
20664 + /* 186 */ "expr ::= expr LT expr",
20665 + /* 187 */ "expr ::= expr GT expr",
20666 + /* 188 */ "expr ::= expr LE expr",
20667 + /* 189 */ "expr ::= expr GE expr",
20668 + /* 190 */ "expr ::= expr NE expr",
20669 + /* 191 */ "expr ::= expr EQ expr",
20670 + /* 192 */ "expr ::= expr BITAND expr",
20671 + /* 193 */ "expr ::= expr BITOR expr",
20672 + /* 194 */ "expr ::= expr LSHIFT expr",
20673 + /* 195 */ "expr ::= expr RSHIFT expr",
20674 + /* 196 */ "expr ::= expr likeop expr",
20675 + /* 197 */ "expr ::= expr NOT likeop expr",
20676 + /* 198 */ "likeop ::= LIKE",
20677 + /* 199 */ "likeop ::= GLOB",
20678 + /* 200 */ "expr ::= expr PLUS expr",
20679 + /* 201 */ "expr ::= expr MINUS expr",
20680 + /* 202 */ "expr ::= expr STAR expr",
20681 + /* 203 */ "expr ::= expr SLASH expr",
20682 + /* 204 */ "expr ::= expr REM expr",
20683 + /* 205 */ "expr ::= expr CONCAT expr",
20684 + /* 206 */ "expr ::= expr ISNULL",
20685 + /* 207 */ "expr ::= expr IS NULL",
20686 + /* 208 */ "expr ::= expr NOTNULL",
20687 + /* 209 */ "expr ::= expr NOT NULL",
20688 + /* 210 */ "expr ::= expr IS NOT NULL",
20689 + /* 211 */ "expr ::= NOT expr",
20690 + /* 212 */ "expr ::= BITNOT expr",
20691 + /* 213 */ "expr ::= MINUS expr",
20692 + /* 214 */ "expr ::= PLUS expr",
20693 + /* 215 */ "expr ::= LP select RP",
20694 + /* 216 */ "expr ::= expr BETWEEN expr AND expr",
20695 + /* 217 */ "expr ::= expr NOT BETWEEN expr AND expr",
20696 + /* 218 */ "expr ::= expr IN LP exprlist RP",
20697 + /* 219 */ "expr ::= expr IN LP select RP",
20698 + /* 220 */ "expr ::= expr NOT IN LP exprlist RP",
20699 + /* 221 */ "expr ::= expr NOT IN LP select RP",
20700 + /* 222 */ "expr ::= expr IN nm dbnm",
20701 + /* 223 */ "expr ::= expr NOT IN nm dbnm",
20702 + /* 224 */ "expr ::= CASE case_operand case_exprlist case_else END",
20703 + /* 225 */ "case_exprlist ::= case_exprlist WHEN expr THEN expr",
20704 + /* 226 */ "case_exprlist ::= WHEN expr THEN expr",
20705 + /* 227 */ "case_else ::= ELSE expr",
20706 + /* 228 */ "case_else ::=",
20707 + /* 229 */ "case_operand ::= expr",
20708 + /* 230 */ "case_operand ::=",
20709 + /* 231 */ "exprlist ::= exprlist COMMA expritem",
20710 + /* 232 */ "exprlist ::= expritem",
20711 + /* 233 */ "expritem ::= expr",
20712 + /* 234 */ "expritem ::=",
20713 + /* 235 */ "cmd ::= CREATE uniqueflag INDEX nm ON nm dbnm LP idxlist RP onconf",
20714 + /* 236 */ "uniqueflag ::= UNIQUE",
20715 + /* 237 */ "uniqueflag ::=",
20716 + /* 238 */ "idxlist_opt ::=",
20717 + /* 239 */ "idxlist_opt ::= LP idxlist RP",
20718 + /* 240 */ "idxlist ::= idxlist COMMA idxitem",
20719 + /* 241 */ "idxlist ::= idxitem",
20720 + /* 242 */ "idxitem ::= nm sortorder",
20721 + /* 243 */ "cmd ::= DROP INDEX nm dbnm",
20722 + /* 244 */ "cmd ::= COPY orconf nm dbnm FROM nm USING DELIMITERS STRING",
20723 + /* 245 */ "cmd ::= COPY orconf nm dbnm FROM nm",
20724 + /* 246 */ "cmd ::= VACUUM",
20725 + /* 247 */ "cmd ::= VACUUM nm",
20726 + /* 248 */ "cmd ::= PRAGMA ids EQ nm",
20727 + /* 249 */ "cmd ::= PRAGMA ids EQ ON",
20728 + /* 250 */ "cmd ::= PRAGMA ids EQ plus_num",
20729 + /* 251 */ "cmd ::= PRAGMA ids EQ minus_num",
20730 + /* 252 */ "cmd ::= PRAGMA ids LP nm RP",
20731 + /* 253 */ "cmd ::= PRAGMA ids",
20732 + /* 254 */ "plus_num ::= plus_opt number",
20733 + /* 255 */ "minus_num ::= MINUS number",
20734 + /* 256 */ "number ::= INTEGER",
20735 + /* 257 */ "number ::= FLOAT",
20736 + /* 258 */ "plus_opt ::= PLUS",
20737 + /* 259 */ "plus_opt ::=",
20738 + /* 260 */ "cmd ::= CREATE trigger_decl BEGIN trigger_cmd_list END",
20739 + /* 261 */ "trigger_decl ::= temp TRIGGER nm trigger_time trigger_event ON nm dbnm foreach_clause when_clause",
20740 + /* 262 */ "trigger_time ::= BEFORE",
20741 + /* 263 */ "trigger_time ::= AFTER",
20742 + /* 264 */ "trigger_time ::= INSTEAD OF",
20743 + /* 265 */ "trigger_time ::=",
20744 + /* 266 */ "trigger_event ::= DELETE",
20745 + /* 267 */ "trigger_event ::= INSERT",
20746 + /* 268 */ "trigger_event ::= UPDATE",
20747 + /* 269 */ "trigger_event ::= UPDATE OF inscollist",
20748 + /* 270 */ "foreach_clause ::=",
20749 + /* 271 */ "foreach_clause ::= FOR EACH ROW",
20750 + /* 272 */ "foreach_clause ::= FOR EACH STATEMENT",
20751 + /* 273 */ "when_clause ::=",
20752 + /* 274 */ "when_clause ::= WHEN expr",
20753 + /* 275 */ "trigger_cmd_list ::= trigger_cmd SEMI trigger_cmd_list",
20754 + /* 276 */ "trigger_cmd_list ::=",
20755 + /* 277 */ "trigger_cmd ::= UPDATE orconf nm SET setlist where_opt",
20756 + /* 278 */ "trigger_cmd ::= insert_cmd INTO nm inscollist_opt VALUES LP itemlist RP",
20757 + /* 279 */ "trigger_cmd ::= insert_cmd INTO nm inscollist_opt select",
20758 + /* 280 */ "trigger_cmd ::= DELETE FROM nm where_opt",
20759 + /* 281 */ "trigger_cmd ::= select",
20760 + /* 282 */ "expr ::= RAISE LP IGNORE RP",
20761 + /* 283 */ "expr ::= RAISE LP ROLLBACK COMMA nm RP",
20762 + /* 284 */ "expr ::= RAISE LP ABORT COMMA nm RP",
20763 + /* 285 */ "expr ::= RAISE LP FAIL COMMA nm RP",
20764 + /* 286 */ "cmd ::= DROP TRIGGER nm dbnm",
20765 + /* 287 */ "cmd ::= ATTACH database_kw_opt ids AS nm key_opt",
20766 + /* 288 */ "key_opt ::= USING ids",
20767 + /* 289 */ "key_opt ::=",
20768 + /* 290 */ "database_kw_opt ::= DATABASE",
20769 + /* 291 */ "database_kw_opt ::=",
20770 + /* 292 */ "cmd ::= DETACH database_kw_opt nm",
20772 +#endif /* NDEBUG */
20775 +#if YYSTACKDEPTH<=0
20777 +** Try to increase the size of the parser stack.
20779 +static void yyGrowStack(yyParser *p){
20781 + yyStackEntry *pNew;
20783 + newSize = p->yystksz*2 + 100;
20784 + pNew = realloc(p->yystack, newSize*sizeof(pNew[0]));
20786 + p->yystack = pNew;
20787 + p->yystksz = newSize;
20789 + if( yyTraceFILE ){
20790 + fprintf(yyTraceFILE,"%sStack grows to %d entries!\n",
20791 + yyTracePrompt, p->yystksz);
20799 +** This function allocates a new parser.
20800 +** The only argument is a pointer to a function which works like
20804 +** A pointer to the function used to allocate memory.
20807 +** A pointer to a parser. This pointer is used in subsequent calls
20808 +** to sqliteParser and sqliteParserFree.
20810 +void *sqliteParserAlloc(void *(*mallocProc)(size_t)){
20811 + yyParser *pParser;
20812 + pParser = (yyParser*)(*mallocProc)( (size_t)sizeof(yyParser) );
20814 + pParser->yyidx = -1;
20815 +#ifdef YYTRACKMAXSTACKDEPTH
20816 + pParser->yyidxMax = 0;
20818 +#if YYSTACKDEPTH<=0
20819 + pParser->yystack = NULL;
20820 + pParser->yystksz = 0;
20821 + yyGrowStack(pParser);
20827 +/* The following function deletes the value associated with a
20828 +** symbol. The symbol can be either a terminal or nonterminal.
20829 +** "yymajor" is the symbol code, and "yypminor" is a pointer to
20832 +static void yy_destructor(
20833 + yyParser *yypParser, /* The parser */
20834 + YYCODETYPE yymajor, /* Type code for object to destroy */
20835 + YYMINORTYPE *yypminor /* The object to be destroyed */
20837 + sqliteParserARG_FETCH;
20838 + switch( yymajor ){
20839 + /* Here is inserted the actions which take place when a
20840 + ** terminal or non-terminal is destroyed. This can happen
20841 + ** when the symbol is popped from the stack during a
20842 + ** reduce or during error processing or when a parser is
20843 + ** being destroyed before it is finished parsing.
20845 + ** Note: during a reduce, the only symbols destroyed are those
20846 + ** which appear on the RHS of the rule, but which are not used
20847 + ** inside the C code.
20849 + case 146: /* select */
20850 + case 171: /* oneselect */
20851 + case 189: /* seltablist_paren */
20853 +#line 286 "ext/sqlite/libsqlite/src/parse.y"
20854 +sqliteSelectDelete((yypminor->yy179));
20855 +#line 1131 "ext/sqlite/libsqlite/src/parse.c"
20858 + case 158: /* expr */
20859 + case 176: /* where_opt */
20860 + case 178: /* having_opt */
20861 + case 187: /* on_opt */
20862 + case 192: /* sortitem */
20863 + case 204: /* expritem */
20865 +#line 533 "ext/sqlite/libsqlite/src/parse.y"
20866 +sqliteExprDelete((yypminor->yy242));
20867 +#line 1143 "ext/sqlite/libsqlite/src/parse.c"
20870 + case 159: /* idxlist_opt */
20871 + case 167: /* idxlist */
20872 + case 188: /* using_opt */
20873 + case 197: /* inscollist_opt */
20874 + case 199: /* inscollist */
20876 +#line 746 "ext/sqlite/libsqlite/src/parse.y"
20877 +sqliteIdListDelete((yypminor->yy320));
20878 +#line 1154 "ext/sqlite/libsqlite/src/parse.c"
20881 + case 174: /* selcollist */
20882 + case 177: /* groupby_opt */
20883 + case 179: /* orderby_opt */
20884 + case 181: /* sclp */
20885 + case 191: /* sortlist */
20886 + case 194: /* exprlist */
20887 + case 195: /* setlist */
20888 + case 198: /* itemlist */
20889 + case 202: /* case_exprlist */
20891 +#line 322 "ext/sqlite/libsqlite/src/parse.y"
20892 +sqliteExprListDelete((yypminor->yy322));
20893 +#line 1169 "ext/sqlite/libsqlite/src/parse.c"
20896 + case 175: /* from */
20897 + case 183: /* seltablist */
20898 + case 184: /* stl_prefix */
20900 +#line 353 "ext/sqlite/libsqlite/src/parse.y"
20901 +sqliteSrcListDelete((yypminor->yy307));
20902 +#line 1178 "ext/sqlite/libsqlite/src/parse.c"
20905 + case 212: /* trigger_cmd_list */
20906 + case 217: /* trigger_cmd */
20908 +#line 828 "ext/sqlite/libsqlite/src/parse.y"
20909 +sqliteDeleteTriggerStep((yypminor->yy19));
20910 +#line 1186 "ext/sqlite/libsqlite/src/parse.c"
20913 + case 214: /* trigger_event */
20915 +#line 812 "ext/sqlite/libsqlite/src/parse.y"
20916 +sqliteIdListDelete((yypminor->yy290).b);
20917 +#line 1193 "ext/sqlite/libsqlite/src/parse.c"
20920 + default: break; /* If no destructor action specified: do nothing */
20925 +** Pop the parser's stack once.
20927 +** If there is a destructor routine associated with the token which
20928 +** is popped from the stack, then call it.
20930 +** Return the major token number for the symbol popped.
20932 +static int yy_pop_parser_stack(yyParser *pParser){
20933 + YYCODETYPE yymajor;
20934 + yyStackEntry *yytos = &pParser->yystack[pParser->yyidx];
20936 + if( pParser->yyidx<0 ) return 0;
20938 + if( yyTraceFILE && pParser->yyidx>=0 ){
20939 + fprintf(yyTraceFILE,"%sPopping %s\n",
20941 + yyTokenName[yytos->major]);
20944 + yymajor = yytos->major;
20945 + yy_destructor(pParser, yymajor, &yytos->minor);
20946 + pParser->yyidx--;
20951 +** Deallocate and destroy a parser. Destructors are all called for
20952 +** all stack elements before shutting the parser down.
20956 +** <li> A pointer to the parser. This should be a pointer
20957 +** obtained from sqliteParserAlloc.
20958 +** <li> A pointer to a function used to reclaim memory obtained
20962 +void sqliteParserFree(
20963 + void *p, /* The parser to be deleted */
20964 + void (*freeProc)(void*) /* Function used to reclaim memory */
20966 + yyParser *pParser = (yyParser*)p;
20967 + if( pParser==0 ) return;
20968 + while( pParser->yyidx>=0 ) yy_pop_parser_stack(pParser);
20969 +#if YYSTACKDEPTH<=0
20970 + free(pParser->yystack);
20972 + (*freeProc)((void*)pParser);
20976 +** Return the peak depth of the stack for a parser.
20978 +#ifdef YYTRACKMAXSTACKDEPTH
20979 +int sqliteParserStackPeak(void *p){
20980 + yyParser *pParser = (yyParser*)p;
20981 + return pParser->yyidxMax;
20986 +** Find the appropriate action for a parser given the terminal
20987 +** look-ahead token iLookAhead.
20989 +** If the look-ahead token is YYNOCODE, then check to see if the action is
20990 +** independent of the look-ahead. If it is, return the action, otherwise
20991 +** return YY_NO_ACTION.
20993 +static int yy_find_shift_action(
20994 + yyParser *pParser, /* The parser */
20995 + YYCODETYPE iLookAhead /* The look-ahead token */
20998 + int stateno = pParser->yystack[pParser->yyidx].stateno;
21000 + if( stateno>YY_SHIFT_COUNT
21001 + || (i = yy_shift_ofst[stateno])==YY_SHIFT_USE_DFLT ){
21002 + return yy_default[stateno];
21004 + assert( iLookAhead!=YYNOCODE );
21006 + if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
21007 + if( iLookAhead>0 ){
21009 + YYCODETYPE iFallback; /* Fallback token */
21010 + if( iLookAhead<sizeof(yyFallback)/sizeof(yyFallback[0])
21011 + && (iFallback = yyFallback[iLookAhead])!=0 ){
21013 + if( yyTraceFILE ){
21014 + fprintf(yyTraceFILE, "%sFALLBACK %s => %s\n",
21015 + yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[iFallback]);
21018 + return yy_find_shift_action(pParser, iFallback);
21023 + int j = i - iLookAhead + YYWILDCARD;
21025 +#if YY_SHIFT_MIN+YYWILDCARD<0
21028 +#if YY_SHIFT_MAX+YYWILDCARD>=YY_ACTTAB_COUNT
21029 + j<YY_ACTTAB_COUNT &&
21031 + yy_lookahead[j]==YYWILDCARD
21034 + if( yyTraceFILE ){
21035 + fprintf(yyTraceFILE, "%sWILDCARD %s => %s\n",
21036 + yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[YYWILDCARD]);
21038 +#endif /* NDEBUG */
21039 + return yy_action[j];
21042 +#endif /* YYWILDCARD */
21044 + return yy_default[stateno];
21046 + return yy_action[i];
21051 +** Find the appropriate action for a parser given the non-terminal
21052 +** look-ahead token iLookAhead.
21054 +** If the look-ahead token is YYNOCODE, then check to see if the action is
21055 +** independent of the look-ahead. If it is, return the action, otherwise
21056 +** return YY_NO_ACTION.
21058 +static int yy_find_reduce_action(
21059 + int stateno, /* Current state number */
21060 + YYCODETYPE iLookAhead /* The look-ahead token */
21063 +#ifdef YYERRORSYMBOL
21064 + if( stateno>YY_REDUCE_COUNT ){
21065 + return yy_default[stateno];
21068 + assert( stateno<=YY_REDUCE_COUNT );
21070 + i = yy_reduce_ofst[stateno];
21071 + assert( i!=YY_REDUCE_USE_DFLT );
21072 + assert( iLookAhead!=YYNOCODE );
21074 +#ifdef YYERRORSYMBOL
21075 + if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
21076 + return yy_default[stateno];
21079 + assert( i>=0 && i<YY_ACTTAB_COUNT );
21080 + assert( yy_lookahead[i]==iLookAhead );
21082 + return yy_action[i];
21086 +** The following routine is called if the stack overflows.
21088 +static void yyStackOverflow(yyParser *yypParser, YYMINORTYPE *yypMinor){
21089 + sqliteParserARG_FETCH;
21090 + yypParser->yyidx--;
21092 + if( yyTraceFILE ){
21093 + fprintf(yyTraceFILE,"%sStack Overflow!\n",yyTracePrompt);
21096 + while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
21097 + /* Here code is inserted which will execute if the parser
21098 + ** stack every overflows */
21099 + sqliteParserARG_STORE; /* Suppress warning about unused %extra_argument var */
21103 +** Perform a shift action.
21105 +static void yy_shift(
21106 + yyParser *yypParser, /* The parser to be shifted */
21107 + int yyNewState, /* The new state to shift in */
21108 + int yyMajor, /* The major token to shift in */
21109 + YYMINORTYPE *yypMinor /* Pointer to the minor token to shift in */
21111 + yyStackEntry *yytos;
21112 + yypParser->yyidx++;
21113 +#ifdef YYTRACKMAXSTACKDEPTH
21114 + if( yypParser->yyidx>yypParser->yyidxMax ){
21115 + yypParser->yyidxMax = yypParser->yyidx;
21118 +#if YYSTACKDEPTH>0
21119 + if( yypParser->yyidx>=YYSTACKDEPTH ){
21120 + yyStackOverflow(yypParser, yypMinor);
21124 + if( yypParser->yyidx>=yypParser->yystksz ){
21125 + yyGrowStack(yypParser);
21126 + if( yypParser->yyidx>=yypParser->yystksz ){
21127 + yyStackOverflow(yypParser, yypMinor);
21132 + yytos = &yypParser->yystack[yypParser->yyidx];
21133 + yytos->stateno = (YYACTIONTYPE)yyNewState;
21134 + yytos->major = (YYCODETYPE)yyMajor;
21135 + yytos->minor = *yypMinor;
21137 + if( yyTraceFILE && yypParser->yyidx>0 ){
21139 + fprintf(yyTraceFILE,"%sShift %d\n",yyTracePrompt,yyNewState);
21140 + fprintf(yyTraceFILE,"%sStack:",yyTracePrompt);
21141 + for(i=1; i<=yypParser->yyidx; i++)
21142 + fprintf(yyTraceFILE," %s",yyTokenName[yypParser->yystack[i].major]);
21143 + fprintf(yyTraceFILE,"\n");
21148 +/* The following table contains information about every rule that
21149 +** is used during the reduce.
21151 +static const struct {
21152 + YYCODETYPE lhs; /* Symbol on the left-hand side of the rule */
21153 + unsigned char nrhs; /* Number of right-hand side symbols in the rule */
21154 +} yyRuleInfo[] = {
21450 +static void yy_accept(yyParser*); /* Forward Declaration */
21453 +** Perform a reduce action and the shift that must immediately
21454 +** follow the reduce.
21456 +static void yy_reduce(
21457 + yyParser *yypParser, /* The parser */
21458 + int yyruleno /* Number of the rule by which to reduce */
21460 + int yygoto; /* The next state */
21461 + int yyact; /* The next action */
21462 + YYMINORTYPE yygotominor; /* The LHS of the rule reduced */
21463 + yyStackEntry *yymsp; /* The top of the parser's stack */
21464 + int yysize; /* Amount to pop the stack */
21465 + sqliteParserARG_FETCH;
21466 + yymsp = &yypParser->yystack[yypParser->yyidx];
21468 + if( yyTraceFILE && yyruleno>=0
21469 + && yyruleno<(int)(sizeof(yyRuleName)/sizeof(yyRuleName[0])) ){
21470 + fprintf(yyTraceFILE, "%sReduce [%s].\n", yyTracePrompt,
21471 + yyRuleName[yyruleno]);
21473 +#endif /* NDEBUG */
21475 + /* Silence complaints from purify about yygotominor being uninitialized
21476 + ** in some cases when it is copied into the stack after the following
21477 + ** switch. yygotominor is uninitialized when a rule reduces that does
21478 + ** not set the value of its left-hand side nonterminal. Leaving the
21479 + ** value of the nonterminal uninitialized is utterly harmless as long
21480 + ** as the value is never used. So really the only thing this code
21481 + ** accomplishes is to quieten purify.
21483 + ** 2007-01-16: The wireshark project (www.wireshark.org) reports that
21484 + ** without this code, their parser segfaults. I'm not sure what there
21485 + ** parser is doing to make this happen. This is the second bug report
21486 + ** from wireshark this week. Clearly they are stressing Lemon in ways
21487 + ** that it has not been previously stressed... (SQLite ticket #2172)
21489 + /*memset(&yygotominor, 0, sizeof(yygotominor));*/
21490 + yygotominor = yyzerominor;
21493 + switch( yyruleno ){
21494 + /* Beginning here are the reduction cases. A typical example
21497 + ** #line <lineno> <grammarfile>
21498 + ** { ... } // User supplied code
21499 + ** #line <lineno> <thisfile>
21502 + case 5: /* cmdx ::= cmd */
21503 +#line 72 "ext/sqlite/libsqlite/src/parse.y"
21504 +{ sqliteExec(pParse); }
21505 +#line 1781 "ext/sqlite/libsqlite/src/parse.c"
21507 + case 6: /* explain ::= EXPLAIN */
21508 +#line 73 "ext/sqlite/libsqlite/src/parse.y"
21509 +{ sqliteBeginParse(pParse, 1); }
21510 +#line 1786 "ext/sqlite/libsqlite/src/parse.c"
21512 + case 7: /* explain ::= */
21513 +#line 74 "ext/sqlite/libsqlite/src/parse.y"
21514 +{ sqliteBeginParse(pParse, 0); }
21515 +#line 1791 "ext/sqlite/libsqlite/src/parse.c"
21517 + case 8: /* cmd ::= BEGIN trans_opt onconf */
21518 +#line 79 "ext/sqlite/libsqlite/src/parse.y"
21519 +{sqliteBeginTransaction(pParse,yymsp[0].minor.yy372);}
21520 +#line 1796 "ext/sqlite/libsqlite/src/parse.c"
21522 + case 12: /* cmd ::= COMMIT trans_opt */
21523 + case 13: /* cmd ::= END trans_opt */ yytestcase(yyruleno==13);
21524 +#line 83 "ext/sqlite/libsqlite/src/parse.y"
21525 +{sqliteCommitTransaction(pParse);}
21526 +#line 1802 "ext/sqlite/libsqlite/src/parse.c"
21528 + case 14: /* cmd ::= ROLLBACK trans_opt */
21529 +#line 85 "ext/sqlite/libsqlite/src/parse.y"
21530 +{sqliteRollbackTransaction(pParse);}
21531 +#line 1807 "ext/sqlite/libsqlite/src/parse.c"
21533 + case 16: /* create_table ::= CREATE temp TABLE nm */
21534 +#line 90 "ext/sqlite/libsqlite/src/parse.y"
21536 + sqliteStartTable(pParse,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0,yymsp[-2].minor.yy372,0);
21538 +#line 1814 "ext/sqlite/libsqlite/src/parse.c"
21540 + case 17: /* temp ::= TEMP */
21541 + case 74: /* init_deferred_pred_opt ::= INITIALLY DEFERRED */ yytestcase(yyruleno==74);
21542 + case 108: /* distinct ::= DISTINCT */ yytestcase(yyruleno==108);
21543 +#line 94 "ext/sqlite/libsqlite/src/parse.y"
21544 +{yygotominor.yy372 = 1;}
21545 +#line 1821 "ext/sqlite/libsqlite/src/parse.c"
21547 + case 18: /* temp ::= */
21548 + case 73: /* init_deferred_pred_opt ::= */ yytestcase(yyruleno==73);
21549 + case 75: /* init_deferred_pred_opt ::= INITIALLY IMMEDIATE */ yytestcase(yyruleno==75);
21550 + case 86: /* defer_subclause_opt ::= */ yytestcase(yyruleno==86);
21551 + case 109: /* distinct ::= ALL */ yytestcase(yyruleno==109);
21552 + case 110: /* distinct ::= */ yytestcase(yyruleno==110);
21553 +#line 95 "ext/sqlite/libsqlite/src/parse.y"
21554 +{yygotominor.yy372 = 0;}
21555 +#line 1831 "ext/sqlite/libsqlite/src/parse.c"
21557 + case 19: /* create_table_args ::= LP columnlist conslist_opt RP */
21558 +#line 96 "ext/sqlite/libsqlite/src/parse.y"
21560 + sqliteEndTable(pParse,&yymsp[0].minor.yy0,0);
21562 +#line 1838 "ext/sqlite/libsqlite/src/parse.c"
21564 + case 20: /* create_table_args ::= AS select */
21565 +#line 99 "ext/sqlite/libsqlite/src/parse.y"
21567 + sqliteEndTable(pParse,0,yymsp[0].minor.yy179);
21568 + sqliteSelectDelete(yymsp[0].minor.yy179);
21570 +#line 1846 "ext/sqlite/libsqlite/src/parse.c"
21572 + case 24: /* columnid ::= nm */
21573 +#line 111 "ext/sqlite/libsqlite/src/parse.y"
21574 +{sqliteAddColumn(pParse,&yymsp[0].minor.yy0);}
21575 +#line 1851 "ext/sqlite/libsqlite/src/parse.c"
21577 + case 25: /* id ::= ID */
21578 + case 26: /* ids ::= ID */ yytestcase(yyruleno==26);
21579 + case 27: /* ids ::= STRING */ yytestcase(yyruleno==27);
21580 + case 28: /* nm ::= ID */ yytestcase(yyruleno==28);
21581 + case 29: /* nm ::= STRING */ yytestcase(yyruleno==29);
21582 + case 30: /* nm ::= JOIN_KW */ yytestcase(yyruleno==30);
21583 + case 35: /* typename ::= ids */ yytestcase(yyruleno==35);
21584 + case 128: /* dbnm ::= DOT nm */ yytestcase(yyruleno==128);
21585 + case 254: /* plus_num ::= plus_opt number */ yytestcase(yyruleno==254);
21586 + case 255: /* minus_num ::= MINUS number */ yytestcase(yyruleno==255);
21587 + case 256: /* number ::= INTEGER */ yytestcase(yyruleno==256);
21588 + case 257: /* number ::= FLOAT */ yytestcase(yyruleno==257);
21589 +#line 117 "ext/sqlite/libsqlite/src/parse.y"
21590 +{yygotominor.yy0 = yymsp[0].minor.yy0;}
21591 +#line 1867 "ext/sqlite/libsqlite/src/parse.c"
21593 + case 32: /* type ::= typename */
21594 +#line 160 "ext/sqlite/libsqlite/src/parse.y"
21595 +{sqliteAddColumnType(pParse,&yymsp[0].minor.yy0,&yymsp[0].minor.yy0);}
21596 +#line 1872 "ext/sqlite/libsqlite/src/parse.c"
21598 + case 33: /* type ::= typename LP signed RP */
21599 +#line 161 "ext/sqlite/libsqlite/src/parse.y"
21600 +{sqliteAddColumnType(pParse,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0);}
21601 +#line 1877 "ext/sqlite/libsqlite/src/parse.c"
21603 + case 34: /* type ::= typename LP signed COMMA signed RP */
21604 +#line 163 "ext/sqlite/libsqlite/src/parse.y"
21605 +{sqliteAddColumnType(pParse,&yymsp[-5].minor.yy0,&yymsp[0].minor.yy0);}
21606 +#line 1882 "ext/sqlite/libsqlite/src/parse.c"
21608 + case 36: /* typename ::= typename ids */
21609 + case 242: /* idxitem ::= nm sortorder */ yytestcase(yyruleno==242);
21610 +#line 166 "ext/sqlite/libsqlite/src/parse.y"
21611 +{yygotominor.yy0 = yymsp[-1].minor.yy0;}
21612 +#line 1888 "ext/sqlite/libsqlite/src/parse.c"
21614 + case 37: /* signed ::= INTEGER */
21615 + case 38: /* signed ::= PLUS INTEGER */ yytestcase(yyruleno==38);
21616 +#line 168 "ext/sqlite/libsqlite/src/parse.y"
21617 +{ yygotominor.yy372 = atoi(yymsp[0].minor.yy0.z); }
21618 +#line 1894 "ext/sqlite/libsqlite/src/parse.c"
21620 + case 39: /* signed ::= MINUS INTEGER */
21621 +#line 170 "ext/sqlite/libsqlite/src/parse.y"
21622 +{ yygotominor.yy372 = -atoi(yymsp[0].minor.yy0.z); }
21623 +#line 1899 "ext/sqlite/libsqlite/src/parse.c"
21625 + case 44: /* carg ::= DEFAULT STRING */
21626 + case 45: /* carg ::= DEFAULT ID */ yytestcase(yyruleno==45);
21627 + case 46: /* carg ::= DEFAULT INTEGER */ yytestcase(yyruleno==46);
21628 + case 47: /* carg ::= DEFAULT PLUS INTEGER */ yytestcase(yyruleno==47);
21629 + case 49: /* carg ::= DEFAULT FLOAT */ yytestcase(yyruleno==49);
21630 + case 50: /* carg ::= DEFAULT PLUS FLOAT */ yytestcase(yyruleno==50);
21631 +#line 175 "ext/sqlite/libsqlite/src/parse.y"
21632 +{sqliteAddDefaultValue(pParse,&yymsp[0].minor.yy0,0);}
21633 +#line 1909 "ext/sqlite/libsqlite/src/parse.c"
21635 + case 48: /* carg ::= DEFAULT MINUS INTEGER */
21636 + case 51: /* carg ::= DEFAULT MINUS FLOAT */ yytestcase(yyruleno==51);
21637 +#line 179 "ext/sqlite/libsqlite/src/parse.y"
21638 +{sqliteAddDefaultValue(pParse,&yymsp[0].minor.yy0,1);}
21639 +#line 1915 "ext/sqlite/libsqlite/src/parse.c"
21641 + case 54: /* ccons ::= NOT NULL onconf */
21642 +#line 189 "ext/sqlite/libsqlite/src/parse.y"
21643 +{sqliteAddNotNull(pParse, yymsp[0].minor.yy372);}
21644 +#line 1920 "ext/sqlite/libsqlite/src/parse.c"
21646 + case 55: /* ccons ::= PRIMARY KEY sortorder onconf */
21647 +#line 190 "ext/sqlite/libsqlite/src/parse.y"
21648 +{sqliteAddPrimaryKey(pParse,0,yymsp[0].minor.yy372);}
21649 +#line 1925 "ext/sqlite/libsqlite/src/parse.c"
21651 + case 56: /* ccons ::= UNIQUE onconf */
21652 +#line 191 "ext/sqlite/libsqlite/src/parse.y"
21653 +{sqliteCreateIndex(pParse,0,0,0,yymsp[0].minor.yy372,0,0);}
21654 +#line 1930 "ext/sqlite/libsqlite/src/parse.c"
21656 + case 57: /* ccons ::= CHECK LP expr RP onconf */
21657 +#line 192 "ext/sqlite/libsqlite/src/parse.y"
21659 + yy_destructor(yypParser,158,&yymsp[-2].minor);
21661 +#line 1937 "ext/sqlite/libsqlite/src/parse.c"
21663 + case 58: /* ccons ::= REFERENCES nm idxlist_opt refargs */
21664 +#line 194 "ext/sqlite/libsqlite/src/parse.y"
21665 +{sqliteCreateForeignKey(pParse,0,&yymsp[-2].minor.yy0,yymsp[-1].minor.yy320,yymsp[0].minor.yy372);}
21666 +#line 1942 "ext/sqlite/libsqlite/src/parse.c"
21668 + case 59: /* ccons ::= defer_subclause */
21669 +#line 195 "ext/sqlite/libsqlite/src/parse.y"
21670 +{sqliteDeferForeignKey(pParse,yymsp[0].minor.yy372);}
21671 +#line 1947 "ext/sqlite/libsqlite/src/parse.c"
21673 + case 60: /* ccons ::= COLLATE id */
21674 +#line 196 "ext/sqlite/libsqlite/src/parse.y"
21676 + sqliteAddCollateType(pParse, sqliteCollateType(yymsp[0].minor.yy0.z, yymsp[0].minor.yy0.n));
21678 +#line 1954 "ext/sqlite/libsqlite/src/parse.c"
21680 + case 61: /* refargs ::= */
21681 +#line 206 "ext/sqlite/libsqlite/src/parse.y"
21682 +{ yygotominor.yy372 = OE_Restrict * 0x010101; }
21683 +#line 1959 "ext/sqlite/libsqlite/src/parse.c"
21685 + case 62: /* refargs ::= refargs refarg */
21686 +#line 207 "ext/sqlite/libsqlite/src/parse.y"
21687 +{ yygotominor.yy372 = (yymsp[-1].minor.yy372 & yymsp[0].minor.yy407.mask) | yymsp[0].minor.yy407.value; }
21688 +#line 1964 "ext/sqlite/libsqlite/src/parse.c"
21690 + case 63: /* refarg ::= MATCH nm */
21691 +#line 209 "ext/sqlite/libsqlite/src/parse.y"
21692 +{ yygotominor.yy407.value = 0; yygotominor.yy407.mask = 0x000000; }
21693 +#line 1969 "ext/sqlite/libsqlite/src/parse.c"
21695 + case 64: /* refarg ::= ON DELETE refact */
21696 +#line 210 "ext/sqlite/libsqlite/src/parse.y"
21697 +{ yygotominor.yy407.value = yymsp[0].minor.yy372; yygotominor.yy407.mask = 0x0000ff; }
21698 +#line 1974 "ext/sqlite/libsqlite/src/parse.c"
21700 + case 65: /* refarg ::= ON UPDATE refact */
21701 +#line 211 "ext/sqlite/libsqlite/src/parse.y"
21702 +{ yygotominor.yy407.value = yymsp[0].minor.yy372<<8; yygotominor.yy407.mask = 0x00ff00; }
21703 +#line 1979 "ext/sqlite/libsqlite/src/parse.c"
21705 + case 66: /* refarg ::= ON INSERT refact */
21706 +#line 212 "ext/sqlite/libsqlite/src/parse.y"
21707 +{ yygotominor.yy407.value = yymsp[0].minor.yy372<<16; yygotominor.yy407.mask = 0xff0000; }
21708 +#line 1984 "ext/sqlite/libsqlite/src/parse.c"
21710 + case 67: /* refact ::= SET NULL */
21711 +#line 214 "ext/sqlite/libsqlite/src/parse.y"
21712 +{ yygotominor.yy372 = OE_SetNull; }
21713 +#line 1989 "ext/sqlite/libsqlite/src/parse.c"
21715 + case 68: /* refact ::= SET DEFAULT */
21716 +#line 215 "ext/sqlite/libsqlite/src/parse.y"
21717 +{ yygotominor.yy372 = OE_SetDflt; }
21718 +#line 1994 "ext/sqlite/libsqlite/src/parse.c"
21720 + case 69: /* refact ::= CASCADE */
21721 +#line 216 "ext/sqlite/libsqlite/src/parse.y"
21722 +{ yygotominor.yy372 = OE_Cascade; }
21723 +#line 1999 "ext/sqlite/libsqlite/src/parse.c"
21725 + case 70: /* refact ::= RESTRICT */
21726 +#line 217 "ext/sqlite/libsqlite/src/parse.y"
21727 +{ yygotominor.yy372 = OE_Restrict; }
21728 +#line 2004 "ext/sqlite/libsqlite/src/parse.c"
21730 + case 71: /* defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */
21731 + case 72: /* defer_subclause ::= DEFERRABLE init_deferred_pred_opt */ yytestcase(yyruleno==72);
21732 + case 87: /* defer_subclause_opt ::= defer_subclause */ yytestcase(yyruleno==87);
21733 + case 164: /* insert_cmd ::= INSERT orconf */ yytestcase(yyruleno==164);
21734 +#line 219 "ext/sqlite/libsqlite/src/parse.y"
21735 +{yygotominor.yy372 = yymsp[0].minor.yy372;}
21736 +#line 2012 "ext/sqlite/libsqlite/src/parse.c"
21738 + case 82: /* tcons ::= PRIMARY KEY LP idxlist RP onconf */
21739 +#line 236 "ext/sqlite/libsqlite/src/parse.y"
21740 +{sqliteAddPrimaryKey(pParse,yymsp[-2].minor.yy320,yymsp[0].minor.yy372);}
21741 +#line 2017 "ext/sqlite/libsqlite/src/parse.c"
21743 + case 83: /* tcons ::= UNIQUE LP idxlist RP onconf */
21744 +#line 238 "ext/sqlite/libsqlite/src/parse.y"
21745 +{sqliteCreateIndex(pParse,0,0,yymsp[-2].minor.yy320,yymsp[0].minor.yy372,0,0);}
21746 +#line 2022 "ext/sqlite/libsqlite/src/parse.c"
21748 + case 84: /* tcons ::= CHECK expr onconf */
21749 +#line 239 "ext/sqlite/libsqlite/src/parse.y"
21751 + yy_destructor(yypParser,158,&yymsp[-1].minor);
21753 +#line 2029 "ext/sqlite/libsqlite/src/parse.c"
21755 + case 85: /* tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt */
21756 +#line 241 "ext/sqlite/libsqlite/src/parse.y"
21758 + sqliteCreateForeignKey(pParse, yymsp[-6].minor.yy320, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy320, yymsp[-1].minor.yy372);
21759 + sqliteDeferForeignKey(pParse, yymsp[0].minor.yy372);
21761 +#line 2037 "ext/sqlite/libsqlite/src/parse.c"
21763 + case 88: /* onconf ::= */
21764 + case 90: /* orconf ::= */ yytestcase(yyruleno==90);
21765 +#line 255 "ext/sqlite/libsqlite/src/parse.y"
21766 +{ yygotominor.yy372 = OE_Default; }
21767 +#line 2043 "ext/sqlite/libsqlite/src/parse.c"
21769 + case 89: /* onconf ::= ON CONFLICT resolvetype */
21770 + case 91: /* orconf ::= OR resolvetype */ yytestcase(yyruleno==91);
21771 +#line 256 "ext/sqlite/libsqlite/src/parse.y"
21772 +{ yygotominor.yy372 = yymsp[0].minor.yy372; }
21773 +#line 2049 "ext/sqlite/libsqlite/src/parse.c"
21775 + case 92: /* resolvetype ::= ROLLBACK */
21776 +#line 259 "ext/sqlite/libsqlite/src/parse.y"
21777 +{ yygotominor.yy372 = OE_Rollback; }
21778 +#line 2054 "ext/sqlite/libsqlite/src/parse.c"
21780 + case 93: /* resolvetype ::= ABORT */
21781 + case 236: /* uniqueflag ::= UNIQUE */ yytestcase(yyruleno==236);
21782 +#line 260 "ext/sqlite/libsqlite/src/parse.y"
21783 +{ yygotominor.yy372 = OE_Abort; }
21784 +#line 2060 "ext/sqlite/libsqlite/src/parse.c"
21786 + case 94: /* resolvetype ::= FAIL */
21787 +#line 261 "ext/sqlite/libsqlite/src/parse.y"
21788 +{ yygotominor.yy372 = OE_Fail; }
21789 +#line 2065 "ext/sqlite/libsqlite/src/parse.c"
21791 + case 95: /* resolvetype ::= IGNORE */
21792 +#line 262 "ext/sqlite/libsqlite/src/parse.y"
21793 +{ yygotominor.yy372 = OE_Ignore; }
21794 +#line 2070 "ext/sqlite/libsqlite/src/parse.c"
21796 + case 96: /* resolvetype ::= REPLACE */
21797 +#line 263 "ext/sqlite/libsqlite/src/parse.y"
21798 +{ yygotominor.yy372 = OE_Replace; }
21799 +#line 2075 "ext/sqlite/libsqlite/src/parse.c"
21801 + case 97: /* cmd ::= DROP TABLE nm */
21802 +#line 267 "ext/sqlite/libsqlite/src/parse.y"
21803 +{sqliteDropTable(pParse,&yymsp[0].minor.yy0,0);}
21804 +#line 2080 "ext/sqlite/libsqlite/src/parse.c"
21806 + case 98: /* cmd ::= CREATE temp VIEW nm AS select */
21807 +#line 271 "ext/sqlite/libsqlite/src/parse.y"
21809 + sqliteCreateView(pParse, &yymsp[-5].minor.yy0, &yymsp[-2].minor.yy0, yymsp[0].minor.yy179, yymsp[-4].minor.yy372);
21811 +#line 2087 "ext/sqlite/libsqlite/src/parse.c"
21813 + case 99: /* cmd ::= DROP VIEW nm */
21814 +#line 274 "ext/sqlite/libsqlite/src/parse.y"
21816 + sqliteDropTable(pParse, &yymsp[0].minor.yy0, 1);
21818 +#line 2094 "ext/sqlite/libsqlite/src/parse.c"
21820 + case 100: /* cmd ::= select */
21821 +#line 280 "ext/sqlite/libsqlite/src/parse.y"
21823 + sqliteSelect(pParse, yymsp[0].minor.yy179, SRT_Callback, 0, 0, 0, 0);
21824 + sqliteSelectDelete(yymsp[0].minor.yy179);
21826 +#line 2102 "ext/sqlite/libsqlite/src/parse.c"
21828 + case 101: /* select ::= oneselect */
21829 + case 125: /* seltablist_paren ::= select */ yytestcase(yyruleno==125);
21830 +#line 290 "ext/sqlite/libsqlite/src/parse.y"
21831 +{yygotominor.yy179 = yymsp[0].minor.yy179;}
21832 +#line 2108 "ext/sqlite/libsqlite/src/parse.c"
21834 + case 102: /* select ::= select multiselect_op oneselect */
21835 +#line 291 "ext/sqlite/libsqlite/src/parse.y"
21837 + if( yymsp[0].minor.yy179 ){
21838 + yymsp[0].minor.yy179->op = yymsp[-1].minor.yy372;
21839 + yymsp[0].minor.yy179->pPrior = yymsp[-2].minor.yy179;
21841 + yygotominor.yy179 = yymsp[0].minor.yy179;
21843 +#line 2119 "ext/sqlite/libsqlite/src/parse.c"
21845 + case 103: /* multiselect_op ::= UNION */
21846 +#line 299 "ext/sqlite/libsqlite/src/parse.y"
21847 +{yygotominor.yy372 = TK_UNION;}
21848 +#line 2124 "ext/sqlite/libsqlite/src/parse.c"
21850 + case 104: /* multiselect_op ::= UNION ALL */
21851 +#line 300 "ext/sqlite/libsqlite/src/parse.y"
21852 +{yygotominor.yy372 = TK_ALL;}
21853 +#line 2129 "ext/sqlite/libsqlite/src/parse.c"
21855 + case 105: /* multiselect_op ::= INTERSECT */
21856 +#line 301 "ext/sqlite/libsqlite/src/parse.y"
21857 +{yygotominor.yy372 = TK_INTERSECT;}
21858 +#line 2134 "ext/sqlite/libsqlite/src/parse.c"
21860 + case 106: /* multiselect_op ::= EXCEPT */
21861 +#line 302 "ext/sqlite/libsqlite/src/parse.y"
21862 +{yygotominor.yy372 = TK_EXCEPT;}
21863 +#line 2139 "ext/sqlite/libsqlite/src/parse.c"
21865 + case 107: /* oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */
21866 +#line 304 "ext/sqlite/libsqlite/src/parse.y"
21868 + yygotominor.yy179 = sqliteSelectNew(yymsp[-6].minor.yy322,yymsp[-5].minor.yy307,yymsp[-4].minor.yy242,yymsp[-3].minor.yy322,yymsp[-2].minor.yy242,yymsp[-1].minor.yy322,yymsp[-7].minor.yy372,yymsp[0].minor.yy124.limit,yymsp[0].minor.yy124.offset);
21870 +#line 2146 "ext/sqlite/libsqlite/src/parse.c"
21872 + case 111: /* sclp ::= selcollist COMMA */
21873 +#line 325 "ext/sqlite/libsqlite/src/parse.y"
21874 +{yygotominor.yy322 = yymsp[-1].minor.yy322;}
21875 +#line 2151 "ext/sqlite/libsqlite/src/parse.c"
21877 + case 112: /* sclp ::= */
21878 + case 138: /* orderby_opt ::= */ yytestcase(yyruleno==138);
21879 + case 148: /* groupby_opt ::= */ yytestcase(yyruleno==148);
21880 +#line 326 "ext/sqlite/libsqlite/src/parse.y"
21881 +{yygotominor.yy322 = 0;}
21882 +#line 2158 "ext/sqlite/libsqlite/src/parse.c"
21884 + case 113: /* selcollist ::= sclp expr as */
21885 +#line 327 "ext/sqlite/libsqlite/src/parse.y"
21887 + yygotominor.yy322 = sqliteExprListAppend(yymsp[-2].minor.yy322,yymsp[-1].minor.yy242,yymsp[0].minor.yy0.n?&yymsp[0].minor.yy0:0);
21889 +#line 2165 "ext/sqlite/libsqlite/src/parse.c"
21891 + case 114: /* selcollist ::= sclp STAR */
21892 +#line 330 "ext/sqlite/libsqlite/src/parse.y"
21894 + yygotominor.yy322 = sqliteExprListAppend(yymsp[-1].minor.yy322, sqliteExpr(TK_ALL, 0, 0, 0), 0);
21896 +#line 2172 "ext/sqlite/libsqlite/src/parse.c"
21898 + case 115: /* selcollist ::= sclp nm DOT STAR */
21899 +#line 333 "ext/sqlite/libsqlite/src/parse.y"
21901 + Expr *pRight = sqliteExpr(TK_ALL, 0, 0, 0);
21902 + Expr *pLeft = sqliteExpr(TK_ID, 0, 0, &yymsp[-2].minor.yy0);
21903 + yygotominor.yy322 = sqliteExprListAppend(yymsp[-3].minor.yy322, sqliteExpr(TK_DOT, pLeft, pRight, 0), 0);
21905 +#line 2181 "ext/sqlite/libsqlite/src/parse.c"
21907 + case 116: /* as ::= AS nm */
21908 + case 117: /* as ::= ids */ yytestcase(yyruleno==117);
21909 + case 288: /* key_opt ::= USING ids */ yytestcase(yyruleno==288);
21910 +#line 343 "ext/sqlite/libsqlite/src/parse.y"
21911 +{ yygotominor.yy0 = yymsp[0].minor.yy0; }
21912 +#line 2188 "ext/sqlite/libsqlite/src/parse.c"
21914 + case 118: /* as ::= */
21915 +#line 345 "ext/sqlite/libsqlite/src/parse.y"
21916 +{ yygotominor.yy0.n = 0; }
21917 +#line 2193 "ext/sqlite/libsqlite/src/parse.c"
21919 + case 119: /* from ::= */
21920 +#line 357 "ext/sqlite/libsqlite/src/parse.y"
21921 +{yygotominor.yy307 = sqliteMalloc(sizeof(*yygotominor.yy307));}
21922 +#line 2198 "ext/sqlite/libsqlite/src/parse.c"
21924 + case 120: /* from ::= FROM seltablist */
21925 +#line 358 "ext/sqlite/libsqlite/src/parse.y"
21926 +{yygotominor.yy307 = yymsp[0].minor.yy307;}
21927 +#line 2203 "ext/sqlite/libsqlite/src/parse.c"
21929 + case 121: /* stl_prefix ::= seltablist joinop */
21930 +#line 363 "ext/sqlite/libsqlite/src/parse.y"
21932 + yygotominor.yy307 = yymsp[-1].minor.yy307;
21933 + if( yygotominor.yy307 && yygotominor.yy307->nSrc>0 ) yygotominor.yy307->a[yygotominor.yy307->nSrc-1].jointype = yymsp[0].minor.yy372;
21935 +#line 2211 "ext/sqlite/libsqlite/src/parse.c"
21937 + case 122: /* stl_prefix ::= */
21938 +#line 367 "ext/sqlite/libsqlite/src/parse.y"
21939 +{yygotominor.yy307 = 0;}
21940 +#line 2216 "ext/sqlite/libsqlite/src/parse.c"
21942 + case 123: /* seltablist ::= stl_prefix nm dbnm as on_opt using_opt */
21943 +#line 368 "ext/sqlite/libsqlite/src/parse.y"
21945 + yygotominor.yy307 = sqliteSrcListAppend(yymsp[-5].minor.yy307,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0);
21946 + if( yymsp[-2].minor.yy0.n ) sqliteSrcListAddAlias(yygotominor.yy307,&yymsp[-2].minor.yy0);
21947 + if( yymsp[-1].minor.yy242 ){
21948 + if( yygotominor.yy307 && yygotominor.yy307->nSrc>1 ){ yygotominor.yy307->a[yygotominor.yy307->nSrc-2].pOn = yymsp[-1].minor.yy242; }
21949 + else { sqliteExprDelete(yymsp[-1].minor.yy242); }
21951 + if( yymsp[0].minor.yy320 ){
21952 + if( yygotominor.yy307 && yygotominor.yy307->nSrc>1 ){ yygotominor.yy307->a[yygotominor.yy307->nSrc-2].pUsing = yymsp[0].minor.yy320; }
21953 + else { sqliteIdListDelete(yymsp[0].minor.yy320); }
21956 +#line 2232 "ext/sqlite/libsqlite/src/parse.c"
21958 + case 124: /* seltablist ::= stl_prefix LP seltablist_paren RP as on_opt using_opt */
21959 +#line 381 "ext/sqlite/libsqlite/src/parse.y"
21961 + yygotominor.yy307 = sqliteSrcListAppend(yymsp[-6].minor.yy307,0,0);
21962 + yygotominor.yy307->a[yygotominor.yy307->nSrc-1].pSelect = yymsp[-4].minor.yy179;
21963 + if( yymsp[-2].minor.yy0.n ) sqliteSrcListAddAlias(yygotominor.yy307,&yymsp[-2].minor.yy0);
21964 + if( yymsp[-1].minor.yy242 ){
21965 + if( yygotominor.yy307 && yygotominor.yy307->nSrc>1 ){ yygotominor.yy307->a[yygotominor.yy307->nSrc-2].pOn = yymsp[-1].minor.yy242; }
21966 + else { sqliteExprDelete(yymsp[-1].minor.yy242); }
21968 + if( yymsp[0].minor.yy320 ){
21969 + if( yygotominor.yy307 && yygotominor.yy307->nSrc>1 ){ yygotominor.yy307->a[yygotominor.yy307->nSrc-2].pUsing = yymsp[0].minor.yy320; }
21970 + else { sqliteIdListDelete(yymsp[0].minor.yy320); }
21973 +#line 2249 "ext/sqlite/libsqlite/src/parse.c"
21975 + case 126: /* seltablist_paren ::= seltablist */
21976 +#line 402 "ext/sqlite/libsqlite/src/parse.y"
21978 + yygotominor.yy179 = sqliteSelectNew(0,yymsp[0].minor.yy307,0,0,0,0,0,-1,0);
21980 +#line 2256 "ext/sqlite/libsqlite/src/parse.c"
21982 + case 127: /* dbnm ::= */
21983 +#line 407 "ext/sqlite/libsqlite/src/parse.y"
21984 +{yygotominor.yy0.z=0; yygotominor.yy0.n=0;}
21985 +#line 2261 "ext/sqlite/libsqlite/src/parse.c"
21987 + case 129: /* joinop ::= COMMA */
21988 + case 130: /* joinop ::= JOIN */ yytestcase(yyruleno==130);
21989 +#line 412 "ext/sqlite/libsqlite/src/parse.y"
21990 +{ yygotominor.yy372 = JT_INNER; }
21991 +#line 2267 "ext/sqlite/libsqlite/src/parse.c"
21993 + case 131: /* joinop ::= JOIN_KW JOIN */
21994 +#line 414 "ext/sqlite/libsqlite/src/parse.y"
21995 +{ yygotominor.yy372 = sqliteJoinType(pParse,&yymsp[-1].minor.yy0,0,0); }
21996 +#line 2272 "ext/sqlite/libsqlite/src/parse.c"
21998 + case 132: /* joinop ::= JOIN_KW nm JOIN */
21999 +#line 415 "ext/sqlite/libsqlite/src/parse.y"
22000 +{ yygotominor.yy372 = sqliteJoinType(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,0); }
22001 +#line 2277 "ext/sqlite/libsqlite/src/parse.c"
22003 + case 133: /* joinop ::= JOIN_KW nm nm JOIN */
22004 +#line 417 "ext/sqlite/libsqlite/src/parse.y"
22005 +{ yygotominor.yy372 = sqliteJoinType(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0); }
22006 +#line 2282 "ext/sqlite/libsqlite/src/parse.c"
22008 + case 134: /* on_opt ::= ON expr */
22009 + case 142: /* sortitem ::= expr */ yytestcase(yyruleno==142);
22010 + case 151: /* having_opt ::= HAVING expr */ yytestcase(yyruleno==151);
22011 + case 158: /* where_opt ::= WHERE expr */ yytestcase(yyruleno==158);
22012 + case 227: /* case_else ::= ELSE expr */ yytestcase(yyruleno==227);
22013 + case 229: /* case_operand ::= expr */ yytestcase(yyruleno==229);
22014 + case 233: /* expritem ::= expr */ yytestcase(yyruleno==233);
22015 +#line 421 "ext/sqlite/libsqlite/src/parse.y"
22016 +{yygotominor.yy242 = yymsp[0].minor.yy242;}
22017 +#line 2293 "ext/sqlite/libsqlite/src/parse.c"
22019 + case 135: /* on_opt ::= */
22020 + case 150: /* having_opt ::= */ yytestcase(yyruleno==150);
22021 + case 157: /* where_opt ::= */ yytestcase(yyruleno==157);
22022 + case 228: /* case_else ::= */ yytestcase(yyruleno==228);
22023 + case 230: /* case_operand ::= */ yytestcase(yyruleno==230);
22024 + case 234: /* expritem ::= */ yytestcase(yyruleno==234);
22025 +#line 422 "ext/sqlite/libsqlite/src/parse.y"
22026 +{yygotominor.yy242 = 0;}
22027 +#line 2303 "ext/sqlite/libsqlite/src/parse.c"
22029 + case 136: /* using_opt ::= USING LP idxlist RP */
22030 + case 169: /* inscollist_opt ::= LP inscollist RP */ yytestcase(yyruleno==169);
22031 + case 239: /* idxlist_opt ::= LP idxlist RP */ yytestcase(yyruleno==239);
22032 +#line 426 "ext/sqlite/libsqlite/src/parse.y"
22033 +{yygotominor.yy320 = yymsp[-1].minor.yy320;}
22034 +#line 2310 "ext/sqlite/libsqlite/src/parse.c"
22036 + case 137: /* using_opt ::= */
22037 + case 168: /* inscollist_opt ::= */ yytestcase(yyruleno==168);
22038 + case 238: /* idxlist_opt ::= */ yytestcase(yyruleno==238);
22039 +#line 427 "ext/sqlite/libsqlite/src/parse.y"
22040 +{yygotominor.yy320 = 0;}
22041 +#line 2317 "ext/sqlite/libsqlite/src/parse.c"
22043 + case 139: /* orderby_opt ::= ORDER BY sortlist */
22044 + case 149: /* groupby_opt ::= GROUP BY exprlist */ yytestcase(yyruleno==149);
22045 +#line 438 "ext/sqlite/libsqlite/src/parse.y"
22046 +{yygotominor.yy322 = yymsp[0].minor.yy322;}
22047 +#line 2323 "ext/sqlite/libsqlite/src/parse.c"
22049 + case 140: /* sortlist ::= sortlist COMMA sortitem collate sortorder */
22050 +#line 439 "ext/sqlite/libsqlite/src/parse.y"
22052 + yygotominor.yy322 = sqliteExprListAppend(yymsp[-4].minor.yy322,yymsp[-2].minor.yy242,0);
22053 + if( yygotominor.yy322 ) yygotominor.yy322->a[yygotominor.yy322->nExpr-1].sortOrder = yymsp[-1].minor.yy372+yymsp[0].minor.yy372;
22055 +#line 2331 "ext/sqlite/libsqlite/src/parse.c"
22057 + case 141: /* sortlist ::= sortitem collate sortorder */
22058 +#line 443 "ext/sqlite/libsqlite/src/parse.y"
22060 + yygotominor.yy322 = sqliteExprListAppend(0,yymsp[-2].minor.yy242,0);
22061 + if( yygotominor.yy322 ) yygotominor.yy322->a[0].sortOrder = yymsp[-1].minor.yy372+yymsp[0].minor.yy372;
22063 +#line 2339 "ext/sqlite/libsqlite/src/parse.c"
22065 + case 143: /* sortorder ::= ASC */
22066 + case 145: /* sortorder ::= */ yytestcase(yyruleno==145);
22067 +#line 452 "ext/sqlite/libsqlite/src/parse.y"
22068 +{yygotominor.yy372 = SQLITE_SO_ASC;}
22069 +#line 2345 "ext/sqlite/libsqlite/src/parse.c"
22071 + case 144: /* sortorder ::= DESC */
22072 +#line 453 "ext/sqlite/libsqlite/src/parse.y"
22073 +{yygotominor.yy372 = SQLITE_SO_DESC;}
22074 +#line 2350 "ext/sqlite/libsqlite/src/parse.c"
22076 + case 146: /* collate ::= */
22077 +#line 455 "ext/sqlite/libsqlite/src/parse.y"
22078 +{yygotominor.yy372 = SQLITE_SO_UNK;}
22079 +#line 2355 "ext/sqlite/libsqlite/src/parse.c"
22081 + case 147: /* collate ::= COLLATE id */
22082 +#line 456 "ext/sqlite/libsqlite/src/parse.y"
22083 +{yygotominor.yy372 = sqliteCollateType(yymsp[0].minor.yy0.z, yymsp[0].minor.yy0.n);}
22084 +#line 2360 "ext/sqlite/libsqlite/src/parse.c"
22086 + case 152: /* limit_opt ::= */
22087 +#line 469 "ext/sqlite/libsqlite/src/parse.y"
22088 +{yygotominor.yy124.limit = -1; yygotominor.yy124.offset = 0;}
22089 +#line 2365 "ext/sqlite/libsqlite/src/parse.c"
22091 + case 153: /* limit_opt ::= LIMIT signed */
22092 +#line 470 "ext/sqlite/libsqlite/src/parse.y"
22093 +{yygotominor.yy124.limit = yymsp[0].minor.yy372; yygotominor.yy124.offset = 0;}
22094 +#line 2370 "ext/sqlite/libsqlite/src/parse.c"
22096 + case 154: /* limit_opt ::= LIMIT signed OFFSET signed */
22097 +#line 472 "ext/sqlite/libsqlite/src/parse.y"
22098 +{yygotominor.yy124.limit = yymsp[-2].minor.yy372; yygotominor.yy124.offset = yymsp[0].minor.yy372;}
22099 +#line 2375 "ext/sqlite/libsqlite/src/parse.c"
22101 + case 155: /* limit_opt ::= LIMIT signed COMMA signed */
22102 +#line 474 "ext/sqlite/libsqlite/src/parse.y"
22103 +{yygotominor.yy124.limit = yymsp[0].minor.yy372; yygotominor.yy124.offset = yymsp[-2].minor.yy372;}
22104 +#line 2380 "ext/sqlite/libsqlite/src/parse.c"
22106 + case 156: /* cmd ::= DELETE FROM nm dbnm where_opt */
22107 +#line 478 "ext/sqlite/libsqlite/src/parse.y"
22109 + sqliteDeleteFrom(pParse, sqliteSrcListAppend(0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0), yymsp[0].minor.yy242);
22111 +#line 2387 "ext/sqlite/libsqlite/src/parse.c"
22113 + case 159: /* cmd ::= UPDATE orconf nm dbnm SET setlist where_opt */
22114 +#line 494 "ext/sqlite/libsqlite/src/parse.y"
22115 +{sqliteUpdate(pParse,sqliteSrcListAppend(0,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0),yymsp[-1].minor.yy322,yymsp[0].minor.yy242,yymsp[-5].minor.yy372);}
22116 +#line 2392 "ext/sqlite/libsqlite/src/parse.c"
22118 + case 160: /* setlist ::= setlist COMMA nm EQ expr */
22119 +#line 497 "ext/sqlite/libsqlite/src/parse.y"
22120 +{yygotominor.yy322 = sqliteExprListAppend(yymsp[-4].minor.yy322,yymsp[0].minor.yy242,&yymsp[-2].minor.yy0);}
22121 +#line 2397 "ext/sqlite/libsqlite/src/parse.c"
22123 + case 161: /* setlist ::= nm EQ expr */
22124 +#line 498 "ext/sqlite/libsqlite/src/parse.y"
22125 +{yygotominor.yy322 = sqliteExprListAppend(0,yymsp[0].minor.yy242,&yymsp[-2].minor.yy0);}
22126 +#line 2402 "ext/sqlite/libsqlite/src/parse.c"
22128 + case 162: /* cmd ::= insert_cmd INTO nm dbnm inscollist_opt VALUES LP itemlist RP */
22129 +#line 504 "ext/sqlite/libsqlite/src/parse.y"
22130 +{sqliteInsert(pParse, sqliteSrcListAppend(0,&yymsp[-6].minor.yy0,&yymsp[-5].minor.yy0), yymsp[-1].minor.yy322, 0, yymsp[-4].minor.yy320, yymsp[-8].minor.yy372);}
22131 +#line 2407 "ext/sqlite/libsqlite/src/parse.c"
22133 + case 163: /* cmd ::= insert_cmd INTO nm dbnm inscollist_opt select */
22134 +#line 506 "ext/sqlite/libsqlite/src/parse.y"
22135 +{sqliteInsert(pParse, sqliteSrcListAppend(0,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0), 0, yymsp[0].minor.yy179, yymsp[-1].minor.yy320, yymsp[-5].minor.yy372);}
22136 +#line 2412 "ext/sqlite/libsqlite/src/parse.c"
22138 + case 165: /* insert_cmd ::= REPLACE */
22139 +#line 510 "ext/sqlite/libsqlite/src/parse.y"
22140 +{yygotominor.yy372 = OE_Replace;}
22141 +#line 2417 "ext/sqlite/libsqlite/src/parse.c"
22143 + case 166: /* itemlist ::= itemlist COMMA expr */
22144 + case 231: /* exprlist ::= exprlist COMMA expritem */ yytestcase(yyruleno==231);
22145 +#line 516 "ext/sqlite/libsqlite/src/parse.y"
22146 +{yygotominor.yy322 = sqliteExprListAppend(yymsp[-2].minor.yy322,yymsp[0].minor.yy242,0);}
22147 +#line 2423 "ext/sqlite/libsqlite/src/parse.c"
22149 + case 167: /* itemlist ::= expr */
22150 + case 232: /* exprlist ::= expritem */ yytestcase(yyruleno==232);
22151 +#line 517 "ext/sqlite/libsqlite/src/parse.y"
22152 +{yygotominor.yy322 = sqliteExprListAppend(0,yymsp[0].minor.yy242,0);}
22153 +#line 2429 "ext/sqlite/libsqlite/src/parse.c"
22155 + case 170: /* inscollist ::= inscollist COMMA nm */
22156 + case 240: /* idxlist ::= idxlist COMMA idxitem */ yytestcase(yyruleno==240);
22157 +#line 526 "ext/sqlite/libsqlite/src/parse.y"
22158 +{yygotominor.yy320 = sqliteIdListAppend(yymsp[-2].minor.yy320,&yymsp[0].minor.yy0);}
22159 +#line 2435 "ext/sqlite/libsqlite/src/parse.c"
22161 + case 171: /* inscollist ::= nm */
22162 + case 241: /* idxlist ::= idxitem */ yytestcase(yyruleno==241);
22163 +#line 527 "ext/sqlite/libsqlite/src/parse.y"
22164 +{yygotominor.yy320 = sqliteIdListAppend(0,&yymsp[0].minor.yy0);}
22165 +#line 2441 "ext/sqlite/libsqlite/src/parse.c"
22167 + case 172: /* expr ::= LP expr RP */
22168 +#line 535 "ext/sqlite/libsqlite/src/parse.y"
22169 +{yygotominor.yy242 = yymsp[-1].minor.yy242; sqliteExprSpan(yygotominor.yy242,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0); }
22170 +#line 2446 "ext/sqlite/libsqlite/src/parse.c"
22172 + case 173: /* expr ::= NULL */
22173 +#line 536 "ext/sqlite/libsqlite/src/parse.y"
22174 +{yygotominor.yy242 = sqliteExpr(TK_NULL, 0, 0, &yymsp[0].minor.yy0);}
22175 +#line 2451 "ext/sqlite/libsqlite/src/parse.c"
22177 + case 174: /* expr ::= ID */
22178 + case 175: /* expr ::= JOIN_KW */ yytestcase(yyruleno==175);
22179 +#line 537 "ext/sqlite/libsqlite/src/parse.y"
22180 +{yygotominor.yy242 = sqliteExpr(TK_ID, 0, 0, &yymsp[0].minor.yy0);}
22181 +#line 2457 "ext/sqlite/libsqlite/src/parse.c"
22183 + case 176: /* expr ::= nm DOT nm */
22184 +#line 539 "ext/sqlite/libsqlite/src/parse.y"
22186 + Expr *temp1 = sqliteExpr(TK_ID, 0, 0, &yymsp[-2].minor.yy0);
22187 + Expr *temp2 = sqliteExpr(TK_ID, 0, 0, &yymsp[0].minor.yy0);
22188 + yygotominor.yy242 = sqliteExpr(TK_DOT, temp1, temp2, 0);
22190 +#line 2466 "ext/sqlite/libsqlite/src/parse.c"
22192 + case 177: /* expr ::= nm DOT nm DOT nm */
22193 +#line 544 "ext/sqlite/libsqlite/src/parse.y"
22195 + Expr *temp1 = sqliteExpr(TK_ID, 0, 0, &yymsp[-4].minor.yy0);
22196 + Expr *temp2 = sqliteExpr(TK_ID, 0, 0, &yymsp[-2].minor.yy0);
22197 + Expr *temp3 = sqliteExpr(TK_ID, 0, 0, &yymsp[0].minor.yy0);
22198 + Expr *temp4 = sqliteExpr(TK_DOT, temp2, temp3, 0);
22199 + yygotominor.yy242 = sqliteExpr(TK_DOT, temp1, temp4, 0);
22201 +#line 2477 "ext/sqlite/libsqlite/src/parse.c"
22203 + case 178: /* expr ::= INTEGER */
22204 +#line 551 "ext/sqlite/libsqlite/src/parse.y"
22205 +{yygotominor.yy242 = sqliteExpr(TK_INTEGER, 0, 0, &yymsp[0].minor.yy0);}
22206 +#line 2482 "ext/sqlite/libsqlite/src/parse.c"
22208 + case 179: /* expr ::= FLOAT */
22209 +#line 552 "ext/sqlite/libsqlite/src/parse.y"
22210 +{yygotominor.yy242 = sqliteExpr(TK_FLOAT, 0, 0, &yymsp[0].minor.yy0);}
22211 +#line 2487 "ext/sqlite/libsqlite/src/parse.c"
22213 + case 180: /* expr ::= STRING */
22214 +#line 553 "ext/sqlite/libsqlite/src/parse.y"
22215 +{yygotominor.yy242 = sqliteExpr(TK_STRING, 0, 0, &yymsp[0].minor.yy0);}
22216 +#line 2492 "ext/sqlite/libsqlite/src/parse.c"
22218 + case 181: /* expr ::= VARIABLE */
22219 +#line 554 "ext/sqlite/libsqlite/src/parse.y"
22221 + yygotominor.yy242 = sqliteExpr(TK_VARIABLE, 0, 0, &yymsp[0].minor.yy0);
22222 + if( yygotominor.yy242 ) yygotominor.yy242->iTable = ++pParse->nVar;
22224 +#line 2500 "ext/sqlite/libsqlite/src/parse.c"
22226 + case 182: /* expr ::= ID LP exprlist RP */
22227 +#line 558 "ext/sqlite/libsqlite/src/parse.y"
22229 + yygotominor.yy242 = sqliteExprFunction(yymsp[-1].minor.yy322, &yymsp[-3].minor.yy0);
22230 + sqliteExprSpan(yygotominor.yy242,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0);
22232 +#line 2508 "ext/sqlite/libsqlite/src/parse.c"
22234 + case 183: /* expr ::= ID LP STAR RP */
22235 +#line 562 "ext/sqlite/libsqlite/src/parse.y"
22237 + yygotominor.yy242 = sqliteExprFunction(0, &yymsp[-3].minor.yy0);
22238 + sqliteExprSpan(yygotominor.yy242,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0);
22240 +#line 2516 "ext/sqlite/libsqlite/src/parse.c"
22242 + case 184: /* expr ::= expr AND expr */
22243 +#line 566 "ext/sqlite/libsqlite/src/parse.y"
22244 +{yygotominor.yy242 = sqliteExpr(TK_AND, yymsp[-2].minor.yy242, yymsp[0].minor.yy242, 0);}
22245 +#line 2521 "ext/sqlite/libsqlite/src/parse.c"
22247 + case 185: /* expr ::= expr OR expr */
22248 +#line 567 "ext/sqlite/libsqlite/src/parse.y"
22249 +{yygotominor.yy242 = sqliteExpr(TK_OR, yymsp[-2].minor.yy242, yymsp[0].minor.yy242, 0);}
22250 +#line 2526 "ext/sqlite/libsqlite/src/parse.c"
22252 + case 186: /* expr ::= expr LT expr */
22253 +#line 568 "ext/sqlite/libsqlite/src/parse.y"
22254 +{yygotominor.yy242 = sqliteExpr(TK_LT, yymsp[-2].minor.yy242, yymsp[0].minor.yy242, 0);}
22255 +#line 2531 "ext/sqlite/libsqlite/src/parse.c"
22257 + case 187: /* expr ::= expr GT expr */
22258 +#line 569 "ext/sqlite/libsqlite/src/parse.y"
22259 +{yygotominor.yy242 = sqliteExpr(TK_GT, yymsp[-2].minor.yy242, yymsp[0].minor.yy242, 0);}
22260 +#line 2536 "ext/sqlite/libsqlite/src/parse.c"
22262 + case 188: /* expr ::= expr LE expr */
22263 +#line 570 "ext/sqlite/libsqlite/src/parse.y"
22264 +{yygotominor.yy242 = sqliteExpr(TK_LE, yymsp[-2].minor.yy242, yymsp[0].minor.yy242, 0);}
22265 +#line 2541 "ext/sqlite/libsqlite/src/parse.c"
22267 + case 189: /* expr ::= expr GE expr */
22268 +#line 571 "ext/sqlite/libsqlite/src/parse.y"
22269 +{yygotominor.yy242 = sqliteExpr(TK_GE, yymsp[-2].minor.yy242, yymsp[0].minor.yy242, 0);}
22270 +#line 2546 "ext/sqlite/libsqlite/src/parse.c"
22272 + case 190: /* expr ::= expr NE expr */
22273 +#line 572 "ext/sqlite/libsqlite/src/parse.y"
22274 +{yygotominor.yy242 = sqliteExpr(TK_NE, yymsp[-2].minor.yy242, yymsp[0].minor.yy242, 0);}
22275 +#line 2551 "ext/sqlite/libsqlite/src/parse.c"
22277 + case 191: /* expr ::= expr EQ expr */
22278 +#line 573 "ext/sqlite/libsqlite/src/parse.y"
22279 +{yygotominor.yy242 = sqliteExpr(TK_EQ, yymsp[-2].minor.yy242, yymsp[0].minor.yy242, 0);}
22280 +#line 2556 "ext/sqlite/libsqlite/src/parse.c"
22282 + case 192: /* expr ::= expr BITAND expr */
22283 +#line 574 "ext/sqlite/libsqlite/src/parse.y"
22284 +{yygotominor.yy242 = sqliteExpr(TK_BITAND, yymsp[-2].minor.yy242, yymsp[0].minor.yy242, 0);}
22285 +#line 2561 "ext/sqlite/libsqlite/src/parse.c"
22287 + case 193: /* expr ::= expr BITOR expr */
22288 +#line 575 "ext/sqlite/libsqlite/src/parse.y"
22289 +{yygotominor.yy242 = sqliteExpr(TK_BITOR, yymsp[-2].minor.yy242, yymsp[0].minor.yy242, 0);}
22290 +#line 2566 "ext/sqlite/libsqlite/src/parse.c"
22292 + case 194: /* expr ::= expr LSHIFT expr */
22293 +#line 576 "ext/sqlite/libsqlite/src/parse.y"
22294 +{yygotominor.yy242 = sqliteExpr(TK_LSHIFT, yymsp[-2].minor.yy242, yymsp[0].minor.yy242, 0);}
22295 +#line 2571 "ext/sqlite/libsqlite/src/parse.c"
22297 + case 195: /* expr ::= expr RSHIFT expr */
22298 +#line 577 "ext/sqlite/libsqlite/src/parse.y"
22299 +{yygotominor.yy242 = sqliteExpr(TK_RSHIFT, yymsp[-2].minor.yy242, yymsp[0].minor.yy242, 0);}
22300 +#line 2576 "ext/sqlite/libsqlite/src/parse.c"
22302 + case 196: /* expr ::= expr likeop expr */
22303 +#line 578 "ext/sqlite/libsqlite/src/parse.y"
22305 + ExprList *pList = sqliteExprListAppend(0, yymsp[0].minor.yy242, 0);
22306 + pList = sqliteExprListAppend(pList, yymsp[-2].minor.yy242, 0);
22307 + yygotominor.yy242 = sqliteExprFunction(pList, 0);
22308 + if( yygotominor.yy242 ) yygotominor.yy242->op = yymsp[-1].minor.yy372;
22309 + sqliteExprSpan(yygotominor.yy242, &yymsp[-2].minor.yy242->span, &yymsp[0].minor.yy242->span);
22311 +#line 2587 "ext/sqlite/libsqlite/src/parse.c"
22313 + case 197: /* expr ::= expr NOT likeop expr */
22314 +#line 585 "ext/sqlite/libsqlite/src/parse.y"
22316 + ExprList *pList = sqliteExprListAppend(0, yymsp[0].minor.yy242, 0);
22317 + pList = sqliteExprListAppend(pList, yymsp[-3].minor.yy242, 0);
22318 + yygotominor.yy242 = sqliteExprFunction(pList, 0);
22319 + if( yygotominor.yy242 ) yygotominor.yy242->op = yymsp[-1].minor.yy372;
22320 + yygotominor.yy242 = sqliteExpr(TK_NOT, yygotominor.yy242, 0, 0);
22321 + sqliteExprSpan(yygotominor.yy242,&yymsp[-3].minor.yy242->span,&yymsp[0].minor.yy242->span);
22323 +#line 2599 "ext/sqlite/libsqlite/src/parse.c"
22325 + case 198: /* likeop ::= LIKE */
22326 +#line 594 "ext/sqlite/libsqlite/src/parse.y"
22327 +{yygotominor.yy372 = TK_LIKE;}
22328 +#line 2604 "ext/sqlite/libsqlite/src/parse.c"
22330 + case 199: /* likeop ::= GLOB */
22331 +#line 595 "ext/sqlite/libsqlite/src/parse.y"
22332 +{yygotominor.yy372 = TK_GLOB;}
22333 +#line 2609 "ext/sqlite/libsqlite/src/parse.c"
22335 + case 200: /* expr ::= expr PLUS expr */
22336 +#line 596 "ext/sqlite/libsqlite/src/parse.y"
22337 +{yygotominor.yy242 = sqliteExpr(TK_PLUS, yymsp[-2].minor.yy242, yymsp[0].minor.yy242, 0);}
22338 +#line 2614 "ext/sqlite/libsqlite/src/parse.c"
22340 + case 201: /* expr ::= expr MINUS expr */
22341 +#line 597 "ext/sqlite/libsqlite/src/parse.y"
22342 +{yygotominor.yy242 = sqliteExpr(TK_MINUS, yymsp[-2].minor.yy242, yymsp[0].minor.yy242, 0);}
22343 +#line 2619 "ext/sqlite/libsqlite/src/parse.c"
22345 + case 202: /* expr ::= expr STAR expr */
22346 +#line 598 "ext/sqlite/libsqlite/src/parse.y"
22347 +{yygotominor.yy242 = sqliteExpr(TK_STAR, yymsp[-2].minor.yy242, yymsp[0].minor.yy242, 0);}
22348 +#line 2624 "ext/sqlite/libsqlite/src/parse.c"
22350 + case 203: /* expr ::= expr SLASH expr */
22351 +#line 599 "ext/sqlite/libsqlite/src/parse.y"
22352 +{yygotominor.yy242 = sqliteExpr(TK_SLASH, yymsp[-2].minor.yy242, yymsp[0].minor.yy242, 0);}
22353 +#line 2629 "ext/sqlite/libsqlite/src/parse.c"
22355 + case 204: /* expr ::= expr REM expr */
22356 +#line 600 "ext/sqlite/libsqlite/src/parse.y"
22357 +{yygotominor.yy242 = sqliteExpr(TK_REM, yymsp[-2].minor.yy242, yymsp[0].minor.yy242, 0);}
22358 +#line 2634 "ext/sqlite/libsqlite/src/parse.c"
22360 + case 205: /* expr ::= expr CONCAT expr */
22361 +#line 601 "ext/sqlite/libsqlite/src/parse.y"
22362 +{yygotominor.yy242 = sqliteExpr(TK_CONCAT, yymsp[-2].minor.yy242, yymsp[0].minor.yy242, 0);}
22363 +#line 2639 "ext/sqlite/libsqlite/src/parse.c"
22365 + case 206: /* expr ::= expr ISNULL */
22366 +#line 602 "ext/sqlite/libsqlite/src/parse.y"
22368 + yygotominor.yy242 = sqliteExpr(TK_ISNULL, yymsp[-1].minor.yy242, 0, 0);
22369 + sqliteExprSpan(yygotominor.yy242,&yymsp[-1].minor.yy242->span,&yymsp[0].minor.yy0);
22371 +#line 2647 "ext/sqlite/libsqlite/src/parse.c"
22373 + case 207: /* expr ::= expr IS NULL */
22374 +#line 606 "ext/sqlite/libsqlite/src/parse.y"
22376 + yygotominor.yy242 = sqliteExpr(TK_ISNULL, yymsp[-2].minor.yy242, 0, 0);
22377 + sqliteExprSpan(yygotominor.yy242,&yymsp[-2].minor.yy242->span,&yymsp[0].minor.yy0);
22379 +#line 2655 "ext/sqlite/libsqlite/src/parse.c"
22381 + case 208: /* expr ::= expr NOTNULL */
22382 +#line 610 "ext/sqlite/libsqlite/src/parse.y"
22384 + yygotominor.yy242 = sqliteExpr(TK_NOTNULL, yymsp[-1].minor.yy242, 0, 0);
22385 + sqliteExprSpan(yygotominor.yy242,&yymsp[-1].minor.yy242->span,&yymsp[0].minor.yy0);
22387 +#line 2663 "ext/sqlite/libsqlite/src/parse.c"
22389 + case 209: /* expr ::= expr NOT NULL */
22390 +#line 614 "ext/sqlite/libsqlite/src/parse.y"
22392 + yygotominor.yy242 = sqliteExpr(TK_NOTNULL, yymsp[-2].minor.yy242, 0, 0);
22393 + sqliteExprSpan(yygotominor.yy242,&yymsp[-2].minor.yy242->span,&yymsp[0].minor.yy0);
22395 +#line 2671 "ext/sqlite/libsqlite/src/parse.c"
22397 + case 210: /* expr ::= expr IS NOT NULL */
22398 +#line 618 "ext/sqlite/libsqlite/src/parse.y"
22400 + yygotominor.yy242 = sqliteExpr(TK_NOTNULL, yymsp[-3].minor.yy242, 0, 0);
22401 + sqliteExprSpan(yygotominor.yy242,&yymsp[-3].minor.yy242->span,&yymsp[0].minor.yy0);
22403 +#line 2679 "ext/sqlite/libsqlite/src/parse.c"
22405 + case 211: /* expr ::= NOT expr */
22406 +#line 622 "ext/sqlite/libsqlite/src/parse.y"
22408 + yygotominor.yy242 = sqliteExpr(TK_NOT, yymsp[0].minor.yy242, 0, 0);
22409 + sqliteExprSpan(yygotominor.yy242,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy242->span);
22411 +#line 2687 "ext/sqlite/libsqlite/src/parse.c"
22413 + case 212: /* expr ::= BITNOT expr */
22414 +#line 626 "ext/sqlite/libsqlite/src/parse.y"
22416 + yygotominor.yy242 = sqliteExpr(TK_BITNOT, yymsp[0].minor.yy242, 0, 0);
22417 + sqliteExprSpan(yygotominor.yy242,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy242->span);
22419 +#line 2695 "ext/sqlite/libsqlite/src/parse.c"
22421 + case 213: /* expr ::= MINUS expr */
22422 +#line 630 "ext/sqlite/libsqlite/src/parse.y"
22424 + yygotominor.yy242 = sqliteExpr(TK_UMINUS, yymsp[0].minor.yy242, 0, 0);
22425 + sqliteExprSpan(yygotominor.yy242,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy242->span);
22427 +#line 2703 "ext/sqlite/libsqlite/src/parse.c"
22429 + case 214: /* expr ::= PLUS expr */
22430 +#line 634 "ext/sqlite/libsqlite/src/parse.y"
22432 + yygotominor.yy242 = sqliteExpr(TK_UPLUS, yymsp[0].minor.yy242, 0, 0);
22433 + sqliteExprSpan(yygotominor.yy242,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy242->span);
22435 +#line 2711 "ext/sqlite/libsqlite/src/parse.c"
22437 + case 215: /* expr ::= LP select RP */
22438 +#line 638 "ext/sqlite/libsqlite/src/parse.y"
22440 + yygotominor.yy242 = sqliteExpr(TK_SELECT, 0, 0, 0);
22441 + if( yygotominor.yy242 ) yygotominor.yy242->pSelect = yymsp[-1].minor.yy179;
22442 + sqliteExprSpan(yygotominor.yy242,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);
22444 +#line 2720 "ext/sqlite/libsqlite/src/parse.c"
22446 + case 216: /* expr ::= expr BETWEEN expr AND expr */
22447 +#line 643 "ext/sqlite/libsqlite/src/parse.y"
22449 + ExprList *pList = sqliteExprListAppend(0, yymsp[-2].minor.yy242, 0);
22450 + pList = sqliteExprListAppend(pList, yymsp[0].minor.yy242, 0);
22451 + yygotominor.yy242 = sqliteExpr(TK_BETWEEN, yymsp[-4].minor.yy242, 0, 0);
22452 + if( yygotominor.yy242 ) yygotominor.yy242->pList = pList;
22453 + sqliteExprSpan(yygotominor.yy242,&yymsp[-4].minor.yy242->span,&yymsp[0].minor.yy242->span);
22455 +#line 2731 "ext/sqlite/libsqlite/src/parse.c"
22457 + case 217: /* expr ::= expr NOT BETWEEN expr AND expr */
22458 +#line 650 "ext/sqlite/libsqlite/src/parse.y"
22460 + ExprList *pList = sqliteExprListAppend(0, yymsp[-2].minor.yy242, 0);
22461 + pList = sqliteExprListAppend(pList, yymsp[0].minor.yy242, 0);
22462 + yygotominor.yy242 = sqliteExpr(TK_BETWEEN, yymsp[-5].minor.yy242, 0, 0);
22463 + if( yygotominor.yy242 ) yygotominor.yy242->pList = pList;
22464 + yygotominor.yy242 = sqliteExpr(TK_NOT, yygotominor.yy242, 0, 0);
22465 + sqliteExprSpan(yygotominor.yy242,&yymsp[-5].minor.yy242->span,&yymsp[0].minor.yy242->span);
22467 +#line 2743 "ext/sqlite/libsqlite/src/parse.c"
22469 + case 218: /* expr ::= expr IN LP exprlist RP */
22470 +#line 658 "ext/sqlite/libsqlite/src/parse.y"
22472 + yygotominor.yy242 = sqliteExpr(TK_IN, yymsp[-4].minor.yy242, 0, 0);
22473 + if( yygotominor.yy242 ) yygotominor.yy242->pList = yymsp[-1].minor.yy322;
22474 + sqliteExprSpan(yygotominor.yy242,&yymsp[-4].minor.yy242->span,&yymsp[0].minor.yy0);
22476 +#line 2752 "ext/sqlite/libsqlite/src/parse.c"
22478 + case 219: /* expr ::= expr IN LP select RP */
22479 +#line 663 "ext/sqlite/libsqlite/src/parse.y"
22481 + yygotominor.yy242 = sqliteExpr(TK_IN, yymsp[-4].minor.yy242, 0, 0);
22482 + if( yygotominor.yy242 ) yygotominor.yy242->pSelect = yymsp[-1].minor.yy179;
22483 + sqliteExprSpan(yygotominor.yy242,&yymsp[-4].minor.yy242->span,&yymsp[0].minor.yy0);
22485 +#line 2761 "ext/sqlite/libsqlite/src/parse.c"
22487 + case 220: /* expr ::= expr NOT IN LP exprlist RP */
22488 +#line 668 "ext/sqlite/libsqlite/src/parse.y"
22490 + yygotominor.yy242 = sqliteExpr(TK_IN, yymsp[-5].minor.yy242, 0, 0);
22491 + if( yygotominor.yy242 ) yygotominor.yy242->pList = yymsp[-1].minor.yy322;
22492 + yygotominor.yy242 = sqliteExpr(TK_NOT, yygotominor.yy242, 0, 0);
22493 + sqliteExprSpan(yygotominor.yy242,&yymsp[-5].minor.yy242->span,&yymsp[0].minor.yy0);
22495 +#line 2771 "ext/sqlite/libsqlite/src/parse.c"
22497 + case 221: /* expr ::= expr NOT IN LP select RP */
22498 +#line 674 "ext/sqlite/libsqlite/src/parse.y"
22500 + yygotominor.yy242 = sqliteExpr(TK_IN, yymsp[-5].minor.yy242, 0, 0);
22501 + if( yygotominor.yy242 ) yygotominor.yy242->pSelect = yymsp[-1].minor.yy179;
22502 + yygotominor.yy242 = sqliteExpr(TK_NOT, yygotominor.yy242, 0, 0);
22503 + sqliteExprSpan(yygotominor.yy242,&yymsp[-5].minor.yy242->span,&yymsp[0].minor.yy0);
22505 +#line 2781 "ext/sqlite/libsqlite/src/parse.c"
22507 + case 222: /* expr ::= expr IN nm dbnm */
22508 +#line 680 "ext/sqlite/libsqlite/src/parse.y"
22510 + SrcList *pSrc = sqliteSrcListAppend(0, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);
22511 + yygotominor.yy242 = sqliteExpr(TK_IN, yymsp[-3].minor.yy242, 0, 0);
22512 + if( yygotominor.yy242 ) yygotominor.yy242->pSelect = sqliteSelectNew(0,pSrc,0,0,0,0,0,-1,0);
22513 + sqliteExprSpan(yygotominor.yy242,&yymsp[-3].minor.yy242->span,yymsp[0].minor.yy0.z?&yymsp[0].minor.yy0:&yymsp[-1].minor.yy0);
22515 +#line 2791 "ext/sqlite/libsqlite/src/parse.c"
22517 + case 223: /* expr ::= expr NOT IN nm dbnm */
22518 +#line 686 "ext/sqlite/libsqlite/src/parse.y"
22520 + SrcList *pSrc = sqliteSrcListAppend(0, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);
22521 + yygotominor.yy242 = sqliteExpr(TK_IN, yymsp[-4].minor.yy242, 0, 0);
22522 + if( yygotominor.yy242 ) yygotominor.yy242->pSelect = sqliteSelectNew(0,pSrc,0,0,0,0,0,-1,0);
22523 + yygotominor.yy242 = sqliteExpr(TK_NOT, yygotominor.yy242, 0, 0);
22524 + sqliteExprSpan(yygotominor.yy242,&yymsp[-4].minor.yy242->span,yymsp[0].minor.yy0.z?&yymsp[0].minor.yy0:&yymsp[-1].minor.yy0);
22526 +#line 2802 "ext/sqlite/libsqlite/src/parse.c"
22528 + case 224: /* expr ::= CASE case_operand case_exprlist case_else END */
22529 +#line 696 "ext/sqlite/libsqlite/src/parse.y"
22531 + yygotominor.yy242 = sqliteExpr(TK_CASE, yymsp[-3].minor.yy242, yymsp[-1].minor.yy242, 0);
22532 + if( yygotominor.yy242 ) yygotominor.yy242->pList = yymsp[-2].minor.yy322;
22533 + sqliteExprSpan(yygotominor.yy242, &yymsp[-4].minor.yy0, &yymsp[0].minor.yy0);
22535 +#line 2811 "ext/sqlite/libsqlite/src/parse.c"
22537 + case 225: /* case_exprlist ::= case_exprlist WHEN expr THEN expr */
22538 +#line 703 "ext/sqlite/libsqlite/src/parse.y"
22540 + yygotominor.yy322 = sqliteExprListAppend(yymsp[-4].minor.yy322, yymsp[-2].minor.yy242, 0);
22541 + yygotominor.yy322 = sqliteExprListAppend(yygotominor.yy322, yymsp[0].minor.yy242, 0);
22543 +#line 2819 "ext/sqlite/libsqlite/src/parse.c"
22545 + case 226: /* case_exprlist ::= WHEN expr THEN expr */
22546 +#line 707 "ext/sqlite/libsqlite/src/parse.y"
22548 + yygotominor.yy322 = sqliteExprListAppend(0, yymsp[-2].minor.yy242, 0);
22549 + yygotominor.yy322 = sqliteExprListAppend(yygotominor.yy322, yymsp[0].minor.yy242, 0);
22551 +#line 2827 "ext/sqlite/libsqlite/src/parse.c"
22553 + case 235: /* cmd ::= CREATE uniqueflag INDEX nm ON nm dbnm LP idxlist RP onconf */
22554 +#line 732 "ext/sqlite/libsqlite/src/parse.y"
22556 + SrcList *pSrc = sqliteSrcListAppend(0, &yymsp[-5].minor.yy0, &yymsp[-4].minor.yy0);
22557 + if( yymsp[-9].minor.yy372!=OE_None ) yymsp[-9].minor.yy372 = yymsp[0].minor.yy372;
22558 + if( yymsp[-9].minor.yy372==OE_Default) yymsp[-9].minor.yy372 = OE_Abort;
22559 + sqliteCreateIndex(pParse, &yymsp[-7].minor.yy0, pSrc, yymsp[-2].minor.yy320, yymsp[-9].minor.yy372, &yymsp[-10].minor.yy0, &yymsp[-1].minor.yy0);
22561 +#line 2837 "ext/sqlite/libsqlite/src/parse.c"
22563 + case 237: /* uniqueflag ::= */
22564 +#line 741 "ext/sqlite/libsqlite/src/parse.y"
22565 +{ yygotominor.yy372 = OE_None; }
22566 +#line 2842 "ext/sqlite/libsqlite/src/parse.c"
22568 + case 243: /* cmd ::= DROP INDEX nm dbnm */
22569 +#line 758 "ext/sqlite/libsqlite/src/parse.y"
22571 + sqliteDropIndex(pParse, sqliteSrcListAppend(0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0));
22573 +#line 2849 "ext/sqlite/libsqlite/src/parse.c"
22575 + case 244: /* cmd ::= COPY orconf nm dbnm FROM nm USING DELIMITERS STRING */
22576 +#line 766 "ext/sqlite/libsqlite/src/parse.y"
22577 +{sqliteCopy(pParse,sqliteSrcListAppend(0,&yymsp[-6].minor.yy0,&yymsp[-5].minor.yy0),&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0,yymsp[-7].minor.yy372);}
22578 +#line 2854 "ext/sqlite/libsqlite/src/parse.c"
22580 + case 245: /* cmd ::= COPY orconf nm dbnm FROM nm */
22581 +#line 768 "ext/sqlite/libsqlite/src/parse.y"
22582 +{sqliteCopy(pParse,sqliteSrcListAppend(0,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0),&yymsp[0].minor.yy0,0,yymsp[-4].minor.yy372);}
22583 +#line 2859 "ext/sqlite/libsqlite/src/parse.c"
22585 + case 246: /* cmd ::= VACUUM */
22586 +#line 772 "ext/sqlite/libsqlite/src/parse.y"
22587 +{sqliteVacuum(pParse,0);}
22588 +#line 2864 "ext/sqlite/libsqlite/src/parse.c"
22590 + case 247: /* cmd ::= VACUUM nm */
22591 +#line 773 "ext/sqlite/libsqlite/src/parse.y"
22592 +{sqliteVacuum(pParse,&yymsp[0].minor.yy0);}
22593 +#line 2869 "ext/sqlite/libsqlite/src/parse.c"
22595 + case 248: /* cmd ::= PRAGMA ids EQ nm */
22596 + case 249: /* cmd ::= PRAGMA ids EQ ON */ yytestcase(yyruleno==249);
22597 + case 250: /* cmd ::= PRAGMA ids EQ plus_num */ yytestcase(yyruleno==250);
22598 +#line 777 "ext/sqlite/libsqlite/src/parse.y"
22599 +{sqlitePragma(pParse,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,0);}
22600 +#line 2876 "ext/sqlite/libsqlite/src/parse.c"
22602 + case 251: /* cmd ::= PRAGMA ids EQ minus_num */
22603 +#line 780 "ext/sqlite/libsqlite/src/parse.y"
22604 +{sqlitePragma(pParse,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,1);}
22605 +#line 2881 "ext/sqlite/libsqlite/src/parse.c"
22607 + case 252: /* cmd ::= PRAGMA ids LP nm RP */
22608 +#line 781 "ext/sqlite/libsqlite/src/parse.y"
22609 +{sqlitePragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,0);}
22610 +#line 2886 "ext/sqlite/libsqlite/src/parse.c"
22612 + case 253: /* cmd ::= PRAGMA ids */
22613 +#line 782 "ext/sqlite/libsqlite/src/parse.y"
22614 +{sqlitePragma(pParse,&yymsp[0].minor.yy0,&yymsp[0].minor.yy0,0);}
22615 +#line 2891 "ext/sqlite/libsqlite/src/parse.c"
22617 + case 260: /* cmd ::= CREATE trigger_decl BEGIN trigger_cmd_list END */
22618 +#line 792 "ext/sqlite/libsqlite/src/parse.y"
22621 + all.z = yymsp[-4].minor.yy0.z;
22622 + all.n = (yymsp[0].minor.yy0.z - yymsp[-4].minor.yy0.z) + yymsp[0].minor.yy0.n;
22623 + sqliteFinishTrigger(pParse, yymsp[-1].minor.yy19, &all);
22625 +#line 2901 "ext/sqlite/libsqlite/src/parse.c"
22627 + case 261: /* trigger_decl ::= temp TRIGGER nm trigger_time trigger_event ON nm dbnm foreach_clause when_clause */
22628 +#line 800 "ext/sqlite/libsqlite/src/parse.y"
22630 + SrcList *pTab = sqliteSrcListAppend(0, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0);
22631 + sqliteBeginTrigger(pParse, &yymsp[-7].minor.yy0, yymsp[-6].minor.yy372, yymsp[-5].minor.yy290.a, yymsp[-5].minor.yy290.b, pTab, yymsp[-1].minor.yy372, yymsp[0].minor.yy182, yymsp[-9].minor.yy372);
22633 +#line 2909 "ext/sqlite/libsqlite/src/parse.c"
22635 + case 262: /* trigger_time ::= BEFORE */
22636 + case 265: /* trigger_time ::= */ yytestcase(yyruleno==265);
22637 +#line 806 "ext/sqlite/libsqlite/src/parse.y"
22638 +{ yygotominor.yy372 = TK_BEFORE; }
22639 +#line 2915 "ext/sqlite/libsqlite/src/parse.c"
22641 + case 263: /* trigger_time ::= AFTER */
22642 +#line 807 "ext/sqlite/libsqlite/src/parse.y"
22643 +{ yygotominor.yy372 = TK_AFTER; }
22644 +#line 2920 "ext/sqlite/libsqlite/src/parse.c"
22646 + case 264: /* trigger_time ::= INSTEAD OF */
22647 +#line 808 "ext/sqlite/libsqlite/src/parse.y"
22648 +{ yygotominor.yy372 = TK_INSTEAD;}
22649 +#line 2925 "ext/sqlite/libsqlite/src/parse.c"
22651 + case 266: /* trigger_event ::= DELETE */
22652 +#line 813 "ext/sqlite/libsqlite/src/parse.y"
22653 +{ yygotominor.yy290.a = TK_DELETE; yygotominor.yy290.b = 0; }
22654 +#line 2930 "ext/sqlite/libsqlite/src/parse.c"
22656 + case 267: /* trigger_event ::= INSERT */
22657 +#line 814 "ext/sqlite/libsqlite/src/parse.y"
22658 +{ yygotominor.yy290.a = TK_INSERT; yygotominor.yy290.b = 0; }
22659 +#line 2935 "ext/sqlite/libsqlite/src/parse.c"
22661 + case 268: /* trigger_event ::= UPDATE */
22662 +#line 815 "ext/sqlite/libsqlite/src/parse.y"
22663 +{ yygotominor.yy290.a = TK_UPDATE; yygotominor.yy290.b = 0;}
22664 +#line 2940 "ext/sqlite/libsqlite/src/parse.c"
22666 + case 269: /* trigger_event ::= UPDATE OF inscollist */
22667 +#line 816 "ext/sqlite/libsqlite/src/parse.y"
22668 +{yygotominor.yy290.a = TK_UPDATE; yygotominor.yy290.b = yymsp[0].minor.yy320; }
22669 +#line 2945 "ext/sqlite/libsqlite/src/parse.c"
22671 + case 270: /* foreach_clause ::= */
22672 + case 271: /* foreach_clause ::= FOR EACH ROW */ yytestcase(yyruleno==271);
22673 +#line 819 "ext/sqlite/libsqlite/src/parse.y"
22674 +{ yygotominor.yy372 = TK_ROW; }
22675 +#line 2951 "ext/sqlite/libsqlite/src/parse.c"
22677 + case 272: /* foreach_clause ::= FOR EACH STATEMENT */
22678 +#line 821 "ext/sqlite/libsqlite/src/parse.y"
22679 +{ yygotominor.yy372 = TK_STATEMENT; }
22680 +#line 2956 "ext/sqlite/libsqlite/src/parse.c"
22682 + case 273: /* when_clause ::= */
22683 +#line 824 "ext/sqlite/libsqlite/src/parse.y"
22684 +{ yygotominor.yy182 = 0; }
22685 +#line 2961 "ext/sqlite/libsqlite/src/parse.c"
22687 + case 274: /* when_clause ::= WHEN expr */
22688 +#line 825 "ext/sqlite/libsqlite/src/parse.y"
22689 +{ yygotominor.yy182 = yymsp[0].minor.yy242; }
22690 +#line 2966 "ext/sqlite/libsqlite/src/parse.c"
22692 + case 275: /* trigger_cmd_list ::= trigger_cmd SEMI trigger_cmd_list */
22693 +#line 829 "ext/sqlite/libsqlite/src/parse.y"
22695 + yymsp[-2].minor.yy19->pNext = yymsp[0].minor.yy19;
22696 + yygotominor.yy19 = yymsp[-2].minor.yy19;
22698 +#line 2974 "ext/sqlite/libsqlite/src/parse.c"
22700 + case 276: /* trigger_cmd_list ::= */
22701 +#line 833 "ext/sqlite/libsqlite/src/parse.y"
22702 +{ yygotominor.yy19 = 0; }
22703 +#line 2979 "ext/sqlite/libsqlite/src/parse.c"
22705 + case 277: /* trigger_cmd ::= UPDATE orconf nm SET setlist where_opt */
22706 +#line 839 "ext/sqlite/libsqlite/src/parse.y"
22707 +{ yygotominor.yy19 = sqliteTriggerUpdateStep(&yymsp[-3].minor.yy0, yymsp[-1].minor.yy322, yymsp[0].minor.yy242, yymsp[-4].minor.yy372); }
22708 +#line 2984 "ext/sqlite/libsqlite/src/parse.c"
22710 + case 278: /* trigger_cmd ::= insert_cmd INTO nm inscollist_opt VALUES LP itemlist RP */
22711 +#line 844 "ext/sqlite/libsqlite/src/parse.y"
22712 +{yygotominor.yy19 = sqliteTriggerInsertStep(&yymsp[-5].minor.yy0, yymsp[-4].minor.yy320, yymsp[-1].minor.yy322, 0, yymsp[-7].minor.yy372);}
22713 +#line 2989 "ext/sqlite/libsqlite/src/parse.c"
22715 + case 279: /* trigger_cmd ::= insert_cmd INTO nm inscollist_opt select */
22716 +#line 847 "ext/sqlite/libsqlite/src/parse.y"
22717 +{yygotominor.yy19 = sqliteTriggerInsertStep(&yymsp[-2].minor.yy0, yymsp[-1].minor.yy320, 0, yymsp[0].minor.yy179, yymsp[-4].minor.yy372);}
22718 +#line 2994 "ext/sqlite/libsqlite/src/parse.c"
22720 + case 280: /* trigger_cmd ::= DELETE FROM nm where_opt */
22721 +#line 851 "ext/sqlite/libsqlite/src/parse.y"
22722 +{yygotominor.yy19 = sqliteTriggerDeleteStep(&yymsp[-1].minor.yy0, yymsp[0].minor.yy242);}
22723 +#line 2999 "ext/sqlite/libsqlite/src/parse.c"
22725 + case 281: /* trigger_cmd ::= select */
22726 +#line 854 "ext/sqlite/libsqlite/src/parse.y"
22727 +{yygotominor.yy19 = sqliteTriggerSelectStep(yymsp[0].minor.yy179); }
22728 +#line 3004 "ext/sqlite/libsqlite/src/parse.c"
22730 + case 282: /* expr ::= RAISE LP IGNORE RP */
22731 +#line 857 "ext/sqlite/libsqlite/src/parse.y"
22733 + yygotominor.yy242 = sqliteExpr(TK_RAISE, 0, 0, 0);
22734 + yygotominor.yy242->iColumn = OE_Ignore;
22735 + sqliteExprSpan(yygotominor.yy242, &yymsp[-3].minor.yy0, &yymsp[0].minor.yy0);
22737 +#line 3013 "ext/sqlite/libsqlite/src/parse.c"
22739 + case 283: /* expr ::= RAISE LP ROLLBACK COMMA nm RP */
22740 +#line 862 "ext/sqlite/libsqlite/src/parse.y"
22742 + yygotominor.yy242 = sqliteExpr(TK_RAISE, 0, 0, &yymsp[-1].minor.yy0);
22743 + yygotominor.yy242->iColumn = OE_Rollback;
22744 + sqliteExprSpan(yygotominor.yy242, &yymsp[-5].minor.yy0, &yymsp[0].minor.yy0);
22746 +#line 3022 "ext/sqlite/libsqlite/src/parse.c"
22748 + case 284: /* expr ::= RAISE LP ABORT COMMA nm RP */
22749 +#line 867 "ext/sqlite/libsqlite/src/parse.y"
22751 + yygotominor.yy242 = sqliteExpr(TK_RAISE, 0, 0, &yymsp[-1].minor.yy0);
22752 + yygotominor.yy242->iColumn = OE_Abort;
22753 + sqliteExprSpan(yygotominor.yy242, &yymsp[-5].minor.yy0, &yymsp[0].minor.yy0);
22755 +#line 3031 "ext/sqlite/libsqlite/src/parse.c"
22757 + case 285: /* expr ::= RAISE LP FAIL COMMA nm RP */
22758 +#line 872 "ext/sqlite/libsqlite/src/parse.y"
22760 + yygotominor.yy242 = sqliteExpr(TK_RAISE, 0, 0, &yymsp[-1].minor.yy0);
22761 + yygotominor.yy242->iColumn = OE_Fail;
22762 + sqliteExprSpan(yygotominor.yy242, &yymsp[-5].minor.yy0, &yymsp[0].minor.yy0);
22764 +#line 3040 "ext/sqlite/libsqlite/src/parse.c"
22766 + case 286: /* cmd ::= DROP TRIGGER nm dbnm */
22767 +#line 879 "ext/sqlite/libsqlite/src/parse.y"
22769 + sqliteDropTrigger(pParse,sqliteSrcListAppend(0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0));
22771 +#line 3047 "ext/sqlite/libsqlite/src/parse.c"
22773 + case 287: /* cmd ::= ATTACH database_kw_opt ids AS nm key_opt */
22774 +#line 884 "ext/sqlite/libsqlite/src/parse.y"
22776 + sqliteAttach(pParse, &yymsp[-3].minor.yy0, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);
22778 +#line 3054 "ext/sqlite/libsqlite/src/parse.c"
22780 + case 289: /* key_opt ::= */
22781 +#line 889 "ext/sqlite/libsqlite/src/parse.y"
22782 +{ yygotominor.yy0.z = 0; yygotominor.yy0.n = 0; }
22783 +#line 3059 "ext/sqlite/libsqlite/src/parse.c"
22785 + case 292: /* cmd ::= DETACH database_kw_opt nm */
22786 +#line 895 "ext/sqlite/libsqlite/src/parse.y"
22788 + sqliteDetach(pParse, &yymsp[0].minor.yy0);
22790 +#line 3066 "ext/sqlite/libsqlite/src/parse.c"
22793 + /* (0) input ::= cmdlist */ yytestcase(yyruleno==0);
22794 + /* (1) cmdlist ::= cmdlist ecmd */ yytestcase(yyruleno==1);
22795 + /* (2) cmdlist ::= ecmd */ yytestcase(yyruleno==2);
22796 + /* (3) ecmd ::= explain cmdx SEMI */ yytestcase(yyruleno==3);
22797 + /* (4) ecmd ::= SEMI */ yytestcase(yyruleno==4);
22798 + /* (9) trans_opt ::= */ yytestcase(yyruleno==9);
22799 + /* (10) trans_opt ::= TRANSACTION */ yytestcase(yyruleno==10);
22800 + /* (11) trans_opt ::= TRANSACTION nm */ yytestcase(yyruleno==11);
22801 + /* (15) cmd ::= create_table create_table_args */ yytestcase(yyruleno==15);
22802 + /* (21) columnlist ::= columnlist COMMA column */ yytestcase(yyruleno==21);
22803 + /* (22) columnlist ::= column */ yytestcase(yyruleno==22);
22804 + /* (23) column ::= columnid type carglist */ yytestcase(yyruleno==23);
22805 + /* (31) type ::= */ yytestcase(yyruleno==31);
22806 + /* (40) carglist ::= carglist carg */ yytestcase(yyruleno==40);
22807 + /* (41) carglist ::= */ yytestcase(yyruleno==41);
22808 + /* (42) carg ::= CONSTRAINT nm ccons */ yytestcase(yyruleno==42);
22809 + /* (43) carg ::= ccons */ yytestcase(yyruleno==43);
22810 + /* (52) carg ::= DEFAULT NULL */ yytestcase(yyruleno==52);
22811 + /* (53) ccons ::= NULL onconf */ yytestcase(yyruleno==53);
22812 + /* (76) conslist_opt ::= */ yytestcase(yyruleno==76);
22813 + /* (77) conslist_opt ::= COMMA conslist */ yytestcase(yyruleno==77);
22814 + /* (78) conslist ::= conslist COMMA tcons */ yytestcase(yyruleno==78);
22815 + /* (79) conslist ::= conslist tcons */ yytestcase(yyruleno==79);
22816 + /* (80) conslist ::= tcons */ yytestcase(yyruleno==80);
22817 + /* (81) tcons ::= CONSTRAINT nm */ yytestcase(yyruleno==81);
22818 + /* (258) plus_opt ::= PLUS */ yytestcase(yyruleno==258);
22819 + /* (259) plus_opt ::= */ yytestcase(yyruleno==259);
22820 + /* (290) database_kw_opt ::= DATABASE */ yytestcase(yyruleno==290);
22821 + /* (291) database_kw_opt ::= */ yytestcase(yyruleno==291);
22824 + yygoto = yyRuleInfo[yyruleno].lhs;
22825 + yysize = yyRuleInfo[yyruleno].nrhs;
22826 + yypParser->yyidx -= yysize;
22827 + yyact = yy_find_reduce_action(yymsp[-yysize].stateno,(YYCODETYPE)yygoto);
22828 + if( yyact < YYNSTATE ){
22830 + /* If we are not debugging and the reduce action popped at least
22831 + ** one element off the stack, then we can push the new element back
22832 + ** onto the stack here, and skip the stack overflow test in yy_shift().
22833 + ** That gives a significant speed improvement. */
22835 + yypParser->yyidx++;
22836 + yymsp -= yysize-1;
22837 + yymsp->stateno = (YYACTIONTYPE)yyact;
22838 + yymsp->major = (YYCODETYPE)yygoto;
22839 + yymsp->minor = yygotominor;
22843 + yy_shift(yypParser,yyact,yygoto,&yygotominor);
22846 + assert( yyact == YYNSTATE + YYNRULE + 1 );
22847 + yy_accept(yypParser);
22852 +** The following code executes when the parse fails
22854 +#ifndef YYNOERRORRECOVERY
22855 +static void yy_parse_failed(
22856 + yyParser *yypParser /* The parser */
22858 + sqliteParserARG_FETCH;
22860 + if( yyTraceFILE ){
22861 + fprintf(yyTraceFILE,"%sFail!\n",yyTracePrompt);
22864 + while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
22865 + /* Here code is inserted which will be executed whenever the
22866 + ** parser fails */
22867 + sqliteParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
22869 +#endif /* YYNOERRORRECOVERY */
22872 +** The following code executes when a syntax error first occurs.
22874 +static void yy_syntax_error(
22875 + yyParser *yypParser, /* The parser */
22876 + int yymajor, /* The major type of the error token */
22877 + YYMINORTYPE yyminor /* The minor type of the error token */
22879 + sqliteParserARG_FETCH;
22880 +#define TOKEN (yyminor.yy0)
22881 +#line 23 "ext/sqlite/libsqlite/src/parse.y"
22883 + if( pParse->zErrMsg==0 ){
22884 + if( TOKEN.z[0] ){
22885 + sqliteErrorMsg(pParse, "near \"%T\": syntax error", &TOKEN);
22887 + sqliteErrorMsg(pParse, "incomplete SQL statement");
22890 +#line 3166 "ext/sqlite/libsqlite/src/parse.c"
22891 + sqliteParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
22895 +** The following is executed when the parser accepts
22897 +static void yy_accept(
22898 + yyParser *yypParser /* The parser */
22900 + sqliteParserARG_FETCH;
22902 + if( yyTraceFILE ){
22903 + fprintf(yyTraceFILE,"%sAccept!\n",yyTracePrompt);
22906 + while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
22907 + /* Here code is inserted which will be executed whenever the
22908 + ** parser accepts */
22909 + sqliteParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
22912 +/* The main parser program.
22913 +** The first argument is a pointer to a structure obtained from
22914 +** "sqliteParserAlloc" which describes the current state of the parser.
22915 +** The second argument is the major token number. The third is
22916 +** the minor token. The fourth optional argument is whatever the
22917 +** user wants (and specified in the grammar) and is available for
22918 +** use by the action routines.
22922 +** <li> A pointer to the parser (an opaque structure.)
22923 +** <li> The major token number.
22924 +** <li> The minor token number.
22925 +** <li> An option argument of a grammar-specified type.
22931 +void sqliteParser(
22932 + void *yyp, /* The parser */
22933 + int yymajor, /* The major token code number */
22934 + sqliteParserTOKENTYPE yyminor /* The value for the token */
22935 + sqliteParserARG_PDECL /* Optional %extra_argument parameter */
22937 + YYMINORTYPE yyminorunion;
22938 + int yyact; /* The parser action. */
22939 + int yyendofinput; /* True if we are at the end of input */
22940 +#ifdef YYERRORSYMBOL
22941 + int yyerrorhit = 0; /* True if yymajor has invoked an error */
22943 + yyParser *yypParser; /* The parser */
22945 + /* (re)initialize the parser, if necessary */
22946 + yypParser = (yyParser*)yyp;
22947 + if( yypParser->yyidx<0 ){
22948 +#if YYSTACKDEPTH<=0
22949 + if( yypParser->yystksz <=0 ){
22950 + /*memset(&yyminorunion, 0, sizeof(yyminorunion));*/
22951 + yyminorunion = yyzerominor;
22952 + yyStackOverflow(yypParser, &yyminorunion);
22956 + yypParser->yyidx = 0;
22957 + yypParser->yyerrcnt = -1;
22958 + yypParser->yystack[0].stateno = 0;
22959 + yypParser->yystack[0].major = 0;
22961 + yyminorunion.yy0 = yyminor;
22962 + yyendofinput = (yymajor==0);
22963 + sqliteParserARG_STORE;
22966 + if( yyTraceFILE ){
22967 + fprintf(yyTraceFILE,"%sInput %s\n",yyTracePrompt,yyTokenName[yymajor]);
22972 + yyact = yy_find_shift_action(yypParser,(YYCODETYPE)yymajor);
22973 + if( yyact<YYNSTATE ){
22974 + assert( !yyendofinput ); /* Impossible to shift the $ token */
22975 + yy_shift(yypParser,yyact,yymajor,&yyminorunion);
22976 + yypParser->yyerrcnt--;
22977 + yymajor = YYNOCODE;
22978 + }else if( yyact < YYNSTATE + YYNRULE ){
22979 + yy_reduce(yypParser,yyact-YYNSTATE);
22981 + assert( yyact == YY_ERROR_ACTION );
22982 +#ifdef YYERRORSYMBOL
22986 + if( yyTraceFILE ){
22987 + fprintf(yyTraceFILE,"%sSyntax Error!\n",yyTracePrompt);
22990 +#ifdef YYERRORSYMBOL
22991 + /* A syntax error has occurred.
22992 + ** The response to an error depends upon whether or not the
22993 + ** grammar defines an error token "ERROR".
22995 + ** This is what we do if the grammar does define ERROR:
22997 + ** * Call the %syntax_error function.
22999 + ** * Begin popping the stack until we enter a state where
23000 + ** it is legal to shift the error symbol, then shift
23001 + ** the error symbol.
23003 + ** * Set the error count to three.
23005 + ** * Begin accepting and shifting new tokens. No new error
23006 + ** processing will occur until three tokens have been
23007 + ** shifted successfully.
23010 + if( yypParser->yyerrcnt<0 ){
23011 + yy_syntax_error(yypParser,yymajor,yyminorunion);
23013 + yymx = yypParser->yystack[yypParser->yyidx].major;
23014 + if( yymx==YYERRORSYMBOL || yyerrorhit ){
23016 + if( yyTraceFILE ){
23017 + fprintf(yyTraceFILE,"%sDiscard input token %s\n",
23018 + yyTracePrompt,yyTokenName[yymajor]);
23021 + yy_destructor(yypParser, (YYCODETYPE)yymajor,&yyminorunion);
23022 + yymajor = YYNOCODE;
23025 + yypParser->yyidx >= 0 &&
23026 + yymx != YYERRORSYMBOL &&
23027 + (yyact = yy_find_reduce_action(
23028 + yypParser->yystack[yypParser->yyidx].stateno,
23029 + YYERRORSYMBOL)) >= YYNSTATE
23031 + yy_pop_parser_stack(yypParser);
23033 + if( yypParser->yyidx < 0 || yymajor==0 ){
23034 + yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
23035 + yy_parse_failed(yypParser);
23036 + yymajor = YYNOCODE;
23037 + }else if( yymx!=YYERRORSYMBOL ){
23039 + u2.YYERRSYMDT = 0;
23040 + yy_shift(yypParser,yyact,YYERRORSYMBOL,&u2);
23043 + yypParser->yyerrcnt = 3;
23045 +#elif defined(YYNOERRORRECOVERY)
23046 + /* If the YYNOERRORRECOVERY macro is defined, then do not attempt to
23047 + ** do any kind of error recovery. Instead, simply invoke the syntax
23048 + ** error routine and continue going as if nothing had happened.
23050 + ** Applications can set this macro (for example inside %include) if
23051 + ** they intend to abandon the parse upon the first syntax error seen.
23053 + yy_syntax_error(yypParser,yymajor,yyminorunion);
23054 + yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
23055 + yymajor = YYNOCODE;
23057 +#else /* YYERRORSYMBOL is not defined */
23058 + /* This is what we do if the grammar does not define ERROR:
23060 + ** * Report an error message, and throw away the input token.
23062 + ** * If the input token is $, then fail the parse.
23064 + ** As before, subsequent error messages are suppressed until
23065 + ** three input tokens have been successfully shifted.
23067 + if( yypParser->yyerrcnt<=0 ){
23068 + yy_syntax_error(yypParser,yymajor,yyminorunion);
23070 + yypParser->yyerrcnt = 3;
23071 + yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
23072 + if( yyendofinput ){
23073 + yy_parse_failed(yypParser);
23075 + yymajor = YYNOCODE;
23078 + }while( yymajor!=YYNOCODE && yypParser->yyidx>=0 );
23082 +++ b/ext/sqlite/libsqlite/src/parse.h
23084 +#define TK_END_OF_FILE 1
23085 +#define TK_ILLEGAL 2
23086 +#define TK_SPACE 3
23087 +#define TK_UNCLOSED_STRING 4
23088 +#define TK_COMMENT 5
23089 +#define TK_FUNCTION 6
23090 +#define TK_COLUMN 7
23091 +#define TK_AGG_FUNCTION 8
23093 +#define TK_EXPLAIN 10
23094 +#define TK_BEGIN 11
23095 +#define TK_TRANSACTION 12
23096 +#define TK_COMMIT 13
23098 +#define TK_ROLLBACK 15
23099 +#define TK_CREATE 16
23100 +#define TK_TABLE 17
23101 +#define TK_TEMP 18
23105 +#define TK_COMMA 22
23107 +#define TK_ABORT 24
23108 +#define TK_AFTER 25
23110 +#define TK_ATTACH 27
23111 +#define TK_BEFORE 28
23112 +#define TK_CASCADE 29
23113 +#define TK_CLUSTER 30
23114 +#define TK_CONFLICT 31
23115 +#define TK_COPY 32
23116 +#define TK_DATABASE 33
23117 +#define TK_DEFERRED 34
23118 +#define TK_DELIMITERS 35
23119 +#define TK_DESC 36
23120 +#define TK_DETACH 37
23121 +#define TK_EACH 38
23122 +#define TK_FAIL 39
23124 +#define TK_GLOB 41
23125 +#define TK_IGNORE 42
23126 +#define TK_IMMEDIATE 43
23127 +#define TK_INITIALLY 44
23128 +#define TK_INSTEAD 45
23129 +#define TK_LIKE 46
23130 +#define TK_MATCH 47
23133 +#define TK_OFFSET 50
23134 +#define TK_PRAGMA 51
23135 +#define TK_RAISE 52
23136 +#define TK_REPLACE 53
23137 +#define TK_RESTRICT 54
23139 +#define TK_STATEMENT 56
23140 +#define TK_TRIGGER 57
23141 +#define TK_VACUUM 58
23142 +#define TK_VIEW 59
23148 +#define TK_ISNULL 65
23149 +#define TK_NOTNULL 66
23151 +#define TK_BETWEEN 68
23157 +#define TK_BITAND 74
23158 +#define TK_BITOR 75
23159 +#define TK_LSHIFT 76
23160 +#define TK_RSHIFT 77
23161 +#define TK_PLUS 78
23162 +#define TK_MINUS 79
23163 +#define TK_STAR 80
23164 +#define TK_SLASH 81
23166 +#define TK_CONCAT 83
23167 +#define TK_UMINUS 84
23168 +#define TK_UPLUS 85
23169 +#define TK_BITNOT 86
23170 +#define TK_STRING 87
23171 +#define TK_JOIN_KW 88
23172 +#define TK_INTEGER 89
23173 +#define TK_CONSTRAINT 90
23174 +#define TK_DEFAULT 91
23175 +#define TK_FLOAT 92
23176 +#define TK_NULL 93
23177 +#define TK_PRIMARY 94
23178 +#define TK_UNIQUE 95
23179 +#define TK_CHECK 96
23180 +#define TK_REFERENCES 97
23181 +#define TK_COLLATE 98
23183 +#define TK_DELETE 100
23184 +#define TK_UPDATE 101
23185 +#define TK_INSERT 102
23186 +#define TK_SET 103
23187 +#define TK_DEFERRABLE 104
23188 +#define TK_FOREIGN 105
23189 +#define TK_DROP 106
23190 +#define TK_UNION 107
23191 +#define TK_ALL 108
23192 +#define TK_INTERSECT 109
23193 +#define TK_EXCEPT 110
23194 +#define TK_SELECT 111
23195 +#define TK_DISTINCT 112
23196 +#define TK_DOT 113
23197 +#define TK_FROM 114
23198 +#define TK_JOIN 115
23199 +#define TK_USING 116
23200 +#define TK_ORDER 117
23202 +#define TK_GROUP 119
23203 +#define TK_HAVING 120
23204 +#define TK_LIMIT 121
23205 +#define TK_WHERE 122
23206 +#define TK_INTO 123
23207 +#define TK_VALUES 124
23208 +#define TK_VARIABLE 125
23209 +#define TK_CASE 126
23210 +#define TK_WHEN 127
23211 +#define TK_THEN 128
23212 +#define TK_ELSE 129
23213 +#define TK_INDEX 130
23215 +++ b/ext/sqlite/libsqlite/src/parse.y
23218 +** 2001 September 15
23220 +** The author disclaims copyright to this source code. In place of
23221 +** a legal notice, here is a blessing:
23223 +** May you do good and not evil.
23224 +** May you find forgiveness for yourself and forgive others.
23225 +** May you share freely, never taking more than you give.
23227 +*************************************************************************
23228 +** This file contains SQLite's grammar for SQL. Process this file
23229 +** using the lemon parser generator to generate C code that runs
23230 +** the parser. Lemon will also generate a header file containing
23231 +** numeric codes for all of the tokens.
23236 +%token_type {Token}
23237 +%default_type {Token}
23238 +%extra_argument {Parse *pParse}
23240 + if( pParse->zErrMsg==0 ){
23241 + if( TOKEN.z[0] ){
23242 + sqliteErrorMsg(pParse, "near \"%T\": syntax error", &TOKEN);
23244 + sqliteErrorMsg(pParse, "incomplete SQL statement");
23248 +%name sqliteParser
23250 +#include "sqliteInt.h"
23251 +#include "parse.h"
23254 +** An instance of this structure holds information about the
23255 +** LIMIT clause of a SELECT statement.
23258 + int limit; /* The LIMIT value. -1 if there is no limit */
23259 + int offset; /* The OFFSET. 0 if there is none */
23263 +** An instance of the following structure describes the event of a
23264 +** TRIGGER. "a" is the event type, one of TK_UPDATE, TK_INSERT,
23265 +** TK_DELETE, or TK_INSTEAD. If the event is of the form
23267 +** UPDATE ON (a,b,c)
23269 +** Then the "b" IdList records the list "a,b,c".
23271 +struct TrigEvent { int a; IdList * b; };
23275 +// These are extra tokens used by the lexer but never seen by the
23276 +// parser. We put them in a rule so that the parser generator will
23277 +// add them to the parse.h output file.
23279 +%nonassoc END_OF_FILE ILLEGAL SPACE UNCLOSED_STRING COMMENT FUNCTION
23280 + COLUMN AGG_FUNCTION.
23282 +// Input is a single SQL command
23283 +input ::= cmdlist.
23284 +cmdlist ::= cmdlist ecmd.
23286 +ecmd ::= explain cmdx SEMI.
23288 +cmdx ::= cmd. { sqliteExec(pParse); }
23289 +explain ::= EXPLAIN. { sqliteBeginParse(pParse, 1); }
23290 +explain ::= . { sqliteBeginParse(pParse, 0); }
23292 +///////////////////// Begin and end transactions. ////////////////////////////
23295 +cmd ::= BEGIN trans_opt onconf(R). {sqliteBeginTransaction(pParse,R);}
23297 +trans_opt ::= TRANSACTION.
23298 +trans_opt ::= TRANSACTION nm.
23299 +cmd ::= COMMIT trans_opt. {sqliteCommitTransaction(pParse);}
23300 +cmd ::= END trans_opt. {sqliteCommitTransaction(pParse);}
23301 +cmd ::= ROLLBACK trans_opt. {sqliteRollbackTransaction(pParse);}
23303 +///////////////////// The CREATE TABLE statement ////////////////////////////
23305 +cmd ::= create_table create_table_args.
23306 +create_table ::= CREATE(X) temp(T) TABLE nm(Y). {
23307 + sqliteStartTable(pParse,&X,&Y,T,0);
23310 +temp(A) ::= TEMP. {A = 1;}
23311 +temp(A) ::= . {A = 0;}
23312 +create_table_args ::= LP columnlist conslist_opt RP(X). {
23313 + sqliteEndTable(pParse,&X,0);
23315 +create_table_args ::= AS select(S). {
23316 + sqliteEndTable(pParse,0,S);
23317 + sqliteSelectDelete(S);
23319 +columnlist ::= columnlist COMMA column.
23320 +columnlist ::= column.
23322 +// About the only information used for a column is the name of the
23323 +// column. The type is always just "text". But the code will accept
23324 +// an elaborate typename. Perhaps someday we'll do something with it.
23326 +column ::= columnid type carglist.
23327 +columnid ::= nm(X). {sqliteAddColumn(pParse,&X);}
23329 +// An IDENTIFIER can be a generic identifier, or one of several
23330 +// keywords. Any non-standard keyword can also be an identifier.
23333 +id(A) ::= ID(X). {A = X;}
23335 +// The following directive causes tokens ABORT, AFTER, ASC, etc. to
23336 +// fallback to ID if they will not parse as their original value.
23337 +// This obviates the need for the "id" nonterminal.
23340 + ABORT AFTER ASC ATTACH BEFORE BEGIN CASCADE CLUSTER CONFLICT
23341 + COPY DATABASE DEFERRED DELIMITERS DESC DETACH EACH END EXPLAIN FAIL FOR
23342 + GLOB IGNORE IMMEDIATE INITIALLY INSTEAD LIKE MATCH KEY
23343 + OF OFFSET PRAGMA RAISE REPLACE RESTRICT ROW STATEMENT
23344 + TEMP TRIGGER VACUUM VIEW.
23346 +// Define operator precedence early so that this is the first occurance
23347 +// of the operator tokens in the grammer. Keeping the operators together
23348 +// causes them to be assigned integer values that are close together,
23349 +// which keeps parser tables smaller.
23354 +%left EQ NE ISNULL NOTNULL IS LIKE GLOB BETWEEN IN.
23355 +%left GT GE LT LE.
23356 +%left BITAND BITOR LSHIFT RSHIFT.
23358 +%left STAR SLASH REM.
23360 +%right UMINUS UPLUS BITNOT.
23362 +// And "ids" is an identifer-or-string.
23365 +ids(A) ::= ID(X). {A = X;}
23366 +ids(A) ::= STRING(X). {A = X;}
23368 +// The name of a column or table can be any of the following:
23371 +nm(A) ::= ID(X). {A = X;}
23372 +nm(A) ::= STRING(X). {A = X;}
23373 +nm(A) ::= JOIN_KW(X). {A = X;}
23376 +type ::= typename(X). {sqliteAddColumnType(pParse,&X,&X);}
23377 +type ::= typename(X) LP signed RP(Y). {sqliteAddColumnType(pParse,&X,&Y);}
23378 +type ::= typename(X) LP signed COMMA signed RP(Y).
23379 + {sqliteAddColumnType(pParse,&X,&Y);}
23380 +%type typename {Token}
23381 +typename(A) ::= ids(X). {A = X;}
23382 +typename(A) ::= typename(X) ids. {A = X;}
23383 +%type signed {int}
23384 +signed(A) ::= INTEGER(X). { A = atoi(X.z); }
23385 +signed(A) ::= PLUS INTEGER(X). { A = atoi(X.z); }
23386 +signed(A) ::= MINUS INTEGER(X). { A = -atoi(X.z); }
23387 +carglist ::= carglist carg.
23389 +carg ::= CONSTRAINT nm ccons.
23391 +carg ::= DEFAULT STRING(X). {sqliteAddDefaultValue(pParse,&X,0);}
23392 +carg ::= DEFAULT ID(X). {sqliteAddDefaultValue(pParse,&X,0);}
23393 +carg ::= DEFAULT INTEGER(X). {sqliteAddDefaultValue(pParse,&X,0);}
23394 +carg ::= DEFAULT PLUS INTEGER(X). {sqliteAddDefaultValue(pParse,&X,0);}
23395 +carg ::= DEFAULT MINUS INTEGER(X). {sqliteAddDefaultValue(pParse,&X,1);}
23396 +carg ::= DEFAULT FLOAT(X). {sqliteAddDefaultValue(pParse,&X,0);}
23397 +carg ::= DEFAULT PLUS FLOAT(X). {sqliteAddDefaultValue(pParse,&X,0);}
23398 +carg ::= DEFAULT MINUS FLOAT(X). {sqliteAddDefaultValue(pParse,&X,1);}
23399 +carg ::= DEFAULT NULL.
23401 +// In addition to the type name, we also care about the primary key and
23402 +// UNIQUE constraints.
23404 +ccons ::= NULL onconf.
23405 +ccons ::= NOT NULL onconf(R). {sqliteAddNotNull(pParse, R);}
23406 +ccons ::= PRIMARY KEY sortorder onconf(R). {sqliteAddPrimaryKey(pParse,0,R);}
23407 +ccons ::= UNIQUE onconf(R). {sqliteCreateIndex(pParse,0,0,0,R,0,0);}
23408 +ccons ::= CHECK LP expr RP onconf.
23409 +ccons ::= REFERENCES nm(T) idxlist_opt(TA) refargs(R).
23410 + {sqliteCreateForeignKey(pParse,0,&T,TA,R);}
23411 +ccons ::= defer_subclause(D). {sqliteDeferForeignKey(pParse,D);}
23412 +ccons ::= COLLATE id(C). {
23413 + sqliteAddCollateType(pParse, sqliteCollateType(C.z, C.n));
23416 +// The next group of rules parses the arguments to a REFERENCES clause
23417 +// that determine if the referential integrity checking is deferred or
23418 +// or immediate and which determine what action to take if a ref-integ
23421 +%type refargs {int}
23422 +refargs(A) ::= . { A = OE_Restrict * 0x010101; }
23423 +refargs(A) ::= refargs(X) refarg(Y). { A = (X & Y.mask) | Y.value; }
23424 +%type refarg {struct {int value; int mask;}}
23425 +refarg(A) ::= MATCH nm. { A.value = 0; A.mask = 0x000000; }
23426 +refarg(A) ::= ON DELETE refact(X). { A.value = X; A.mask = 0x0000ff; }
23427 +refarg(A) ::= ON UPDATE refact(X). { A.value = X<<8; A.mask = 0x00ff00; }
23428 +refarg(A) ::= ON INSERT refact(X). { A.value = X<<16; A.mask = 0xff0000; }
23429 +%type refact {int}
23430 +refact(A) ::= SET NULL. { A = OE_SetNull; }
23431 +refact(A) ::= SET DEFAULT. { A = OE_SetDflt; }
23432 +refact(A) ::= CASCADE. { A = OE_Cascade; }
23433 +refact(A) ::= RESTRICT. { A = OE_Restrict; }
23434 +%type defer_subclause {int}
23435 +defer_subclause(A) ::= NOT DEFERRABLE init_deferred_pred_opt(X). {A = X;}
23436 +defer_subclause(A) ::= DEFERRABLE init_deferred_pred_opt(X). {A = X;}
23437 +%type init_deferred_pred_opt {int}
23438 +init_deferred_pred_opt(A) ::= . {A = 0;}
23439 +init_deferred_pred_opt(A) ::= INITIALLY DEFERRED. {A = 1;}
23440 +init_deferred_pred_opt(A) ::= INITIALLY IMMEDIATE. {A = 0;}
23442 +// For the time being, the only constraint we care about is the primary
23443 +// key and UNIQUE. Both create indices.
23445 +conslist_opt ::= .
23446 +conslist_opt ::= COMMA conslist.
23447 +conslist ::= conslist COMMA tcons.
23448 +conslist ::= conslist tcons.
23449 +conslist ::= tcons.
23450 +tcons ::= CONSTRAINT nm.
23451 +tcons ::= PRIMARY KEY LP idxlist(X) RP onconf(R).
23452 + {sqliteAddPrimaryKey(pParse,X,R);}
23453 +tcons ::= UNIQUE LP idxlist(X) RP onconf(R).
23454 + {sqliteCreateIndex(pParse,0,0,X,R,0,0);}
23455 +tcons ::= CHECK expr onconf.
23456 +tcons ::= FOREIGN KEY LP idxlist(FA) RP
23457 + REFERENCES nm(T) idxlist_opt(TA) refargs(R) defer_subclause_opt(D). {
23458 + sqliteCreateForeignKey(pParse, FA, &T, TA, R);
23459 + sqliteDeferForeignKey(pParse, D);
23461 +%type defer_subclause_opt {int}
23462 +defer_subclause_opt(A) ::= . {A = 0;}
23463 +defer_subclause_opt(A) ::= defer_subclause(X). {A = X;}
23465 +// The following is a non-standard extension that allows us to declare the
23466 +// default behavior when there is a constraint conflict.
23468 +%type onconf {int}
23469 +%type orconf {int}
23470 +%type resolvetype {int}
23471 +onconf(A) ::= . { A = OE_Default; }
23472 +onconf(A) ::= ON CONFLICT resolvetype(X). { A = X; }
23473 +orconf(A) ::= . { A = OE_Default; }
23474 +orconf(A) ::= OR resolvetype(X). { A = X; }
23475 +resolvetype(A) ::= ROLLBACK. { A = OE_Rollback; }
23476 +resolvetype(A) ::= ABORT. { A = OE_Abort; }
23477 +resolvetype(A) ::= FAIL. { A = OE_Fail; }
23478 +resolvetype(A) ::= IGNORE. { A = OE_Ignore; }
23479 +resolvetype(A) ::= REPLACE. { A = OE_Replace; }
23481 +////////////////////////// The DROP TABLE /////////////////////////////////////
23483 +cmd ::= DROP TABLE nm(X). {sqliteDropTable(pParse,&X,0);}
23485 +///////////////////// The CREATE VIEW statement /////////////////////////////
23487 +cmd ::= CREATE(X) temp(T) VIEW nm(Y) AS select(S). {
23488 + sqliteCreateView(pParse, &X, &Y, S, T);
23490 +cmd ::= DROP VIEW nm(X). {
23491 + sqliteDropTable(pParse, &X, 1);
23494 +//////////////////////// The SELECT statement /////////////////////////////////
23496 +cmd ::= select(X). {
23497 + sqliteSelect(pParse, X, SRT_Callback, 0, 0, 0, 0);
23498 + sqliteSelectDelete(X);
23501 +%type select {Select*}
23502 +%destructor select {sqliteSelectDelete($$);}
23503 +%type oneselect {Select*}
23504 +%destructor oneselect {sqliteSelectDelete($$);}
23506 +select(A) ::= oneselect(X). {A = X;}
23507 +select(A) ::= select(X) multiselect_op(Y) oneselect(Z). {
23514 +%type multiselect_op {int}
23515 +multiselect_op(A) ::= UNION. {A = TK_UNION;}
23516 +multiselect_op(A) ::= UNION ALL. {A = TK_ALL;}
23517 +multiselect_op(A) ::= INTERSECT. {A = TK_INTERSECT;}
23518 +multiselect_op(A) ::= EXCEPT. {A = TK_EXCEPT;}
23519 +oneselect(A) ::= SELECT distinct(D) selcollist(W) from(X) where_opt(Y)
23520 + groupby_opt(P) having_opt(Q) orderby_opt(Z) limit_opt(L). {
23521 + A = sqliteSelectNew(W,X,Y,P,Q,Z,D,L.limit,L.offset);
23524 +// The "distinct" nonterminal is true (1) if the DISTINCT keyword is
23525 +// present and false (0) if it is not.
23527 +%type distinct {int}
23528 +distinct(A) ::= DISTINCT. {A = 1;}
23529 +distinct(A) ::= ALL. {A = 0;}
23530 +distinct(A) ::= . {A = 0;}
23532 +// selcollist is a list of expressions that are to become the return
23533 +// values of the SELECT statement. The "*" in statements like
23534 +// "SELECT * FROM ..." is encoded as a special expression with an
23535 +// opcode of TK_ALL.
23537 +%type selcollist {ExprList*}
23538 +%destructor selcollist {sqliteExprListDelete($$);}
23539 +%type sclp {ExprList*}
23540 +%destructor sclp {sqliteExprListDelete($$);}
23541 +sclp(A) ::= selcollist(X) COMMA. {A = X;}
23542 +sclp(A) ::= . {A = 0;}
23543 +selcollist(A) ::= sclp(P) expr(X) as(Y). {
23544 + A = sqliteExprListAppend(P,X,Y.n?&Y:0);
23546 +selcollist(A) ::= sclp(P) STAR. {
23547 + A = sqliteExprListAppend(P, sqliteExpr(TK_ALL, 0, 0, 0), 0);
23549 +selcollist(A) ::= sclp(P) nm(X) DOT STAR. {
23550 + Expr *pRight = sqliteExpr(TK_ALL, 0, 0, 0);
23551 + Expr *pLeft = sqliteExpr(TK_ID, 0, 0, &X);
23552 + A = sqliteExprListAppend(P, sqliteExpr(TK_DOT, pLeft, pRight, 0), 0);
23555 +// An option "AS <id>" phrase that can follow one of the expressions that
23556 +// define the result set, or one of the tables in the FROM clause.
23559 +as(X) ::= AS nm(Y). { X = Y; }
23560 +as(X) ::= ids(Y). { X = Y; }
23561 +as(X) ::= . { X.n = 0; }
23564 +%type seltablist {SrcList*}
23565 +%destructor seltablist {sqliteSrcListDelete($$);}
23566 +%type stl_prefix {SrcList*}
23567 +%destructor stl_prefix {sqliteSrcListDelete($$);}
23568 +%type from {SrcList*}
23569 +%destructor from {sqliteSrcListDelete($$);}
23571 +// A complete FROM clause.
23573 +from(A) ::= . {A = sqliteMalloc(sizeof(*A));}
23574 +from(A) ::= FROM seltablist(X). {A = X;}
23576 +// "seltablist" is a "Select Table List" - the content of the FROM clause
23577 +// in a SELECT statement. "stl_prefix" is a prefix of this list.
23579 +stl_prefix(A) ::= seltablist(X) joinop(Y). {
23581 + if( A && A->nSrc>0 ) A->a[A->nSrc-1].jointype = Y;
23583 +stl_prefix(A) ::= . {A = 0;}
23584 +seltablist(A) ::= stl_prefix(X) nm(Y) dbnm(D) as(Z) on_opt(N) using_opt(U). {
23585 + A = sqliteSrcListAppend(X,&Y,&D);
23586 + if( Z.n ) sqliteSrcListAddAlias(A,&Z);
23588 + if( A && A->nSrc>1 ){ A->a[A->nSrc-2].pOn = N; }
23589 + else { sqliteExprDelete(N); }
23592 + if( A && A->nSrc>1 ){ A->a[A->nSrc-2].pUsing = U; }
23593 + else { sqliteIdListDelete(U); }
23596 +seltablist(A) ::= stl_prefix(X) LP seltablist_paren(S) RP
23597 + as(Z) on_opt(N) using_opt(U). {
23598 + A = sqliteSrcListAppend(X,0,0);
23599 + A->a[A->nSrc-1].pSelect = S;
23600 + if( Z.n ) sqliteSrcListAddAlias(A,&Z);
23602 + if( A && A->nSrc>1 ){ A->a[A->nSrc-2].pOn = N; }
23603 + else { sqliteExprDelete(N); }
23606 + if( A && A->nSrc>1 ){ A->a[A->nSrc-2].pUsing = U; }
23607 + else { sqliteIdListDelete(U); }
23611 +// A seltablist_paren nonterminal represents anything in a FROM that
23612 +// is contained inside parentheses. This can be either a subquery or
23613 +// a grouping of table and subqueries.
23615 +%type seltablist_paren {Select*}
23616 +%destructor seltablist_paren {sqliteSelectDelete($$);}
23617 +seltablist_paren(A) ::= select(S). {A = S;}
23618 +seltablist_paren(A) ::= seltablist(F). {
23619 + A = sqliteSelectNew(0,F,0,0,0,0,0,-1,0);
23622 +%type dbnm {Token}
23623 +dbnm(A) ::= . {A.z=0; A.n=0;}
23624 +dbnm(A) ::= DOT nm(X). {A = X;}
23626 +%type joinop {int}
23627 +%type joinop2 {int}
23628 +joinop(X) ::= COMMA. { X = JT_INNER; }
23629 +joinop(X) ::= JOIN. { X = JT_INNER; }
23630 +joinop(X) ::= JOIN_KW(A) JOIN. { X = sqliteJoinType(pParse,&A,0,0); }
23631 +joinop(X) ::= JOIN_KW(A) nm(B) JOIN. { X = sqliteJoinType(pParse,&A,&B,0); }
23632 +joinop(X) ::= JOIN_KW(A) nm(B) nm(C) JOIN.
23633 + { X = sqliteJoinType(pParse,&A,&B,&C); }
23635 +%type on_opt {Expr*}
23636 +%destructor on_opt {sqliteExprDelete($$);}
23637 +on_opt(N) ::= ON expr(E). {N = E;}
23638 +on_opt(N) ::= . {N = 0;}
23640 +%type using_opt {IdList*}
23641 +%destructor using_opt {sqliteIdListDelete($$);}
23642 +using_opt(U) ::= USING LP idxlist(L) RP. {U = L;}
23643 +using_opt(U) ::= . {U = 0;}
23646 +%type orderby_opt {ExprList*}
23647 +%destructor orderby_opt {sqliteExprListDelete($$);}
23648 +%type sortlist {ExprList*}
23649 +%destructor sortlist {sqliteExprListDelete($$);}
23650 +%type sortitem {Expr*}
23651 +%destructor sortitem {sqliteExprDelete($$);}
23653 +orderby_opt(A) ::= . {A = 0;}
23654 +orderby_opt(A) ::= ORDER BY sortlist(X). {A = X;}
23655 +sortlist(A) ::= sortlist(X) COMMA sortitem(Y) collate(C) sortorder(Z). {
23656 + A = sqliteExprListAppend(X,Y,0);
23657 + if( A ) A->a[A->nExpr-1].sortOrder = C+Z;
23659 +sortlist(A) ::= sortitem(Y) collate(C) sortorder(Z). {
23660 + A = sqliteExprListAppend(0,Y,0);
23661 + if( A ) A->a[0].sortOrder = C+Z;
23663 +sortitem(A) ::= expr(X). {A = X;}
23665 +%type sortorder {int}
23666 +%type collate {int}
23668 +sortorder(A) ::= ASC. {A = SQLITE_SO_ASC;}
23669 +sortorder(A) ::= DESC. {A = SQLITE_SO_DESC;}
23670 +sortorder(A) ::= . {A = SQLITE_SO_ASC;}
23671 +collate(C) ::= . {C = SQLITE_SO_UNK;}
23672 +collate(C) ::= COLLATE id(X). {C = sqliteCollateType(X.z, X.n);}
23674 +%type groupby_opt {ExprList*}
23675 +%destructor groupby_opt {sqliteExprListDelete($$);}
23676 +groupby_opt(A) ::= . {A = 0;}
23677 +groupby_opt(A) ::= GROUP BY exprlist(X). {A = X;}
23679 +%type having_opt {Expr*}
23680 +%destructor having_opt {sqliteExprDelete($$);}
23681 +having_opt(A) ::= . {A = 0;}
23682 +having_opt(A) ::= HAVING expr(X). {A = X;}
23684 +%type limit_opt {struct LimitVal}
23685 +limit_opt(A) ::= . {A.limit = -1; A.offset = 0;}
23686 +limit_opt(A) ::= LIMIT signed(X). {A.limit = X; A.offset = 0;}
23687 +limit_opt(A) ::= LIMIT signed(X) OFFSET signed(Y).
23688 + {A.limit = X; A.offset = Y;}
23689 +limit_opt(A) ::= LIMIT signed(X) COMMA signed(Y).
23690 + {A.limit = Y; A.offset = X;}
23692 +/////////////////////////// The DELETE statement /////////////////////////////
23694 +cmd ::= DELETE FROM nm(X) dbnm(D) where_opt(Y). {
23695 + sqliteDeleteFrom(pParse, sqliteSrcListAppend(0,&X,&D), Y);
23698 +%type where_opt {Expr*}
23699 +%destructor where_opt {sqliteExprDelete($$);}
23701 +where_opt(A) ::= . {A = 0;}
23702 +where_opt(A) ::= WHERE expr(X). {A = X;}
23704 +%type setlist {ExprList*}
23705 +%destructor setlist {sqliteExprListDelete($$);}
23707 +////////////////////////// The UPDATE command ////////////////////////////////
23709 +cmd ::= UPDATE orconf(R) nm(X) dbnm(D) SET setlist(Y) where_opt(Z).
23710 + {sqliteUpdate(pParse,sqliteSrcListAppend(0,&X,&D),Y,Z,R);}
23712 +setlist(A) ::= setlist(Z) COMMA nm(X) EQ expr(Y).
23713 + {A = sqliteExprListAppend(Z,Y,&X);}
23714 +setlist(A) ::= nm(X) EQ expr(Y). {A = sqliteExprListAppend(0,Y,&X);}
23716 +////////////////////////// The INSERT command /////////////////////////////////
23718 +cmd ::= insert_cmd(R) INTO nm(X) dbnm(D) inscollist_opt(F)
23719 + VALUES LP itemlist(Y) RP.
23720 + {sqliteInsert(pParse, sqliteSrcListAppend(0,&X,&D), Y, 0, F, R);}
23721 +cmd ::= insert_cmd(R) INTO nm(X) dbnm(D) inscollist_opt(F) select(S).
23722 + {sqliteInsert(pParse, sqliteSrcListAppend(0,&X,&D), 0, S, F, R);}
23724 +%type insert_cmd {int}
23725 +insert_cmd(A) ::= INSERT orconf(R). {A = R;}
23726 +insert_cmd(A) ::= REPLACE. {A = OE_Replace;}
23729 +%type itemlist {ExprList*}
23730 +%destructor itemlist {sqliteExprListDelete($$);}
23732 +itemlist(A) ::= itemlist(X) COMMA expr(Y). {A = sqliteExprListAppend(X,Y,0);}
23733 +itemlist(A) ::= expr(X). {A = sqliteExprListAppend(0,X,0);}
23735 +%type inscollist_opt {IdList*}
23736 +%destructor inscollist_opt {sqliteIdListDelete($$);}
23737 +%type inscollist {IdList*}
23738 +%destructor inscollist {sqliteIdListDelete($$);}
23740 +inscollist_opt(A) ::= . {A = 0;}
23741 +inscollist_opt(A) ::= LP inscollist(X) RP. {A = X;}
23742 +inscollist(A) ::= inscollist(X) COMMA nm(Y). {A = sqliteIdListAppend(X,&Y);}
23743 +inscollist(A) ::= nm(Y). {A = sqliteIdListAppend(0,&Y);}
23745 +/////////////////////////// Expression Processing /////////////////////////////
23748 +%type expr {Expr*}
23749 +%destructor expr {sqliteExprDelete($$);}
23751 +expr(A) ::= LP(B) expr(X) RP(E). {A = X; sqliteExprSpan(A,&B,&E); }
23752 +expr(A) ::= NULL(X). {A = sqliteExpr(TK_NULL, 0, 0, &X);}
23753 +expr(A) ::= ID(X). {A = sqliteExpr(TK_ID, 0, 0, &X);}
23754 +expr(A) ::= JOIN_KW(X). {A = sqliteExpr(TK_ID, 0, 0, &X);}
23755 +expr(A) ::= nm(X) DOT nm(Y). {
23756 + Expr *temp1 = sqliteExpr(TK_ID, 0, 0, &X);
23757 + Expr *temp2 = sqliteExpr(TK_ID, 0, 0, &Y);
23758 + A = sqliteExpr(TK_DOT, temp1, temp2, 0);
23760 +expr(A) ::= nm(X) DOT nm(Y) DOT nm(Z). {
23761 + Expr *temp1 = sqliteExpr(TK_ID, 0, 0, &X);
23762 + Expr *temp2 = sqliteExpr(TK_ID, 0, 0, &Y);
23763 + Expr *temp3 = sqliteExpr(TK_ID, 0, 0, &Z);
23764 + Expr *temp4 = sqliteExpr(TK_DOT, temp2, temp3, 0);
23765 + A = sqliteExpr(TK_DOT, temp1, temp4, 0);
23767 +expr(A) ::= INTEGER(X). {A = sqliteExpr(TK_INTEGER, 0, 0, &X);}
23768 +expr(A) ::= FLOAT(X). {A = sqliteExpr(TK_FLOAT, 0, 0, &X);}
23769 +expr(A) ::= STRING(X). {A = sqliteExpr(TK_STRING, 0, 0, &X);}
23770 +expr(A) ::= VARIABLE(X). {
23771 + A = sqliteExpr(TK_VARIABLE, 0, 0, &X);
23772 + if( A ) A->iTable = ++pParse->nVar;
23774 +expr(A) ::= ID(X) LP exprlist(Y) RP(E). {
23775 + A = sqliteExprFunction(Y, &X);
23776 + sqliteExprSpan(A,&X,&E);
23778 +expr(A) ::= ID(X) LP STAR RP(E). {
23779 + A = sqliteExprFunction(0, &X);
23780 + sqliteExprSpan(A,&X,&E);
23782 +expr(A) ::= expr(X) AND expr(Y). {A = sqliteExpr(TK_AND, X, Y, 0);}
23783 +expr(A) ::= expr(X) OR expr(Y). {A = sqliteExpr(TK_OR, X, Y, 0);}
23784 +expr(A) ::= expr(X) LT expr(Y). {A = sqliteExpr(TK_LT, X, Y, 0);}
23785 +expr(A) ::= expr(X) GT expr(Y). {A = sqliteExpr(TK_GT, X, Y, 0);}
23786 +expr(A) ::= expr(X) LE expr(Y). {A = sqliteExpr(TK_LE, X, Y, 0);}
23787 +expr(A) ::= expr(X) GE expr(Y). {A = sqliteExpr(TK_GE, X, Y, 0);}
23788 +expr(A) ::= expr(X) NE expr(Y). {A = sqliteExpr(TK_NE, X, Y, 0);}
23789 +expr(A) ::= expr(X) EQ expr(Y). {A = sqliteExpr(TK_EQ, X, Y, 0);}
23790 +expr(A) ::= expr(X) BITAND expr(Y). {A = sqliteExpr(TK_BITAND, X, Y, 0);}
23791 +expr(A) ::= expr(X) BITOR expr(Y). {A = sqliteExpr(TK_BITOR, X, Y, 0);}
23792 +expr(A) ::= expr(X) LSHIFT expr(Y). {A = sqliteExpr(TK_LSHIFT, X, Y, 0);}
23793 +expr(A) ::= expr(X) RSHIFT expr(Y). {A = sqliteExpr(TK_RSHIFT, X, Y, 0);}
23794 +expr(A) ::= expr(X) likeop(OP) expr(Y). [LIKE] {
23795 + ExprList *pList = sqliteExprListAppend(0, Y, 0);
23796 + pList = sqliteExprListAppend(pList, X, 0);
23797 + A = sqliteExprFunction(pList, 0);
23798 + if( A ) A->op = OP;
23799 + sqliteExprSpan(A, &X->span, &Y->span);
23801 +expr(A) ::= expr(X) NOT likeop(OP) expr(Y). [LIKE] {
23802 + ExprList *pList = sqliteExprListAppend(0, Y, 0);
23803 + pList = sqliteExprListAppend(pList, X, 0);
23804 + A = sqliteExprFunction(pList, 0);
23805 + if( A ) A->op = OP;
23806 + A = sqliteExpr(TK_NOT, A, 0, 0);
23807 + sqliteExprSpan(A,&X->span,&Y->span);
23809 +%type likeop {int}
23810 +likeop(A) ::= LIKE. {A = TK_LIKE;}
23811 +likeop(A) ::= GLOB. {A = TK_GLOB;}
23812 +expr(A) ::= expr(X) PLUS expr(Y). {A = sqliteExpr(TK_PLUS, X, Y, 0);}
23813 +expr(A) ::= expr(X) MINUS expr(Y). {A = sqliteExpr(TK_MINUS, X, Y, 0);}
23814 +expr(A) ::= expr(X) STAR expr(Y). {A = sqliteExpr(TK_STAR, X, Y, 0);}
23815 +expr(A) ::= expr(X) SLASH expr(Y). {A = sqliteExpr(TK_SLASH, X, Y, 0);}
23816 +expr(A) ::= expr(X) REM expr(Y). {A = sqliteExpr(TK_REM, X, Y, 0);}
23817 +expr(A) ::= expr(X) CONCAT expr(Y). {A = sqliteExpr(TK_CONCAT, X, Y, 0);}
23818 +expr(A) ::= expr(X) ISNULL(E). {
23819 + A = sqliteExpr(TK_ISNULL, X, 0, 0);
23820 + sqliteExprSpan(A,&X->span,&E);
23822 +expr(A) ::= expr(X) IS NULL(E). {
23823 + A = sqliteExpr(TK_ISNULL, X, 0, 0);
23824 + sqliteExprSpan(A,&X->span,&E);
23826 +expr(A) ::= expr(X) NOTNULL(E). {
23827 + A = sqliteExpr(TK_NOTNULL, X, 0, 0);
23828 + sqliteExprSpan(A,&X->span,&E);
23830 +expr(A) ::= expr(X) NOT NULL(E). {
23831 + A = sqliteExpr(TK_NOTNULL, X, 0, 0);
23832 + sqliteExprSpan(A,&X->span,&E);
23834 +expr(A) ::= expr(X) IS NOT NULL(E). {
23835 + A = sqliteExpr(TK_NOTNULL, X, 0, 0);
23836 + sqliteExprSpan(A,&X->span,&E);
23838 +expr(A) ::= NOT(B) expr(X). {
23839 + A = sqliteExpr(TK_NOT, X, 0, 0);
23840 + sqliteExprSpan(A,&B,&X->span);
23842 +expr(A) ::= BITNOT(B) expr(X). {
23843 + A = sqliteExpr(TK_BITNOT, X, 0, 0);
23844 + sqliteExprSpan(A,&B,&X->span);
23846 +expr(A) ::= MINUS(B) expr(X). [UMINUS] {
23847 + A = sqliteExpr(TK_UMINUS, X, 0, 0);
23848 + sqliteExprSpan(A,&B,&X->span);
23850 +expr(A) ::= PLUS(B) expr(X). [UPLUS] {
23851 + A = sqliteExpr(TK_UPLUS, X, 0, 0);
23852 + sqliteExprSpan(A,&B,&X->span);
23854 +expr(A) ::= LP(B) select(X) RP(E). {
23855 + A = sqliteExpr(TK_SELECT, 0, 0, 0);
23856 + if( A ) A->pSelect = X;
23857 + sqliteExprSpan(A,&B,&E);
23859 +expr(A) ::= expr(W) BETWEEN expr(X) AND expr(Y). {
23860 + ExprList *pList = sqliteExprListAppend(0, X, 0);
23861 + pList = sqliteExprListAppend(pList, Y, 0);
23862 + A = sqliteExpr(TK_BETWEEN, W, 0, 0);
23863 + if( A ) A->pList = pList;
23864 + sqliteExprSpan(A,&W->span,&Y->span);
23866 +expr(A) ::= expr(W) NOT BETWEEN expr(X) AND expr(Y). {
23867 + ExprList *pList = sqliteExprListAppend(0, X, 0);
23868 + pList = sqliteExprListAppend(pList, Y, 0);
23869 + A = sqliteExpr(TK_BETWEEN, W, 0, 0);
23870 + if( A ) A->pList = pList;
23871 + A = sqliteExpr(TK_NOT, A, 0, 0);
23872 + sqliteExprSpan(A,&W->span,&Y->span);
23874 +expr(A) ::= expr(X) IN LP exprlist(Y) RP(E). {
23875 + A = sqliteExpr(TK_IN, X, 0, 0);
23876 + if( A ) A->pList = Y;
23877 + sqliteExprSpan(A,&X->span,&E);
23879 +expr(A) ::= expr(X) IN LP select(Y) RP(E). {
23880 + A = sqliteExpr(TK_IN, X, 0, 0);
23881 + if( A ) A->pSelect = Y;
23882 + sqliteExprSpan(A,&X->span,&E);
23884 +expr(A) ::= expr(X) NOT IN LP exprlist(Y) RP(E). {
23885 + A = sqliteExpr(TK_IN, X, 0, 0);
23886 + if( A ) A->pList = Y;
23887 + A = sqliteExpr(TK_NOT, A, 0, 0);
23888 + sqliteExprSpan(A,&X->span,&E);
23890 +expr(A) ::= expr(X) NOT IN LP select(Y) RP(E). {
23891 + A = sqliteExpr(TK_IN, X, 0, 0);
23892 + if( A ) A->pSelect = Y;
23893 + A = sqliteExpr(TK_NOT, A, 0, 0);
23894 + sqliteExprSpan(A,&X->span,&E);
23896 +expr(A) ::= expr(X) IN nm(Y) dbnm(D). {
23897 + SrcList *pSrc = sqliteSrcListAppend(0, &Y, &D);
23898 + A = sqliteExpr(TK_IN, X, 0, 0);
23899 + if( A ) A->pSelect = sqliteSelectNew(0,pSrc,0,0,0,0,0,-1,0);
23900 + sqliteExprSpan(A,&X->span,D.z?&D:&Y);
23902 +expr(A) ::= expr(X) NOT IN nm(Y) dbnm(D). {
23903 + SrcList *pSrc = sqliteSrcListAppend(0, &Y, &D);
23904 + A = sqliteExpr(TK_IN, X, 0, 0);
23905 + if( A ) A->pSelect = sqliteSelectNew(0,pSrc,0,0,0,0,0,-1,0);
23906 + A = sqliteExpr(TK_NOT, A, 0, 0);
23907 + sqliteExprSpan(A,&X->span,D.z?&D:&Y);
23911 +/* CASE expressions */
23912 +expr(A) ::= CASE(C) case_operand(X) case_exprlist(Y) case_else(Z) END(E). {
23913 + A = sqliteExpr(TK_CASE, X, Z, 0);
23914 + if( A ) A->pList = Y;
23915 + sqliteExprSpan(A, &C, &E);
23917 +%type case_exprlist {ExprList*}
23918 +%destructor case_exprlist {sqliteExprListDelete($$);}
23919 +case_exprlist(A) ::= case_exprlist(X) WHEN expr(Y) THEN expr(Z). {
23920 + A = sqliteExprListAppend(X, Y, 0);
23921 + A = sqliteExprListAppend(A, Z, 0);
23923 +case_exprlist(A) ::= WHEN expr(Y) THEN expr(Z). {
23924 + A = sqliteExprListAppend(0, Y, 0);
23925 + A = sqliteExprListAppend(A, Z, 0);
23927 +%type case_else {Expr*}
23928 +case_else(A) ::= ELSE expr(X). {A = X;}
23929 +case_else(A) ::= . {A = 0;}
23930 +%type case_operand {Expr*}
23931 +case_operand(A) ::= expr(X). {A = X;}
23932 +case_operand(A) ::= . {A = 0;}
23934 +%type exprlist {ExprList*}
23935 +%destructor exprlist {sqliteExprListDelete($$);}
23936 +%type expritem {Expr*}
23937 +%destructor expritem {sqliteExprDelete($$);}
23939 +exprlist(A) ::= exprlist(X) COMMA expritem(Y).
23940 + {A = sqliteExprListAppend(X,Y,0);}
23941 +exprlist(A) ::= expritem(X). {A = sqliteExprListAppend(0,X,0);}
23942 +expritem(A) ::= expr(X). {A = X;}
23943 +expritem(A) ::= . {A = 0;}
23945 +///////////////////////////// The CREATE INDEX command ///////////////////////
23947 +cmd ::= CREATE(S) uniqueflag(U) INDEX nm(X)
23948 + ON nm(Y) dbnm(D) LP idxlist(Z) RP(E) onconf(R). {
23949 + SrcList *pSrc = sqliteSrcListAppend(0, &Y, &D);
23950 + if( U!=OE_None ) U = R;
23951 + if( U==OE_Default) U = OE_Abort;
23952 + sqliteCreateIndex(pParse, &X, pSrc, Z, U, &S, &E);
23955 +%type uniqueflag {int}
23956 +uniqueflag(A) ::= UNIQUE. { A = OE_Abort; }
23957 +uniqueflag(A) ::= . { A = OE_None; }
23959 +%type idxlist {IdList*}
23960 +%destructor idxlist {sqliteIdListDelete($$);}
23961 +%type idxlist_opt {IdList*}
23962 +%destructor idxlist_opt {sqliteIdListDelete($$);}
23963 +%type idxitem {Token}
23965 +idxlist_opt(A) ::= . {A = 0;}
23966 +idxlist_opt(A) ::= LP idxlist(X) RP. {A = X;}
23967 +idxlist(A) ::= idxlist(X) COMMA idxitem(Y). {A = sqliteIdListAppend(X,&Y);}
23968 +idxlist(A) ::= idxitem(Y). {A = sqliteIdListAppend(0,&Y);}
23969 +idxitem(A) ::= nm(X) sortorder. {A = X;}
23971 +///////////////////////////// The DROP INDEX command /////////////////////////
23974 +cmd ::= DROP INDEX nm(X) dbnm(Y). {
23975 + sqliteDropIndex(pParse, sqliteSrcListAppend(0,&X,&Y));
23979 +///////////////////////////// The COPY command ///////////////////////////////
23981 +cmd ::= COPY orconf(R) nm(X) dbnm(D) FROM nm(Y) USING DELIMITERS STRING(Z).
23982 + {sqliteCopy(pParse,sqliteSrcListAppend(0,&X,&D),&Y,&Z,R);}
23983 +cmd ::= COPY orconf(R) nm(X) dbnm(D) FROM nm(Y).
23984 + {sqliteCopy(pParse,sqliteSrcListAppend(0,&X,&D),&Y,0,R);}
23986 +///////////////////////////// The VACUUM command /////////////////////////////
23988 +cmd ::= VACUUM. {sqliteVacuum(pParse,0);}
23989 +cmd ::= VACUUM nm(X). {sqliteVacuum(pParse,&X);}
23991 +///////////////////////////// The PRAGMA command /////////////////////////////
23993 +cmd ::= PRAGMA ids(X) EQ nm(Y). {sqlitePragma(pParse,&X,&Y,0);}
23994 +cmd ::= PRAGMA ids(X) EQ ON(Y). {sqlitePragma(pParse,&X,&Y,0);}
23995 +cmd ::= PRAGMA ids(X) EQ plus_num(Y). {sqlitePragma(pParse,&X,&Y,0);}
23996 +cmd ::= PRAGMA ids(X) EQ minus_num(Y). {sqlitePragma(pParse,&X,&Y,1);}
23997 +cmd ::= PRAGMA ids(X) LP nm(Y) RP. {sqlitePragma(pParse,&X,&Y,0);}
23998 +cmd ::= PRAGMA ids(X). {sqlitePragma(pParse,&X,&X,0);}
23999 +plus_num(A) ::= plus_opt number(X). {A = X;}
24000 +minus_num(A) ::= MINUS number(X). {A = X;}
24001 +number(A) ::= INTEGER(X). {A = X;}
24002 +number(A) ::= FLOAT(X). {A = X;}
24003 +plus_opt ::= PLUS.
24006 +//////////////////////////// The CREATE TRIGGER command /////////////////////
24008 +cmd ::= CREATE(A) trigger_decl BEGIN trigger_cmd_list(S) END(Z). {
24011 + all.n = (Z.z - A.z) + Z.n;
24012 + sqliteFinishTrigger(pParse, S, &all);
24015 +trigger_decl ::= temp(T) TRIGGER nm(B) trigger_time(C) trigger_event(D)
24016 + ON nm(E) dbnm(DB) foreach_clause(F) when_clause(G). {
24017 + SrcList *pTab = sqliteSrcListAppend(0, &E, &DB);
24018 + sqliteBeginTrigger(pParse, &B, C, D.a, D.b, pTab, F, G, T);
24021 +%type trigger_time {int}
24022 +trigger_time(A) ::= BEFORE. { A = TK_BEFORE; }
24023 +trigger_time(A) ::= AFTER. { A = TK_AFTER; }
24024 +trigger_time(A) ::= INSTEAD OF. { A = TK_INSTEAD;}
24025 +trigger_time(A) ::= . { A = TK_BEFORE; }
24027 +%type trigger_event {struct TrigEvent}
24028 +%destructor trigger_event {sqliteIdListDelete($$.b);}
24029 +trigger_event(A) ::= DELETE. { A.a = TK_DELETE; A.b = 0; }
24030 +trigger_event(A) ::= INSERT. { A.a = TK_INSERT; A.b = 0; }
24031 +trigger_event(A) ::= UPDATE. { A.a = TK_UPDATE; A.b = 0;}
24032 +trigger_event(A) ::= UPDATE OF inscollist(X). {A.a = TK_UPDATE; A.b = X; }
24034 +%type foreach_clause {int}
24035 +foreach_clause(A) ::= . { A = TK_ROW; }
24036 +foreach_clause(A) ::= FOR EACH ROW. { A = TK_ROW; }
24037 +foreach_clause(A) ::= FOR EACH STATEMENT. { A = TK_STATEMENT; }
24039 +%type when_clause {Expr *}
24040 +when_clause(A) ::= . { A = 0; }
24041 +when_clause(A) ::= WHEN expr(X). { A = X; }
24043 +%type trigger_cmd_list {TriggerStep *}
24044 +%destructor trigger_cmd_list {sqliteDeleteTriggerStep($$);}
24045 +trigger_cmd_list(A) ::= trigger_cmd(X) SEMI trigger_cmd_list(Y). {
24049 +trigger_cmd_list(A) ::= . { A = 0; }
24051 +%type trigger_cmd {TriggerStep *}
24052 +%destructor trigger_cmd {sqliteDeleteTriggerStep($$);}
24054 +trigger_cmd(A) ::= UPDATE orconf(R) nm(X) SET setlist(Y) where_opt(Z).
24055 + { A = sqliteTriggerUpdateStep(&X, Y, Z, R); }
24058 +trigger_cmd(A) ::= insert_cmd(R) INTO nm(X) inscollist_opt(F)
24059 + VALUES LP itemlist(Y) RP.
24060 +{A = sqliteTriggerInsertStep(&X, F, Y, 0, R);}
24062 +trigger_cmd(A) ::= insert_cmd(R) INTO nm(X) inscollist_opt(F) select(S).
24063 + {A = sqliteTriggerInsertStep(&X, F, 0, S, R);}
24066 +trigger_cmd(A) ::= DELETE FROM nm(X) where_opt(Y).
24067 + {A = sqliteTriggerDeleteStep(&X, Y);}
24070 +trigger_cmd(A) ::= select(X). {A = sqliteTriggerSelectStep(X); }
24072 +// The special RAISE expression that may occur in trigger programs
24073 +expr(A) ::= RAISE(X) LP IGNORE RP(Y). {
24074 + A = sqliteExpr(TK_RAISE, 0, 0, 0);
24075 + A->iColumn = OE_Ignore;
24076 + sqliteExprSpan(A, &X, &Y);
24078 +expr(A) ::= RAISE(X) LP ROLLBACK COMMA nm(Z) RP(Y). {
24079 + A = sqliteExpr(TK_RAISE, 0, 0, &Z);
24080 + A->iColumn = OE_Rollback;
24081 + sqliteExprSpan(A, &X, &Y);
24083 +expr(A) ::= RAISE(X) LP ABORT COMMA nm(Z) RP(Y). {
24084 + A = sqliteExpr(TK_RAISE, 0, 0, &Z);
24085 + A->iColumn = OE_Abort;
24086 + sqliteExprSpan(A, &X, &Y);
24088 +expr(A) ::= RAISE(X) LP FAIL COMMA nm(Z) RP(Y). {
24089 + A = sqliteExpr(TK_RAISE, 0, 0, &Z);
24090 + A->iColumn = OE_Fail;
24091 + sqliteExprSpan(A, &X, &Y);
24094 +//////////////////////// DROP TRIGGER statement //////////////////////////////
24095 +cmd ::= DROP TRIGGER nm(X) dbnm(D). {
24096 + sqliteDropTrigger(pParse,sqliteSrcListAppend(0,&X,&D));
24099 +//////////////////////// ATTACH DATABASE file AS name /////////////////////////
24100 +cmd ::= ATTACH database_kw_opt ids(F) AS nm(D) key_opt(K). {
24101 + sqliteAttach(pParse, &F, &D, &K);
24103 +%type key_opt {Token}
24104 +key_opt(A) ::= USING ids(X). { A = X; }
24105 +key_opt(A) ::= . { A.z = 0; A.n = 0; }
24107 +database_kw_opt ::= DATABASE.
24108 +database_kw_opt ::= .
24110 +//////////////////////// DETACH DATABASE name /////////////////////////////////
24111 +cmd ::= DETACH database_kw_opt nm(D). {
24112 + sqliteDetach(pParse, &D);
24115 +++ b/ext/sqlite/libsqlite/src/pragma.c
24120 +** The author disclaims copyright to this source code. In place of
24121 +** a legal notice, here is a blessing:
24123 +** May you do good and not evil.
24124 +** May you find forgiveness for yourself and forgive others.
24125 +** May you share freely, never taking more than you give.
24127 +*************************************************************************
24128 +** This file contains code used to implement the PRAGMA command.
24132 +#include "sqliteInt.h"
24133 +#include <ctype.h>
24136 +** Interpret the given string as a boolean value.
24138 +static int getBoolean(const char *z){
24139 + static char *azTrue[] = { "yes", "on", "true" };
24141 + if( z[0]==0 ) return 0;
24142 + if( isdigit(z[0]) || (z[0]=='-' && isdigit(z[1])) ){
24145 + for(i=0; i<sizeof(azTrue)/sizeof(azTrue[0]); i++){
24146 + if( sqliteStrICmp(z,azTrue[i])==0 ) return 1;
24152 +** Interpret the given string as a safety level. Return 0 for OFF,
24153 +** 1 for ON or NORMAL and 2 for FULL. Return 1 for an empty or
24154 +** unrecognized string argument.
24156 +** Note that the values returned are one less that the values that
24157 +** should be passed into sqliteBtreeSetSafetyLevel(). The is done
24158 +** to support legacy SQL code. The safety level used to be boolean
24159 +** and older scripts may have used numbers 0 for OFF and 1 for ON.
24161 +static int getSafetyLevel(char *z){
24162 + static const struct {
24163 + const char *zWord;
24175 + if( z[0]==0 ) return 1;
24176 + if( isdigit(z[0]) || (z[0]=='-' && isdigit(z[1])) ){
24179 + for(i=0; i<sizeof(aKey)/sizeof(aKey[0]); i++){
24180 + if( sqliteStrICmp(z,aKey[i].zWord)==0 ) return aKey[i].val;
24186 +** Interpret the given string as a temp db location. Return 1 for file
24187 +** backed temporary databases, 2 for the Red-Black tree in memory database
24188 +** and 0 to use the compile-time default.
24190 +static int getTempStore(const char *z){
24191 + if( z[0]>='0' && z[0]<='2' ){
24192 + return z[0] - '0';
24193 + }else if( sqliteStrICmp(z, "file")==0 ){
24195 + }else if( sqliteStrICmp(z, "memory")==0 ){
24203 +** If the TEMP database is open, close it and mark the database schema
24204 +** as needing reloading. This must be done when using the TEMP_STORE
24205 +** or DEFAULT_TEMP_STORE pragmas.
24207 +static int changeTempStorage(Parse *pParse, const char *zStorageType){
24208 + int ts = getTempStore(zStorageType);
24209 + sqlite *db = pParse->db;
24210 + if( db->temp_store==ts ) return SQLITE_OK;
24211 + if( db->aDb[1].pBt!=0 ){
24212 + if( db->flags & SQLITE_InTrans ){
24213 + sqliteErrorMsg(pParse, "temporary storage cannot be changed "
24214 + "from within a transaction");
24215 + return SQLITE_ERROR;
24217 + sqliteBtreeClose(db->aDb[1].pBt);
24218 + db->aDb[1].pBt = 0;
24219 + sqliteResetInternalSchema(db, 0);
24221 + db->temp_store = ts;
24222 + return SQLITE_OK;
24226 +** Check to see if zRight and zLeft refer to a pragma that queries
24227 +** or changes one of the flags in db->flags. Return 1 if so and 0 if not.
24228 +** Also, implement the pragma.
24230 +static int flagPragma(Parse *pParse, const char *zLeft, const char *zRight){
24231 + static const struct {
24232 + const char *zName; /* Name of the pragma */
24233 + int mask; /* Mask for the db->flags value */
24235 + { "vdbe_trace", SQLITE_VdbeTrace },
24236 + { "full_column_names", SQLITE_FullColNames },
24237 + { "short_column_names", SQLITE_ShortColNames },
24238 + { "show_datatypes", SQLITE_ReportTypes },
24239 + { "count_changes", SQLITE_CountRows },
24240 + { "empty_result_callbacks", SQLITE_NullCallback },
24243 + for(i=0; i<sizeof(aPragma)/sizeof(aPragma[0]); i++){
24244 + if( sqliteStrICmp(zLeft, aPragma[i].zName)==0 ){
24245 + sqlite *db = pParse->db;
24247 + if( strcmp(zLeft,zRight)==0 && (v = sqliteGetVdbe(pParse))!=0 ){
24248 + sqliteVdbeOp3(v, OP_ColumnName, 0, 1, aPragma[i].zName, P3_STATIC);
24249 + sqliteVdbeOp3(v, OP_ColumnName, 1, 0, "boolean", P3_STATIC);
24250 + sqliteVdbeCode(v, OP_Integer, (db->flags & aPragma[i].mask)!=0, 0,
24251 + OP_Callback, 1, 0,
24253 + }else if( getBoolean(zRight) ){
24254 + db->flags |= aPragma[i].mask;
24256 + db->flags &= ~aPragma[i].mask;
24265 +** Process a pragma statement.
24267 +** Pragmas are of this form:
24269 +** PRAGMA id = value
24271 +** The identifier might also be a string. The value is a string, and
24272 +** identifier, or a number. If minusFlag is true, then the value is
24273 +** a number that was preceded by a minus sign.
24275 +void sqlitePragma(Parse *pParse, Token *pLeft, Token *pRight, int minusFlag){
24277 + char *zRight = 0;
24278 + sqlite *db = pParse->db;
24279 + Vdbe *v = sqliteGetVdbe(pParse);
24280 + if( v==0 ) return;
24282 + zLeft = sqliteStrNDup(pLeft->z, pLeft->n);
24283 + sqliteDequote(zLeft);
24286 + sqliteSetNString(&zRight, "-", 1, pRight->z, pRight->n, 0);
24288 + zRight = sqliteStrNDup(pRight->z, pRight->n);
24289 + sqliteDequote(zRight);
24291 + if( sqliteAuthCheck(pParse, SQLITE_PRAGMA, zLeft, zRight, 0) ){
24292 + sqliteFree(zLeft);
24293 + sqliteFree(zRight);
24298 + ** PRAGMA default_cache_size
24299 + ** PRAGMA default_cache_size=N
24301 + ** The first form reports the current persistent setting for the
24302 + ** page cache size. The value returned is the maximum number of
24303 + ** pages in the page cache. The second form sets both the current
24304 + ** page cache size value and the persistent page cache size value
24305 + ** stored in the database file.
24307 + ** The default cache size is stored in meta-value 2 of page 1 of the
24308 + ** database file. The cache size is actually the absolute value of
24309 + ** this memory location. The sign of meta-value 2 determines the
24310 + ** synchronous setting. A negative value means synchronous is off
24311 + ** and a positive value means synchronous is on.
24313 + if( sqliteStrICmp(zLeft,"default_cache_size")==0 ){
24314 + static VdbeOpList getCacheSize[] = {
24315 + { OP_ReadCookie, 0, 2, 0},
24316 + { OP_AbsValue, 0, 0, 0},
24317 + { OP_Dup, 0, 0, 0},
24318 + { OP_Integer, 0, 0, 0},
24319 + { OP_Ne, 0, 6, 0},
24320 + { OP_Integer, 0, 0, 0}, /* 5 */
24321 + { OP_ColumnName, 0, 1, "cache_size"},
24322 + { OP_Callback, 1, 0, 0},
24325 + if( pRight->z==pLeft->z ){
24326 + addr = sqliteVdbeAddOpList(v, ArraySize(getCacheSize), getCacheSize);
24327 + sqliteVdbeChangeP1(v, addr+5, MAX_PAGES);
24329 + int size = atoi(zRight);
24330 + if( size<0 ) size = -size;
24331 + sqliteBeginWriteOperation(pParse, 0, 0);
24332 + sqliteVdbeAddOp(v, OP_Integer, size, 0);
24333 + sqliteVdbeAddOp(v, OP_ReadCookie, 0, 2);
24334 + addr = sqliteVdbeAddOp(v, OP_Integer, 0, 0);
24335 + sqliteVdbeAddOp(v, OP_Ge, 0, addr+3);
24336 + sqliteVdbeAddOp(v, OP_Negative, 0, 0);
24337 + sqliteVdbeAddOp(v, OP_SetCookie, 0, 2);
24338 + sqliteEndWriteOperation(pParse);
24339 + db->cache_size = db->cache_size<0 ? -size : size;
24340 + sqliteBtreeSetCacheSize(db->aDb[0].pBt, db->cache_size);
24345 + ** PRAGMA cache_size
24346 + ** PRAGMA cache_size=N
24348 + ** The first form reports the current local setting for the
24349 + ** page cache size. The local setting can be different from
24350 + ** the persistent cache size value that is stored in the database
24351 + ** file itself. The value returned is the maximum number of
24352 + ** pages in the page cache. The second form sets the local
24353 + ** page cache size value. It does not change the persistent
24354 + ** cache size stored on the disk so the cache size will revert
24355 + ** to its default value when the database is closed and reopened.
24356 + ** N should be a positive integer.
24358 + if( sqliteStrICmp(zLeft,"cache_size")==0 ){
24359 + static VdbeOpList getCacheSize[] = {
24360 + { OP_ColumnName, 0, 1, "cache_size"},
24361 + { OP_Callback, 1, 0, 0},
24363 + if( pRight->z==pLeft->z ){
24364 + int size = db->cache_size;;
24365 + if( size<0 ) size = -size;
24366 + sqliteVdbeAddOp(v, OP_Integer, size, 0);
24367 + sqliteVdbeAddOpList(v, ArraySize(getCacheSize), getCacheSize);
24369 + int size = atoi(zRight);
24370 + if( size<0 ) size = -size;
24371 + if( db->cache_size<0 ) size = -size;
24372 + db->cache_size = size;
24373 + sqliteBtreeSetCacheSize(db->aDb[0].pBt, db->cache_size);
24378 + ** PRAGMA default_synchronous
24379 + ** PRAGMA default_synchronous=ON|OFF|NORMAL|FULL
24381 + ** The first form returns the persistent value of the "synchronous" setting
24382 + ** that is stored in the database. This is the synchronous setting that
24383 + ** is used whenever the database is opened unless overridden by a separate
24384 + ** "synchronous" pragma. The second form changes the persistent and the
24385 + ** local synchronous setting to the value given.
24387 + ** If synchronous is OFF, SQLite does not attempt any fsync() systems calls
24388 + ** to make sure data is committed to disk. Write operations are very fast,
24389 + ** but a power failure can leave the database in an inconsistent state.
24390 + ** If synchronous is ON or NORMAL, SQLite will do an fsync() system call to
24391 + ** make sure data is being written to disk. The risk of corruption due to
24392 + ** a power loss in this mode is negligible but non-zero. If synchronous
24393 + ** is FULL, extra fsync()s occur to reduce the risk of corruption to near
24394 + ** zero, but with a write performance penalty. The default mode is NORMAL.
24396 + if( sqliteStrICmp(zLeft,"default_synchronous")==0 ){
24397 + static VdbeOpList getSync[] = {
24398 + { OP_ColumnName, 0, 1, "synchronous"},
24399 + { OP_ReadCookie, 0, 3, 0},
24400 + { OP_Dup, 0, 0, 0},
24401 + { OP_If, 0, 0, 0}, /* 3 */
24402 + { OP_ReadCookie, 0, 2, 0},
24403 + { OP_Integer, 0, 0, 0},
24404 + { OP_Lt, 0, 5, 0},
24405 + { OP_AddImm, 1, 0, 0},
24406 + { OP_Callback, 1, 0, 0},
24407 + { OP_Halt, 0, 0, 0},
24408 + { OP_AddImm, -1, 0, 0}, /* 10 */
24409 + { OP_Callback, 1, 0, 0}
24411 + if( pRight->z==pLeft->z ){
24412 + int addr = sqliteVdbeAddOpList(v, ArraySize(getSync), getSync);
24413 + sqliteVdbeChangeP2(v, addr+3, addr+10);
24416 + int size = db->cache_size;
24417 + if( size<0 ) size = -size;
24418 + sqliteBeginWriteOperation(pParse, 0, 0);
24419 + sqliteVdbeAddOp(v, OP_ReadCookie, 0, 2);
24420 + sqliteVdbeAddOp(v, OP_Dup, 0, 0);
24421 + addr = sqliteVdbeAddOp(v, OP_Integer, 0, 0);
24422 + sqliteVdbeAddOp(v, OP_Ne, 0, addr+3);
24423 + sqliteVdbeAddOp(v, OP_AddImm, MAX_PAGES, 0);
24424 + sqliteVdbeAddOp(v, OP_AbsValue, 0, 0);
24425 + db->safety_level = getSafetyLevel(zRight)+1;
24426 + if( db->safety_level==1 ){
24427 + sqliteVdbeAddOp(v, OP_Negative, 0, 0);
24430 + sqliteVdbeAddOp(v, OP_SetCookie, 0, 2);
24431 + sqliteVdbeAddOp(v, OP_Integer, db->safety_level, 0);
24432 + sqliteVdbeAddOp(v, OP_SetCookie, 0, 3);
24433 + sqliteEndWriteOperation(pParse);
24434 + db->cache_size = size;
24435 + sqliteBtreeSetCacheSize(db->aDb[0].pBt, db->cache_size);
24436 + sqliteBtreeSetSafetyLevel(db->aDb[0].pBt, db->safety_level);
24441 + ** PRAGMA synchronous
24442 + ** PRAGMA synchronous=OFF|ON|NORMAL|FULL
24444 + ** Return or set the local value of the synchronous flag. Changing
24445 + ** the local value does not make changes to the disk file and the
24446 + ** default value will be restored the next time the database is
24449 + if( sqliteStrICmp(zLeft,"synchronous")==0 ){
24450 + static VdbeOpList getSync[] = {
24451 + { OP_ColumnName, 0, 1, "synchronous"},
24452 + { OP_Callback, 1, 0, 0},
24454 + if( pRight->z==pLeft->z ){
24455 + sqliteVdbeAddOp(v, OP_Integer, db->safety_level-1, 0);
24456 + sqliteVdbeAddOpList(v, ArraySize(getSync), getSync);
24458 + int size = db->cache_size;
24459 + if( size<0 ) size = -size;
24460 + db->safety_level = getSafetyLevel(zRight)+1;
24461 + if( db->safety_level==1 ) size = -size;
24462 + db->cache_size = size;
24463 + sqliteBtreeSetCacheSize(db->aDb[0].pBt, db->cache_size);
24464 + sqliteBtreeSetSafetyLevel(db->aDb[0].pBt, db->safety_level);
24469 + if( sqliteStrICmp(zLeft, "trigger_overhead_test")==0 ){
24470 + if( getBoolean(zRight) ){
24471 + always_code_trigger_setup = 1;
24473 + always_code_trigger_setup = 0;
24478 + if( flagPragma(pParse, zLeft, zRight) ){
24479 + /* The flagPragma() call also generates any necessary code */
24482 + if( sqliteStrICmp(zLeft, "table_info")==0 ){
24484 + pTab = sqliteFindTable(db, zRight, 0);
24486 + static VdbeOpList tableInfoPreface[] = {
24487 + { OP_ColumnName, 0, 0, "cid"},
24488 + { OP_ColumnName, 1, 0, "name"},
24489 + { OP_ColumnName, 2, 0, "type"},
24490 + { OP_ColumnName, 3, 0, "notnull"},
24491 + { OP_ColumnName, 4, 0, "dflt_value"},
24492 + { OP_ColumnName, 5, 1, "pk"},
24495 + sqliteVdbeAddOpList(v, ArraySize(tableInfoPreface), tableInfoPreface);
24496 + sqliteViewGetColumnNames(pParse, pTab);
24497 + for(i=0; i<pTab->nCol; i++){
24498 + sqliteVdbeAddOp(v, OP_Integer, i, 0);
24499 + sqliteVdbeOp3(v, OP_String, 0, 0, pTab->aCol[i].zName, 0);
24500 + sqliteVdbeOp3(v, OP_String, 0, 0,
24501 + pTab->aCol[i].zType ? pTab->aCol[i].zType : "numeric", 0);
24502 + sqliteVdbeAddOp(v, OP_Integer, pTab->aCol[i].notNull, 0);
24503 + sqliteVdbeOp3(v, OP_String, 0, 0,
24504 + pTab->aCol[i].zDflt, P3_STATIC);
24505 + sqliteVdbeAddOp(v, OP_Integer, pTab->aCol[i].isPrimKey, 0);
24506 + sqliteVdbeAddOp(v, OP_Callback, 6, 0);
24511 + if( sqliteStrICmp(zLeft, "index_info")==0 ){
24514 + pIdx = sqliteFindIndex(db, zRight, 0);
24516 + static VdbeOpList tableInfoPreface[] = {
24517 + { OP_ColumnName, 0, 0, "seqno"},
24518 + { OP_ColumnName, 1, 0, "cid"},
24519 + { OP_ColumnName, 2, 1, "name"},
24522 + pTab = pIdx->pTable;
24523 + sqliteVdbeAddOpList(v, ArraySize(tableInfoPreface), tableInfoPreface);
24524 + for(i=0; i<pIdx->nColumn; i++){
24525 + int cnum = pIdx->aiColumn[i];
24526 + sqliteVdbeAddOp(v, OP_Integer, i, 0);
24527 + sqliteVdbeAddOp(v, OP_Integer, cnum, 0);
24528 + assert( pTab->nCol>cnum );
24529 + sqliteVdbeOp3(v, OP_String, 0, 0, pTab->aCol[cnum].zName, 0);
24530 + sqliteVdbeAddOp(v, OP_Callback, 3, 0);
24535 + if( sqliteStrICmp(zLeft, "index_list")==0 ){
24538 + pTab = sqliteFindTable(db, zRight, 0);
24540 + v = sqliteGetVdbe(pParse);
24541 + pIdx = pTab->pIndex;
24543 + if( pTab && pIdx ){
24545 + static VdbeOpList indexListPreface[] = {
24546 + { OP_ColumnName, 0, 0, "seq"},
24547 + { OP_ColumnName, 1, 0, "name"},
24548 + { OP_ColumnName, 2, 1, "unique"},
24551 + sqliteVdbeAddOpList(v, ArraySize(indexListPreface), indexListPreface);
24553 + sqliteVdbeAddOp(v, OP_Integer, i, 0);
24554 + sqliteVdbeOp3(v, OP_String, 0, 0, pIdx->zName, 0);
24555 + sqliteVdbeAddOp(v, OP_Integer, pIdx->onError!=OE_None, 0);
24556 + sqliteVdbeAddOp(v, OP_Callback, 3, 0);
24558 + pIdx = pIdx->pNext;
24563 + if( sqliteStrICmp(zLeft, "foreign_key_list")==0 ){
24566 + pTab = sqliteFindTable(db, zRight, 0);
24568 + v = sqliteGetVdbe(pParse);
24569 + pFK = pTab->pFKey;
24571 + if( pTab && pFK ){
24573 + static VdbeOpList indexListPreface[] = {
24574 + { OP_ColumnName, 0, 0, "id"},
24575 + { OP_ColumnName, 1, 0, "seq"},
24576 + { OP_ColumnName, 2, 0, "table"},
24577 + { OP_ColumnName, 3, 0, "from"},
24578 + { OP_ColumnName, 4, 1, "to"},
24581 + sqliteVdbeAddOpList(v, ArraySize(indexListPreface), indexListPreface);
24584 + for(j=0; j<pFK->nCol; j++){
24585 + sqliteVdbeAddOp(v, OP_Integer, i, 0);
24586 + sqliteVdbeAddOp(v, OP_Integer, j, 0);
24587 + sqliteVdbeOp3(v, OP_String, 0, 0, pFK->zTo, 0);
24588 + sqliteVdbeOp3(v, OP_String, 0, 0,
24589 + pTab->aCol[pFK->aCol[j].iFrom].zName, 0);
24590 + sqliteVdbeOp3(v, OP_String, 0, 0, pFK->aCol[j].zCol, 0);
24591 + sqliteVdbeAddOp(v, OP_Callback, 5, 0);
24594 + pFK = pFK->pNextFrom;
24599 + if( sqliteStrICmp(zLeft, "database_list")==0 ){
24601 + static VdbeOpList indexListPreface[] = {
24602 + { OP_ColumnName, 0, 0, "seq"},
24603 + { OP_ColumnName, 1, 0, "name"},
24604 + { OP_ColumnName, 2, 1, "file"},
24607 + sqliteVdbeAddOpList(v, ArraySize(indexListPreface), indexListPreface);
24608 + for(i=0; i<db->nDb; i++){
24609 + if( db->aDb[i].pBt==0 ) continue;
24610 + assert( db->aDb[i].zName!=0 );
24611 + sqliteVdbeAddOp(v, OP_Integer, i, 0);
24612 + sqliteVdbeOp3(v, OP_String, 0, 0, db->aDb[i].zName, 0);
24613 + sqliteVdbeOp3(v, OP_String, 0, 0,
24614 + sqliteBtreeGetFilename(db->aDb[i].pBt), 0);
24615 + sqliteVdbeAddOp(v, OP_Callback, 3, 0);
24621 + ** PRAGMA temp_store
24622 + ** PRAGMA temp_store = "default"|"memory"|"file"
24624 + ** Return or set the local value of the temp_store flag. Changing
24625 + ** the local value does not make changes to the disk file and the default
24626 + ** value will be restored the next time the database is opened.
24628 + ** Note that it is possible for the library compile-time options to
24629 + ** override this setting
24631 + if( sqliteStrICmp(zLeft, "temp_store")==0 ){
24632 + static VdbeOpList getTmpDbLoc[] = {
24633 + { OP_ColumnName, 0, 1, "temp_store"},
24634 + { OP_Callback, 1, 0, 0},
24636 + if( pRight->z==pLeft->z ){
24637 + sqliteVdbeAddOp(v, OP_Integer, db->temp_store, 0);
24638 + sqliteVdbeAddOpList(v, ArraySize(getTmpDbLoc), getTmpDbLoc);
24640 + changeTempStorage(pParse, zRight);
24645 + ** PRAGMA default_temp_store
24646 + ** PRAGMA default_temp_store = "default"|"memory"|"file"
24648 + ** Return or set the value of the persistent temp_store flag. Any
24649 + ** change does not take effect until the next time the database is
24652 + ** Note that it is possible for the library compile-time options to
24653 + ** override this setting
24655 + if( sqliteStrICmp(zLeft, "default_temp_store")==0 ){
24656 + static VdbeOpList getTmpDbLoc[] = {
24657 + { OP_ColumnName, 0, 1, "temp_store"},
24658 + { OP_ReadCookie, 0, 5, 0},
24659 + { OP_Callback, 1, 0, 0}};
24660 + if( pRight->z==pLeft->z ){
24661 + sqliteVdbeAddOpList(v, ArraySize(getTmpDbLoc), getTmpDbLoc);
24663 + sqliteBeginWriteOperation(pParse, 0, 0);
24664 + sqliteVdbeAddOp(v, OP_Integer, getTempStore(zRight), 0);
24665 + sqliteVdbeAddOp(v, OP_SetCookie, 0, 5);
24666 + sqliteEndWriteOperation(pParse);
24671 + if( sqliteStrICmp(zLeft, "parser_trace")==0 ){
24672 + extern void sqliteParserTrace(FILE*, char *);
24673 + if( getBoolean(zRight) ){
24674 + sqliteParserTrace(stdout, "parser: ");
24676 + sqliteParserTrace(0, 0);
24681 + if( sqliteStrICmp(zLeft, "integrity_check")==0 ){
24684 + /* Code that initializes the integrity check program. Set the
24687 + static VdbeOpList initCode[] = {
24688 + { OP_Integer, 0, 0, 0},
24689 + { OP_MemStore, 0, 1, 0},
24690 + { OP_ColumnName, 0, 1, "integrity_check"},
24693 + /* Code to do an BTree integrity check on a single database file.
24695 + static VdbeOpList checkDb[] = {
24696 + { OP_SetInsert, 0, 0, "2"},
24697 + { OP_Integer, 0, 0, 0}, /* 1 */
24698 + { OP_OpenRead, 0, 2, 0},
24699 + { OP_Rewind, 0, 7, 0}, /* 3 */
24700 + { OP_Column, 0, 3, 0}, /* 4 */
24701 + { OP_SetInsert, 0, 0, 0},
24702 + { OP_Next, 0, 4, 0}, /* 6 */
24703 + { OP_IntegrityCk, 0, 0, 0}, /* 7 */
24704 + { OP_Dup, 0, 1, 0},
24705 + { OP_String, 0, 0, "ok"},
24706 + { OP_StrEq, 0, 12, 0}, /* 10 */
24707 + { OP_MemIncr, 0, 0, 0},
24708 + { OP_String, 0, 0, "*** in database "},
24709 + { OP_String, 0, 0, 0}, /* 13 */
24710 + { OP_String, 0, 0, " ***\n"},
24711 + { OP_Pull, 3, 0, 0},
24712 + { OP_Concat, 4, 1, 0},
24713 + { OP_Callback, 1, 0, 0},
24716 + /* Code that appears at the end of the integrity check. If no error
24717 + ** messages have been generated, output OK. Otherwise output the
24720 + static VdbeOpList endCode[] = {
24721 + { OP_MemLoad, 0, 0, 0},
24722 + { OP_Integer, 0, 0, 0},
24723 + { OP_Ne, 0, 0, 0}, /* 2 */
24724 + { OP_String, 0, 0, "ok"},
24725 + { OP_Callback, 1, 0, 0},
24728 + /* Initialize the VDBE program */
24729 + sqliteVdbeAddOpList(v, ArraySize(initCode), initCode);
24731 + /* Do an integrity check on each database file */
24732 + for(i=0; i<db->nDb; i++){
24735 + /* Do an integrity check of the B-Tree
24737 + addr = sqliteVdbeAddOpList(v, ArraySize(checkDb), checkDb);
24738 + sqliteVdbeChangeP1(v, addr+1, i);
24739 + sqliteVdbeChangeP2(v, addr+3, addr+7);
24740 + sqliteVdbeChangeP2(v, addr+6, addr+4);
24741 + sqliteVdbeChangeP2(v, addr+7, i);
24742 + sqliteVdbeChangeP2(v, addr+10, addr+ArraySize(checkDb));
24743 + sqliteVdbeChangeP3(v, addr+13, db->aDb[i].zName, P3_STATIC);
24745 + /* Make sure all the indices are constructed correctly.
24747 + sqliteCodeVerifySchema(pParse, i);
24748 + for(x=sqliteHashFirst(&db->aDb[i].tblHash); x; x=sqliteHashNext(x)){
24749 + Table *pTab = sqliteHashData(x);
24753 + if( pTab->pIndex==0 ) continue;
24754 + sqliteVdbeAddOp(v, OP_Integer, i, 0);
24755 + sqliteVdbeOp3(v, OP_OpenRead, 1, pTab->tnum, pTab->zName, 0);
24756 + for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
24757 + if( pIdx->tnum==0 ) continue;
24758 + sqliteVdbeAddOp(v, OP_Integer, pIdx->iDb, 0);
24759 + sqliteVdbeOp3(v, OP_OpenRead, j+2, pIdx->tnum, pIdx->zName, 0);
24761 + sqliteVdbeAddOp(v, OP_Integer, 0, 0);
24762 + sqliteVdbeAddOp(v, OP_MemStore, 1, 1);
24763 + loopTop = sqliteVdbeAddOp(v, OP_Rewind, 1, 0);
24764 + sqliteVdbeAddOp(v, OP_MemIncr, 1, 0);
24765 + for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
24767 + static VdbeOpList idxErr[] = {
24768 + { OP_MemIncr, 0, 0, 0},
24769 + { OP_String, 0, 0, "rowid "},
24770 + { OP_Recno, 1, 0, 0},
24771 + { OP_String, 0, 0, " missing from index "},
24772 + { OP_String, 0, 0, 0}, /* 4 */
24773 + { OP_Concat, 4, 0, 0},
24774 + { OP_Callback, 1, 0, 0},
24776 + sqliteVdbeAddOp(v, OP_Recno, 1, 0);
24777 + for(k=0; k<pIdx->nColumn; k++){
24778 + int idx = pIdx->aiColumn[k];
24779 + if( idx==pTab->iPKey ){
24780 + sqliteVdbeAddOp(v, OP_Recno, 1, 0);
24782 + sqliteVdbeAddOp(v, OP_Column, 1, idx);
24785 + sqliteVdbeAddOp(v, OP_MakeIdxKey, pIdx->nColumn, 0);
24786 + if( db->file_format>=4 ) sqliteAddIdxKeyType(v, pIdx);
24787 + jmp2 = sqliteVdbeAddOp(v, OP_Found, j+2, 0);
24788 + addr = sqliteVdbeAddOpList(v, ArraySize(idxErr), idxErr);
24789 + sqliteVdbeChangeP3(v, addr+4, pIdx->zName, P3_STATIC);
24790 + sqliteVdbeChangeP2(v, jmp2, sqliteVdbeCurrentAddr(v));
24792 + sqliteVdbeAddOp(v, OP_Next, 1, loopTop+1);
24793 + sqliteVdbeChangeP2(v, loopTop, sqliteVdbeCurrentAddr(v));
24794 + for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
24795 + static VdbeOpList cntIdx[] = {
24796 + { OP_Integer, 0, 0, 0},
24797 + { OP_MemStore, 2, 1, 0},
24798 + { OP_Rewind, 0, 0, 0}, /* 2 */
24799 + { OP_MemIncr, 2, 0, 0},
24800 + { OP_Next, 0, 0, 0}, /* 4 */
24801 + { OP_MemLoad, 1, 0, 0},
24802 + { OP_MemLoad, 2, 0, 0},
24803 + { OP_Eq, 0, 0, 0}, /* 7 */
24804 + { OP_MemIncr, 0, 0, 0},
24805 + { OP_String, 0, 0, "wrong # of entries in index "},
24806 + { OP_String, 0, 0, 0}, /* 10 */
24807 + { OP_Concat, 2, 0, 0},
24808 + { OP_Callback, 1, 0, 0},
24810 + if( pIdx->tnum==0 ) continue;
24811 + addr = sqliteVdbeAddOpList(v, ArraySize(cntIdx), cntIdx);
24812 + sqliteVdbeChangeP1(v, addr+2, j+2);
24813 + sqliteVdbeChangeP2(v, addr+2, addr+5);
24814 + sqliteVdbeChangeP1(v, addr+4, j+2);
24815 + sqliteVdbeChangeP2(v, addr+4, addr+3);
24816 + sqliteVdbeChangeP2(v, addr+7, addr+ArraySize(cntIdx));
24817 + sqliteVdbeChangeP3(v, addr+10, pIdx->zName, P3_STATIC);
24821 + addr = sqliteVdbeAddOpList(v, ArraySize(endCode), endCode);
24822 + sqliteVdbeChangeP2(v, addr+2, addr+ArraySize(endCode));
24826 + sqliteFree(zLeft);
24827 + sqliteFree(zRight);
24830 +++ b/ext/sqlite/libsqlite/src/printf.c
24833 +** The "printf" code that follows dates from the 1980's. It is in
24834 +** the public domain. The original comments are included here for
24835 +** completeness. They are very out-of-date but might be useful as
24836 +** an historical reference. Most of the "enhancements" have been backed
24837 +** out so that the functionality is now the same as standard printf().
24839 +**************************************************************************
24841 +** The following modules is an enhanced replacement for the "printf" subroutines
24842 +** found in the standard C library. The following enhancements are
24845 +** + Additional functions. The standard set of "printf" functions
24846 +** includes printf, fprintf, sprintf, vprintf, vfprintf, and
24847 +** vsprintf. This module adds the following:
24849 +** * snprintf -- Works like sprintf, but has an extra argument
24850 +** which is the size of the buffer written to.
24852 +** * mprintf -- Similar to sprintf. Writes output to memory
24853 +** obtained from malloc.
24855 +** * xprintf -- Calls a function to dispose of output.
24857 +** * nprintf -- No output, but returns the number of characters
24858 +** that would have been output by printf.
24860 +** * A v- version (ex: vsnprintf) of every function is also
24863 +** + A few extensions to the formatting notation are supported:
24865 +** * The "=" flag (similar to "-") causes the output to be
24866 +** be centered in the appropriately sized field.
24868 +** * The %b field outputs an integer in binary notation.
24870 +** * The %c field now accepts a precision. The character output
24871 +** is repeated by the number of times the precision specifies.
24873 +** * The %' field works like %c, but takes as its character the
24874 +** next character of the format string, instead of the next
24875 +** argument. For example, printf("%.78'-") prints 78 minus
24876 +** signs, the same as printf("%.78c",'-').
24878 +** + When compiled using GCC on a SPARC, this version of printf is
24879 +** faster than the library printf for SUN OS 4.1.
24881 +** + All functions are fully reentrant.
24884 +#include "sqliteInt.h"
24887 +** Conversion types fall into various categories as defined by the
24888 +** following enumeration.
24890 +#define etRADIX 1 /* Integer types. %d, %x, %o, and so forth */
24891 +#define etFLOAT 2 /* Floating point. %f */
24892 +#define etEXP 3 /* Exponentional notation. %e and %E */
24893 +#define etGENERIC 4 /* Floating or exponential, depending on exponent. %g */
24894 +#define etSIZE 5 /* Return number of characters processed so far. %n */
24895 +#define etSTRING 6 /* Strings. %s */
24896 +#define etDYNSTRING 7 /* Dynamically allocated strings. %z */
24897 +#define etPERCENT 8 /* Percent symbol. %% */
24898 +#define etCHARX 9 /* Characters. %c */
24899 +#define etERROR 10 /* Used to indicate no such conversion type */
24900 +/* The rest are extensions, not normally found in printf() */
24901 +#define etCHARLIT 11 /* Literal characters. %' */
24902 +#define etSQLESCAPE 12 /* Strings with '\'' doubled. %q */
24903 +#define etSQLESCAPE2 13 /* Strings with '\'' doubled and enclosed in '',
24904 + NULL pointers replaced by SQL NULL. %Q */
24905 +#define etTOKEN 14 /* a pointer to a Token structure */
24906 +#define etSRCLIST 15 /* a pointer to a SrcList */
24910 +** An "etByte" is an 8-bit unsigned value.
24912 +typedef unsigned char etByte;
24915 +** Each builtin conversion character (ex: the 'd' in "%d") is described
24916 +** by an instance of the following structure
24918 +typedef struct et_info { /* Information about each format field */
24919 + char fmttype; /* The format field code letter */
24920 + etByte base; /* The base for radix conversion */
24921 + etByte flags; /* One or more of FLAG_ constants below */
24922 + etByte type; /* Conversion paradigm */
24923 + char *charset; /* The character set for conversion */
24924 + char *prefix; /* Prefix on non-zero values in alt format */
24928 +** Allowed values for et_info.flags
24930 +#define FLAG_SIGNED 1 /* True if the value to convert is signed */
24931 +#define FLAG_INTERN 2 /* True if for internal use only */
24935 +** The following table is searched linearly, so it is good to put the
24936 +** most frequently used conversion types first.
24938 +static et_info fmtinfo[] = {
24939 + { 'd', 10, 1, etRADIX, "0123456789", 0 },
24940 + { 's', 0, 0, etSTRING, 0, 0 },
24941 + { 'z', 0, 2, etDYNSTRING, 0, 0 },
24942 + { 'q', 0, 0, etSQLESCAPE, 0, 0 },
24943 + { 'Q', 0, 0, etSQLESCAPE2, 0, 0 },
24944 + { 'c', 0, 0, etCHARX, 0, 0 },
24945 + { 'o', 8, 0, etRADIX, "01234567", "0" },
24946 + { 'u', 10, 0, etRADIX, "0123456789", 0 },
24947 + { 'x', 16, 0, etRADIX, "0123456789abcdef", "x0" },
24948 + { 'X', 16, 0, etRADIX, "0123456789ABCDEF", "X0" },
24949 + { 'f', 0, 1, etFLOAT, 0, 0 },
24950 + { 'e', 0, 1, etEXP, "e", 0 },
24951 + { 'E', 0, 1, etEXP, "E", 0 },
24952 + { 'g', 0, 1, etGENERIC, "e", 0 },
24953 + { 'G', 0, 1, etGENERIC, "E", 0 },
24954 + { 'i', 10, 1, etRADIX, "0123456789", 0 },
24955 + { 'n', 0, 0, etSIZE, 0, 0 },
24956 + { '%', 0, 0, etPERCENT, 0, 0 },
24957 + { 'p', 10, 0, etRADIX, "0123456789", 0 },
24958 + { 'T', 0, 2, etTOKEN, 0, 0 },
24959 + { 'S', 0, 2, etSRCLIST, 0, 0 },
24961 +#define etNINFO (sizeof(fmtinfo)/sizeof(fmtinfo[0]))
24964 +** If NOFLOATINGPOINT is defined, then none of the floating point
24965 +** conversions will work.
24967 +#ifndef etNOFLOATINGPOINT
24969 +** "*val" is a double such that 0.1 <= *val < 10.0
24970 +** Return the ascii code for the leading digit of *val, then
24971 +** multiply "*val" by 10.0 to renormalize.
24974 +** input: *val = 3.14159
24975 +** output: *val = 1.4159 function return = '3'
24977 +** The counter *cnt is incremented each time. After counter exceeds
24978 +** 16 (the number of significant digits in a 64-bit float) '0' is
24979 +** always returned.
24981 +static int et_getdigit(LONGDOUBLE_TYPE *val, int *cnt){
24983 + LONGDOUBLE_TYPE d;
24984 + if( (*cnt)++ >= 16 ) return '0';
24985 + digit = (int)*val;
24988 + *val = (*val - d)*10.0;
24993 +#define etBUFSIZE 1000 /* Size of the output buffer */
24996 +** The root program. All variations call this core.
24999 +** func This is a pointer to a function taking three arguments
25000 +** 1. A pointer to anything. Same as the "arg" parameter.
25001 +** 2. A pointer to the list of characters to be output
25002 +** (Note, this list is NOT null terminated.)
25003 +** 3. An integer number of characters to be output.
25004 +** (Note: This number might be zero.)
25006 +** arg This is the pointer to anything which will be passed as the
25007 +** first argument to "func". Use it for whatever you like.
25009 +** fmt This is the format string, as in the usual print.
25011 +** ap This is a pointer to a list of arguments. Same as in
25015 +** The return value is the total number of characters sent to
25016 +** the function "func". Returns -1 on a error.
25018 +** Note that the order in which automatic variables are declared below
25019 +** seems to make a big difference in determining how fast this beast
25022 +static int vxprintf(
25023 + void (*func)(void*,const char*,int), /* Consumer of text */
25024 + void *arg, /* First argument to the consumer */
25025 + int useExtended, /* Allow extended %-conversions */
25026 + const char *fmt, /* Format string */
25027 + va_list ap /* arguments */
25029 + int c; /* Next character in the format string */
25030 + char *bufpt; /* Pointer to the conversion buffer */
25031 + int precision; /* Precision of the current field */
25032 + int length; /* Length of the field */
25033 + int idx; /* A general purpose loop counter */
25034 + int count; /* Total number of characters output */
25035 + int width; /* Width of the current field */
25036 + etByte flag_leftjustify; /* True if "-" flag is present */
25037 + etByte flag_plussign; /* True if "+" flag is present */
25038 + etByte flag_blanksign; /* True if " " flag is present */
25039 + etByte flag_alternateform; /* True if "#" flag is present */
25040 + etByte flag_zeropad; /* True if field width constant starts with zero */
25041 + etByte flag_long; /* True if "l" flag is present */
25042 + unsigned long longvalue; /* Value for integer types */
25043 + LONGDOUBLE_TYPE realvalue; /* Value for real types */
25044 + et_info *infop; /* Pointer to the appropriate info structure */
25045 + char buf[etBUFSIZE]; /* Conversion buffer */
25046 + char prefix; /* Prefix character. "+" or "-" or " " or '\0'. */
25047 + etByte errorflag = 0; /* True if an error is encountered */
25048 + etByte xtype; /* Conversion paradigm */
25049 + char *zExtra; /* Extra memory used for etTCLESCAPE conversions */
25050 + static char spaces[] = " ";
25051 +#define etSPACESIZE (sizeof(spaces)-1)
25052 +#ifndef etNOFLOATINGPOINT
25053 + int exp; /* exponent of real numbers */
25054 + double rounder; /* Used for rounding floating point values */
25055 + etByte flag_dp; /* True if decimal point should be shown */
25056 + etByte flag_rtz; /* True if trailing zeros should be removed */
25057 + etByte flag_exp; /* True to force display of the exponent */
25058 + int nsd; /* Number of significant digits returned */
25062 + count = length = 0;
25064 + for(; (c=(*fmt))!=0; ++fmt){
25067 + bufpt = (char *)fmt;
25069 + while( (c=(*++fmt))!='%' && c!=0 ) amt++;
25070 + (*func)(arg,bufpt,amt);
25072 + if( c==0 ) break;
25074 + if( (c=(*++fmt))==0 ){
25076 + (*func)(arg,"%",1);
25080 + /* Find out what flags are present */
25081 + flag_leftjustify = flag_plussign = flag_blanksign =
25082 + flag_alternateform = flag_zeropad = 0;
25085 + case '-': flag_leftjustify = 1; c = 0; break;
25086 + case '+': flag_plussign = 1; c = 0; break;
25087 + case ' ': flag_blanksign = 1; c = 0; break;
25088 + case '#': flag_alternateform = 1; c = 0; break;
25089 + case '0': flag_zeropad = 1; c = 0; break;
25092 + }while( c==0 && (c=(*++fmt))!=0 );
25093 + /* Get the field width */
25096 + width = va_arg(ap,int);
25098 + flag_leftjustify = 1;
25103 + while( c>='0' && c<='9' ){
25104 + width = width*10 + c - '0';
25108 + if( width > etBUFSIZE-10 ){
25109 + width = etBUFSIZE-10;
25111 + /* Get the precision */
25116 + precision = va_arg(ap,int);
25117 + if( precision<0 ) precision = -precision;
25120 + while( c>='0' && c<='9' ){
25121 + precision = precision*10 + c - '0';
25125 + /* Limit the precision to prevent overflowing buf[] during conversion */
25126 + if( precision>etBUFSIZE-40 ) precision = etBUFSIZE-40;
25130 + /* Get the conversion type modifier */
25137 + /* Fetch the info entry for the field */
25140 + for(idx=0; idx<etNINFO; idx++){
25141 + if( c==fmtinfo[idx].fmttype ){
25142 + infop = &fmtinfo[idx];
25143 + if( useExtended || (infop->flags & FLAG_INTERN)==0 ){
25144 + xtype = infop->type;
25152 + ** At this point, variables are initialized as follows:
25154 + ** flag_alternateform TRUE if a '#' is present.
25155 + ** flag_plussign TRUE if a '+' is present.
25156 + ** flag_leftjustify TRUE if a '-' is present or if the
25157 + ** field width was negative.
25158 + ** flag_zeropad TRUE if the width began with 0.
25159 + ** flag_long TRUE if the letter 'l' (ell) prefixed
25160 + ** the conversion character.
25161 + ** flag_blanksign TRUE if a ' ' is present.
25162 + ** width The specified field width. This is
25163 + ** always non-negative. Zero is the default.
25164 + ** precision The specified precision. The default
25166 + ** xtype The class of the conversion.
25167 + ** infop Pointer to the appropriate info struct.
25171 + if( flag_long ) longvalue = va_arg(ap,long);
25172 + else longvalue = va_arg(ap,int);
25174 + /* For the format %#x, the value zero is printed "0" not "0x0".
25175 + ** I think this is stupid. */
25176 + if( longvalue==0 ) flag_alternateform = 0;
25178 + /* More sensible: turn off the prefix for octal (to prevent "00"),
25179 + ** but leave the prefix for hex. */
25180 + if( longvalue==0 && infop->base==8 ) flag_alternateform = 0;
25182 + if( infop->flags & FLAG_SIGNED ){
25183 + if( *(long*)&longvalue<0 ){
25184 + longvalue = -*(long*)&longvalue;
25186 + }else if( flag_plussign ) prefix = '+';
25187 + else if( flag_blanksign ) prefix = ' ';
25189 + }else prefix = 0;
25190 + if( flag_zeropad && precision<width-(prefix!=0) ){
25191 + precision = width-(prefix!=0);
25193 + bufpt = &buf[etBUFSIZE-1];
25195 + register char *cset; /* Use registers for speed */
25196 + register int base;
25197 + cset = infop->charset;
25198 + base = infop->base;
25199 + do{ /* Convert to ascii */
25200 + *(--bufpt) = cset[longvalue%base];
25201 + longvalue = longvalue/base;
25202 + }while( longvalue>0 );
25204 + length = &buf[etBUFSIZE-1]-bufpt;
25205 + for(idx=precision-length; idx>0; idx--){
25206 + *(--bufpt) = '0'; /* Zero pad */
25208 + if( prefix ) *(--bufpt) = prefix; /* Add sign */
25209 + if( flag_alternateform && infop->prefix ){ /* Add "0" or "0x" */
25211 + pre = infop->prefix;
25212 + if( *bufpt!=pre[0] ){
25213 + for(pre=infop->prefix; (x=(*pre))!=0; pre++) *(--bufpt) = x;
25216 + length = &buf[etBUFSIZE-1]-bufpt;
25221 + realvalue = va_arg(ap,double);
25222 +#ifndef etNOFLOATINGPOINT
25223 + if( precision<0 ) precision = 6; /* Set default precision */
25224 + if( precision>etBUFSIZE-10 ) precision = etBUFSIZE-10;
25225 + if( realvalue<0.0 ){
25226 + realvalue = -realvalue;
25229 + if( flag_plussign ) prefix = '+';
25230 + else if( flag_blanksign ) prefix = ' ';
25233 + if( infop->type==etGENERIC && precision>0 ) precision--;
25236 + /* Rounding works like BSD when the constant 0.4999 is used. Wierd! */
25237 + for(idx=precision, rounder=0.4999; idx>0; idx--, rounder*=0.1);
25239 + /* It makes more sense to use 0.5 */
25240 + for(idx=precision, rounder=0.5; idx>0; idx--, rounder*=0.1);
25242 + if( infop->type==etFLOAT ) realvalue += rounder;
25243 + /* Normalize realvalue to within 10.0 > realvalue >= 1.0 */
25245 + if( realvalue>0.0 ){
25246 + while( realvalue>=1e8 && exp<=350 ){ realvalue *= 1e-8; exp+=8; }
25247 + while( realvalue>=10.0 && exp<=350 ){ realvalue *= 0.1; exp++; }
25248 + while( realvalue<1e-8 && exp>=-350 ){ realvalue *= 1e8; exp-=8; }
25249 + while( realvalue<1.0 && exp>=-350 ){ realvalue *= 10.0; exp--; }
25250 + if( exp>350 || exp<-350 ){
25258 + ** If the field type is etGENERIC, then convert to either etEXP
25259 + ** or etFLOAT, as appropriate.
25261 + flag_exp = xtype==etEXP;
25262 + if( xtype!=etFLOAT ){
25263 + realvalue += rounder;
25264 + if( realvalue>=10.0 ){ realvalue *= 0.1; exp++; }
25266 + if( xtype==etGENERIC ){
25267 + flag_rtz = !flag_alternateform;
25268 + if( exp<-4 || exp>precision ){
25271 + precision = precision - exp;
25278 + ** The "exp+precision" test causes output to be of type etEXP if
25279 + ** the precision is too large to fit in buf[].
25282 + if( xtype==etFLOAT && exp+precision<etBUFSIZE-30 ){
25283 + flag_dp = (precision>0 || flag_alternateform);
25284 + if( prefix ) *(bufpt++) = prefix; /* Sign */
25285 + if( exp<0 ) *(bufpt++) = '0'; /* Digits before "." */
25286 + else for(; exp>=0; exp--) *(bufpt++) = et_getdigit(&realvalue,&nsd);
25287 + if( flag_dp ) *(bufpt++) = '.'; /* The decimal point */
25288 + for(exp++; exp<0 && precision>0; precision--, exp++){
25289 + *(bufpt++) = '0';
25291 + while( (precision--)>0 ) *(bufpt++) = et_getdigit(&realvalue,&nsd);
25292 + *(bufpt--) = 0; /* Null terminate */
25293 + if( flag_rtz && flag_dp ){ /* Remove trailing zeros and "." */
25294 + while( bufpt>=buf && *bufpt=='0' ) *(bufpt--) = 0;
25295 + if( bufpt>=buf && *bufpt=='.' ) *(bufpt--) = 0;
25297 + bufpt++; /* point to next free slot */
25298 + }else{ /* etEXP or etGENERIC */
25299 + flag_dp = (precision>0 || flag_alternateform);
25300 + if( prefix ) *(bufpt++) = prefix; /* Sign */
25301 + *(bufpt++) = et_getdigit(&realvalue,&nsd); /* First digit */
25302 + if( flag_dp ) *(bufpt++) = '.'; /* Decimal point */
25303 + while( (precision--)>0 ) *(bufpt++) = et_getdigit(&realvalue,&nsd);
25304 + bufpt--; /* point to last digit */
25305 + if( flag_rtz && flag_dp ){ /* Remove tail zeros */
25306 + while( bufpt>=buf && *bufpt=='0' ) *(bufpt--) = 0;
25307 + if( bufpt>=buf && *bufpt=='.' ) *(bufpt--) = 0;
25309 + bufpt++; /* point to next free slot */
25310 + if( exp || flag_exp ){
25311 + *(bufpt++) = infop->charset[0];
25312 + if( exp<0 ){ *(bufpt++) = '-'; exp = -exp; } /* sign of exp */
25313 + else { *(bufpt++) = '+'; }
25315 + *(bufpt++) = (exp/100)+'0'; /* 100's digit */
25318 + *(bufpt++) = exp/10+'0'; /* 10's digit */
25319 + *(bufpt++) = exp%10+'0'; /* 1's digit */
25322 + /* The converted number is in buf[] and zero terminated. Output it.
25323 + ** Note that the number is in the usual order, not reversed as with
25324 + ** integer conversions. */
25325 + length = bufpt-buf;
25328 + /* Special case: Add leading zeros if the flag_zeropad flag is
25329 + ** set and we are not left justified */
25330 + if( flag_zeropad && !flag_leftjustify && length < width){
25332 + int nPad = width - length;
25333 + for(i=width; i>=nPad; i--){
25334 + bufpt[i] = bufpt[i-nPad];
25337 + while( nPad-- ) bufpt[i++] = '0';
25343 + *(va_arg(ap,int*)) = count;
25344 + length = width = 0;
25353 + c = buf[0] = (xtype==etCHARX ? va_arg(ap,int) : *++fmt);
25354 + if( precision>=0 ){
25355 + for(idx=1; idx<precision; idx++) buf[idx] = c;
25356 + length = precision;
25363 + case etDYNSTRING:
25364 + bufpt = va_arg(ap,char*);
25367 + }else if( xtype==etDYNSTRING ){
25370 + length = strlen(bufpt);
25371 + if( precision>=0 && precision<length ) length = precision;
25373 + case etSQLESCAPE:
25374 + case etSQLESCAPE2:
25376 + int i, j, n, c, isnull;
25377 + char *arg = va_arg(ap,char*);
25379 + if( isnull ) arg = (xtype==etSQLESCAPE2 ? "NULL" : "(NULL)");
25380 + for(i=n=0; (c=arg[i])!=0; i++){
25381 + if( c=='\'' ) n++;
25383 + n += i + 1 + ((!isnull && xtype==etSQLESCAPE2) ? 2 : 0);
25384 + if( n>etBUFSIZE ){
25385 + bufpt = zExtra = sqliteMalloc( n );
25386 + if( bufpt==0 ) return -1;
25391 + if( !isnull && xtype==etSQLESCAPE2 ) bufpt[j++] = '\'';
25392 + for(i=0; (c=arg[i])!=0; i++){
25394 + if( c=='\'' ) bufpt[j++] = c;
25396 + if( !isnull && xtype==etSQLESCAPE2 ) bufpt[j++] = '\'';
25399 + if( precision>=0 && precision<length ) length = precision;
25403 + Token *pToken = va_arg(ap, Token*);
25404 + (*func)(arg, pToken->z, pToken->n);
25405 + length = width = 0;
25408 + case etSRCLIST: {
25409 + SrcList *pSrc = va_arg(ap, SrcList*);
25410 + int k = va_arg(ap, int);
25411 + struct SrcList_item *pItem = &pSrc->a[k];
25412 + assert( k>=0 && k<pSrc->nSrc );
25413 + if( pItem->zDatabase && pItem->zDatabase[0] ){
25414 + (*func)(arg, pItem->zDatabase, strlen(pItem->zDatabase));
25415 + (*func)(arg, ".", 1);
25417 + (*func)(arg, pItem->zName, strlen(pItem->zName));
25418 + length = width = 0;
25426 + (*func)(arg,"%",idx);
25428 + if( c==0 ) fmt--;
25430 + }/* End switch over the format type */
25432 + ** The text of the conversion is pointed to by "bufpt" and is
25433 + ** "length" characters long. The field width is "width". Do
25436 + if( !flag_leftjustify ){
25437 + register int nspace;
25438 + nspace = width-length;
25441 + while( nspace>=etSPACESIZE ){
25442 + (*func)(arg,spaces,etSPACESIZE);
25443 + nspace -= etSPACESIZE;
25445 + if( nspace>0 ) (*func)(arg,spaces,nspace);
25449 + (*func)(arg,bufpt,length);
25452 + if( flag_leftjustify ){
25453 + register int nspace;
25454 + nspace = width-length;
25457 + while( nspace>=etSPACESIZE ){
25458 + (*func)(arg,spaces,etSPACESIZE);
25459 + nspace -= etSPACESIZE;
25461 + if( nspace>0 ) (*func)(arg,spaces,nspace);
25465 + sqliteFree(zExtra);
25467 + }/* End for loop over the format string */
25468 + return errorflag ? -1 : count;
25469 +} /* End of function */
25472 +/* This structure is used to store state information about the
25473 +** write to memory that is currently in progress.
25475 +struct sgMprintf {
25476 + char *zBase; /* A base allocation */
25477 + char *zText; /* The string collected so far */
25478 + int nChar; /* Length of the string so far */
25479 + int nTotal; /* Output size if unconstrained */
25480 + int nAlloc; /* Amount of space allocated in zText */
25481 + void *(*xRealloc)(void*,int); /* Function used to realloc memory */
25485 +** This function implements the callback from vxprintf.
25487 +** This routine add nNewChar characters of text in zNewText to
25488 +** the sgMprintf structure pointed to by "arg".
25490 +static void mout(void *arg, const char *zNewText, int nNewChar){
25491 + struct sgMprintf *pM = (struct sgMprintf*)arg;
25492 + pM->nTotal += nNewChar;
25493 + if( pM->nChar + nNewChar + 1 > pM->nAlloc ){
25494 + if( pM->xRealloc==0 ){
25495 + nNewChar = pM->nAlloc - pM->nChar - 1;
25497 + pM->nAlloc = pM->nChar + nNewChar*2 + 1;
25498 + if( pM->zText==pM->zBase ){
25499 + pM->zText = pM->xRealloc(0, pM->nAlloc);
25500 + if( pM->zText && pM->nChar ){
25501 + memcpy(pM->zText, pM->zBase, pM->nChar);
25504 + pM->zText = pM->xRealloc(pM->zText, pM->nAlloc);
25509 + if( nNewChar>0 ){
25510 + memcpy(&pM->zText[pM->nChar], zNewText, nNewChar);
25511 + pM->nChar += nNewChar;
25513 + pM->zText[pM->nChar] = 0;
25518 +** This routine is a wrapper around xprintf() that invokes mout() as
25521 +static char *base_vprintf(
25522 + void *(*xRealloc)(void*,int), /* Routine to realloc memory. May be NULL */
25523 + int useInternal, /* Use internal %-conversions if true */
25524 + char *zInitBuf, /* Initially write here, before mallocing */
25525 + int nInitBuf, /* Size of zInitBuf[] */
25526 + const char *zFormat, /* format string */
25527 + va_list ap /* arguments */
25529 + struct sgMprintf sM;
25530 + sM.zBase = sM.zText = zInitBuf;
25531 + sM.nChar = sM.nTotal = 0;
25532 + sM.nAlloc = nInitBuf;
25533 + sM.xRealloc = xRealloc;
25534 + vxprintf(mout, &sM, useInternal, zFormat, ap);
25536 + if( sM.zText==sM.zBase ){
25537 + sM.zText = xRealloc(0, sM.nChar+1);
25538 + memcpy(sM.zText, sM.zBase, sM.nChar+1);
25539 + }else if( sM.nAlloc>sM.nChar+10 ){
25540 + sM.zText = xRealloc(sM.zText, sM.nChar+1);
25547 +** Realloc that is a real function, not a macro.
25549 +static void *printf_realloc(void *old, int size){
25550 + return sqliteRealloc(old,size);
25554 +** Print into memory obtained from sqliteMalloc(). Use the internal
25555 +** %-conversion extensions.
25557 +char *sqliteVMPrintf(const char *zFormat, va_list ap){
25558 + char zBase[1000];
25559 + return base_vprintf(printf_realloc, 1, zBase, sizeof(zBase), zFormat, ap);
25563 +** Print into memory obtained from sqliteMalloc(). Use the internal
25564 +** %-conversion extensions.
25566 +char *sqliteMPrintf(const char *zFormat, ...){
25569 + char zBase[1000];
25570 + va_start(ap, zFormat);
25571 + z = base_vprintf(printf_realloc, 1, zBase, sizeof(zBase), zFormat, ap);
25577 +** Print into memory obtained from malloc(). Do not use the internal
25578 +** %-conversion extensions. This routine is for use by external users.
25580 +char *sqlite_mprintf(const char *zFormat, ...){
25585 + va_start(ap,zFormat);
25586 + z = base_vprintf((void*(*)(void*,int))realloc, 0,
25587 + zBuf, sizeof(zBuf), zFormat, ap);
25592 +/* This is the varargs version of sqlite_mprintf.
25594 +char *sqlite_vmprintf(const char *zFormat, va_list ap){
25596 + return base_vprintf((void*(*)(void*,int))realloc, 0,
25597 + zBuf, sizeof(zBuf), zFormat, ap);
25601 +** sqlite_snprintf() works like snprintf() except that it ignores the
25602 +** current locale settings. This is important for SQLite because we
25603 +** are not able to use a "," as the decimal point in place of "." as
25604 +** specified by some locales.
25606 +char *sqlite_snprintf(int n, char *zBuf, const char *zFormat, ...){
25610 + va_start(ap,zFormat);
25611 + z = base_vprintf(0, 0, zBuf, n, zFormat, ap);
25617 +** The following four routines implement the varargs versions of the
25618 +** sqlite_exec() and sqlite_get_table() interfaces. See the sqlite.h
25619 +** header files for a more detailed description of how these interfaces
25622 +** These routines are all just simple wrappers.
25624 +int sqlite_exec_printf(
25625 + sqlite *db, /* An open database */
25626 + const char *sqlFormat, /* printf-style format string for the SQL */
25627 + sqlite_callback xCallback, /* Callback function */
25628 + void *pArg, /* 1st argument to callback function */
25629 + char **errmsg, /* Error msg written here */
25630 + ... /* Arguments to the format string. */
25635 + va_start(ap, errmsg);
25636 + rc = sqlite_exec_vprintf(db, sqlFormat, xCallback, pArg, errmsg, ap);
25640 +int sqlite_exec_vprintf(
25641 + sqlite *db, /* An open database */
25642 + const char *sqlFormat, /* printf-style format string for the SQL */
25643 + sqlite_callback xCallback, /* Callback function */
25644 + void *pArg, /* 1st argument to callback function */
25645 + char **errmsg, /* Error msg written here */
25646 + va_list ap /* Arguments to the format string. */
25651 + zSql = sqlite_vmprintf(sqlFormat, ap);
25652 + rc = sqlite_exec(db, zSql, xCallback, pArg, errmsg);
25656 +int sqlite_get_table_printf(
25657 + sqlite *db, /* An open database */
25658 + const char *sqlFormat, /* printf-style format string for the SQL */
25659 + char ***resultp, /* Result written to a char *[] that this points to */
25660 + int *nrow, /* Number of result rows written here */
25661 + int *ncol, /* Number of result columns written here */
25662 + char **errmsg, /* Error msg written here */
25663 + ... /* Arguments to the format string */
25668 + va_start(ap, errmsg);
25669 + rc = sqlite_get_table_vprintf(db, sqlFormat, resultp, nrow, ncol, errmsg, ap);
25673 +int sqlite_get_table_vprintf(
25674 + sqlite *db, /* An open database */
25675 + const char *sqlFormat, /* printf-style format string for the SQL */
25676 + char ***resultp, /* Result written to a char *[] that this points to */
25677 + int *nrow, /* Number of result rows written here */
25678 + int *ncolumn, /* Number of result columns written here */
25679 + char **errmsg, /* Error msg written here */
25680 + va_list ap /* Arguments to the format string */
25685 + zSql = sqlite_vmprintf(sqlFormat, ap);
25686 + rc = sqlite_get_table(db, zSql, resultp, nrow, ncolumn, errmsg);
25691 +++ b/ext/sqlite/libsqlite/src/random.c
25694 +** 2001 September 15
25696 +** The author disclaims copyright to this source code. In place of
25697 +** a legal notice, here is a blessing:
25699 +** May you do good and not evil.
25700 +** May you find forgiveness for yourself and forgive others.
25701 +** May you share freely, never taking more than you give.
25703 +*************************************************************************
25704 +** This file contains code to implement a pseudo-random number
25705 +** generator (PRNG) for SQLite.
25707 +** Random numbers are used by some of the database backends in order
25708 +** to generate random integer keys for tables or random filenames.
25712 +#include "sqliteInt.h"
25717 +** Get a single 8-bit random value from the RC4 PRNG. The Mutex
25718 +** must be held while executing this routine.
25720 +** Why not just use a library random generator like lrand48() for this?
25721 +** Because the OP_NewRecno opcode in the VDBE depends on having a very
25722 +** good source of random numbers. The lrand48() library function may
25723 +** well be good enough. But maybe not. Or maybe lrand48() has some
25724 +** subtle problems on some systems that could cause problems. It is hard
25725 +** to know. To minimize the risk of problems due to bad lrand48()
25726 +** implementations, SQLite uses this random number generator based
25727 +** on RC4, which we know works very well.
25729 +static int randomByte(){
25732 + /* All threads share a single random number generator.
25733 + ** This structure is the current state of the generator.
25736 + unsigned char isInit; /* True if initialized */
25737 + unsigned char i, j; /* State variables */
25738 + unsigned char s[256]; /* State variables */
25741 + /* Initialize the state of the random number generator once,
25742 + ** the first time this routine is called. The seed value does
25743 + ** not need to contain a lot of randomness since we are not
25744 + ** trying to do secure encryption or anything like that...
25746 + ** Nothing in this file or anywhere else in SQLite does any kind of
25747 + ** encryption. The RC4 algorithm is being used as a PRNG (pseudo-random
25748 + ** number generator) not as an encryption device.
25750 + if( !prng.isInit ){
25755 + sqliteOsRandomSeed(k);
25756 + for(i=0; i<256; i++){
25759 + for(i=0; i<256; i++){
25760 + prng.j += prng.s[i] + k[i];
25761 + t = prng.s[prng.j];
25762 + prng.s[prng.j] = prng.s[i];
25768 + /* Generate and return single random byte
25771 + t = prng.s[prng.i];
25773 + prng.s[prng.i] = prng.s[prng.j];
25774 + prng.s[prng.j] = t;
25775 + t += prng.s[prng.i];
25776 + return prng.s[t];
25780 +** Return N random bytes.
25782 +void sqliteRandomness(int N, void *pBuf){
25783 + unsigned char *zBuf = pBuf;
25784 + sqliteOsEnterMutex();
25786 + *(zBuf++) = randomByte();
25788 + sqliteOsLeaveMutex();
25791 +++ b/ext/sqlite/libsqlite/src/select.c
25794 +** 2001 September 15
25796 +** The author disclaims copyright to this source code. In place of
25797 +** a legal notice, here is a blessing:
25799 +** May you do good and not evil.
25800 +** May you find forgiveness for yourself and forgive others.
25801 +** May you share freely, never taking more than you give.
25803 +*************************************************************************
25804 +** This file contains C code routines that are called by the parser
25805 +** to handle SELECT statements in SQLite.
25809 +#include "sqliteInt.h"
25813 +** Allocate a new Select structure and return a pointer to that
25816 +Select *sqliteSelectNew(
25817 + ExprList *pEList, /* which columns to include in the result */
25818 + SrcList *pSrc, /* the FROM clause -- which tables to scan */
25819 + Expr *pWhere, /* the WHERE clause */
25820 + ExprList *pGroupBy, /* the GROUP BY clause */
25821 + Expr *pHaving, /* the HAVING clause */
25822 + ExprList *pOrderBy, /* the ORDER BY clause */
25823 + int isDistinct, /* true if the DISTINCT keyword is present */
25824 + int nLimit, /* LIMIT value. -1 means not used */
25825 + int nOffset /* OFFSET value. 0 means no offset */
25828 + pNew = sqliteMalloc( sizeof(*pNew) );
25830 + sqliteExprListDelete(pEList);
25831 + sqliteSrcListDelete(pSrc);
25832 + sqliteExprDelete(pWhere);
25833 + sqliteExprListDelete(pGroupBy);
25834 + sqliteExprDelete(pHaving);
25835 + sqliteExprListDelete(pOrderBy);
25838 + pEList = sqliteExprListAppend(0, sqliteExpr(TK_ALL,0,0,0), 0);
25840 + pNew->pEList = pEList;
25841 + pNew->pSrc = pSrc;
25842 + pNew->pWhere = pWhere;
25843 + pNew->pGroupBy = pGroupBy;
25844 + pNew->pHaving = pHaving;
25845 + pNew->pOrderBy = pOrderBy;
25846 + pNew->isDistinct = isDistinct;
25847 + pNew->op = TK_SELECT;
25848 + pNew->nLimit = nLimit;
25849 + pNew->nOffset = nOffset;
25850 + pNew->iLimit = -1;
25851 + pNew->iOffset = -1;
25857 +** Given 1 to 3 identifiers preceeding the JOIN keyword, determine the
25858 +** type of join. Return an integer constant that expresses that type
25859 +** in terms of the following bit values:
25867 +** A full outer join is the combination of JT_LEFT and JT_RIGHT.
25869 +** If an illegal or unsupported join type is seen, then still return
25870 +** a join type, but put an error in the pParse structure.
25872 +int sqliteJoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
25873 + int jointype = 0;
25877 + const char *zKeyword;
25881 + { "natural", 7, JT_NATURAL },
25882 + { "left", 4, JT_LEFT|JT_OUTER },
25883 + { "right", 5, JT_RIGHT|JT_OUTER },
25884 + { "full", 4, JT_LEFT|JT_RIGHT|JT_OUTER },
25885 + { "outer", 5, JT_OUTER },
25886 + { "inner", 5, JT_INNER },
25887 + { "cross", 5, JT_INNER },
25893 + for(i=0; i<3 && apAll[i]; i++){
25895 + for(j=0; j<sizeof(keywords)/sizeof(keywords[0]); j++){
25896 + if( p->n==keywords[j].nChar
25897 + && sqliteStrNICmp(p->z, keywords[j].zKeyword, p->n)==0 ){
25898 + jointype |= keywords[j].code;
25902 + if( j>=sizeof(keywords)/sizeof(keywords[0]) ){
25903 + jointype |= JT_ERROR;
25908 + (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
25909 + (jointype & JT_ERROR)!=0
25911 + static Token dummy = { 0, 0 };
25912 + char *zSp1 = " ", *zSp2 = " ";
25913 + if( pB==0 ){ pB = &dummy; zSp1 = 0; }
25914 + if( pC==0 ){ pC = &dummy; zSp2 = 0; }
25915 + sqliteSetNString(&pParse->zErrMsg, "unknown or unsupported join type: ", 0,
25916 + pA->z, pA->n, zSp1, 1, pB->z, pB->n, zSp2, 1, pC->z, pC->n, 0);
25918 + jointype = JT_INNER;
25919 + }else if( jointype & JT_RIGHT ){
25920 + sqliteErrorMsg(pParse,
25921 + "RIGHT and FULL OUTER JOINs are not currently supported");
25922 + jointype = JT_INNER;
25928 +** Return the index of a column in a table. Return -1 if the column
25929 +** is not contained in the table.
25931 +static int columnIndex(Table *pTab, const char *zCol){
25933 + for(i=0; i<pTab->nCol; i++){
25934 + if( sqliteStrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
25940 +** Add a term to the WHERE expression in *ppExpr that requires the
25941 +** zCol column to be equal in the two tables pTab1 and pTab2.
25943 +static void addWhereTerm(
25944 + const char *zCol, /* Name of the column */
25945 + const Table *pTab1, /* First table */
25946 + const Table *pTab2, /* Second table */
25947 + Expr **ppExpr /* Add the equality term to this expression */
25950 + Expr *pE1a, *pE1b, *pE1c;
25951 + Expr *pE2a, *pE2b, *pE2c;
25955 + dummy.n = strlen(zCol);
25957 + pE1a = sqliteExpr(TK_ID, 0, 0, &dummy);
25958 + pE2a = sqliteExpr(TK_ID, 0, 0, &dummy);
25959 + dummy.z = pTab1->zName;
25960 + dummy.n = strlen(dummy.z);
25961 + pE1b = sqliteExpr(TK_ID, 0, 0, &dummy);
25962 + dummy.z = pTab2->zName;
25963 + dummy.n = strlen(dummy.z);
25964 + pE2b = sqliteExpr(TK_ID, 0, 0, &dummy);
25965 + pE1c = sqliteExpr(TK_DOT, pE1b, pE1a, 0);
25966 + pE2c = sqliteExpr(TK_DOT, pE2b, pE2a, 0);
25967 + pE = sqliteExpr(TK_EQ, pE1c, pE2c, 0);
25968 + ExprSetProperty(pE, EP_FromJoin);
25970 + *ppExpr = sqliteExpr(TK_AND, *ppExpr, pE, 0);
25977 +** Set the EP_FromJoin property on all terms of the given expression.
25979 +** The EP_FromJoin property is used on terms of an expression to tell
25980 +** the LEFT OUTER JOIN processing logic that this term is part of the
25981 +** join restriction specified in the ON or USING clause and not a part
25982 +** of the more general WHERE clause. These terms are moved over to the
25983 +** WHERE clause during join processing but we need to remember that they
25984 +** originated in the ON or USING clause.
25986 +static void setJoinExpr(Expr *p){
25988 + ExprSetProperty(p, EP_FromJoin);
25989 + setJoinExpr(p->pLeft);
25995 +** This routine processes the join information for a SELECT statement.
25996 +** ON and USING clauses are converted into extra terms of the WHERE clause.
25997 +** NATURAL joins also create extra WHERE clause terms.
25999 +** This routine returns the number of errors encountered.
26001 +static int sqliteProcessJoin(Parse *pParse, Select *p){
26005 + for(i=0; i<pSrc->nSrc-1; i++){
26006 + struct SrcList_item *pTerm = &pSrc->a[i];
26007 + struct SrcList_item *pOther = &pSrc->a[i+1];
26009 + if( pTerm->pTab==0 || pOther->pTab==0 ) continue;
26011 + /* When the NATURAL keyword is present, add WHERE clause terms for
26012 + ** every column that the two tables have in common.
26014 + if( pTerm->jointype & JT_NATURAL ){
26016 + if( pTerm->pOn || pTerm->pUsing ){
26017 + sqliteErrorMsg(pParse, "a NATURAL join may not have "
26018 + "an ON or USING clause", 0);
26021 + pTab = pTerm->pTab;
26022 + for(j=0; j<pTab->nCol; j++){
26023 + if( columnIndex(pOther->pTab, pTab->aCol[j].zName)>=0 ){
26024 + addWhereTerm(pTab->aCol[j].zName, pTab, pOther->pTab, &p->pWhere);
26029 + /* Disallow both ON and USING clauses in the same join
26031 + if( pTerm->pOn && pTerm->pUsing ){
26032 + sqliteErrorMsg(pParse, "cannot have both ON and USING "
26033 + "clauses in the same join");
26037 + /* Add the ON clause to the end of the WHERE clause, connected by
26038 + ** and AND operator.
26040 + if( pTerm->pOn ){
26041 + setJoinExpr(pTerm->pOn);
26042 + if( p->pWhere==0 ){
26043 + p->pWhere = pTerm->pOn;
26045 + p->pWhere = sqliteExpr(TK_AND, p->pWhere, pTerm->pOn, 0);
26050 + /* Create extra terms on the WHERE clause for each column named
26051 + ** in the USING clause. Example: If the two tables to be joined are
26052 + ** A and B and the USING clause names X, Y, and Z, then add this
26053 + ** to the WHERE clause: A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
26054 + ** Report an error if any column mentioned in the USING clause is
26055 + ** not contained in both tables to be joined.
26057 + if( pTerm->pUsing ){
26060 + assert( i<pSrc->nSrc-1 );
26061 + pList = pTerm->pUsing;
26062 + for(j=0; j<pList->nId; j++){
26063 + if( columnIndex(pTerm->pTab, pList->a[j].zName)<0 ||
26064 + columnIndex(pOther->pTab, pList->a[j].zName)<0 ){
26065 + sqliteErrorMsg(pParse, "cannot join using column %s - column "
26066 + "not present in both tables", pList->a[j].zName);
26069 + addWhereTerm(pList->a[j].zName, pTerm->pTab, pOther->pTab, &p->pWhere);
26077 +** Delete the given Select structure and all of its substructures.
26079 +void sqliteSelectDelete(Select *p){
26080 + if( p==0 ) return;
26081 + sqliteExprListDelete(p->pEList);
26082 + sqliteSrcListDelete(p->pSrc);
26083 + sqliteExprDelete(p->pWhere);
26084 + sqliteExprListDelete(p->pGroupBy);
26085 + sqliteExprDelete(p->pHaving);
26086 + sqliteExprListDelete(p->pOrderBy);
26087 + sqliteSelectDelete(p->pPrior);
26088 + sqliteFree(p->zSelect);
26093 +** Delete the aggregate information from the parse structure.
26095 +static void sqliteAggregateInfoReset(Parse *pParse){
26096 + sqliteFree(pParse->aAgg);
26097 + pParse->aAgg = 0;
26098 + pParse->nAgg = 0;
26099 + pParse->useAgg = 0;
26103 +** Insert code into "v" that will push the record on the top of the
26104 +** stack into the sorter.
26106 +static void pushOntoSorter(Parse *pParse, Vdbe *v, ExprList *pOrderBy){
26107 + char *zSortOrder;
26109 + zSortOrder = sqliteMalloc( pOrderBy->nExpr + 1 );
26110 + if( zSortOrder==0 ) return;
26111 + for(i=0; i<pOrderBy->nExpr; i++){
26112 + int order = pOrderBy->a[i].sortOrder;
26115 + if( (order & SQLITE_SO_TYPEMASK)==SQLITE_SO_TEXT ){
26116 + type = SQLITE_SO_TEXT;
26117 + }else if( (order & SQLITE_SO_TYPEMASK)==SQLITE_SO_NUM ){
26118 + type = SQLITE_SO_NUM;
26119 + }else if( pParse->db->file_format>=4 ){
26120 + type = sqliteExprType(pOrderBy->a[i].pExpr);
26122 + type = SQLITE_SO_NUM;
26124 + if( (order & SQLITE_SO_DIRMASK)==SQLITE_SO_ASC ){
26125 + c = type==SQLITE_SO_TEXT ? 'A' : '+';
26127 + c = type==SQLITE_SO_TEXT ? 'D' : '-';
26129 + zSortOrder[i] = c;
26130 + sqliteExprCode(pParse, pOrderBy->a[i].pExpr);
26132 + zSortOrder[pOrderBy->nExpr] = 0;
26133 + sqliteVdbeOp3(v, OP_SortMakeKey, pOrderBy->nExpr, 0, zSortOrder, P3_DYNAMIC);
26134 + sqliteVdbeAddOp(v, OP_SortPut, 0, 0);
26138 +** This routine adds a P3 argument to the last VDBE opcode that was
26139 +** inserted. The P3 argument added is a string suitable for the
26140 +** OP_MakeKey or OP_MakeIdxKey opcodes. The string consists of
26141 +** characters 't' or 'n' depending on whether or not the various
26142 +** fields of the key to be generated should be treated as numeric
26143 +** or as text. See the OP_MakeKey and OP_MakeIdxKey opcode
26144 +** documentation for additional information about the P3 string.
26145 +** See also the sqliteAddIdxKeyType() routine.
26147 +void sqliteAddKeyType(Vdbe *v, ExprList *pEList){
26148 + int nColumn = pEList->nExpr;
26149 + char *zType = sqliteMalloc( nColumn+1 );
26151 + if( zType==0 ) return;
26152 + for(i=0; i<nColumn; i++){
26153 + zType[i] = sqliteExprType(pEList->a[i].pExpr)==SQLITE_SO_NUM ? 'n' : 't';
26156 + sqliteVdbeChangeP3(v, -1, zType, P3_DYNAMIC);
26160 +** Add code to implement the OFFSET and LIMIT
26162 +static void codeLimiter(
26163 + Vdbe *v, /* Generate code into this VM */
26164 + Select *p, /* The SELECT statement being coded */
26165 + int iContinue, /* Jump here to skip the current record */
26166 + int iBreak, /* Jump here to end the loop */
26167 + int nPop /* Number of times to pop stack when jumping */
26169 + if( p->iOffset>=0 ){
26170 + int addr = sqliteVdbeCurrentAddr(v) + 2;
26171 + if( nPop>0 ) addr++;
26172 + sqliteVdbeAddOp(v, OP_MemIncr, p->iOffset, addr);
26174 + sqliteVdbeAddOp(v, OP_Pop, nPop, 0);
26176 + sqliteVdbeAddOp(v, OP_Goto, 0, iContinue);
26178 + if( p->iLimit>=0 ){
26179 + sqliteVdbeAddOp(v, OP_MemIncr, p->iLimit, iBreak);
26184 +** This routine generates the code for the inside of the inner loop
26187 +** If srcTab and nColumn are both zero, then the pEList expressions
26188 +** are evaluated in order to get the data for this row. If nColumn>0
26189 +** then data is pulled from srcTab and pEList is used only to get the
26190 +** datatypes for each column.
26192 +static int selectInnerLoop(
26193 + Parse *pParse, /* The parser context */
26194 + Select *p, /* The complete select statement being coded */
26195 + ExprList *pEList, /* List of values being extracted */
26196 + int srcTab, /* Pull data from this table */
26197 + int nColumn, /* Number of columns in the source table */
26198 + ExprList *pOrderBy, /* If not NULL, sort results using this key */
26199 + int distinct, /* If >=0, make sure results are distinct */
26200 + int eDest, /* How to dispose of the results */
26201 + int iParm, /* An argument to the disposal method */
26202 + int iContinue, /* Jump here to continue with next row */
26203 + int iBreak /* Jump here to break out of the inner loop */
26205 + Vdbe *v = pParse->pVdbe;
26207 + int hasDistinct; /* True if the DISTINCT keyword is present */
26209 + if( v==0 ) return 0;
26210 + assert( pEList!=0 );
26212 + /* If there was a LIMIT clause on the SELECT statement, then do the check
26213 + ** to see if this row should be output.
26215 + hasDistinct = distinct>=0 && pEList && pEList->nExpr>0;
26216 + if( pOrderBy==0 && !hasDistinct ){
26217 + codeLimiter(v, p, iContinue, iBreak, 0);
26220 + /* Pull the requested columns.
26223 + for(i=0; i<nColumn; i++){
26224 + sqliteVdbeAddOp(v, OP_Column, srcTab, i);
26227 + nColumn = pEList->nExpr;
26228 + for(i=0; i<pEList->nExpr; i++){
26229 + sqliteExprCode(pParse, pEList->a[i].pExpr);
26233 + /* If the DISTINCT keyword was present on the SELECT statement
26234 + ** and this row has been seen before, then do not make this row
26235 + ** part of the result.
26237 + if( hasDistinct ){
26238 +#if NULL_ALWAYS_DISTINCT
26239 + sqliteVdbeAddOp(v, OP_IsNull, -pEList->nExpr, sqliteVdbeCurrentAddr(v)+7);
26241 + sqliteVdbeAddOp(v, OP_MakeKey, pEList->nExpr, 1);
26242 + if( pParse->db->file_format>=4 ) sqliteAddKeyType(v, pEList);
26243 + sqliteVdbeAddOp(v, OP_Distinct, distinct, sqliteVdbeCurrentAddr(v)+3);
26244 + sqliteVdbeAddOp(v, OP_Pop, pEList->nExpr+1, 0);
26245 + sqliteVdbeAddOp(v, OP_Goto, 0, iContinue);
26246 + sqliteVdbeAddOp(v, OP_String, 0, 0);
26247 + sqliteVdbeAddOp(v, OP_PutStrKey, distinct, 0);
26248 + if( pOrderBy==0 ){
26249 + codeLimiter(v, p, iContinue, iBreak, nColumn);
26254 + /* In this mode, write each query result to the key of the temporary
26257 + case SRT_Union: {
26258 + sqliteVdbeAddOp(v, OP_MakeRecord, nColumn, NULL_ALWAYS_DISTINCT);
26259 + sqliteVdbeAddOp(v, OP_String, 0, 0);
26260 + sqliteVdbeAddOp(v, OP_PutStrKey, iParm, 0);
26264 + /* Store the result as data using a unique key.
26267 + case SRT_TempTable: {
26268 + sqliteVdbeAddOp(v, OP_MakeRecord, nColumn, 0);
26270 + pushOntoSorter(pParse, v, pOrderBy);
26272 + sqliteVdbeAddOp(v, OP_NewRecno, iParm, 0);
26273 + sqliteVdbeAddOp(v, OP_Pull, 1, 0);
26274 + sqliteVdbeAddOp(v, OP_PutIntKey, iParm, 0);
26279 + /* Construct a record from the query result, but instead of
26280 + ** saving that record, use it as a key to delete elements from
26281 + ** the temporary table iParm.
26283 + case SRT_Except: {
26285 + addr = sqliteVdbeAddOp(v, OP_MakeRecord, nColumn, NULL_ALWAYS_DISTINCT);
26286 + sqliteVdbeAddOp(v, OP_NotFound, iParm, addr+3);
26287 + sqliteVdbeAddOp(v, OP_Delete, iParm, 0);
26291 + /* If we are creating a set for an "expr IN (SELECT ...)" construct,
26292 + ** then there should be a single item on the stack. Write this
26293 + ** item into the set table with bogus data.
26296 + int addr1 = sqliteVdbeCurrentAddr(v);
26298 + assert( nColumn==1 );
26299 + sqliteVdbeAddOp(v, OP_NotNull, -1, addr1+3);
26300 + sqliteVdbeAddOp(v, OP_Pop, 1, 0);
26301 + addr2 = sqliteVdbeAddOp(v, OP_Goto, 0, 0);
26303 + pushOntoSorter(pParse, v, pOrderBy);
26305 + sqliteVdbeAddOp(v, OP_String, 0, 0);
26306 + sqliteVdbeAddOp(v, OP_PutStrKey, iParm, 0);
26308 + sqliteVdbeChangeP2(v, addr2, sqliteVdbeCurrentAddr(v));
26312 + /* If this is a scalar select that is part of an expression, then
26313 + ** store the results in the appropriate memory cell and break out
26314 + ** of the scan loop.
26317 + assert( nColumn==1 );
26319 + pushOntoSorter(pParse, v, pOrderBy);
26321 + sqliteVdbeAddOp(v, OP_MemStore, iParm, 1);
26322 + sqliteVdbeAddOp(v, OP_Goto, 0, iBreak);
26327 + /* Send the data to the callback function.
26329 + case SRT_Callback:
26330 + case SRT_Sorter: {
26332 + sqliteVdbeAddOp(v, OP_SortMakeRec, nColumn, 0);
26333 + pushOntoSorter(pParse, v, pOrderBy);
26335 + assert( eDest==SRT_Callback );
26336 + sqliteVdbeAddOp(v, OP_Callback, nColumn, 0);
26341 + /* Invoke a subroutine to handle the results. The subroutine itself
26342 + ** is responsible for popping the results off of the stack.
26344 + case SRT_Subroutine: {
26346 + sqliteVdbeAddOp(v, OP_MakeRecord, nColumn, 0);
26347 + pushOntoSorter(pParse, v, pOrderBy);
26349 + sqliteVdbeAddOp(v, OP_Gosub, 0, iParm);
26354 + /* Discard the results. This is used for SELECT statements inside
26355 + ** the body of a TRIGGER. The purpose of such selects is to call
26356 + ** user-defined functions that have side effects. We do not care
26357 + ** about the actual results of the select.
26360 + assert( eDest==SRT_Discard );
26361 + sqliteVdbeAddOp(v, OP_Pop, nColumn, 0);
26369 +** If the inner loop was generated using a non-null pOrderBy argument,
26370 +** then the results were placed in a sorter. After the loop is terminated
26371 +** we need to run the sorter and output the results. The following
26372 +** routine generates the code needed to do that.
26374 +static void generateSortTail(
26375 + Select *p, /* The SELECT statement */
26376 + Vdbe *v, /* Generate code into this VDBE */
26377 + int nColumn, /* Number of columns of data */
26378 + int eDest, /* Write the sorted results here */
26379 + int iParm /* Optional parameter associated with eDest */
26381 + int end1 = sqliteVdbeMakeLabel(v);
26382 + int end2 = sqliteVdbeMakeLabel(v);
26384 + if( eDest==SRT_Sorter ) return;
26385 + sqliteVdbeAddOp(v, OP_Sort, 0, 0);
26386 + addr = sqliteVdbeAddOp(v, OP_SortNext, 0, end1);
26387 + codeLimiter(v, p, addr, end2, 1);
26389 + case SRT_Callback: {
26390 + sqliteVdbeAddOp(v, OP_SortCallback, nColumn, 0);
26394 + case SRT_TempTable: {
26395 + sqliteVdbeAddOp(v, OP_NewRecno, iParm, 0);
26396 + sqliteVdbeAddOp(v, OP_Pull, 1, 0);
26397 + sqliteVdbeAddOp(v, OP_PutIntKey, iParm, 0);
26401 + assert( nColumn==1 );
26402 + sqliteVdbeAddOp(v, OP_NotNull, -1, sqliteVdbeCurrentAddr(v)+3);
26403 + sqliteVdbeAddOp(v, OP_Pop, 1, 0);
26404 + sqliteVdbeAddOp(v, OP_Goto, 0, sqliteVdbeCurrentAddr(v)+3);
26405 + sqliteVdbeAddOp(v, OP_String, 0, 0);
26406 + sqliteVdbeAddOp(v, OP_PutStrKey, iParm, 0);
26410 + assert( nColumn==1 );
26411 + sqliteVdbeAddOp(v, OP_MemStore, iParm, 1);
26412 + sqliteVdbeAddOp(v, OP_Goto, 0, end1);
26415 + case SRT_Subroutine: {
26417 + for(i=0; i<nColumn; i++){
26418 + sqliteVdbeAddOp(v, OP_Column, -1-i, i);
26420 + sqliteVdbeAddOp(v, OP_Gosub, 0, iParm);
26421 + sqliteVdbeAddOp(v, OP_Pop, 1, 0);
26429 + sqliteVdbeAddOp(v, OP_Goto, 0, addr);
26430 + sqliteVdbeResolveLabel(v, end2);
26431 + sqliteVdbeAddOp(v, OP_Pop, 1, 0);
26432 + sqliteVdbeResolveLabel(v, end1);
26433 + sqliteVdbeAddOp(v, OP_SortReset, 0, 0);
26437 +** Generate code that will tell the VDBE the datatypes of
26438 +** columns in the result set.
26440 +** This routine only generates code if the "PRAGMA show_datatypes=on"
26441 +** has been executed. The datatypes are reported out in the azCol
26442 +** parameter to the callback function. The first N azCol[] entries
26443 +** are the names of the columns, and the second N entries are the
26444 +** datatypes for the columns.
26446 +** The "datatype" for a result that is a column of a type is the
26447 +** datatype definition extracted from the CREATE TABLE statement.
26448 +** The datatype for an expression is either TEXT or NUMERIC. The
26449 +** datatype for a ROWID field is INTEGER.
26451 +static void generateColumnTypes(
26452 + Parse *pParse, /* Parser context */
26453 + SrcList *pTabList, /* List of tables */
26454 + ExprList *pEList /* Expressions defining the result set */
26456 + Vdbe *v = pParse->pVdbe;
26458 + for(i=0; i<pEList->nExpr; i++){
26459 + Expr *p = pEList->a[i].pExpr;
26461 + if( p==0 ) continue;
26462 + if( p->op==TK_COLUMN && pTabList ){
26464 + int iCol = p->iColumn;
26465 + for(j=0; j<pTabList->nSrc && pTabList->a[j].iCursor!=p->iTable; j++){}
26466 + assert( j<pTabList->nSrc );
26467 + pTab = pTabList->a[j].pTab;
26468 + if( iCol<0 ) iCol = pTab->iPKey;
26469 + assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
26471 + zType = "INTEGER";
26473 + zType = pTab->aCol[iCol].zType;
26476 + if( sqliteExprType(p)==SQLITE_SO_TEXT ){
26479 + zType = "NUMERIC";
26482 + sqliteVdbeOp3(v, OP_ColumnName, i + pEList->nExpr, 0, zType, 0);
26487 +** Generate code that will tell the VDBE the names of columns
26488 +** in the result set. This information is used to provide the
26489 +** azCol[] values in the callback.
26491 +static void generateColumnNames(
26492 + Parse *pParse, /* Parser context */
26493 + SrcList *pTabList, /* List of tables */
26494 + ExprList *pEList /* Expressions defining the result set */
26496 + Vdbe *v = pParse->pVdbe;
26498 + sqlite *db = pParse->db;
26499 + int fullNames, shortNames;
26502 + if( pParse->colNamesSet || v==0 || sqlite_malloc_failed ) return;
26503 + pParse->colNamesSet = 1;
26504 + fullNames = (db->flags & SQLITE_FullColNames)!=0;
26505 + shortNames = (db->flags & SQLITE_ShortColNames)!=0;
26506 + for(i=0; i<pEList->nExpr; i++){
26508 + int p2 = i==pEList->nExpr-1;
26509 + p = pEList->a[i].pExpr;
26510 + if( p==0 ) continue;
26511 + if( pEList->a[i].zName ){
26512 + char *zName = pEList->a[i].zName;
26513 + sqliteVdbeOp3(v, OP_ColumnName, i, p2, zName, 0);
26516 + if( p->op==TK_COLUMN && pTabList ){
26519 + int iCol = p->iColumn;
26520 + for(j=0; j<pTabList->nSrc && pTabList->a[j].iCursor!=p->iTable; j++){}
26521 + assert( j<pTabList->nSrc );
26522 + pTab = pTabList->a[j].pTab;
26523 + if( iCol<0 ) iCol = pTab->iPKey;
26524 + assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
26526 + zCol = "_ROWID_";
26528 + zCol = pTab->aCol[iCol].zName;
26530 + if( !shortNames && !fullNames && p->span.z && p->span.z[0] ){
26531 + int addr = sqliteVdbeOp3(v,OP_ColumnName, i, p2, p->span.z, p->span.n);
26532 + sqliteVdbeCompressSpace(v, addr);
26533 + }else if( fullNames || (!shortNames && pTabList->nSrc>1) ){
26537 + zTab = pTabList->a[j].zAlias;
26538 + if( fullNames || zTab==0 ) zTab = pTab->zName;
26539 + sqliteSetString(&zName, zTab, ".", zCol, 0);
26540 + sqliteVdbeOp3(v, OP_ColumnName, i, p2, zName, P3_DYNAMIC);
26542 + sqliteVdbeOp3(v, OP_ColumnName, i, p2, zCol, 0);
26544 + }else if( p->span.z && p->span.z[0] ){
26545 + int addr = sqliteVdbeOp3(v,OP_ColumnName, i, p2, p->span.z, p->span.n);
26546 + sqliteVdbeCompressSpace(v, addr);
26549 + assert( p->op!=TK_COLUMN || pTabList==0 );
26550 + sprintf(zName, "column%d", i+1);
26551 + sqliteVdbeOp3(v, OP_ColumnName, i, p2, zName, 0);
26557 +** Name of the connection operator, used for error messages.
26559 +static const char *selectOpName(int id){
26562 + case TK_ALL: z = "UNION ALL"; break;
26563 + case TK_INTERSECT: z = "INTERSECT"; break;
26564 + case TK_EXCEPT: z = "EXCEPT"; break;
26565 + default: z = "UNION"; break;
26571 +** Forward declaration
26573 +static int fillInColumnList(Parse*, Select*);
26576 +** Given a SELECT statement, generate a Table structure that describes
26577 +** the result set of that SELECT.
26579 +Table *sqliteResultSetOfSelect(Parse *pParse, char *zTabName, Select *pSelect){
26582 + ExprList *pEList;
26585 + if( fillInColumnList(pParse, pSelect) ){
26588 + pTab = sqliteMalloc( sizeof(Table) );
26592 + pTab->zName = zTabName ? sqliteStrDup(zTabName) : 0;
26593 + pEList = pSelect->pEList;
26594 + pTab->nCol = pEList->nExpr;
26595 + assert( pTab->nCol>0 );
26596 + pTab->aCol = aCol = sqliteMalloc( sizeof(pTab->aCol[0])*pTab->nCol );
26597 + for(i=0; i<pTab->nCol; i++){
26599 + if( pEList->a[i].zName ){
26600 + aCol[i].zName = sqliteStrDup(pEList->a[i].zName);
26601 + }else if( (p=pEList->a[i].pExpr)->op==TK_DOT
26602 + && (pR=p->pRight)!=0 && pR->token.z && pR->token.z[0] ){
26604 + sqliteSetNString(&aCol[i].zName, pR->token.z, pR->token.n, 0);
26605 + for(j=cnt=0; j<i; j++){
26606 + if( sqliteStrICmp(aCol[j].zName, aCol[i].zName)==0 ){
26609 + sprintf(zBuf,"_%d",++cnt);
26610 + n = strlen(zBuf);
26611 + sqliteSetNString(&aCol[i].zName, pR->token.z, pR->token.n, zBuf, n,0);
26615 + }else if( p->span.z && p->span.z[0] ){
26616 + sqliteSetNString(&pTab->aCol[i].zName, p->span.z, p->span.n, 0);
26619 + sprintf(zBuf, "column%d", i+1);
26620 + aCol[i].zName = sqliteStrDup(zBuf);
26622 + sqliteDequote(aCol[i].zName);
26624 + pTab->iPKey = -1;
26629 +** For the given SELECT statement, do three things.
26631 +** (1) Fill in the pTabList->a[].pTab fields in the SrcList that
26632 +** defines the set of tables that should be scanned. For views,
26633 +** fill pTabList->a[].pSelect with a copy of the SELECT statement
26634 +** that implements the view. A copy is made of the view's SELECT
26635 +** statement so that we can freely modify or delete that statement
26636 +** without worrying about messing up the presistent representation
26639 +** (2) Add terms to the WHERE clause to accomodate the NATURAL keyword
26640 +** on joins and the ON and USING clause of joins.
26642 +** (3) Scan the list of columns in the result set (pEList) looking
26643 +** for instances of the "*" operator or the TABLE.* operator.
26644 +** If found, expand each "*" to be every column in every table
26645 +** and TABLE.* to be every column in TABLE.
26647 +** Return 0 on success. If there are problems, leave an error message
26648 +** in pParse and return non-zero.
26650 +static int fillInColumnList(Parse *pParse, Select *p){
26652 + SrcList *pTabList;
26653 + ExprList *pEList;
26656 + if( p==0 || p->pSrc==0 ) return 1;
26657 + pTabList = p->pSrc;
26658 + pEList = p->pEList;
26660 + /* Look up every table in the table list.
26662 + for(i=0; i<pTabList->nSrc; i++){
26663 + if( pTabList->a[i].pTab ){
26664 + /* This routine has run before! No need to continue */
26667 + if( pTabList->a[i].zName==0 ){
26668 + /* A sub-query in the FROM clause of a SELECT */
26669 + assert( pTabList->a[i].pSelect!=0 );
26670 + if( pTabList->a[i].zAlias==0 ){
26671 + char zFakeName[60];
26672 + sprintf(zFakeName, "sqlite_subquery_%p_",
26673 + (void*)pTabList->a[i].pSelect);
26674 + sqliteSetString(&pTabList->a[i].zAlias, zFakeName, 0);
26676 + pTabList->a[i].pTab = pTab =
26677 + sqliteResultSetOfSelect(pParse, pTabList->a[i].zAlias,
26678 + pTabList->a[i].pSelect);
26682 + /* The isTransient flag indicates that the Table structure has been
26683 + ** dynamically allocated and may be freed at any time. In other words,
26684 + ** pTab is not pointing to a persistent table structure that defines
26685 + ** part of the schema. */
26686 + pTab->isTransient = 1;
26688 + /* An ordinary table or view name in the FROM clause */
26689 + pTabList->a[i].pTab = pTab =
26690 + sqliteLocateTable(pParse,pTabList->a[i].zName,pTabList->a[i].zDatabase);
26694 + if( pTab->pSelect ){
26695 + /* We reach here if the named table is a really a view */
26696 + if( sqliteViewGetColumnNames(pParse, pTab) ){
26699 + /* If pTabList->a[i].pSelect!=0 it means we are dealing with a
26700 + ** view within a view. The SELECT structure has already been
26701 + ** copied by the outer view so we can skip the copy step here
26702 + ** in the inner view.
26704 + if( pTabList->a[i].pSelect==0 ){
26705 + pTabList->a[i].pSelect = sqliteSelectDup(pTab->pSelect);
26711 + /* Process NATURAL keywords, and ON and USING clauses of joins.
26713 + if( sqliteProcessJoin(pParse, p) ) return 1;
26715 + /* For every "*" that occurs in the column list, insert the names of
26716 + ** all columns in all tables. And for every TABLE.* insert the names
26717 + ** of all columns in TABLE. The parser inserted a special expression
26718 + ** with the TK_ALL operator for each "*" that it found in the column list.
26719 + ** The following code just has to locate the TK_ALL expressions and expand
26720 + ** each one to the list of all columns in all tables.
26722 + ** The first loop just checks to see if there are any "*" operators
26723 + ** that need expanding.
26725 + for(k=0; k<pEList->nExpr; k++){
26726 + Expr *pE = pEList->a[k].pExpr;
26727 + if( pE->op==TK_ALL ) break;
26728 + if( pE->op==TK_DOT && pE->pRight && pE->pRight->op==TK_ALL
26729 + && pE->pLeft && pE->pLeft->op==TK_ID ) break;
26732 + if( k<pEList->nExpr ){
26734 + ** If we get here it means the result set contains one or more "*"
26735 + ** operators that need to be expanded. Loop through each expression
26736 + ** in the result set and expand them one by one.
26738 + struct ExprList_item *a = pEList->a;
26739 + ExprList *pNew = 0;
26740 + for(k=0; k<pEList->nExpr; k++){
26741 + Expr *pE = a[k].pExpr;
26742 + if( pE->op!=TK_ALL &&
26743 + (pE->op!=TK_DOT || pE->pRight==0 || pE->pRight->op!=TK_ALL) ){
26744 + /* This particular expression does not need to be expanded.
26746 + pNew = sqliteExprListAppend(pNew, a[k].pExpr, 0);
26747 + pNew->a[pNew->nExpr-1].zName = a[k].zName;
26751 + /* This expression is a "*" or a "TABLE.*" and needs to be
26753 + int tableSeen = 0; /* Set to 1 when TABLE matches */
26754 + char *zTName; /* text of name of TABLE */
26755 + if( pE->op==TK_DOT && pE->pLeft ){
26756 + zTName = sqliteTableNameFromToken(&pE->pLeft->token);
26760 + for(i=0; i<pTabList->nSrc; i++){
26761 + Table *pTab = pTabList->a[i].pTab;
26762 + char *zTabName = pTabList->a[i].zAlias;
26763 + if( zTabName==0 || zTabName[0]==0 ){
26764 + zTabName = pTab->zName;
26766 + if( zTName && (zTabName==0 || zTabName[0]==0 ||
26767 + sqliteStrICmp(zTName, zTabName)!=0) ){
26771 + for(j=0; j<pTab->nCol; j++){
26772 + Expr *pExpr, *pLeft, *pRight;
26773 + char *zName = pTab->aCol[j].zName;
26775 + if( i>0 && (pTabList->a[i-1].jointype & JT_NATURAL)!=0 &&
26776 + columnIndex(pTabList->a[i-1].pTab, zName)>=0 ){
26777 + /* In a NATURAL join, omit the join columns from the
26778 + ** table on the right */
26781 + if( i>0 && sqliteIdListIndex(pTabList->a[i-1].pUsing, zName)>=0 ){
26782 + /* In a join with a USING clause, omit columns in the
26783 + ** using clause from the table on the right. */
26786 + pRight = sqliteExpr(TK_ID, 0, 0, 0);
26787 + if( pRight==0 ) break;
26788 + pRight->token.z = zName;
26789 + pRight->token.n = strlen(zName);
26790 + pRight->token.dyn = 0;
26791 + if( zTabName && pTabList->nSrc>1 ){
26792 + pLeft = sqliteExpr(TK_ID, 0, 0, 0);
26793 + pExpr = sqliteExpr(TK_DOT, pLeft, pRight, 0);
26794 + if( pExpr==0 ) break;
26795 + pLeft->token.z = zTabName;
26796 + pLeft->token.n = strlen(zTabName);
26797 + pLeft->token.dyn = 0;
26798 + sqliteSetString((char**)&pExpr->span.z, zTabName, ".", zName, 0);
26799 + pExpr->span.n = strlen(pExpr->span.z);
26800 + pExpr->span.dyn = 1;
26801 + pExpr->token.z = 0;
26802 + pExpr->token.n = 0;
26803 + pExpr->token.dyn = 0;
26806 + pExpr->span = pExpr->token;
26808 + pNew = sqliteExprListAppend(pNew, pExpr, 0);
26811 + if( !tableSeen ){
26813 + sqliteErrorMsg(pParse, "no such table: %s", zTName);
26815 + sqliteErrorMsg(pParse, "no tables specified");
26819 + sqliteFree(zTName);
26822 + sqliteExprListDelete(pEList);
26823 + p->pEList = pNew;
26829 +** This routine recursively unlinks the Select.pSrc.a[].pTab pointers
26830 +** in a select structure. It just sets the pointers to NULL. This
26831 +** routine is recursive in the sense that if the Select.pSrc.a[].pSelect
26832 +** pointer is not NULL, this routine is called recursively on that pointer.
26834 +** This routine is called on the Select structure that defines a
26835 +** VIEW in order to undo any bindings to tables. This is necessary
26836 +** because those tables might be DROPed by a subsequent SQL command.
26837 +** If the bindings are not removed, then the Select.pSrc->a[].pTab field
26838 +** will be left pointing to a deallocated Table structure after the
26839 +** DROP and a coredump will occur the next time the VIEW is used.
26841 +void sqliteSelectUnbind(Select *p){
26843 + SrcList *pSrc = p->pSrc;
26845 + if( p==0 ) return;
26846 + for(i=0; i<pSrc->nSrc; i++){
26847 + if( (pTab = pSrc->a[i].pTab)!=0 ){
26848 + if( pTab->isTransient ){
26849 + sqliteDeleteTable(0, pTab);
26851 + pSrc->a[i].pTab = 0;
26852 + if( pSrc->a[i].pSelect ){
26853 + sqliteSelectUnbind(pSrc->a[i].pSelect);
26860 +** This routine associates entries in an ORDER BY expression list with
26861 +** columns in a result. For each ORDER BY expression, the opcode of
26862 +** the top-level node is changed to TK_COLUMN and the iColumn value of
26863 +** the top-level node is filled in with column number and the iTable
26864 +** value of the top-level node is filled with iTable parameter.
26866 +** If there are prior SELECT clauses, they are processed first. A match
26867 +** in an earlier SELECT takes precedence over a later SELECT.
26869 +** Any entry that does not match is flagged as an error. The number
26870 +** of errors is returned.
26872 +** This routine does NOT correctly initialize the Expr.dataType field
26873 +** of the ORDER BY expressions. The multiSelectSortOrder() routine
26874 +** must be called to do that after the individual select statements
26875 +** have all been analyzed. This routine is unable to compute Expr.dataType
26876 +** because it must be called before the individual select statements
26877 +** have been analyzed.
26879 +static int matchOrderbyToColumn(
26880 + Parse *pParse, /* A place to leave error messages */
26881 + Select *pSelect, /* Match to result columns of this SELECT */
26882 + ExprList *pOrderBy, /* The ORDER BY values to match against columns */
26883 + int iTable, /* Insert this value in iTable */
26884 + int mustComplete /* If TRUE all ORDER BYs must match */
26888 + ExprList *pEList;
26890 + if( pSelect==0 || pOrderBy==0 ) return 1;
26891 + if( mustComplete ){
26892 + for(i=0; i<pOrderBy->nExpr; i++){ pOrderBy->a[i].done = 0; }
26894 + if( fillInColumnList(pParse, pSelect) ){
26897 + if( pSelect->pPrior ){
26898 + if( matchOrderbyToColumn(pParse, pSelect->pPrior, pOrderBy, iTable, 0) ){
26902 + pEList = pSelect->pEList;
26903 + for(i=0; i<pOrderBy->nExpr; i++){
26904 + Expr *pE = pOrderBy->a[i].pExpr;
26906 + if( pOrderBy->a[i].done ) continue;
26907 + if( sqliteExprIsInteger(pE, &iCol) ){
26908 + if( iCol<=0 || iCol>pEList->nExpr ){
26909 + sqliteErrorMsg(pParse,
26910 + "ORDER BY position %d should be between 1 and %d",
26911 + iCol, pEList->nExpr);
26915 + if( !mustComplete ) continue;
26918 + for(j=0; iCol<0 && j<pEList->nExpr; j++){
26919 + if( pEList->a[j].zName && (pE->op==TK_ID || pE->op==TK_STRING) ){
26920 + char *zName, *zLabel;
26921 + zName = pEList->a[j].zName;
26922 + assert( pE->token.z );
26923 + zLabel = sqliteStrNDup(pE->token.z, pE->token.n);
26924 + sqliteDequote(zLabel);
26925 + if( sqliteStrICmp(zName, zLabel)==0 ){
26928 + sqliteFree(zLabel);
26930 + if( iCol<0 && sqliteExprCompare(pE, pEList->a[j].pExpr) ){
26935 + pE->op = TK_COLUMN;
26936 + pE->iColumn = iCol;
26937 + pE->iTable = iTable;
26938 + pOrderBy->a[i].done = 1;
26940 + if( iCol<0 && mustComplete ){
26941 + sqliteErrorMsg(pParse,
26942 + "ORDER BY term number %d does not match any result column", i+1);
26951 +** Get a VDBE for the given parser context. Create a new one if necessary.
26952 +** If an error occurs, return NULL and leave a message in pParse.
26954 +Vdbe *sqliteGetVdbe(Parse *pParse){
26955 + Vdbe *v = pParse->pVdbe;
26957 + v = pParse->pVdbe = sqliteVdbeCreate(pParse->db);
26963 +** This routine sets the Expr.dataType field on all elements of
26964 +** the pOrderBy expression list. The pOrderBy list will have been
26965 +** set up by matchOrderbyToColumn(). Hence each expression has
26966 +** a TK_COLUMN as its root node. The Expr.iColumn refers to a
26967 +** column in the result set. The datatype is set to SQLITE_SO_TEXT
26968 +** if the corresponding column in p and every SELECT to the left of
26969 +** p has a datatype of SQLITE_SO_TEXT. If the cooressponding column
26970 +** in p or any of the left SELECTs is SQLITE_SO_NUM, then the datatype
26971 +** of the order-by expression is set to SQLITE_SO_NUM.
26975 +** CREATE TABLE one(a INTEGER, b TEXT);
26976 +** CREATE TABLE two(c VARCHAR(5), d FLOAT);
26978 +** SELECT b, b FROM one UNION SELECT d, c FROM two ORDER BY 1, 2;
26980 +** The primary sort key will use SQLITE_SO_NUM because the "d" in
26981 +** the second SELECT is numeric. The 1st column of the first SELECT
26982 +** is text but that does not matter because a numeric always overrides
26985 +** The secondary key will use the SQLITE_SO_TEXT sort order because
26986 +** both the (second) "b" in the first SELECT and the "c" in the second
26987 +** SELECT have a datatype of text.
26989 +static void multiSelectSortOrder(Select *p, ExprList *pOrderBy){
26991 + ExprList *pEList;
26992 + if( pOrderBy==0 ) return;
26994 + for(i=0; i<pOrderBy->nExpr; i++){
26995 + pOrderBy->a[i].pExpr->dataType = SQLITE_SO_TEXT;
26999 + multiSelectSortOrder(p->pPrior, pOrderBy);
27000 + pEList = p->pEList;
27001 + for(i=0; i<pOrderBy->nExpr; i++){
27002 + Expr *pE = pOrderBy->a[i].pExpr;
27003 + if( pE->dataType==SQLITE_SO_NUM ) continue;
27004 + assert( pE->iColumn>=0 );
27005 + if( pEList->nExpr>pE->iColumn ){
27006 + pE->dataType = sqliteExprType(pEList->a[pE->iColumn].pExpr);
27012 +** Compute the iLimit and iOffset fields of the SELECT based on the
27013 +** nLimit and nOffset fields. nLimit and nOffset hold the integers
27014 +** that appear in the original SQL statement after the LIMIT and OFFSET
27015 +** keywords. Or that hold -1 and 0 if those keywords are omitted.
27016 +** iLimit and iOffset are the integer memory register numbers for
27017 +** counters used to compute the limit and offset. If there is no
27018 +** limit and/or offset, then iLimit and iOffset are negative.
27020 +** This routine changes the values if iLimit and iOffset only if
27021 +** a limit or offset is defined by nLimit and nOffset. iLimit and
27022 +** iOffset should have been preset to appropriate default values
27023 +** (usually but not always -1) prior to calling this routine.
27024 +** Only if nLimit>=0 or nOffset>0 do the limit registers get
27025 +** redefined. The UNION ALL operator uses this property to force
27026 +** the reuse of the same limit and offset registers across multiple
27027 +** SELECT statements.
27029 +static void computeLimitRegisters(Parse *pParse, Select *p){
27031 + ** If the comparison is p->nLimit>0 then "LIMIT 0" shows
27032 + ** all rows. It is the same as no limit. If the comparision is
27033 + ** p->nLimit>=0 then "LIMIT 0" show no rows at all.
27034 + ** "LIMIT -1" always shows all rows. There is some
27035 + ** contraversy about what the correct behavior should be.
27036 + ** The current implementation interprets "LIMIT 0" to mean
27039 + if( p->nLimit>=0 ){
27040 + int iMem = pParse->nMem++;
27041 + Vdbe *v = sqliteGetVdbe(pParse);
27042 + if( v==0 ) return;
27043 + sqliteVdbeAddOp(v, OP_Integer, -p->nLimit, 0);
27044 + sqliteVdbeAddOp(v, OP_MemStore, iMem, 1);
27045 + p->iLimit = iMem;
27047 + if( p->nOffset>0 ){
27048 + int iMem = pParse->nMem++;
27049 + Vdbe *v = sqliteGetVdbe(pParse);
27050 + if( v==0 ) return;
27051 + sqliteVdbeAddOp(v, OP_Integer, -p->nOffset, 0);
27052 + sqliteVdbeAddOp(v, OP_MemStore, iMem, 1);
27053 + p->iOffset = iMem;
27058 +** This routine is called to process a query that is really the union
27059 +** or intersection of two or more separate queries.
27061 +** "p" points to the right-most of the two queries. the query on the
27062 +** left is p->pPrior. The left query could also be a compound query
27063 +** in which case this routine will be called recursively.
27065 +** The results of the total query are to be written into a destination
27066 +** of type eDest with parameter iParm.
27068 +** Example 1: Consider a three-way compound SQL statement.
27070 +** SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
27072 +** This statement is parsed up as follows:
27074 +** SELECT c FROM t3
27076 +** `-----> SELECT b FROM t2
27078 +** `------> SELECT a FROM t1
27080 +** The arrows in the diagram above represent the Select.pPrior pointer.
27081 +** So if this routine is called with p equal to the t3 query, then
27082 +** pPrior will be the t2 query. p->op will be TK_UNION in this case.
27084 +** Notice that because of the way SQLite parses compound SELECTs, the
27085 +** individual selects always group from left to right.
27087 +static int multiSelect(Parse *pParse, Select *p, int eDest, int iParm){
27088 + int rc; /* Success code from a subroutine */
27089 + Select *pPrior; /* Another SELECT immediately to our left */
27090 + Vdbe *v; /* Generate code to this VDBE */
27092 + /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs. Only
27093 + ** the last SELECT in the series may have an ORDER BY or LIMIT.
27095 + if( p==0 || p->pPrior==0 ) return 1;
27096 + pPrior = p->pPrior;
27097 + if( pPrior->pOrderBy ){
27098 + sqliteErrorMsg(pParse,"ORDER BY clause should come after %s not before",
27099 + selectOpName(p->op));
27102 + if( pPrior->nLimit>=0 || pPrior->nOffset>0 ){
27103 + sqliteErrorMsg(pParse,"LIMIT clause should come after %s not before",
27104 + selectOpName(p->op));
27108 + /* Make sure we have a valid query engine. If not, create a new one.
27110 + v = sqliteGetVdbe(pParse);
27111 + if( v==0 ) return 1;
27113 + /* Create the destination temporary table if necessary
27115 + if( eDest==SRT_TempTable ){
27116 + sqliteVdbeAddOp(v, OP_OpenTemp, iParm, 0);
27117 + eDest = SRT_Table;
27120 + /* Generate code for the left and right SELECT statements.
27124 + if( p->pOrderBy==0 ){
27125 + pPrior->nLimit = p->nLimit;
27126 + pPrior->nOffset = p->nOffset;
27127 + rc = sqliteSelect(pParse, pPrior, eDest, iParm, 0, 0, 0);
27128 + if( rc ) return rc;
27130 + p->iLimit = pPrior->iLimit;
27131 + p->iOffset = pPrior->iOffset;
27134 + rc = sqliteSelect(pParse, p, eDest, iParm, 0, 0, 0);
27135 + p->pPrior = pPrior;
27136 + if( rc ) return rc;
27139 + /* For UNION ALL ... ORDER BY fall through to the next case */
27143 + int unionTab; /* Cursor number of the temporary table holding result */
27144 + int op; /* One of the SRT_ operations to apply to self */
27145 + int priorOp; /* The SRT_ operation to apply to prior selects */
27146 + int nLimit, nOffset; /* Saved values of p->nLimit and p->nOffset */
27147 + ExprList *pOrderBy; /* The ORDER BY clause for the right SELECT */
27149 + priorOp = p->op==TK_ALL ? SRT_Table : SRT_Union;
27150 + if( eDest==priorOp && p->pOrderBy==0 && p->nLimit<0 && p->nOffset==0 ){
27151 + /* We can reuse a temporary table generated by a SELECT to our
27154 + unionTab = iParm;
27156 + /* We will need to create our own temporary table to hold the
27157 + ** intermediate results.
27159 + unionTab = pParse->nTab++;
27161 + && matchOrderbyToColumn(pParse, p, p->pOrderBy, unionTab, 1) ){
27164 + if( p->op!=TK_ALL ){
27165 + sqliteVdbeAddOp(v, OP_OpenTemp, unionTab, 1);
27166 + sqliteVdbeAddOp(v, OP_KeyAsData, unionTab, 1);
27168 + sqliteVdbeAddOp(v, OP_OpenTemp, unionTab, 0);
27172 + /* Code the SELECT statements to our left
27174 + rc = sqliteSelect(pParse, pPrior, priorOp, unionTab, 0, 0, 0);
27175 + if( rc ) return rc;
27177 + /* Code the current SELECT statement
27180 + case TK_EXCEPT: op = SRT_Except; break;
27181 + case TK_UNION: op = SRT_Union; break;
27182 + case TK_ALL: op = SRT_Table; break;
27185 + pOrderBy = p->pOrderBy;
27187 + nLimit = p->nLimit;
27189 + nOffset = p->nOffset;
27191 + rc = sqliteSelect(pParse, p, op, unionTab, 0, 0, 0);
27192 + p->pPrior = pPrior;
27193 + p->pOrderBy = pOrderBy;
27194 + p->nLimit = nLimit;
27195 + p->nOffset = nOffset;
27196 + if( rc ) return rc;
27198 + /* Convert the data in the temporary table into whatever form
27199 + ** it is that we currently need.
27201 + if( eDest!=priorOp || unionTab!=iParm ){
27202 + int iCont, iBreak, iStart;
27203 + assert( p->pEList );
27204 + if( eDest==SRT_Callback ){
27205 + generateColumnNames(pParse, 0, p->pEList);
27206 + generateColumnTypes(pParse, p->pSrc, p->pEList);
27208 + iBreak = sqliteVdbeMakeLabel(v);
27209 + iCont = sqliteVdbeMakeLabel(v);
27210 + sqliteVdbeAddOp(v, OP_Rewind, unionTab, iBreak);
27211 + computeLimitRegisters(pParse, p);
27212 + iStart = sqliteVdbeCurrentAddr(v);
27213 + multiSelectSortOrder(p, p->pOrderBy);
27214 + rc = selectInnerLoop(pParse, p, p->pEList, unionTab, p->pEList->nExpr,
27215 + p->pOrderBy, -1, eDest, iParm,
27217 + if( rc ) return 1;
27218 + sqliteVdbeResolveLabel(v, iCont);
27219 + sqliteVdbeAddOp(v, OP_Next, unionTab, iStart);
27220 + sqliteVdbeResolveLabel(v, iBreak);
27221 + sqliteVdbeAddOp(v, OP_Close, unionTab, 0);
27222 + if( p->pOrderBy ){
27223 + generateSortTail(p, v, p->pEList->nExpr, eDest, iParm);
27228 + case TK_INTERSECT: {
27230 + int iCont, iBreak, iStart;
27231 + int nLimit, nOffset;
27233 + /* INTERSECT is different from the others since it requires
27234 + ** two temporary tables. Hence it has its own case. Begin
27235 + ** by allocating the tables we will need.
27237 + tab1 = pParse->nTab++;
27238 + tab2 = pParse->nTab++;
27239 + if( p->pOrderBy && matchOrderbyToColumn(pParse,p,p->pOrderBy,tab1,1) ){
27242 + sqliteVdbeAddOp(v, OP_OpenTemp, tab1, 1);
27243 + sqliteVdbeAddOp(v, OP_KeyAsData, tab1, 1);
27245 + /* Code the SELECTs to our left into temporary table "tab1".
27247 + rc = sqliteSelect(pParse, pPrior, SRT_Union, tab1, 0, 0, 0);
27248 + if( rc ) return rc;
27250 + /* Code the current SELECT into temporary table "tab2"
27252 + sqliteVdbeAddOp(v, OP_OpenTemp, tab2, 1);
27253 + sqliteVdbeAddOp(v, OP_KeyAsData, tab2, 1);
27255 + nLimit = p->nLimit;
27257 + nOffset = p->nOffset;
27259 + rc = sqliteSelect(pParse, p, SRT_Union, tab2, 0, 0, 0);
27260 + p->pPrior = pPrior;
27261 + p->nLimit = nLimit;
27262 + p->nOffset = nOffset;
27263 + if( rc ) return rc;
27265 + /* Generate code to take the intersection of the two temporary
27268 + assert( p->pEList );
27269 + if( eDest==SRT_Callback ){
27270 + generateColumnNames(pParse, 0, p->pEList);
27271 + generateColumnTypes(pParse, p->pSrc, p->pEList);
27273 + iBreak = sqliteVdbeMakeLabel(v);
27274 + iCont = sqliteVdbeMakeLabel(v);
27275 + sqliteVdbeAddOp(v, OP_Rewind, tab1, iBreak);
27276 + computeLimitRegisters(pParse, p);
27277 + iStart = sqliteVdbeAddOp(v, OP_FullKey, tab1, 0);
27278 + sqliteVdbeAddOp(v, OP_NotFound, tab2, iCont);
27279 + multiSelectSortOrder(p, p->pOrderBy);
27280 + rc = selectInnerLoop(pParse, p, p->pEList, tab1, p->pEList->nExpr,
27281 + p->pOrderBy, -1, eDest, iParm,
27283 + if( rc ) return 1;
27284 + sqliteVdbeResolveLabel(v, iCont);
27285 + sqliteVdbeAddOp(v, OP_Next, tab1, iStart);
27286 + sqliteVdbeResolveLabel(v, iBreak);
27287 + sqliteVdbeAddOp(v, OP_Close, tab2, 0);
27288 + sqliteVdbeAddOp(v, OP_Close, tab1, 0);
27289 + if( p->pOrderBy ){
27290 + generateSortTail(p, v, p->pEList->nExpr, eDest, iParm);
27295 + assert( p->pEList && pPrior->pEList );
27296 + if( p->pEList->nExpr!=pPrior->pEList->nExpr ){
27297 + sqliteErrorMsg(pParse, "SELECTs to the left and right of %s"
27298 + " do not have the same number of result columns", selectOpName(p->op));
27305 +** Scan through the expression pExpr. Replace every reference to
27306 +** a column in table number iTable with a copy of the iColumn-th
27307 +** entry in pEList. (But leave references to the ROWID column
27310 +** This routine is part of the flattening procedure. A subquery
27311 +** whose result set is defined by pEList appears as entry in the
27312 +** FROM clause of a SELECT such that the VDBE cursor assigned to that
27313 +** FORM clause entry is iTable. This routine make the necessary
27314 +** changes to pExpr so that it refers directly to the source table
27315 +** of the subquery rather the result set of the subquery.
27317 +static void substExprList(ExprList*,int,ExprList*); /* Forward Decl */
27318 +static void substExpr(Expr *pExpr, int iTable, ExprList *pEList){
27319 + if( pExpr==0 ) return;
27320 + if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){
27321 + if( pExpr->iColumn<0 ){
27322 + pExpr->op = TK_NULL;
27325 + assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
27326 + assert( pExpr->pLeft==0 && pExpr->pRight==0 && pExpr->pList==0 );
27327 + pNew = pEList->a[pExpr->iColumn].pExpr;
27328 + assert( pNew!=0 );
27329 + pExpr->op = pNew->op;
27330 + pExpr->dataType = pNew->dataType;
27331 + assert( pExpr->pLeft==0 );
27332 + pExpr->pLeft = sqliteExprDup(pNew->pLeft);
27333 + assert( pExpr->pRight==0 );
27334 + pExpr->pRight = sqliteExprDup(pNew->pRight);
27335 + assert( pExpr->pList==0 );
27336 + pExpr->pList = sqliteExprListDup(pNew->pList);
27337 + pExpr->iTable = pNew->iTable;
27338 + pExpr->iColumn = pNew->iColumn;
27339 + pExpr->iAgg = pNew->iAgg;
27340 + sqliteTokenCopy(&pExpr->token, &pNew->token);
27341 + sqliteTokenCopy(&pExpr->span, &pNew->span);
27344 + substExpr(pExpr->pLeft, iTable, pEList);
27345 + substExpr(pExpr->pRight, iTable, pEList);
27346 + substExprList(pExpr->pList, iTable, pEList);
27350 +substExprList(ExprList *pList, int iTable, ExprList *pEList){
27352 + if( pList==0 ) return;
27353 + for(i=0; i<pList->nExpr; i++){
27354 + substExpr(pList->a[i].pExpr, iTable, pEList);
27359 +** This routine attempts to flatten subqueries in order to speed
27360 +** execution. It returns 1 if it makes changes and 0 if no flattening
27363 +** To understand the concept of flattening, consider the following
27366 +** SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
27368 +** The default way of implementing this query is to execute the
27369 +** subquery first and store the results in a temporary table, then
27370 +** run the outer query on that temporary table. This requires two
27371 +** passes over the data. Furthermore, because the temporary table
27372 +** has no indices, the WHERE clause on the outer query cannot be
27375 +** This routine attempts to rewrite queries such as the above into
27376 +** a single flat select, like this:
27378 +** SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
27380 +** The code generated for this simpification gives the same result
27381 +** but only has to scan the data once. And because indices might
27382 +** exist on the table t1, a complete scan of the data might be
27385 +** Flattening is only attempted if all of the following are true:
27387 +** (1) The subquery and the outer query do not both use aggregates.
27389 +** (2) The subquery is not an aggregate or the outer query is not a join.
27391 +** (3) The subquery is not the right operand of a left outer join, or
27392 +** the subquery is not itself a join. (Ticket #306)
27394 +** (4) The subquery is not DISTINCT or the outer query is not a join.
27396 +** (5) The subquery is not DISTINCT or the outer query does not use
27399 +** (6) The subquery does not use aggregates or the outer query is not
27402 +** (7) The subquery has a FROM clause.
27404 +** (8) The subquery does not use LIMIT or the outer query is not a join.
27406 +** (9) The subquery does not use LIMIT or the outer query does not use
27409 +** (10) The subquery does not use aggregates or the outer query does not
27412 +** (11) The subquery and the outer query do not both have ORDER BY clauses.
27414 +** (12) The subquery is not the right term of a LEFT OUTER JOIN or the
27415 +** subquery has no WHERE clause. (added by ticket #350)
27417 +** In this routine, the "p" parameter is a pointer to the outer query.
27418 +** The subquery is p->pSrc->a[iFrom]. isAgg is true if the outer query
27419 +** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
27421 +** If flattening is not attempted, this routine is a no-op and returns 0.
27422 +** If flattening is attempted this routine returns 1.
27424 +** All of the expression analysis must occur on both the outer query and
27425 +** the subquery before this routine runs.
27427 +static int flattenSubquery(
27428 + Parse *pParse, /* The parsing context */
27429 + Select *p, /* The parent or outer SELECT statement */
27430 + int iFrom, /* Index in p->pSrc->a[] of the inner subquery */
27431 + int isAgg, /* True if outer SELECT uses aggregate functions */
27432 + int subqueryIsAgg /* True if the subquery uses aggregate functions */
27434 + Select *pSub; /* The inner query or "subquery" */
27435 + SrcList *pSrc; /* The FROM clause of the outer query */
27436 + SrcList *pSubSrc; /* The FROM clause of the subquery */
27437 + ExprList *pList; /* The result set of the outer query */
27438 + int iParent; /* VDBE cursor number of the pSub result set temp table */
27442 + /* Check to see if flattening is permitted. Return 0 if not.
27444 + if( p==0 ) return 0;
27446 + assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
27447 + pSub = pSrc->a[iFrom].pSelect;
27448 + assert( pSub!=0 );
27449 + if( isAgg && subqueryIsAgg ) return 0;
27450 + if( subqueryIsAgg && pSrc->nSrc>1 ) return 0;
27451 + pSubSrc = pSub->pSrc;
27452 + assert( pSubSrc );
27453 + if( pSubSrc->nSrc==0 ) return 0;
27454 + if( (pSub->isDistinct || pSub->nLimit>=0) && (pSrc->nSrc>1 || isAgg) ){
27457 + if( (p->isDistinct || p->nLimit>=0) && subqueryIsAgg ) return 0;
27458 + if( p->pOrderBy && pSub->pOrderBy ) return 0;
27460 + /* Restriction 3: If the subquery is a join, make sure the subquery is
27461 + ** not used as the right operand of an outer join. Examples of why this
27462 + ** is not allowed:
27464 + ** t1 LEFT OUTER JOIN (t2 JOIN t3)
27466 + ** If we flatten the above, we would get
27468 + ** (t1 LEFT OUTER JOIN t2) JOIN t3
27470 + ** which is not at all the same thing.
27472 + if( pSubSrc->nSrc>1 && iFrom>0 && (pSrc->a[iFrom-1].jointype & JT_OUTER)!=0 ){
27476 + /* Restriction 12: If the subquery is the right operand of a left outer
27477 + ** join, make sure the subquery has no WHERE clause.
27478 + ** An examples of why this is not allowed:
27480 + ** t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0)
27482 + ** If we flatten the above, we would get
27484 + ** (t1 LEFT OUTER JOIN t2) WHERE t2.x>0
27486 + ** But the t2.x>0 test will always fail on a NULL row of t2, which
27487 + ** effectively converts the OUTER JOIN into an INNER JOIN.
27489 + if( iFrom>0 && (pSrc->a[iFrom-1].jointype & JT_OUTER)!=0
27490 + && pSub->pWhere!=0 ){
27494 + /* If we reach this point, it means flattening is permitted for the
27495 + ** iFrom-th entry of the FROM clause in the outer query.
27498 + /* Move all of the FROM elements of the subquery into the
27499 + ** the FROM clause of the outer query. Before doing this, remember
27500 + ** the cursor number for the original outer query FROM element in
27501 + ** iParent. The iParent cursor will never be used. Subsequent code
27502 + ** will scan expressions looking for iParent references and replace
27503 + ** those references with expressions that resolve to the subquery FROM
27504 + ** elements we are now copying in.
27506 + iParent = pSrc->a[iFrom].iCursor;
27508 + int nSubSrc = pSubSrc->nSrc;
27509 + int jointype = pSrc->a[iFrom].jointype;
27511 + if( pSrc->a[iFrom].pTab && pSrc->a[iFrom].pTab->isTransient ){
27512 + sqliteDeleteTable(0, pSrc->a[iFrom].pTab);
27514 + sqliteFree(pSrc->a[iFrom].zDatabase);
27515 + sqliteFree(pSrc->a[iFrom].zName);
27516 + sqliteFree(pSrc->a[iFrom].zAlias);
27518 + int extra = nSubSrc - 1;
27519 + for(i=1; i<nSubSrc; i++){
27520 + pSrc = sqliteSrcListAppend(pSrc, 0, 0);
27523 + for(i=pSrc->nSrc-1; i-extra>=iFrom; i--){
27524 + pSrc->a[i] = pSrc->a[i-extra];
27527 + for(i=0; i<nSubSrc; i++){
27528 + pSrc->a[i+iFrom] = pSubSrc->a[i];
27529 + memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
27531 + pSrc->a[iFrom+nSubSrc-1].jointype = jointype;
27534 + /* Now begin substituting subquery result set expressions for
27535 + ** references to the iParent in the outer query.
27539 + ** SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
27540 + ** \ \_____________ subquery __________/ /
27541 + ** \_____________________ outer query ______________________________/
27543 + ** We look at every expression in the outer query and every place we see
27544 + ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
27546 + substExprList(p->pEList, iParent, pSub->pEList);
27547 + pList = p->pEList;
27548 + for(i=0; i<pList->nExpr; i++){
27550 + if( pList->a[i].zName==0 && (pExpr = pList->a[i].pExpr)->span.z!=0 ){
27551 + pList->a[i].zName = sqliteStrNDup(pExpr->span.z, pExpr->span.n);
27555 + substExprList(p->pGroupBy, iParent, pSub->pEList);
27556 + substExpr(p->pHaving, iParent, pSub->pEList);
27558 + if( pSub->pOrderBy ){
27559 + assert( p->pOrderBy==0 );
27560 + p->pOrderBy = pSub->pOrderBy;
27561 + pSub->pOrderBy = 0;
27562 + }else if( p->pOrderBy ){
27563 + substExprList(p->pOrderBy, iParent, pSub->pEList);
27565 + if( pSub->pWhere ){
27566 + pWhere = sqliteExprDup(pSub->pWhere);
27570 + if( subqueryIsAgg ){
27571 + assert( p->pHaving==0 );
27572 + p->pHaving = p->pWhere;
27573 + p->pWhere = pWhere;
27574 + substExpr(p->pHaving, iParent, pSub->pEList);
27575 + if( pSub->pHaving ){
27576 + Expr *pHaving = sqliteExprDup(pSub->pHaving);
27577 + if( p->pHaving ){
27578 + p->pHaving = sqliteExpr(TK_AND, p->pHaving, pHaving, 0);
27580 + p->pHaving = pHaving;
27583 + assert( p->pGroupBy==0 );
27584 + p->pGroupBy = sqliteExprListDup(pSub->pGroupBy);
27585 + }else if( p->pWhere==0 ){
27586 + p->pWhere = pWhere;
27588 + substExpr(p->pWhere, iParent, pSub->pEList);
27590 + p->pWhere = sqliteExpr(TK_AND, p->pWhere, pWhere, 0);
27594 + /* The flattened query is distinct if either the inner or the
27595 + ** outer query is distinct.
27597 + p->isDistinct = p->isDistinct || pSub->isDistinct;
27599 + /* Transfer the limit expression from the subquery to the outer
27602 + if( pSub->nLimit>=0 ){
27603 + if( p->nLimit<0 ){
27604 + p->nLimit = pSub->nLimit;
27605 + }else if( p->nLimit+p->nOffset > pSub->nLimit+pSub->nOffset ){
27606 + p->nLimit = pSub->nLimit + pSub->nOffset - p->nOffset;
27609 + p->nOffset += pSub->nOffset;
27611 + /* Finially, delete what is left of the subquery and return
27614 + sqliteSelectDelete(pSub);
27619 +** Analyze the SELECT statement passed in as an argument to see if it
27620 +** is a simple min() or max() query. If it is and this query can be
27621 +** satisfied using a single seek to the beginning or end of an index,
27622 +** then generate the code for this SELECT and return 1. If this is not a
27623 +** simple min() or max() query, then return 0;
27625 +** A simply min() or max() query looks like this:
27627 +** SELECT min(a) FROM table;
27628 +** SELECT max(a) FROM table;
27630 +** The query may have only a single table in its FROM argument. There
27631 +** can be no GROUP BY or HAVING or WHERE clauses. The result set must
27632 +** be the min() or max() of a single column of the table. The column
27633 +** in the min() or max() function must be indexed.
27635 +** The parameters to this routine are the same as for sqliteSelect().
27636 +** See the header comment on that routine for additional information.
27638 +static int simpleMinMaxQuery(Parse *pParse, Select *p, int eDest, int iParm){
27647 + ExprList *pEList, *pList, eList;
27648 + struct ExprList_item eListItem;
27652 + /* Check to see if this query is a simple min() or max() query. Return
27653 + ** zero if it is not.
27655 + if( p->pGroupBy || p->pHaving || p->pWhere ) return 0;
27657 + if( pSrc->nSrc!=1 ) return 0;
27658 + pEList = p->pEList;
27659 + if( pEList->nExpr!=1 ) return 0;
27660 + pExpr = pEList->a[0].pExpr;
27661 + if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
27662 + pList = pExpr->pList;
27663 + if( pList==0 || pList->nExpr!=1 ) return 0;
27664 + if( pExpr->token.n!=3 ) return 0;
27665 + if( sqliteStrNICmp(pExpr->token.z,"min",3)==0 ){
27666 + seekOp = OP_Rewind;
27667 + }else if( sqliteStrNICmp(pExpr->token.z,"max",3)==0 ){
27668 + seekOp = OP_Last;
27672 + pExpr = pList->a[0].pExpr;
27673 + if( pExpr->op!=TK_COLUMN ) return 0;
27674 + iCol = pExpr->iColumn;
27675 + pTab = pSrc->a[0].pTab;
27677 + /* If we get to here, it means the query is of the correct form.
27678 + ** Check to make sure we have an index and make pIdx point to the
27679 + ** appropriate index. If the min() or max() is on an INTEGER PRIMARY
27680 + ** key column, no index is necessary so set pIdx to NULL. If no
27681 + ** usable index is found, return 0.
27686 + for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
27687 + assert( pIdx->nColumn>=1 );
27688 + if( pIdx->aiColumn[0]==iCol ) break;
27690 + if( pIdx==0 ) return 0;
27693 + /* Identify column types if we will be using the callback. This
27694 + ** step is skipped if the output is going to a table or a memory cell.
27695 + ** The column names have already been generated in the calling function.
27697 + v = sqliteGetVdbe(pParse);
27698 + if( v==0 ) return 0;
27699 + if( eDest==SRT_Callback ){
27700 + generateColumnTypes(pParse, p->pSrc, p->pEList);
27703 + /* If the output is destined for a temporary table, open that table.
27705 + if( eDest==SRT_TempTable ){
27706 + sqliteVdbeAddOp(v, OP_OpenTemp, iParm, 0);
27709 + /* Generating code to find the min or the max. Basically all we have
27710 + ** to do is find the first or the last entry in the chosen index. If
27711 + ** the min() or max() is on the INTEGER PRIMARY KEY, then find the first
27712 + ** or last entry in the main table.
27714 + sqliteCodeVerifySchema(pParse, pTab->iDb);
27715 + base = pSrc->a[0].iCursor;
27716 + computeLimitRegisters(pParse, p);
27717 + if( pSrc->a[0].pSelect==0 ){
27718 + sqliteVdbeAddOp(v, OP_Integer, pTab->iDb, 0);
27719 + sqliteVdbeOp3(v, OP_OpenRead, base, pTab->tnum, pTab->zName, 0);
27721 + cont = sqliteVdbeMakeLabel(v);
27723 + sqliteVdbeAddOp(v, seekOp, base, 0);
27725 + sqliteVdbeAddOp(v, OP_Integer, pIdx->iDb, 0);
27726 + sqliteVdbeOp3(v, OP_OpenRead, base+1, pIdx->tnum, pIdx->zName, P3_STATIC);
27727 + if( seekOp==OP_Rewind ){
27728 + sqliteVdbeAddOp(v, OP_String, 0, 0);
27729 + sqliteVdbeAddOp(v, OP_MakeKey, 1, 0);
27730 + sqliteVdbeAddOp(v, OP_IncrKey, 0, 0);
27731 + seekOp = OP_MoveTo;
27733 + sqliteVdbeAddOp(v, seekOp, base+1, 0);
27734 + sqliteVdbeAddOp(v, OP_IdxRecno, base+1, 0);
27735 + sqliteVdbeAddOp(v, OP_Close, base+1, 0);
27736 + sqliteVdbeAddOp(v, OP_MoveTo, base, 0);
27739 + memset(&eListItem, 0, sizeof(eListItem));
27740 + eList.a = &eListItem;
27741 + eList.a[0].pExpr = pExpr;
27742 + selectInnerLoop(pParse, p, &eList, 0, 0, 0, -1, eDest, iParm, cont, cont);
27743 + sqliteVdbeResolveLabel(v, cont);
27744 + sqliteVdbeAddOp(v, OP_Close, base, 0);
27750 +** Generate code for the given SELECT statement.
27752 +** The results are distributed in various ways depending on the
27753 +** value of eDest and iParm.
27755 +** eDest Value Result
27756 +** ------------ -------------------------------------------
27757 +** SRT_Callback Invoke the callback for each row of the result.
27759 +** SRT_Mem Store first result in memory cell iParm
27761 +** SRT_Set Store results as keys of a table with cursor iParm
27763 +** SRT_Union Store results as a key in a temporary table iParm
27765 +** SRT_Except Remove results from the temporary table iParm.
27767 +** SRT_Table Store results in temporary table iParm
27769 +** The table above is incomplete. Additional eDist value have be added
27770 +** since this comment was written. See the selectInnerLoop() function for
27771 +** a complete listing of the allowed values of eDest and their meanings.
27773 +** This routine returns the number of errors. If any errors are
27774 +** encountered, then an appropriate error message is left in
27775 +** pParse->zErrMsg.
27777 +** This routine does NOT free the Select structure passed in. The
27778 +** calling function needs to do that.
27780 +** The pParent, parentTab, and *pParentAgg fields are filled in if this
27781 +** SELECT is a subquery. This routine may try to combine this SELECT
27782 +** with its parent to form a single flat query. In so doing, it might
27783 +** change the parent query from a non-aggregate to an aggregate query.
27784 +** For that reason, the pParentAgg flag is passed as a pointer, so it
27785 +** can be changed.
27787 +** Example 1: The meaning of the pParent parameter.
27789 +** SELECT * FROM t1 JOIN (SELECT x, count(*) FROM t2) JOIN t3;
27790 +** \ \_______ subquery _______/ /
27792 +** \____________________ outer query ___________________/
27794 +** This routine is called for the outer query first. For that call,
27795 +** pParent will be NULL. During the processing of the outer query, this
27796 +** routine is called recursively to handle the subquery. For the recursive
27797 +** call, pParent will point to the outer query. Because the subquery is
27798 +** the second element in a three-way join, the parentTab parameter will
27799 +** be 1 (the 2nd value of a 0-indexed array.)
27802 + Parse *pParse, /* The parser context */
27803 + Select *p, /* The SELECT statement being coded. */
27804 + int eDest, /* How to dispose of the results */
27805 + int iParm, /* A parameter used by the eDest disposal method */
27806 + Select *pParent, /* Another SELECT for which this is a sub-query */
27807 + int parentTab, /* Index in pParent->pSrc of this query */
27808 + int *pParentAgg /* True if pParent uses aggregate functions */
27811 + WhereInfo *pWInfo;
27813 + int isAgg = 0; /* True for select lists like "count(*)" */
27814 + ExprList *pEList; /* List of columns to extract. */
27815 + SrcList *pTabList; /* List of tables to select from */
27816 + Expr *pWhere; /* The WHERE clause. May be NULL */
27817 + ExprList *pOrderBy; /* The ORDER BY clause. May be NULL */
27818 + ExprList *pGroupBy; /* The GROUP BY clause. May be NULL */
27819 + Expr *pHaving; /* The HAVING clause. May be NULL */
27820 + int isDistinct; /* True if the DISTINCT keyword is present */
27821 + int distinct; /* Table to use for the distinct set */
27822 + int rc = 1; /* Value to return from this function */
27824 + if( sqlite_malloc_failed || pParse->nErr || p==0 ) return 1;
27825 + if( sqliteAuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
27827 + /* If there is are a sequence of queries, do the earlier ones first.
27830 + return multiSelect(pParse, p, eDest, iParm);
27833 + /* Make local copies of the parameters for this query.
27835 + pTabList = p->pSrc;
27836 + pWhere = p->pWhere;
27837 + pOrderBy = p->pOrderBy;
27838 + pGroupBy = p->pGroupBy;
27839 + pHaving = p->pHaving;
27840 + isDistinct = p->isDistinct;
27842 + /* Allocate VDBE cursors for each table in the FROM clause
27844 + sqliteSrcListAssignCursors(pParse, pTabList);
27847 + ** Do not even attempt to generate any code if we have already seen
27848 + ** errors before this routine starts.
27850 + if( pParse->nErr>0 ) goto select_end;
27852 + /* Expand any "*" terms in the result set. (For example the "*" in
27853 + ** "SELECT * FROM t1") The fillInColumnlist() routine also does some
27854 + ** other housekeeping - see the header comment for details.
27856 + if( fillInColumnList(pParse, p) ){
27859 + pWhere = p->pWhere;
27860 + pEList = p->pEList;
27861 + if( pEList==0 ) goto select_end;
27863 + /* If writing to memory or generating a set
27864 + ** only a single column may be output.
27866 + if( (eDest==SRT_Mem || eDest==SRT_Set) && pEList->nExpr>1 ){
27867 + sqliteErrorMsg(pParse, "only a single result allowed for "
27868 + "a SELECT that is part of an expression");
27872 + /* ORDER BY is ignored for some destinations.
27877 + case SRT_Discard:
27884 + /* At this point, we should have allocated all the cursors that we
27885 + ** need to handle subquerys and temporary tables.
27887 + ** Resolve the column names and do a semantics check on all the expressions.
27889 + for(i=0; i<pEList->nExpr; i++){
27890 + if( sqliteExprResolveIds(pParse, pTabList, 0, pEList->a[i].pExpr) ){
27893 + if( sqliteExprCheck(pParse, pEList->a[i].pExpr, 1, &isAgg) ){
27898 + if( sqliteExprResolveIds(pParse, pTabList, pEList, pWhere) ){
27901 + if( sqliteExprCheck(pParse, pWhere, 0, 0) ){
27906 + if( pGroupBy==0 ){
27907 + sqliteErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
27910 + if( sqliteExprResolveIds(pParse, pTabList, pEList, pHaving) ){
27913 + if( sqliteExprCheck(pParse, pHaving, 1, &isAgg) ){
27918 + for(i=0; i<pOrderBy->nExpr; i++){
27920 + Expr *pE = pOrderBy->a[i].pExpr;
27921 + if( sqliteExprIsInteger(pE, &iCol) && iCol>0 && iCol<=pEList->nExpr ){
27922 + sqliteExprDelete(pE);
27923 + pE = pOrderBy->a[i].pExpr = sqliteExprDup(pEList->a[iCol-1].pExpr);
27925 + if( sqliteExprResolveIds(pParse, pTabList, pEList, pE) ){
27928 + if( sqliteExprCheck(pParse, pE, isAgg, 0) ){
27931 + if( sqliteExprIsConstant(pE) ){
27932 + if( sqliteExprIsInteger(pE, &iCol)==0 ){
27933 + sqliteErrorMsg(pParse,
27934 + "ORDER BY terms must not be non-integer constants");
27936 + }else if( iCol<=0 || iCol>pEList->nExpr ){
27937 + sqliteErrorMsg(pParse,
27938 + "ORDER BY column number %d out of range - should be "
27939 + "between 1 and %d", iCol, pEList->nExpr);
27946 + for(i=0; i<pGroupBy->nExpr; i++){
27948 + Expr *pE = pGroupBy->a[i].pExpr;
27949 + if( sqliteExprIsInteger(pE, &iCol) && iCol>0 && iCol<=pEList->nExpr ){
27950 + sqliteExprDelete(pE);
27951 + pE = pGroupBy->a[i].pExpr = sqliteExprDup(pEList->a[iCol-1].pExpr);
27953 + if( sqliteExprResolveIds(pParse, pTabList, pEList, pE) ){
27956 + if( sqliteExprCheck(pParse, pE, isAgg, 0) ){
27959 + if( sqliteExprIsConstant(pE) ){
27960 + if( sqliteExprIsInteger(pE, &iCol)==0 ){
27961 + sqliteErrorMsg(pParse,
27962 + "GROUP BY terms must not be non-integer constants");
27964 + }else if( iCol<=0 || iCol>pEList->nExpr ){
27965 + sqliteErrorMsg(pParse,
27966 + "GROUP BY column number %d out of range - should be "
27967 + "between 1 and %d", iCol, pEList->nExpr);
27974 + /* Begin generating code.
27976 + v = sqliteGetVdbe(pParse);
27977 + if( v==0 ) goto select_end;
27979 + /* Identify column names if we will be using them in a callback. This
27980 + ** step is skipped if the output is going to some other destination.
27982 + if( eDest==SRT_Callback ){
27983 + generateColumnNames(pParse, pTabList, pEList);
27986 + /* Generate code for all sub-queries in the FROM clause
27988 + for(i=0; i<pTabList->nSrc; i++){
27989 + const char *zSavedAuthContext;
27990 + int needRestoreContext;
27992 + if( pTabList->a[i].pSelect==0 ) continue;
27993 + if( pTabList->a[i].zName!=0 ){
27994 + zSavedAuthContext = pParse->zAuthContext;
27995 + pParse->zAuthContext = pTabList->a[i].zName;
27996 + needRestoreContext = 1;
27998 + needRestoreContext = 0;
28000 + sqliteSelect(pParse, pTabList->a[i].pSelect, SRT_TempTable,
28001 + pTabList->a[i].iCursor, p, i, &isAgg);
28002 + if( needRestoreContext ){
28003 + pParse->zAuthContext = zSavedAuthContext;
28005 + pTabList = p->pSrc;
28006 + pWhere = p->pWhere;
28007 + if( eDest!=SRT_Union && eDest!=SRT_Except && eDest!=SRT_Discard ){
28008 + pOrderBy = p->pOrderBy;
28010 + pGroupBy = p->pGroupBy;
28011 + pHaving = p->pHaving;
28012 + isDistinct = p->isDistinct;
28015 + /* Check for the special case of a min() or max() function by itself
28016 + ** in the result set.
28018 + if( simpleMinMaxQuery(pParse, p, eDest, iParm) ){
28023 + /* Check to see if this is a subquery that can be "flattened" into its parent.
28024 + ** If flattening is a possiblity, do so and return immediately.
28026 + if( pParent && pParentAgg &&
28027 + flattenSubquery(pParse, pParent, parentTab, *pParentAgg, isAgg) ){
28028 + if( isAgg ) *pParentAgg = 1;
28032 + /* Set the limiter.
28034 + computeLimitRegisters(pParse, p);
28036 + /* Identify column types if we will be using a callback. This
28037 + ** step is skipped if the output is going to a destination other
28038 + ** than a callback.
28040 + ** We have to do this separately from the creation of column names
28041 + ** above because if the pTabList contains views then they will not
28042 + ** have been resolved and we will not know the column types until
28045 + if( eDest==SRT_Callback ){
28046 + generateColumnTypes(pParse, pTabList, pEList);
28049 + /* If the output is destined for a temporary table, open that table.
28051 + if( eDest==SRT_TempTable ){
28052 + sqliteVdbeAddOp(v, OP_OpenTemp, iParm, 0);
28055 + /* Do an analysis of aggregate expressions.
28057 + sqliteAggregateInfoReset(pParse);
28058 + if( isAgg || pGroupBy ){
28059 + assert( pParse->nAgg==0 );
28061 + for(i=0; i<pEList->nExpr; i++){
28062 + if( sqliteExprAnalyzeAggregates(pParse, pEList->a[i].pExpr) ){
28067 + for(i=0; i<pGroupBy->nExpr; i++){
28068 + if( sqliteExprAnalyzeAggregates(pParse, pGroupBy->a[i].pExpr) ){
28073 + if( pHaving && sqliteExprAnalyzeAggregates(pParse, pHaving) ){
28077 + for(i=0; i<pOrderBy->nExpr; i++){
28078 + if( sqliteExprAnalyzeAggregates(pParse, pOrderBy->a[i].pExpr) ){
28085 + /* Reset the aggregator
28088 + sqliteVdbeAddOp(v, OP_AggReset, 0, pParse->nAgg);
28089 + for(i=0; i<pParse->nAgg; i++){
28091 + if( (pFunc = pParse->aAgg[i].pFunc)!=0 && pFunc->xFinalize!=0 ){
28092 + sqliteVdbeOp3(v, OP_AggInit, 0, i, (char*)pFunc, P3_POINTER);
28095 + if( pGroupBy==0 ){
28096 + sqliteVdbeAddOp(v, OP_String, 0, 0);
28097 + sqliteVdbeAddOp(v, OP_AggFocus, 0, 0);
28101 + /* Initialize the memory cell to NULL
28103 + if( eDest==SRT_Mem ){
28104 + sqliteVdbeAddOp(v, OP_String, 0, 0);
28105 + sqliteVdbeAddOp(v, OP_MemStore, iParm, 1);
28108 + /* Open a temporary table to use for the distinct set.
28110 + if( isDistinct ){
28111 + distinct = pParse->nTab++;
28112 + sqliteVdbeAddOp(v, OP_OpenTemp, distinct, 1);
28117 + /* Begin the database scan
28119 + pWInfo = sqliteWhereBegin(pParse, pTabList, pWhere, 0,
28120 + pGroupBy ? 0 : &pOrderBy);
28121 + if( pWInfo==0 ) goto select_end;
28123 + /* Use the standard inner loop if we are not dealing with
28127 + if( selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, distinct, eDest,
28128 + iParm, pWInfo->iContinue, pWInfo->iBreak) ){
28133 + /* If we are dealing with aggregates, then do the special aggregate
28140 + for(i=0; i<pGroupBy->nExpr; i++){
28141 + sqliteExprCode(pParse, pGroupBy->a[i].pExpr);
28143 + sqliteVdbeAddOp(v, OP_MakeKey, pGroupBy->nExpr, 0);
28144 + if( pParse->db->file_format>=4 ) sqliteAddKeyType(v, pGroupBy);
28145 + lbl1 = sqliteVdbeMakeLabel(v);
28146 + sqliteVdbeAddOp(v, OP_AggFocus, 0, lbl1);
28147 + for(i=0, pAgg=pParse->aAgg; i<pParse->nAgg; i++, pAgg++){
28148 + if( pAgg->isAgg ) continue;
28149 + sqliteExprCode(pParse, pAgg->pExpr);
28150 + sqliteVdbeAddOp(v, OP_AggSet, 0, i);
28152 + sqliteVdbeResolveLabel(v, lbl1);
28154 + for(i=0, pAgg=pParse->aAgg; i<pParse->nAgg; i++, pAgg++){
28158 + if( !pAgg->isAgg ) continue;
28159 + assert( pAgg->pFunc!=0 );
28160 + assert( pAgg->pFunc->xStep!=0 );
28161 + pDef = pAgg->pFunc;
28162 + pE = pAgg->pExpr;
28164 + assert( pE->op==TK_AGG_FUNCTION );
28165 + nExpr = sqliteExprCodeExprList(pParse, pE->pList, pDef->includeTypes);
28166 + sqliteVdbeAddOp(v, OP_Integer, i, 0);
28167 + sqliteVdbeOp3(v, OP_AggFunc, 0, nExpr, (char*)pDef, P3_POINTER);
28171 + /* End the database scan loop.
28173 + sqliteWhereEnd(pWInfo);
28175 + /* If we are processing aggregates, we need to set up a second loop
28176 + ** over all of the aggregate values and process them.
28179 + int endagg = sqliteVdbeMakeLabel(v);
28181 + startagg = sqliteVdbeAddOp(v, OP_AggNext, 0, endagg);
28182 + pParse->useAgg = 1;
28184 + sqliteExprIfFalse(pParse, pHaving, startagg, 1);
28186 + if( selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, distinct, eDest,
28187 + iParm, startagg, endagg) ){
28190 + sqliteVdbeAddOp(v, OP_Goto, 0, startagg);
28191 + sqliteVdbeResolveLabel(v, endagg);
28192 + sqliteVdbeAddOp(v, OP_Noop, 0, 0);
28193 + pParse->useAgg = 0;
28196 + /* If there is an ORDER BY clause, then we need to sort the results
28197 + ** and send them to the callback one by one.
28200 + generateSortTail(p, v, pEList->nExpr, eDest, iParm);
28203 + /* If this was a subquery, we have now converted the subquery into a
28204 + ** temporary table. So delete the subquery structure from the parent
28205 + ** to prevent this subquery from being evaluated again and to force the
28206 + ** the use of the temporary table.
28209 + assert( pParent->pSrc->nSrc>parentTab );
28210 + assert( pParent->pSrc->a[parentTab].pSelect==p );
28211 + sqliteSelectDelete(p);
28212 + pParent->pSrc->a[parentTab].pSelect = 0;
28215 + /* The SELECT was successfully coded. Set the return code to 0
28216 + ** to indicate no errors.
28220 + /* Control jumps to here if an error is encountered above, or upon
28221 + ** successful coding of the SELECT.
28224 + sqliteAggregateInfoReset(pParse);
28228 +++ b/ext/sqlite/libsqlite/src/sqlite_config.w32.h
28230 +#include "config.w32.h"
28232 +# define THREADSAFE 1
28234 +#if !ZEND_DEBUG && !defined(NDEBUG)
28237 +#define SQLITE_PTR_SZ 4
28238 \ No newline at end of file
28240 +++ b/ext/sqlite/libsqlite/src/sqlite.h.in
28243 +** 2001 September 15
28245 +** The author disclaims copyright to this source code. In place of
28246 +** a legal notice, here is a blessing:
28248 +** May you do good and not evil.
28249 +** May you find forgiveness for yourself and forgive others.
28250 +** May you share freely, never taking more than you give.
28252 +*************************************************************************
28253 +** This header file defines the interface that the SQLite library
28254 +** presents to client programs.
28258 +#ifndef _SQLITE_H_
28259 +#define _SQLITE_H_
28260 +#include <stdarg.h> /* Needed for the definition of va_list */
28263 +** Make sure we can call this stuff from C++.
28265 +#ifdef __cplusplus
28270 +** The version of the SQLite library.
28272 +#ifdef SQLITE_VERSION
28273 +# undef SQLITE_VERSION
28275 +# define SQLITE_VERSION "--VERS--"
28279 +** The version string is also compiled into the library so that a program
28280 +** can check to make sure that the lib*.a file and the *.h file are from
28281 +** the same version.
28283 +extern const char sqlite_version[];
28286 +** The SQLITE_UTF8 macro is defined if the library expects to see
28287 +** UTF-8 encoded data. The SQLITE_ISO8859 macro is defined if the
28288 +** iso8859 encoded should be used.
28290 +#define SQLITE_--ENCODING-- 1
28293 +** The following constant holds one of two strings, "UTF-8" or "iso8859",
28294 +** depending on which character encoding the SQLite library expects to
28295 +** see. The character encoding makes a difference for the LIKE and GLOB
28296 +** operators and for the LENGTH() and SUBSTR() functions.
28298 +extern const char sqlite_encoding[];
28301 +** Each open sqlite database is represented by an instance of the
28302 +** following opaque structure.
28304 +typedef struct sqlite sqlite;
28307 +** A function to open a new sqlite database.
28309 +** If the database does not exist and mode indicates write
28310 +** permission, then a new database is created. If the database
28311 +** does not exist and mode does not indicate write permission,
28312 +** then the open fails, an error message generated (if errmsg!=0)
28313 +** and the function returns 0.
28315 +** If mode does not indicates user write permission, then the
28316 +** database is opened read-only.
28318 +** The Truth: As currently implemented, all databases are opened
28319 +** for writing all the time. Maybe someday we will provide the
28320 +** ability to open a database readonly. The mode parameters is
28321 +** provided in anticipation of that enhancement.
28323 +sqlite *sqlite_open(const char *filename, int mode, char **errmsg);
28326 +** A function to close the database.
28328 +** Call this function with a pointer to a structure that was previously
28329 +** returned from sqlite_open() and the corresponding database will by closed.
28331 +void sqlite_close(sqlite *);
28334 +** The type for a callback function.
28336 +typedef int (*sqlite_callback)(void*,int,char**, char**);
28339 +** A function to executes one or more statements of SQL.
28341 +** If one or more of the SQL statements are queries, then
28342 +** the callback function specified by the 3rd parameter is
28343 +** invoked once for each row of the query result. This callback
28344 +** should normally return 0. If the callback returns a non-zero
28345 +** value then the query is aborted, all subsequent SQL statements
28346 +** are skipped and the sqlite_exec() function returns the SQLITE_ABORT.
28348 +** The 4th parameter is an arbitrary pointer that is passed
28349 +** to the callback function as its first parameter.
28351 +** The 2nd parameter to the callback function is the number of
28352 +** columns in the query result. The 3rd parameter to the callback
28353 +** is an array of strings holding the values for each column.
28354 +** The 4th parameter to the callback is an array of strings holding
28355 +** the names of each column.
28357 +** The callback function may be NULL, even for queries. A NULL
28358 +** callback is not an error. It just means that no callback
28359 +** will be invoked.
28361 +** If an error occurs while parsing or evaluating the SQL (but
28362 +** not while executing the callback) then an appropriate error
28363 +** message is written into memory obtained from malloc() and
28364 +** *errmsg is made to point to that message. The calling function
28365 +** is responsible for freeing the memory that holds the error
28366 +** message. Use sqlite_freemem() for this. If errmsg==NULL,
28367 +** then no error message is ever written.
28369 +** The return value is is SQLITE_OK if there are no errors and
28370 +** some other return code if there is an error. The particular
28371 +** return value depends on the type of error.
28373 +** If the query could not be executed because a database file is
28374 +** locked or busy, then this function returns SQLITE_BUSY. (This
28375 +** behavior can be modified somewhat using the sqlite_busy_handler()
28376 +** and sqlite_busy_timeout() functions below.)
28379 + sqlite*, /* An open database */
28380 + const char *sql, /* SQL to be executed */
28381 + sqlite_callback, /* Callback function */
28382 + void *, /* 1st argument to callback function */
28383 + char **errmsg /* Error msg written here */
28387 +** Return values for sqlite_exec() and sqlite_step()
28389 +#define SQLITE_OK 0 /* Successful result */
28390 +#define SQLITE_ERROR 1 /* SQL error or missing database */
28391 +#define SQLITE_INTERNAL 2 /* An internal logic error in SQLite */
28392 +#define SQLITE_PERM 3 /* Access permission denied */
28393 +#define SQLITE_ABORT 4 /* Callback routine requested an abort */
28394 +#define SQLITE_BUSY 5 /* The database file is locked */
28395 +#define SQLITE_LOCKED 6 /* A table in the database is locked */
28396 +#define SQLITE_NOMEM 7 /* A malloc() failed */
28397 +#define SQLITE_READONLY 8 /* Attempt to write a readonly database */
28398 +#define SQLITE_INTERRUPT 9 /* Operation terminated by sqlite_interrupt() */
28399 +#define SQLITE_IOERR 10 /* Some kind of disk I/O error occurred */
28400 +#define SQLITE_CORRUPT 11 /* The database disk image is malformed */
28401 +#define SQLITE_NOTFOUND 12 /* (Internal Only) Table or record not found */
28402 +#define SQLITE_FULL 13 /* Insertion failed because database is full */
28403 +#define SQLITE_CANTOPEN 14 /* Unable to open the database file */
28404 +#define SQLITE_PROTOCOL 15 /* Database lock protocol error */
28405 +#define SQLITE_EMPTY 16 /* (Internal Only) Database table is empty */
28406 +#define SQLITE_SCHEMA 17 /* The database schema changed */
28407 +#define SQLITE_TOOBIG 18 /* Too much data for one row of a table */
28408 +#define SQLITE_CONSTRAINT 19 /* Abort due to contraint violation */
28409 +#define SQLITE_MISMATCH 20 /* Data type mismatch */
28410 +#define SQLITE_MISUSE 21 /* Library used incorrectly */
28411 +#define SQLITE_NOLFS 22 /* Uses OS features not supported on host */
28412 +#define SQLITE_AUTH 23 /* Authorization denied */
28413 +#define SQLITE_FORMAT 24 /* Auxiliary database format error */
28414 +#define SQLITE_RANGE 25 /* 2nd parameter to sqlite_bind out of range */
28415 +#define SQLITE_NOTADB 26 /* File opened that is not a database file */
28416 +#define SQLITE_ROW 100 /* sqlite_step() has another row ready */
28417 +#define SQLITE_DONE 101 /* sqlite_step() has finished executing */
28420 +** Each entry in an SQLite table has a unique integer key. (The key is
28421 +** the value of the INTEGER PRIMARY KEY column if there is such a column,
28422 +** otherwise the key is generated at random. The unique key is always
28423 +** available as the ROWID, OID, or _ROWID_ column.) The following routine
28424 +** returns the integer key of the most recent insert in the database.
28426 +** This function is similar to the mysql_insert_id() function from MySQL.
28428 +int sqlite_last_insert_rowid(sqlite*);
28431 +** This function returns the number of database rows that were changed
28432 +** (or inserted or deleted) by the most recent called sqlite_exec().
28434 +** All changes are counted, even if they were later undone by a
28435 +** ROLLBACK or ABORT. Except, changes associated with creating and
28436 +** dropping tables are not counted.
28438 +** If a callback invokes sqlite_exec() recursively, then the changes
28439 +** in the inner, recursive call are counted together with the changes
28440 +** in the outer call.
28442 +** SQLite implements the command "DELETE FROM table" without a WHERE clause
28443 +** by dropping and recreating the table. (This is much faster than going
28444 +** through and deleting individual elements form the table.) Because of
28445 +** this optimization, the change count for "DELETE FROM table" will be
28446 +** zero regardless of the number of elements that were originally in the
28447 +** table. To get an accurate count of the number of rows deleted, use
28448 +** "DELETE FROM table WHERE 1" instead.
28450 +int sqlite_changes(sqlite*);
28453 +** This function returns the number of database rows that were changed
28454 +** by the last INSERT, UPDATE, or DELETE statment executed by sqlite_exec(),
28455 +** or by the last VM to run to completion. The change count is not updated
28456 +** by SQL statements other than INSERT, UPDATE or DELETE.
28458 +** Changes are counted, even if they are later undone by a ROLLBACK or
28459 +** ABORT. Changes associated with trigger programs that execute as a
28460 +** result of the INSERT, UPDATE, or DELETE statement are not counted.
28462 +** If a callback invokes sqlite_exec() recursively, then the changes
28463 +** in the inner, recursive call are counted together with the changes
28464 +** in the outer call.
28466 +** SQLite implements the command "DELETE FROM table" without a WHERE clause
28467 +** by dropping and recreating the table. (This is much faster than going
28468 +** through and deleting individual elements form the table.) Because of
28469 +** this optimization, the change count for "DELETE FROM table" will be
28470 +** zero regardless of the number of elements that were originally in the
28471 +** table. To get an accurate count of the number of rows deleted, use
28472 +** "DELETE FROM table WHERE 1" instead.
28474 +******* THIS IS AN EXPERIMENTAL API AND IS SUBJECT TO CHANGE ******
28476 +int sqlite_last_statement_changes(sqlite*);
28478 +/* If the parameter to this routine is one of the return value constants
28479 +** defined above, then this routine returns a constant text string which
28480 +** descripts (in English) the meaning of the return value.
28482 +const char *sqlite_error_string(int);
28483 +#define sqliteErrStr sqlite_error_string /* Legacy. Do not use in new code. */
28485 +/* This function causes any pending database operation to abort and
28486 +** return at its earliest opportunity. This routine is typically
28487 +** called in response to a user action such as pressing "Cancel"
28488 +** or Ctrl-C where the user wants a long query operation to halt
28491 +void sqlite_interrupt(sqlite*);
28494 +/* This function returns true if the given input string comprises
28495 +** one or more complete SQL statements.
28497 +** The algorithm is simple. If the last token other than spaces
28498 +** and comments is a semicolon, then return true. otherwise return
28501 +int sqlite_complete(const char *sql);
28504 +** This routine identifies a callback function that is invoked
28505 +** whenever an attempt is made to open a database table that is
28506 +** currently locked by another process or thread. If the busy callback
28507 +** is NULL, then sqlite_exec() returns SQLITE_BUSY immediately if
28508 +** it finds a locked table. If the busy callback is not NULL, then
28509 +** sqlite_exec() invokes the callback with three arguments. The
28510 +** second argument is the name of the locked table and the third
28511 +** argument is the number of times the table has been busy. If the
28512 +** busy callback returns 0, then sqlite_exec() immediately returns
28513 +** SQLITE_BUSY. If the callback returns non-zero, then sqlite_exec()
28514 +** tries to open the table again and the cycle repeats.
28516 +** The default busy callback is NULL.
28518 +** Sqlite is re-entrant, so the busy handler may start a new query.
28519 +** (It is not clear why anyone would every want to do this, but it
28520 +** is allowed, in theory.) But the busy handler may not close the
28521 +** database. Closing the database from a busy handler will delete
28522 +** data structures out from under the executing query and will
28523 +** probably result in a coredump.
28525 +void sqlite_busy_handler(sqlite*, int(*)(void*,const char*,int), void*);
28528 +** This routine sets a busy handler that sleeps for a while when a
28529 +** table is locked. The handler will sleep multiple times until
28530 +** at least "ms" milleseconds of sleeping have been done. After
28531 +** "ms" milleseconds of sleeping, the handler returns 0 which
28532 +** causes sqlite_exec() to return SQLITE_BUSY.
28534 +** Calling this routine with an argument less than or equal to zero
28535 +** turns off all busy handlers.
28537 +void sqlite_busy_timeout(sqlite*, int ms);
28540 +** This next routine is really just a wrapper around sqlite_exec().
28541 +** Instead of invoking a user-supplied callback for each row of the
28542 +** result, this routine remembers each row of the result in memory
28543 +** obtained from malloc(), then returns all of the result after the
28544 +** query has finished.
28546 +** As an example, suppose the query result where this table:
28549 +** -----------------------
28554 +** If the 3rd argument were &azResult then after the function returns
28555 +** azResult will contain the following data:
28557 +** azResult[0] = "Name";
28558 +** azResult[1] = "Age";
28559 +** azResult[2] = "Alice";
28560 +** azResult[3] = "43";
28561 +** azResult[4] = "Bob";
28562 +** azResult[5] = "28";
28563 +** azResult[6] = "Cindy";
28564 +** azResult[7] = "21";
28566 +** Notice that there is an extra row of data containing the column
28567 +** headers. But the *nrow return value is still 3. *ncolumn is
28568 +** set to 2. In general, the number of values inserted into azResult
28569 +** will be ((*nrow) + 1)*(*ncolumn).
28571 +** After the calling function has finished using the result, it should
28572 +** pass the result data pointer to sqlite_free_table() in order to
28573 +** release the memory that was malloc-ed. Because of the way the
28574 +** malloc() happens, the calling function must not try to call
28575 +** malloc() directly. Only sqlite_free_table() is able to release
28576 +** the memory properly and safely.
28578 +** The return value of this routine is the same as from sqlite_exec().
28580 +int sqlite_get_table(
28581 + sqlite*, /* An open database */
28582 + const char *sql, /* SQL to be executed */
28583 + char ***resultp, /* Result written to a char *[] that this points to */
28584 + int *nrow, /* Number of result rows written here */
28585 + int *ncolumn, /* Number of result columns written here */
28586 + char **errmsg /* Error msg written here */
28590 +** Call this routine to free the memory that sqlite_get_table() allocated.
28592 +void sqlite_free_table(char **result);
28595 +** The following routines are wrappers around sqlite_exec() and
28596 +** sqlite_get_table(). The only difference between the routines that
28597 +** follow and the originals is that the second argument to the
28598 +** routines that follow is really a printf()-style format
28599 +** string describing the SQL to be executed. Arguments to the format
28600 +** string appear at the end of the argument list.
28602 +** All of the usual printf formatting options apply. In addition, there
28603 +** is a "%q" option. %q works like %s in that it substitutes a null-terminated
28604 +** string from the argument list. But %q also doubles every '\'' character.
28605 +** %q is designed for use inside a string literal. By doubling each '\''
28606 +** character it escapes that character and allows it to be inserted into
28609 +** For example, so some string variable contains text as follows:
28611 +** char *zText = "It's a happy day!";
28613 +** We can use this text in an SQL statement as follows:
28615 +** sqlite_exec_printf(db, "INSERT INTO table VALUES('%q')",
28616 +** callback1, 0, 0, zText);
28618 +** Because the %q format string is used, the '\'' character in zText
28619 +** is escaped and the SQL generated is as follows:
28621 +** INSERT INTO table1 VALUES('It''s a happy day!')
28623 +** This is correct. Had we used %s instead of %q, the generated SQL
28624 +** would have looked like this:
28626 +** INSERT INTO table1 VALUES('It's a happy day!');
28628 +** This second example is an SQL syntax error. As a general rule you
28629 +** should always use %q instead of %s when inserting text into a string
28632 +int sqlite_exec_printf(
28633 + sqlite*, /* An open database */
28634 + const char *sqlFormat, /* printf-style format string for the SQL */
28635 + sqlite_callback, /* Callback function */
28636 + void *, /* 1st argument to callback function */
28637 + char **errmsg, /* Error msg written here */
28638 + ... /* Arguments to the format string. */
28640 +int sqlite_exec_vprintf(
28641 + sqlite*, /* An open database */
28642 + const char *sqlFormat, /* printf-style format string for the SQL */
28643 + sqlite_callback, /* Callback function */
28644 + void *, /* 1st argument to callback function */
28645 + char **errmsg, /* Error msg written here */
28646 + va_list ap /* Arguments to the format string. */
28648 +int sqlite_get_table_printf(
28649 + sqlite*, /* An open database */
28650 + const char *sqlFormat, /* printf-style format string for the SQL */
28651 + char ***resultp, /* Result written to a char *[] that this points to */
28652 + int *nrow, /* Number of result rows written here */
28653 + int *ncolumn, /* Number of result columns written here */
28654 + char **errmsg, /* Error msg written here */
28655 + ... /* Arguments to the format string */
28657 +int sqlite_get_table_vprintf(
28658 + sqlite*, /* An open database */
28659 + const char *sqlFormat, /* printf-style format string for the SQL */
28660 + char ***resultp, /* Result written to a char *[] that this points to */
28661 + int *nrow, /* Number of result rows written here */
28662 + int *ncolumn, /* Number of result columns written here */
28663 + char **errmsg, /* Error msg written here */
28664 + va_list ap /* Arguments to the format string */
28666 +char *sqlite_mprintf(const char*,...);
28667 +char *sqlite_vmprintf(const char*, va_list);
28670 +** Windows systems should call this routine to free memory that
28671 +** is returned in the in the errmsg parameter of sqlite_open() when
28672 +** SQLite is a DLL. For some reason, it does not work to call free()
28675 +void sqlite_freemem(void *p);
28678 +** Windows systems need functions to call to return the sqlite_version
28679 +** and sqlite_encoding strings.
28681 +const char *sqlite_libversion(void);
28682 +const char *sqlite_libencoding(void);
28685 +** A pointer to the following structure is used to communicate with
28686 +** the implementations of user-defined functions.
28688 +typedef struct sqlite_func sqlite_func;
28691 +** Use the following routines to create new user-defined functions. See
28692 +** the documentation for details.
28694 +int sqlite_create_function(
28695 + sqlite*, /* Database where the new function is registered */
28696 + const char *zName, /* Name of the new function */
28697 + int nArg, /* Number of arguments. -1 means any number */
28698 + void (*xFunc)(sqlite_func*,int,const char**), /* C code to implement */
28699 + void *pUserData /* Available via the sqlite_user_data() call */
28701 +int sqlite_create_aggregate(
28702 + sqlite*, /* Database where the new function is registered */
28703 + const char *zName, /* Name of the function */
28704 + int nArg, /* Number of arguments */
28705 + void (*xStep)(sqlite_func*,int,const char**), /* Called for each row */
28706 + void (*xFinalize)(sqlite_func*), /* Called once to get final result */
28707 + void *pUserData /* Available via the sqlite_user_data() call */
28711 +** Use the following routine to define the datatype returned by a
28712 +** user-defined function. The second argument can be one of the
28713 +** constants SQLITE_NUMERIC, SQLITE_TEXT, or SQLITE_ARGS or it
28714 +** can be an integer greater than or equal to zero. When the datatype
28715 +** parameter is non-negative, the type of the result will be the
28716 +** same as the datatype-th argument. If datatype==SQLITE_NUMERIC
28717 +** then the result is always numeric. If datatype==SQLITE_TEXT then
28718 +** the result is always text. If datatype==SQLITE_ARGS then the result
28719 +** is numeric if any argument is numeric and is text otherwise.
28721 +int sqlite_function_type(
28722 + sqlite *db, /* The database there the function is registered */
28723 + const char *zName, /* Name of the function */
28724 + int datatype /* The datatype for this function */
28726 +#define SQLITE_NUMERIC (-1)
28727 +/* #define SQLITE_TEXT (-2) // See below */
28728 +#define SQLITE_ARGS (-3)
28731 +** SQLite version 3 defines SQLITE_TEXT differently. To allow both
28732 +** version 2 and version 3 to be included, undefine them both if a
28733 +** conflict is seen. Define SQLITE2_TEXT to be the version 2 value.
28735 +#ifdef SQLITE_TEXT
28736 +# undef SQLITE_TEXT
28738 +# define SQLITE_TEXT (-2)
28740 +#define SQLITE2_TEXT (-2)
28745 +** The user function implementations call one of the following four routines
28746 +** in order to return their results. The first parameter to each of these
28747 +** routines is a copy of the first argument to xFunc() or xFinialize().
28748 +** The second parameter to these routines is the result to be returned.
28749 +** A NULL can be passed as the second parameter to sqlite_set_result_string()
28750 +** in order to return a NULL result.
28752 +** The 3rd argument to _string and _error is the number of characters to
28753 +** take from the string. If this argument is negative, then all characters
28754 +** up to and including the first '\000' are used.
28756 +** The sqlite_set_result_string() function allocates a buffer to hold the
28757 +** result and returns a pointer to this buffer. The calling routine
28758 +** (that is, the implmentation of a user function) can alter the content
28759 +** of this buffer if desired.
28761 +char *sqlite_set_result_string(sqlite_func*,const char*,int);
28762 +void sqlite_set_result_int(sqlite_func*,int);
28763 +void sqlite_set_result_double(sqlite_func*,double);
28764 +void sqlite_set_result_error(sqlite_func*,const char*,int);
28767 +** The pUserData parameter to the sqlite_create_function() and
28768 +** sqlite_create_aggregate() routines used to register user functions
28769 +** is available to the implementation of the function using this
28772 +void *sqlite_user_data(sqlite_func*);
28775 +** Aggregate functions use the following routine to allocate
28776 +** a structure for storing their state. The first time this routine
28777 +** is called for a particular aggregate, a new structure of size nBytes
28778 +** is allocated, zeroed, and returned. On subsequent calls (for the
28779 +** same aggregate instance) the same buffer is returned. The implementation
28780 +** of the aggregate can use the returned buffer to accumulate data.
28782 +** The buffer allocated is freed automatically be SQLite.
28784 +void *sqlite_aggregate_context(sqlite_func*, int nBytes);
28787 +** The next routine returns the number of calls to xStep for a particular
28788 +** aggregate function instance. The current call to xStep counts so this
28789 +** routine always returns at least 1.
28791 +int sqlite_aggregate_count(sqlite_func*);
28794 +** This routine registers a callback with the SQLite library. The
28795 +** callback is invoked (at compile-time, not at run-time) for each
28796 +** attempt to access a column of a table in the database. The callback
28797 +** returns SQLITE_OK if access is allowed, SQLITE_DENY if the entire
28798 +** SQL statement should be aborted with an error and SQLITE_IGNORE
28799 +** if the column should be treated as a NULL value.
28801 +int sqlite_set_authorizer(
28803 + int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
28808 +** The second parameter to the access authorization function above will
28809 +** be one of the values below. These values signify what kind of operation
28810 +** is to be authorized. The 3rd and 4th parameters to the authorization
28811 +** function will be parameters or NULL depending on which of the following
28812 +** codes is used as the second parameter. The 5th parameter is the name
28813 +** of the database ("main", "temp", etc.) if applicable. The 6th parameter
28814 +** is the name of the inner-most trigger or view that is responsible for
28815 +** the access attempt or NULL if this access attempt is directly from
28816 +** input SQL code.
28820 +#define SQLITE_COPY 0 /* Table Name File Name */
28821 +#define SQLITE_CREATE_INDEX 1 /* Index Name Table Name */
28822 +#define SQLITE_CREATE_TABLE 2 /* Table Name NULL */
28823 +#define SQLITE_CREATE_TEMP_INDEX 3 /* Index Name Table Name */
28824 +#define SQLITE_CREATE_TEMP_TABLE 4 /* Table Name NULL */
28825 +#define SQLITE_CREATE_TEMP_TRIGGER 5 /* Trigger Name Table Name */
28826 +#define SQLITE_CREATE_TEMP_VIEW 6 /* View Name NULL */
28827 +#define SQLITE_CREATE_TRIGGER 7 /* Trigger Name Table Name */
28828 +#define SQLITE_CREATE_VIEW 8 /* View Name NULL */
28829 +#define SQLITE_DELETE 9 /* Table Name NULL */
28830 +#define SQLITE_DROP_INDEX 10 /* Index Name Table Name */
28831 +#define SQLITE_DROP_TABLE 11 /* Table Name NULL */
28832 +#define SQLITE_DROP_TEMP_INDEX 12 /* Index Name Table Name */
28833 +#define SQLITE_DROP_TEMP_TABLE 13 /* Table Name NULL */
28834 +#define SQLITE_DROP_TEMP_TRIGGER 14 /* Trigger Name Table Name */
28835 +#define SQLITE_DROP_TEMP_VIEW 15 /* View Name NULL */
28836 +#define SQLITE_DROP_TRIGGER 16 /* Trigger Name Table Name */
28837 +#define SQLITE_DROP_VIEW 17 /* View Name NULL */
28838 +#define SQLITE_INSERT 18 /* Table Name NULL */
28839 +#define SQLITE_PRAGMA 19 /* Pragma Name 1st arg or NULL */
28840 +#define SQLITE_READ 20 /* Table Name Column Name */
28841 +#define SQLITE_SELECT 21 /* NULL NULL */
28842 +#define SQLITE_TRANSACTION 22 /* NULL NULL */
28843 +#define SQLITE_UPDATE 23 /* Table Name Column Name */
28844 +#define SQLITE_ATTACH 24 /* Filename NULL */
28845 +#define SQLITE_DETACH 25 /* Database Name NULL */
28849 +** The return value of the authorization function should be one of the
28850 +** following constants:
28852 +/* #define SQLITE_OK 0 // Allow access (This is actually defined above) */
28853 +#define SQLITE_DENY 1 /* Abort the SQL statement with an error */
28854 +#define SQLITE_IGNORE 2 /* Don't allow access, but don't generate an error */
28857 +** Register a function that is called at every invocation of sqlite_exec()
28858 +** or sqlite_compile(). This function can be used (for example) to generate
28859 +** a log file of all SQL executed against a database.
28861 +void *sqlite_trace(sqlite*, void(*xTrace)(void*,const char*), void*);
28863 +/*** The Callback-Free API
28865 +** The following routines implement a new way to access SQLite that does not
28866 +** involve the use of callbacks.
28868 +** An sqlite_vm is an opaque object that represents a single SQL statement
28869 +** that is ready to be executed.
28871 +typedef struct sqlite_vm sqlite_vm;
28874 +** To execute an SQLite query without the use of callbacks, you first have
28875 +** to compile the SQL using this routine. The 1st parameter "db" is a pointer
28876 +** to an sqlite object obtained from sqlite_open(). The 2nd parameter
28877 +** "zSql" is the text of the SQL to be compiled. The remaining parameters
28878 +** are all outputs.
28880 +** *pzTail is made to point to the first character past the end of the first
28881 +** SQL statement in zSql. This routine only compiles the first statement
28882 +** in zSql, so *pzTail is left pointing to what remains uncompiled.
28884 +** *ppVm is left pointing to a "virtual machine" that can be used to execute
28885 +** the compiled statement. Or if there is an error, *ppVm may be set to NULL.
28886 +** If the input text contained no SQL (if the input is and empty string or
28887 +** a comment) then *ppVm is set to NULL.
28889 +** If any errors are detected during compilation, an error message is written
28890 +** into space obtained from malloc() and *pzErrMsg is made to point to that
28891 +** error message. The calling routine is responsible for freeing the text
28892 +** of this message when it has finished with it. Use sqlite_freemem() to
28893 +** free the message. pzErrMsg may be NULL in which case no error message
28894 +** will be generated.
28896 +** On success, SQLITE_OK is returned. Otherwise and error code is returned.
28898 +int sqlite_compile(
28899 + sqlite *db, /* The open database */
28900 + const char *zSql, /* SQL statement to be compiled */
28901 + const char **pzTail, /* OUT: uncompiled tail of zSql */
28902 + sqlite_vm **ppVm, /* OUT: the virtual machine to execute zSql */
28903 + char **pzErrmsg /* OUT: Error message. */
28907 +** After an SQL statement has been compiled, it is handed to this routine
28908 +** to be executed. This routine executes the statement as far as it can
28909 +** go then returns. The return value will be one of SQLITE_DONE,
28910 +** SQLITE_ERROR, SQLITE_BUSY, SQLITE_ROW, or SQLITE_MISUSE.
28912 +** SQLITE_DONE means that the execute of the SQL statement is complete
28913 +** an no errors have occurred. sqlite_step() should not be called again
28914 +** for the same virtual machine. *pN is set to the number of columns in
28915 +** the result set and *pazColName is set to an array of strings that
28916 +** describe the column names and datatypes. The name of the i-th column
28917 +** is (*pazColName)[i] and the datatype of the i-th column is
28918 +** (*pazColName)[i+*pN]. *pazValue is set to NULL.
28920 +** SQLITE_ERROR means that the virtual machine encountered a run-time
28921 +** error. sqlite_step() should not be called again for the same
28922 +** virtual machine. *pN is set to 0 and *pazColName and *pazValue are set
28923 +** to NULL. Use sqlite_finalize() to obtain the specific error code
28924 +** and the error message text for the error.
28926 +** SQLITE_BUSY means that an attempt to open the database failed because
28927 +** another thread or process is holding a lock. The calling routine
28928 +** can try again to open the database by calling sqlite_step() again.
28929 +** The return code will only be SQLITE_BUSY if no busy handler is registered
28930 +** using the sqlite_busy_handler() or sqlite_busy_timeout() routines. If
28931 +** a busy handler callback has been registered but returns 0, then this
28932 +** routine will return SQLITE_ERROR and sqltie_finalize() will return
28933 +** SQLITE_BUSY when it is called.
28935 +** SQLITE_ROW means that a single row of the result is now available.
28936 +** The data is contained in *pazValue. The value of the i-th column is
28937 +** (*azValue)[i]. *pN and *pazColName are set as described in SQLITE_DONE.
28938 +** Invoke sqlite_step() again to advance to the next row.
28940 +** SQLITE_MISUSE is returned if sqlite_step() is called incorrectly.
28941 +** For example, if you call sqlite_step() after the virtual machine
28942 +** has halted (after a prior call to sqlite_step() has returned SQLITE_DONE)
28943 +** or if you call sqlite_step() with an incorrectly initialized virtual
28944 +** machine or a virtual machine that has been deleted or that is associated
28945 +** with an sqlite structure that has been closed.
28948 + sqlite_vm *pVm, /* The virtual machine to execute */
28949 + int *pN, /* OUT: Number of columns in result */
28950 + const char ***pazValue, /* OUT: Column data */
28951 + const char ***pazColName /* OUT: Column names and datatypes */
28955 +** This routine is called to delete a virtual machine after it has finished
28956 +** executing. The return value is the result code. SQLITE_OK is returned
28957 +** if the statement executed successfully and some other value is returned if
28958 +** there was any kind of error. If an error occurred and pzErrMsg is not
28959 +** NULL, then an error message is written into memory obtained from malloc()
28960 +** and *pzErrMsg is made to point to that error message. The calling routine
28961 +** should use sqlite_freemem() to delete this message when it has finished
28964 +** This routine can be called at any point during the execution of the
28965 +** virtual machine. If the virtual machine has not completed execution
28966 +** when this routine is called, that is like encountering an error or
28967 +** an interrupt. (See sqlite_interrupt().) Incomplete updates may be
28968 +** rolled back and transactions cancelled, depending on the circumstances,
28969 +** and the result code returned will be SQLITE_ABORT.
28971 +int sqlite_finalize(sqlite_vm*, char **pzErrMsg);
28974 +** This routine deletes the virtual machine, writes any error message to
28975 +** *pzErrMsg and returns an SQLite return code in the same way as the
28976 +** sqlite_finalize() function.
28978 +** Additionally, if ppVm is not NULL, *ppVm is left pointing to a new virtual
28979 +** machine loaded with the compiled version of the original query ready for
28982 +** If sqlite_reset() returns SQLITE_SCHEMA, then *ppVm is set to NULL.
28984 +******* THIS IS AN EXPERIMENTAL API AND IS SUBJECT TO CHANGE ******
28986 +int sqlite_reset(sqlite_vm*, char **pzErrMsg);
28989 +** If the SQL that was handed to sqlite_compile contains variables that
28990 +** are represeted in the SQL text by a question mark ('?'). This routine
28991 +** is used to assign values to those variables.
28993 +** The first parameter is a virtual machine obtained from sqlite_compile().
28994 +** The 2nd "idx" parameter determines which variable in the SQL statement
28995 +** to bind the value to. The left most '?' is 1. The 3rd parameter is
28996 +** the value to assign to that variable. The 4th parameter is the number
28997 +** of bytes in the value, including the terminating \000 for strings.
28998 +** Finally, the 5th "copy" parameter is TRUE if SQLite should make its
28999 +** own private copy of this value, or false if the space that the 3rd
29000 +** parameter points to will be unchanging and can be used directly by
29003 +** Unbound variables are treated as having a value of NULL. To explicitly
29004 +** set a variable to NULL, call this routine with the 3rd parameter as a
29007 +** If the 4th "len" parameter is -1, then strlen() is used to find the
29010 +** This routine can only be called immediately after sqlite_compile()
29011 +** or sqlite_reset() and before any calls to sqlite_step().
29013 +******* THIS IS AN EXPERIMENTAL API AND IS SUBJECT TO CHANGE ******
29015 +int sqlite_bind(sqlite_vm*, int idx, const char *value, int len, int copy);
29018 +** This routine configures a callback function - the progress callback - that
29019 +** is invoked periodically during long running calls to sqlite_exec(),
29020 +** sqlite_step() and sqlite_get_table(). An example use for this API is to keep
29021 +** a GUI updated during a large query.
29023 +** The progress callback is invoked once for every N virtual machine opcodes,
29024 +** where N is the second argument to this function. The progress callback
29025 +** itself is identified by the third argument to this function. The fourth
29026 +** argument to this function is a void pointer passed to the progress callback
29027 +** function each time it is invoked.
29029 +** If a call to sqlite_exec(), sqlite_step() or sqlite_get_table() results
29030 +** in less than N opcodes being executed, then the progress callback is not
29033 +** Calling this routine overwrites any previously installed progress callback.
29034 +** To remove the progress callback altogether, pass NULL as the third
29035 +** argument to this function.
29037 +** If the progress callback returns a result other than 0, then the current
29038 +** query is immediately terminated and any database changes rolled back. If the
29039 +** query was part of a larger transaction, then the transaction is not rolled
29040 +** back and remains active. The sqlite_exec() call returns SQLITE_ABORT.
29042 +******* THIS IS AN EXPERIMENTAL API AND IS SUBJECT TO CHANGE ******
29044 +void sqlite_progress_handler(sqlite*, int, int(*)(void*), void*);
29047 +** Register a callback function to be invoked whenever a new transaction
29048 +** is committed. The pArg argument is passed through to the callback.
29049 +** callback. If the callback function returns non-zero, then the commit
29050 +** is converted into a rollback.
29052 +** If another function was previously registered, its pArg value is returned.
29053 +** Otherwise NULL is returned.
29055 +** Registering a NULL function disables the callback.
29057 +******* THIS IS AN EXPERIMENTAL API AND IS SUBJECT TO CHANGE ******
29059 +void *sqlite_commit_hook(sqlite*, int(*)(void*), void*);
29062 +** Open an encrypted SQLite database. If pKey==0 or nKey==0, this routine
29063 +** is the same as sqlite_open().
29065 +** The code to implement this API is not available in the public release
29068 +sqlite *sqlite_open_encrypted(
29069 + const char *zFilename, /* Name of the encrypted database */
29070 + const void *pKey, /* Pointer to the key */
29071 + int nKey, /* Number of bytes in the key */
29072 + int *pErrcode, /* Write error code here */
29073 + char **pzErrmsg /* Write error message here */
29077 +** Change the key on an open database. If the current database is not
29078 +** encrypted, this routine will encrypt it. If pNew==0 or nNew==0, the
29079 +** database is decrypted.
29081 +** The code to implement this API is not available in the public release
29085 + sqlite *db, /* Database to be rekeyed */
29086 + const void *pKey, int nKey /* The new key */
29090 +** Encode a binary buffer "in" of size n bytes so that it contains
29091 +** no instances of characters '\'' or '\000'. The output is
29092 +** null-terminated and can be used as a string value in an INSERT
29093 +** or UPDATE statement. Use sqlite_decode_binary() to convert the
29094 +** string back into its original binary.
29096 +** The result is written into a preallocated output buffer "out".
29097 +** "out" must be able to hold at least 2 +(257*n)/254 bytes.
29098 +** In other words, the output will be expanded by as much as 3
29099 +** bytes for every 254 bytes of input plus 2 bytes of fixed overhead.
29100 +** (This is approximately 2 + 1.0118*n or about a 1.2% size increase.)
29102 +** The return value is the number of characters in the encoded
29103 +** string, excluding the "\000" terminator.
29105 +** If out==NULL then no output is generated but the routine still returns
29106 +** the number of characters that would have been generated if out had
29109 +int sqlite_encode_binary(const unsigned char *in, int n, unsigned char *out);
29112 +** Decode the string "in" into binary data and write it into "out".
29113 +** This routine reverses the encoding created by sqlite_encode_binary().
29114 +** The output will always be a few bytes less than the input. The number
29115 +** of bytes of output is returned. If the input is not a well-formed
29116 +** encoding, -1 is returned.
29118 +** The "in" and "out" parameters may point to the same buffer in order
29119 +** to decode a string in place.
29121 +int sqlite_decode_binary(const unsigned char *in, unsigned char *out);
29123 +#ifdef __cplusplus
29124 +} /* End of the 'extern "C"' block */
29127 +#endif /* _SQLITE_H_ */
29129 +++ b/ext/sqlite/libsqlite/src/sqliteInt.h
29132 +** 2001 September 15
29134 +** The author disclaims copyright to this source code. In place of
29135 +** a legal notice, here is a blessing:
29137 +** May you do good and not evil.
29138 +** May you find forgiveness for yourself and forgive others.
29139 +** May you share freely, never taking more than you give.
29141 +*************************************************************************
29142 +** Internal interface definitions for SQLite.
29146 +#include "config.h"
29147 +#include "sqlite.h"
29149 +#include "parse.h"
29150 +#include "btree.h"
29151 +#include <stdio.h>
29152 +#include <stdlib.h>
29153 +#include <string.h>
29154 +#include <assert.h>
29157 +** The maximum number of in-memory pages to use for the main database
29158 +** table and for temporary tables.
29160 +#define MAX_PAGES 2000
29161 +#define TEMP_PAGES 500
29164 +** If the following macro is set to 1, then NULL values are considered
29165 +** distinct for the SELECT DISTINCT statement and for UNION or EXCEPT
29166 +** compound queries. No other SQL database engine (among those tested)
29167 +** works this way except for OCELOT. But the SQL92 spec implies that
29168 +** this is how things should work.
29170 +** If the following macro is set to 0, then NULLs are indistinct for
29171 +** SELECT DISTINCT and for UNION.
29173 +#define NULL_ALWAYS_DISTINCT 0
29176 +** If the following macro is set to 1, then NULL values are considered
29177 +** distinct when determining whether or not two entries are the same
29178 +** in a UNIQUE index. This is the way PostgreSQL, Oracle, DB2, MySQL,
29179 +** OCELOT, and Firebird all work. The SQL92 spec explicitly says this
29180 +** is the way things are suppose to work.
29182 +** If the following macro is set to 0, the NULLs are indistinct for
29183 +** a UNIQUE index. In this mode, you can only have a single NULL entry
29184 +** for a column declared UNIQUE. This is the way Informix and SQL Server
29187 +#define NULL_DISTINCT_FOR_UNIQUE 1
29190 +** The maximum number of attached databases. This must be at least 2
29191 +** in order to support the main database file (0) and the file used to
29192 +** hold temporary tables (1). And it must be less than 256 because
29193 +** an unsigned character is used to stored the database index.
29195 +#define MAX_ATTACHED 10
29198 +** The next macro is used to determine where TEMP tables and indices
29199 +** are stored. Possible values:
29201 +** 0 Always use a temporary files
29202 +** 1 Use a file unless overridden by "PRAGMA temp_store"
29203 +** 2 Use memory unless overridden by "PRAGMA temp_store"
29204 +** 3 Always use memory
29206 +#ifndef TEMP_STORE
29207 +# define TEMP_STORE 1
29211 +** When building SQLite for embedded systems where memory is scarce,
29212 +** you can define one or more of the following macros to omit extra
29213 +** features of the library and thus keep the size of the library to
29216 +/* #define SQLITE_OMIT_AUTHORIZATION 1 */
29217 +/* #define SQLITE_OMIT_INMEMORYDB 1 */
29218 +/* #define SQLITE_OMIT_VACUUM 1 */
29219 +/* #define SQLITE_OMIT_DATETIME_FUNCS 1 */
29220 +/* #define SQLITE_OMIT_PROGRESS_CALLBACK 1 */
29223 +** Integers of known sizes. These typedefs might change for architectures
29224 +** where the sizes very. Preprocessor macros are available so that the
29225 +** types can be conveniently redefined at compile-type. Like this:
29227 +** cc '-DUINTPTR_TYPE=long long int' ...
29229 +#ifndef UINT32_TYPE
29230 +# define UINT32_TYPE unsigned int
29232 +#ifndef UINT16_TYPE
29233 +# define UINT16_TYPE unsigned short int
29235 +#ifndef INT16_TYPE
29236 +# define INT16_TYPE short int
29238 +#ifndef UINT8_TYPE
29239 +# define UINT8_TYPE unsigned char
29242 +# define INT8_TYPE signed char
29244 +#ifndef INTPTR_TYPE
29245 +# if SQLITE_PTR_SZ==4
29246 +# define INTPTR_TYPE int
29248 +# define INTPTR_TYPE long long
29251 +typedef UINT32_TYPE u32; /* 4-byte unsigned integer */
29252 +typedef UINT16_TYPE u16; /* 2-byte unsigned integer */
29253 +typedef INT16_TYPE i16; /* 2-byte signed integer */
29254 +typedef UINT8_TYPE u8; /* 1-byte unsigned integer */
29255 +typedef UINT8_TYPE i8; /* 1-byte signed integer */
29256 +typedef INTPTR_TYPE ptr; /* Big enough to hold a pointer */
29257 +typedef unsigned INTPTR_TYPE uptr; /* Big enough to hold a pointer */
29260 +** Defer sourcing vdbe.h until after the "u8" typedef is defined.
29265 +** Most C compilers these days recognize "long double", don't they?
29266 +** Just in case we encounter one that does not, we will create a macro
29267 +** for long double so that it can be easily changed to just "double".
29269 +#ifndef LONGDOUBLE_TYPE
29270 +# define LONGDOUBLE_TYPE long double
29274 +** This macro casts a pointer to an integer. Useful for doing
29275 +** pointer arithmetic.
29277 +#define Addr(X) ((uptr)X)
29280 +** The maximum number of bytes of data that can be put into a single
29281 +** row of a single table. The upper bound on this limit is 16777215
29282 +** bytes (or 16MB-1). We have arbitrarily set the limit to just 1MB
29283 +** here because the overflow page chain is inefficient for really big
29284 +** records and we want to discourage people from thinking that
29285 +** multi-megabyte records are OK. If your needs are different, you can
29286 +** change this define and recompile to increase or decrease the record
29289 +** The 16777198 is computed as follows: 238 bytes of payload on the
29290 +** original pages plus 16448 overflow pages each holding 1020 bytes of
29293 +#define MAX_BYTES_PER_ROW 1048576
29294 +/* #define MAX_BYTES_PER_ROW 16777198 */
29297 +** If memory allocation problems are found, recompile with
29299 +** -DMEMORY_DEBUG=1
29301 +** to enable some sanity checking on malloc() and free(). To
29302 +** check for memory leaks, recompile with
29304 +** -DMEMORY_DEBUG=2
29306 +** and a line of text will be written to standard error for
29307 +** each malloc() and free(). This output can be analyzed
29308 +** by an AWK script to determine if there are any leaks.
29310 +#ifdef MEMORY_DEBUG
29311 +# define sqliteMalloc(X) sqliteMalloc_(X,1,__FILE__,__LINE__)
29312 +# define sqliteMallocRaw(X) sqliteMalloc_(X,0,__FILE__,__LINE__)
29313 +# define sqliteFree(X) sqliteFree_(X,__FILE__,__LINE__)
29314 +# define sqliteRealloc(X,Y) sqliteRealloc_(X,Y,__FILE__,__LINE__)
29315 +# define sqliteStrDup(X) sqliteStrDup_(X,__FILE__,__LINE__)
29316 +# define sqliteStrNDup(X,Y) sqliteStrNDup_(X,Y,__FILE__,__LINE__)
29317 + void sqliteStrRealloc(char**);
29319 +# define sqliteRealloc_(X,Y) sqliteRealloc(X,Y)
29320 +# define sqliteStrRealloc(X)
29324 +** This variable gets set if malloc() ever fails. After it gets set,
29325 +** the SQLite library shuts down permanently.
29327 +extern int sqlite_malloc_failed;
29330 +** The following global variables are used for testing and debugging
29331 +** only. They only work if MEMORY_DEBUG is defined.
29333 +#ifdef MEMORY_DEBUG
29334 +extern int sqlite_nMalloc; /* Number of sqliteMalloc() calls */
29335 +extern int sqlite_nFree; /* Number of sqliteFree() calls */
29336 +extern int sqlite_iMallocFail; /* Fail sqliteMalloc() after this many calls */
29340 +** Name of the master database table. The master database table
29341 +** is a special table that holds the names and attributes of all
29342 +** user tables and indices.
29344 +#define MASTER_NAME "sqlite_master"
29345 +#define TEMP_MASTER_NAME "sqlite_temp_master"
29348 +** The name of the schema table.
29350 +#define SCHEMA_TABLE(x) (x?TEMP_MASTER_NAME:MASTER_NAME)
29353 +** A convenience macro that returns the number of elements in
29356 +#define ArraySize(X) (sizeof(X)/sizeof(X[0]))
29359 +** Forward references to structures
29361 +typedef struct Column Column;
29362 +typedef struct Table Table;
29363 +typedef struct Index Index;
29364 +typedef struct Instruction Instruction;
29365 +typedef struct Expr Expr;
29366 +typedef struct ExprList ExprList;
29367 +typedef struct Parse Parse;
29368 +typedef struct Token Token;
29369 +typedef struct IdList IdList;
29370 +typedef struct SrcList SrcList;
29371 +typedef struct WhereInfo WhereInfo;
29372 +typedef struct WhereLevel WhereLevel;
29373 +typedef struct Select Select;
29374 +typedef struct AggExpr AggExpr;
29375 +typedef struct FuncDef FuncDef;
29376 +typedef struct Trigger Trigger;
29377 +typedef struct TriggerStep TriggerStep;
29378 +typedef struct TriggerStack TriggerStack;
29379 +typedef struct FKey FKey;
29380 +typedef struct Db Db;
29381 +typedef struct AuthContext AuthContext;
29384 +** Each database file to be accessed by the system is an instance
29385 +** of the following structure. There are normally two of these structures
29386 +** in the sqlite.aDb[] array. aDb[0] is the main database file and
29387 +** aDb[1] is the database file used to hold temporary tables. Additional
29388 +** databases may be attached.
29391 + char *zName; /* Name of this database */
29392 + Btree *pBt; /* The B*Tree structure for this database file */
29393 + int schema_cookie; /* Database schema version number for this file */
29394 + Hash tblHash; /* All tables indexed by name */
29395 + Hash idxHash; /* All (named) indices indexed by name */
29396 + Hash trigHash; /* All triggers indexed by name */
29397 + Hash aFKey; /* Foreign keys indexed by to-table */
29398 + u8 inTrans; /* 0: not writable. 1: Transaction. 2: Checkpoint */
29399 + u16 flags; /* Flags associated with this database */
29400 + void *pAux; /* Auxiliary data. Usually NULL */
29401 + void (*xFreeAux)(void*); /* Routine to free pAux */
29405 +** These macros can be used to test, set, or clear bits in the
29406 +** Db.flags field.
29408 +#define DbHasProperty(D,I,P) (((D)->aDb[I].flags&(P))==(P))
29409 +#define DbHasAnyProperty(D,I,P) (((D)->aDb[I].flags&(P))!=0)
29410 +#define DbSetProperty(D,I,P) (D)->aDb[I].flags|=(P)
29411 +#define DbClearProperty(D,I,P) (D)->aDb[I].flags&=~(P)
29414 +** Allowed values for the DB.flags field.
29416 +** The DB_Locked flag is set when the first OP_Transaction or OP_Checkpoint
29417 +** opcode is emitted for a database. This prevents multiple occurances
29418 +** of those opcodes for the same database in the same program. Similarly,
29419 +** the DB_Cookie flag is set when the OP_VerifyCookie opcode is emitted,
29420 +** and prevents duplicate OP_VerifyCookies from taking up space and slowing
29421 +** down execution.
29423 +** The DB_SchemaLoaded flag is set after the database schema has been
29424 +** read into internal hash tables.
29426 +** DB_UnresetViews means that one or more views have column names that
29427 +** have been filled out. If the schema changes, these column names might
29428 +** changes and so the view will need to be reset.
29430 +#define DB_Locked 0x0001 /* OP_Transaction opcode has been emitted */
29431 +#define DB_Cookie 0x0002 /* OP_VerifyCookie opcode has been emiited */
29432 +#define DB_SchemaLoaded 0x0004 /* The schema has been loaded */
29433 +#define DB_UnresetViews 0x0008 /* Some views have defined column names */
29437 +** Each database is an instance of the following structure.
29439 +** The sqlite.file_format is initialized by the database file
29440 +** and helps determines how the data in the database file is
29441 +** represented. This field allows newer versions of the library
29442 +** to read and write older databases. The various file formats
29443 +** are as follows:
29445 +** file_format==1 Version 2.1.0.
29446 +** file_format==2 Version 2.2.0. Add support for INTEGER PRIMARY KEY.
29447 +** file_format==3 Version 2.6.0. Fix empty-string index bug.
29448 +** file_format==4 Version 2.7.0. Add support for separate numeric and
29449 +** text datatypes.
29451 +** The sqlite.temp_store determines where temporary database files
29452 +** are stored. If 1, then a file is created to hold those tables. If
29453 +** 2, then they are held in memory. 0 means use the default value in
29454 +** the TEMP_STORE macro.
29456 +** The sqlite.lastRowid records the last insert rowid generated by an
29457 +** insert statement. Inserts on views do not affect its value. Each
29458 +** trigger has its own context, so that lastRowid can be updated inside
29459 +** triggers as usual. The previous value will be restored once the trigger
29460 +** exits. Upon entering a before or instead of trigger, lastRowid is no
29461 +** longer (since after version 2.8.12) reset to -1.
29463 +** The sqlite.nChange does not count changes within triggers and keeps no
29464 +** context. It is reset at start of sqlite_exec.
29465 +** The sqlite.lsChange represents the number of changes made by the last
29466 +** insert, update, or delete statement. It remains constant throughout the
29467 +** length of a statement and is then updated by OP_SetCounts. It keeps a
29468 +** context stack just like lastRowid so that the count of changes
29469 +** within a trigger is not seen outside the trigger. Changes to views do not
29470 +** affect the value of lsChange.
29471 +** The sqlite.csChange keeps track of the number of current changes (since
29472 +** the last statement) and is used to update sqlite_lsChange.
29475 + int nDb; /* Number of backends currently in use */
29476 + Db *aDb; /* All backends */
29477 + Db aDbStatic[2]; /* Static space for the 2 default backends */
29478 + int flags; /* Miscellanous flags. See below */
29479 + u8 file_format; /* What file format version is this database? */
29480 + u8 safety_level; /* How aggressive at synching data to disk */
29481 + u8 want_to_close; /* Close after all VDBEs are deallocated */
29482 + u8 temp_store; /* 1=file, 2=memory, 0=compile-time default */
29483 + u8 onError; /* Default conflict algorithm */
29484 + int next_cookie; /* Next value of aDb[0].schema_cookie */
29485 + int cache_size; /* Number of pages to use in the cache */
29486 + int nTable; /* Number of tables in the database */
29487 + void *pBusyArg; /* 1st Argument to the busy callback */
29488 + int (*xBusyCallback)(void *,const char*,int); /* The busy callback */
29489 + void *pCommitArg; /* Argument to xCommitCallback() */
29490 + int (*xCommitCallback)(void*);/* Invoked at every commit. */
29491 + Hash aFunc; /* All functions that can be in SQL exprs */
29492 + int lastRowid; /* ROWID of most recent insert (see above) */
29493 + int priorNewRowid; /* Last randomly generated ROWID */
29494 + int magic; /* Magic number for detect library misuse */
29495 + int nChange; /* Number of rows changed (see above) */
29496 + int lsChange; /* Last statement change count (see above) */
29497 + int csChange; /* Current statement change count (see above) */
29498 + struct sqliteInitInfo { /* Information used during initialization */
29499 + int iDb; /* When back is being initialized */
29500 + int newTnum; /* Rootpage of table being initialized */
29501 + u8 busy; /* TRUE if currently initializing */
29503 + struct Vdbe *pVdbe; /* List of active virtual machines */
29504 + void (*xTrace)(void*,const char*); /* Trace function */
29505 + void *pTraceArg; /* Argument to the trace function */
29506 +#ifndef SQLITE_OMIT_AUTHORIZATION
29507 + int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
29508 + /* Access authorization function */
29509 + void *pAuthArg; /* 1st argument to the access auth function */
29511 +#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
29512 + int (*xProgress)(void *); /* The progress callback */
29513 + void *pProgressArg; /* Argument to the progress callback */
29514 + int nProgressOps; /* Number of opcodes for progress callback */
29519 +** Possible values for the sqlite.flags and or Db.flags fields.
29521 +** On sqlite.flags, the SQLITE_InTrans value means that we have
29522 +** executed a BEGIN. On Db.flags, SQLITE_InTrans means a statement
29523 +** transaction is active on that particular database file.
29525 +#define SQLITE_VdbeTrace 0x00000001 /* True to trace VDBE execution */
29526 +#define SQLITE_Initialized 0x00000002 /* True after initialization */
29527 +#define SQLITE_Interrupt 0x00000004 /* Cancel current operation */
29528 +#define SQLITE_InTrans 0x00000008 /* True if in a transaction */
29529 +#define SQLITE_InternChanges 0x00000010 /* Uncommitted Hash table changes */
29530 +#define SQLITE_FullColNames 0x00000020 /* Show full column names on SELECT */
29531 +#define SQLITE_ShortColNames 0x00000040 /* Show short columns names */
29532 +#define SQLITE_CountRows 0x00000080 /* Count rows changed by INSERT, */
29533 + /* DELETE, or UPDATE and return */
29534 + /* the count using a callback. */
29535 +#define SQLITE_NullCallback 0x00000100 /* Invoke the callback once if the */
29536 + /* result set is empty */
29537 +#define SQLITE_ReportTypes 0x00000200 /* Include information on datatypes */
29538 + /* in 4th argument of callback */
29541 +** Possible values for the sqlite.magic field.
29542 +** The numbers are obtained at random and have no special meaning, other
29543 +** than being distinct from one another.
29545 +#define SQLITE_MAGIC_OPEN 0xa029a697 /* Database is open */
29546 +#define SQLITE_MAGIC_CLOSED 0x9f3c2d33 /* Database is closed */
29547 +#define SQLITE_MAGIC_BUSY 0xf03b7906 /* Database currently in use */
29548 +#define SQLITE_MAGIC_ERROR 0xb5357930 /* An SQLITE_MISUSE error occurred */
29551 +** Each SQL function is defined by an instance of the following
29552 +** structure. A pointer to this structure is stored in the sqlite.aFunc
29553 +** hash table. When multiple functions have the same name, the hash table
29554 +** points to a linked list of these structures.
29557 + void (*xFunc)(sqlite_func*,int,const char**); /* Regular function */
29558 + void (*xStep)(sqlite_func*,int,const char**); /* Aggregate function step */
29559 + void (*xFinalize)(sqlite_func*); /* Aggregate function finializer */
29560 + signed char nArg; /* Number of arguments. -1 means unlimited */
29561 + signed char dataType; /* Arg that determines datatype. -1=NUMERIC, */
29562 + /* -2=TEXT. -3=SQLITE_ARGS */
29563 + u8 includeTypes; /* Add datatypes to args of xFunc and xStep */
29564 + void *pUserData; /* User data parameter */
29565 + FuncDef *pNext; /* Next function with same name */
29569 +** information about each column of an SQL table is held in an instance
29570 +** of this structure.
29573 + char *zName; /* Name of this column */
29574 + char *zDflt; /* Default value of this column */
29575 + char *zType; /* Data type for this column */
29576 + u8 notNull; /* True if there is a NOT NULL constraint */
29577 + u8 isPrimKey; /* True if this column is part of the PRIMARY KEY */
29578 + u8 sortOrder; /* Some combination of SQLITE_SO_... values */
29579 + u8 dottedName; /* True if zName contains a "." character */
29583 +** The allowed sort orders.
29585 +** The TEXT and NUM values use bits that do not overlap with DESC and ASC.
29586 +** That way the two can be combined into a single number.
29588 +#define SQLITE_SO_UNK 0 /* Use the default collating type. (SCT_NUM) */
29589 +#define SQLITE_SO_TEXT 2 /* Sort using memcmp() */
29590 +#define SQLITE_SO_NUM 4 /* Sort using sqliteCompare() */
29591 +#define SQLITE_SO_TYPEMASK 6 /* Mask to extract the collating sequence */
29592 +#define SQLITE_SO_ASC 0 /* Sort in ascending order */
29593 +#define SQLITE_SO_DESC 1 /* Sort in descending order */
29594 +#define SQLITE_SO_DIRMASK 1 /* Mask to extract the sort direction */
29597 +** Each SQL table is represented in memory by an instance of the
29598 +** following structure.
29600 +** Table.zName is the name of the table. The case of the original
29601 +** CREATE TABLE statement is stored, but case is not significant for
29604 +** Table.nCol is the number of columns in this table. Table.aCol is a
29605 +** pointer to an array of Column structures, one for each column.
29607 +** If the table has an INTEGER PRIMARY KEY, then Table.iPKey is the index of
29608 +** the column that is that key. Otherwise Table.iPKey is negative. Note
29609 +** that the datatype of the PRIMARY KEY must be INTEGER for this field to
29610 +** be set. An INTEGER PRIMARY KEY is used as the rowid for each row of
29611 +** the table. If a table has no INTEGER PRIMARY KEY, then a random rowid
29612 +** is generated for each row of the table. Table.hasPrimKey is true if
29613 +** the table has any PRIMARY KEY, INTEGER or otherwise.
29615 +** Table.tnum is the page number for the root BTree page of the table in the
29616 +** database file. If Table.iDb is the index of the database table backend
29617 +** in sqlite.aDb[]. 0 is for the main database and 1 is for the file that
29618 +** holds temporary tables and indices. If Table.isTransient
29619 +** is true, then the table is stored in a file that is automatically deleted
29620 +** when the VDBE cursor to the table is closed. In this case Table.tnum
29621 +** refers VDBE cursor number that holds the table open, not to the root
29622 +** page number. Transient tables are used to hold the results of a
29623 +** sub-query that appears instead of a real table name in the FROM clause
29624 +** of a SELECT statement.
29627 + char *zName; /* Name of the table */
29628 + int nCol; /* Number of columns in this table */
29629 + Column *aCol; /* Information about each column */
29630 + int iPKey; /* If not less then 0, use aCol[iPKey] as the primary key */
29631 + Index *pIndex; /* List of SQL indexes on this table. */
29632 + int tnum; /* Root BTree node for this table (see note above) */
29633 + Select *pSelect; /* NULL for tables. Points to definition if a view. */
29634 + u8 readOnly; /* True if this table should not be written by the user */
29635 + u8 iDb; /* Index into sqlite.aDb[] of the backend for this table */
29636 + u8 isTransient; /* True if automatically deleted when VDBE finishes */
29637 + u8 hasPrimKey; /* True if there exists a primary key */
29638 + u8 keyConf; /* What to do in case of uniqueness conflict on iPKey */
29639 + Trigger *pTrigger; /* List of SQL triggers on this table */
29640 + FKey *pFKey; /* Linked list of all foreign keys in this table */
29644 +** Each foreign key constraint is an instance of the following structure.
29646 +** A foreign key is associated with two tables. The "from" table is
29647 +** the table that contains the REFERENCES clause that creates the foreign
29648 +** key. The "to" table is the table that is named in the REFERENCES clause.
29649 +** Consider this example:
29651 +** CREATE TABLE ex1(
29652 +** a INTEGER PRIMARY KEY,
29653 +** b INTEGER CONSTRAINT fk1 REFERENCES ex2(x)
29656 +** For foreign key "fk1", the from-table is "ex1" and the to-table is "ex2".
29658 +** Each REFERENCES clause generates an instance of the following structure
29659 +** which is attached to the from-table. The to-table need not exist when
29660 +** the from-table is created. The existance of the to-table is not checked
29661 +** until an attempt is made to insert data into the from-table.
29663 +** The sqlite.aFKey hash table stores pointers to this structure
29664 +** given the name of a to-table. For each to-table, all foreign keys
29665 +** associated with that table are on a linked list using the FKey.pNextTo
29669 + Table *pFrom; /* The table that constains the REFERENCES clause */
29670 + FKey *pNextFrom; /* Next foreign key in pFrom */
29671 + char *zTo; /* Name of table that the key points to */
29672 + FKey *pNextTo; /* Next foreign key that points to zTo */
29673 + int nCol; /* Number of columns in this key */
29674 + struct sColMap { /* Mapping of columns in pFrom to columns in zTo */
29675 + int iFrom; /* Index of column in pFrom */
29676 + char *zCol; /* Name of column in zTo. If 0 use PRIMARY KEY */
29677 + } *aCol; /* One entry for each of nCol column s */
29678 + u8 isDeferred; /* True if constraint checking is deferred till COMMIT */
29679 + u8 updateConf; /* How to resolve conflicts that occur on UPDATE */
29680 + u8 deleteConf; /* How to resolve conflicts that occur on DELETE */
29681 + u8 insertConf; /* How to resolve conflicts that occur on INSERT */
29685 +** SQLite supports many different ways to resolve a contraint
29686 +** error. ROLLBACK processing means that a constraint violation
29687 +** causes the operation in process to fail and for the current transaction
29688 +** to be rolled back. ABORT processing means the operation in process
29689 +** fails and any prior changes from that one operation are backed out,
29690 +** but the transaction is not rolled back. FAIL processing means that
29691 +** the operation in progress stops and returns an error code. But prior
29692 +** changes due to the same operation are not backed out and no rollback
29693 +** occurs. IGNORE means that the particular row that caused the constraint
29694 +** error is not inserted or updated. Processing continues and no error
29695 +** is returned. REPLACE means that preexisting database rows that caused
29696 +** a UNIQUE constraint violation are removed so that the new insert or
29697 +** update can proceed. Processing continues and no error is reported.
29699 +** RESTRICT, SETNULL, and CASCADE actions apply only to foreign keys.
29700 +** RESTRICT is the same as ABORT for IMMEDIATE foreign keys and the
29701 +** same as ROLLBACK for DEFERRED keys. SETNULL means that the foreign
29702 +** key is set to NULL. CASCADE means that a DELETE or UPDATE of the
29703 +** referenced table row is propagated into the row that holds the
29706 +** The following symbolic values are used to record which type
29707 +** of action to take.
29709 +#define OE_None 0 /* There is no constraint to check */
29710 +#define OE_Rollback 1 /* Fail the operation and rollback the transaction */
29711 +#define OE_Abort 2 /* Back out changes but do no rollback transaction */
29712 +#define OE_Fail 3 /* Stop the operation but leave all prior changes */
29713 +#define OE_Ignore 4 /* Ignore the error. Do not do the INSERT or UPDATE */
29714 +#define OE_Replace 5 /* Delete existing record, then do INSERT or UPDATE */
29716 +#define OE_Restrict 6 /* OE_Abort for IMMEDIATE, OE_Rollback for DEFERRED */
29717 +#define OE_SetNull 7 /* Set the foreign key value to NULL */
29718 +#define OE_SetDflt 8 /* Set the foreign key value to its default */
29719 +#define OE_Cascade 9 /* Cascade the changes */
29721 +#define OE_Default 99 /* Do whatever the default action is */
29724 +** Each SQL index is represented in memory by an
29725 +** instance of the following structure.
29727 +** The columns of the table that are to be indexed are described
29728 +** by the aiColumn[] field of this structure. For example, suppose
29729 +** we have the following table and index:
29731 +** CREATE TABLE Ex1(c1 int, c2 int, c3 text);
29732 +** CREATE INDEX Ex2 ON Ex1(c3,c1);
29734 +** In the Table structure describing Ex1, nCol==3 because there are
29735 +** three columns in the table. In the Index structure describing
29736 +** Ex2, nColumn==2 since 2 of the 3 columns of Ex1 are indexed.
29737 +** The value of aiColumn is {2, 0}. aiColumn[0]==2 because the
29738 +** first column to be indexed (c3) has an index of 2 in Ex1.aCol[].
29739 +** The second column to be indexed (c1) has an index of 0 in
29740 +** Ex1.aCol[], hence Ex2.aiColumn[1]==0.
29742 +** The Index.onError field determines whether or not the indexed columns
29743 +** must be unique and what to do if they are not. When Index.onError=OE_None,
29744 +** it means this is not a unique index. Otherwise it is a unique index
29745 +** and the value of Index.onError indicate the which conflict resolution
29746 +** algorithm to employ whenever an attempt is made to insert a non-unique
29750 + char *zName; /* Name of this index */
29751 + int nColumn; /* Number of columns in the table used by this index */
29752 + int *aiColumn; /* Which columns are used by this index. 1st is 0 */
29753 + Table *pTable; /* The SQL table being indexed */
29754 + int tnum; /* Page containing root of this index in database file */
29755 + u8 onError; /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
29756 + u8 autoIndex; /* True if is automatically created (ex: by UNIQUE) */
29757 + u8 iDb; /* Index in sqlite.aDb[] of where this index is stored */
29758 + Index *pNext; /* The next index associated with the same table */
29762 +** Each token coming out of the lexer is an instance of
29763 +** this structure. Tokens are also used as part of an expression.
29765 +** Note if Token.z==0 then Token.dyn and Token.n are undefined and
29766 +** may contain random values. Do not make any assuptions about Token.dyn
29767 +** and Token.n when Token.z==0.
29770 + const char *z; /* Text of the token. Not NULL-terminated! */
29771 + unsigned dyn : 1; /* True for malloced memory, false for static */
29772 + unsigned n : 31; /* Number of characters in this token */
29776 +** Each node of an expression in the parse tree is an instance
29777 +** of this structure.
29779 +** Expr.op is the opcode. The integer parser token codes are reused
29780 +** as opcodes here. For example, the parser defines TK_GE to be an integer
29781 +** code representing the ">=" operator. This same integer code is reused
29782 +** to represent the greater-than-or-equal-to operator in the expression
29785 +** Expr.pRight and Expr.pLeft are subexpressions. Expr.pList is a list
29786 +** of argument if the expression is a function.
29788 +** Expr.token is the operator token for this node. For some expressions
29789 +** that have subexpressions, Expr.token can be the complete text that gave
29790 +** rise to the Expr. In the latter case, the token is marked as being
29791 +** a compound token.
29793 +** An expression of the form ID or ID.ID refers to a column in a table.
29794 +** For such expressions, Expr.op is set to TK_COLUMN and Expr.iTable is
29795 +** the integer cursor number of a VDBE cursor pointing to that table and
29796 +** Expr.iColumn is the column number for the specific column. If the
29797 +** expression is used as a result in an aggregate SELECT, then the
29798 +** value is also stored in the Expr.iAgg column in the aggregate so that
29799 +** it can be accessed after all aggregates are computed.
29801 +** If the expression is a function, the Expr.iTable is an integer code
29802 +** representing which function. If the expression is an unbound variable
29803 +** marker (a question mark character '?' in the original SQL) then the
29804 +** Expr.iTable holds the index number for that variable.
29806 +** The Expr.pSelect field points to a SELECT statement. The SELECT might
29807 +** be the right operand of an IN operator. Or, if a scalar SELECT appears
29808 +** in an expression the opcode is TK_SELECT and Expr.pSelect is the only
29812 + u8 op; /* Operation performed by this node */
29813 + u8 dataType; /* Either SQLITE_SO_TEXT or SQLITE_SO_NUM */
29814 + u8 iDb; /* Database referenced by this expression */
29815 + u8 flags; /* Various flags. See below */
29816 + Expr *pLeft, *pRight; /* Left and right subnodes */
29817 + ExprList *pList; /* A list of expressions used as function arguments
29818 + ** or in "<expr> IN (<expr-list)" */
29819 + Token token; /* An operand token */
29820 + Token span; /* Complete text of the expression */
29821 + int iTable, iColumn; /* When op==TK_COLUMN, then this expr node means the
29822 + ** iColumn-th field of the iTable-th table. */
29823 + int iAgg; /* When op==TK_COLUMN and pParse->useAgg==TRUE, pull
29824 + ** result from the iAgg-th element of the aggregator */
29825 + Select *pSelect; /* When the expression is a sub-select. Also the
29826 + ** right side of "<expr> IN (<select>)" */
29830 +** The following are the meanings of bits in the Expr.flags field.
29832 +#define EP_FromJoin 0x0001 /* Originated in ON or USING clause of a join */
29835 +** These macros can be used to test, set, or clear bits in the
29836 +** Expr.flags field.
29838 +#define ExprHasProperty(E,P) (((E)->flags&(P))==(P))
29839 +#define ExprHasAnyProperty(E,P) (((E)->flags&(P))!=0)
29840 +#define ExprSetProperty(E,P) (E)->flags|=(P)
29841 +#define ExprClearProperty(E,P) (E)->flags&=~(P)
29844 +** A list of expressions. Each expression may optionally have a
29845 +** name. An expr/name combination can be used in several ways, such
29846 +** as the list of "expr AS ID" fields following a "SELECT" or in the
29847 +** list of "ID = expr" items in an UPDATE. A list of expressions can
29848 +** also be used as the argument to a function, in which case the a.zName
29849 +** field is not used.
29852 + int nExpr; /* Number of expressions on the list */
29853 + int nAlloc; /* Number of entries allocated below */
29854 + struct ExprList_item {
29855 + Expr *pExpr; /* The list of expressions */
29856 + char *zName; /* Token associated with this expression */
29857 + u8 sortOrder; /* 1 for DESC or 0 for ASC */
29858 + u8 isAgg; /* True if this is an aggregate like count(*) */
29859 + u8 done; /* A flag to indicate when processing is finished */
29860 + } *a; /* One entry for each expression */
29864 +** An instance of this structure can hold a simple list of identifiers,
29865 +** such as the list "a,b,c" in the following statements:
29867 +** INSERT INTO t(a,b,c) VALUES ...;
29868 +** CREATE INDEX idx ON t(a,b,c);
29869 +** CREATE TRIGGER trig BEFORE UPDATE ON t(a,b,c) ...;
29871 +** The IdList.a.idx field is used when the IdList represents the list of
29872 +** column names after a table name in an INSERT statement. In the statement
29874 +** INSERT INTO t(a,b,c) ...
29876 +** If "a" is the k-th column of table "t", then IdList.a[0].idx==k.
29879 + int nId; /* Number of identifiers on the list */
29880 + int nAlloc; /* Number of entries allocated for a[] below */
29881 + struct IdList_item {
29882 + char *zName; /* Name of the identifier */
29883 + int idx; /* Index in some Table.aCol[] of a column named zName */
29888 +** The following structure describes the FROM clause of a SELECT statement.
29889 +** Each table or subquery in the FROM clause is a separate element of
29890 +** the SrcList.a[] array.
29892 +** With the addition of multiple database support, the following structure
29893 +** can also be used to describe a particular table such as the table that
29894 +** is modified by an INSERT, DELETE, or UPDATE statement. In standard SQL,
29895 +** such a table must be a simple name: ID. But in SQLite, the table can
29896 +** now be identified by a database name, a dot, then the table name: ID.ID.
29899 + i16 nSrc; /* Number of tables or subqueries in the FROM clause */
29900 + i16 nAlloc; /* Number of entries allocated in a[] below */
29901 + struct SrcList_item {
29902 + char *zDatabase; /* Name of database holding this table */
29903 + char *zName; /* Name of the table */
29904 + char *zAlias; /* The "B" part of a "A AS B" phrase. zName is the "A" */
29905 + Table *pTab; /* An SQL table corresponding to zName */
29906 + Select *pSelect; /* A SELECT statement used in place of a table name */
29907 + int jointype; /* Type of join between this table and the next */
29908 + int iCursor; /* The VDBE cursor number used to access this table */
29909 + Expr *pOn; /* The ON clause of a join */
29910 + IdList *pUsing; /* The USING clause of a join */
29911 + } a[1]; /* One entry for each identifier on the list */
29915 +** Permitted values of the SrcList.a.jointype field
29917 +#define JT_INNER 0x0001 /* Any kind of inner or cross join */
29918 +#define JT_NATURAL 0x0002 /* True for a "natural" join */
29919 +#define JT_LEFT 0x0004 /* Left outer join */
29920 +#define JT_RIGHT 0x0008 /* Right outer join */
29921 +#define JT_OUTER 0x0010 /* The "OUTER" keyword is present */
29922 +#define JT_ERROR 0x0020 /* unknown or unsupported join type */
29925 +** For each nested loop in a WHERE clause implementation, the WhereInfo
29926 +** structure contains a single instance of this structure. This structure
29927 +** is intended to be private the the where.c module and should not be
29928 +** access or modified by other modules.
29930 +struct WhereLevel {
29931 + int iMem; /* Memory cell used by this level */
29932 + Index *pIdx; /* Index used */
29933 + int iCur; /* Cursor number used for this index */
29934 + int score; /* How well this indexed scored */
29935 + int brk; /* Jump here to break out of the loop */
29936 + int cont; /* Jump here to continue with the next loop cycle */
29937 + int op, p1, p2; /* Opcode used to terminate the loop */
29938 + int iLeftJoin; /* Memory cell used to implement LEFT OUTER JOIN */
29939 + int top; /* First instruction of interior of the loop */
29940 + int inOp, inP1, inP2;/* Opcode used to implement an IN operator */
29941 + int bRev; /* Do the scan in the reverse direction */
29945 +** The WHERE clause processing routine has two halves. The
29946 +** first part does the start of the WHERE loop and the second
29947 +** half does the tail of the WHERE loop. An instance of
29948 +** this structure is returned by the first half and passed
29949 +** into the second half to give some continuity.
29951 +struct WhereInfo {
29953 + SrcList *pTabList; /* List of tables in the join */
29954 + int iContinue; /* Jump here to continue with next record */
29955 + int iBreak; /* Jump here to break out of the loop */
29956 + int nLevel; /* Number of nested loop */
29957 + int savedNTab; /* Value of pParse->nTab before WhereBegin() */
29958 + int peakNTab; /* Value of pParse->nTab after WhereBegin() */
29959 + WhereLevel a[1]; /* Information about each nest loop in the WHERE */
29963 +** An instance of the following structure contains all information
29964 +** needed to generate code for a single SELECT statement.
29966 +** The zSelect field is used when the Select structure must be persistent.
29967 +** Normally, the expression tree points to tokens in the original input
29968 +** string that encodes the select. But if the Select structure must live
29969 +** longer than its input string (for example when it is used to describe
29970 +** a VIEW) we have to make a copy of the input string so that the nodes
29971 +** of the expression tree will have something to point to. zSelect is used
29972 +** to hold that copy.
29974 +** nLimit is set to -1 if there is no LIMIT clause. nOffset is set to 0.
29975 +** If there is a LIMIT clause, the parser sets nLimit to the value of the
29976 +** limit and nOffset to the value of the offset (or 0 if there is not
29977 +** offset). But later on, nLimit and nOffset become the memory locations
29978 +** in the VDBE that record the limit and offset counters.
29981 + ExprList *pEList; /* The fields of the result */
29982 + u8 op; /* One of: TK_UNION TK_ALL TK_INTERSECT TK_EXCEPT */
29983 + u8 isDistinct; /* True if the DISTINCT keyword is present */
29984 + SrcList *pSrc; /* The FROM clause */
29985 + Expr *pWhere; /* The WHERE clause */
29986 + ExprList *pGroupBy; /* The GROUP BY clause */
29987 + Expr *pHaving; /* The HAVING clause */
29988 + ExprList *pOrderBy; /* The ORDER BY clause */
29989 + Select *pPrior; /* Prior select in a compound select statement */
29990 + int nLimit, nOffset; /* LIMIT and OFFSET values. -1 means not used */
29991 + int iLimit, iOffset; /* Memory registers holding LIMIT & OFFSET counters */
29992 + char *zSelect; /* Complete text of the SELECT command */
29996 +** The results of a select can be distributed in several ways.
29998 +#define SRT_Callback 1 /* Invoke a callback with each row of result */
29999 +#define SRT_Mem 2 /* Store result in a memory cell */
30000 +#define SRT_Set 3 /* Store result as unique keys in a table */
30001 +#define SRT_Union 5 /* Store result as keys in a table */
30002 +#define SRT_Except 6 /* Remove result from a UNION table */
30003 +#define SRT_Table 7 /* Store result as data with a unique key */
30004 +#define SRT_TempTable 8 /* Store result in a trasient table */
30005 +#define SRT_Discard 9 /* Do not save the results anywhere */
30006 +#define SRT_Sorter 10 /* Store results in the sorter */
30007 +#define SRT_Subroutine 11 /* Call a subroutine to handle results */
30010 +** When a SELECT uses aggregate functions (like "count(*)" or "avg(f1)")
30011 +** we have to do some additional analysis of expressions. An instance
30012 +** of the following structure holds information about a single subexpression
30013 +** somewhere in the SELECT statement. An array of these structures holds
30014 +** all the information we need to generate code for aggregate
30017 +** Note that when analyzing a SELECT containing aggregates, both
30018 +** non-aggregate field variables and aggregate functions are stored
30019 +** in the AggExpr array of the Parser structure.
30021 +** The pExpr field points to an expression that is part of either the
30022 +** field list, the GROUP BY clause, the HAVING clause or the ORDER BY
30023 +** clause. The expression will be freed when those clauses are cleaned
30024 +** up. Do not try to delete the expression attached to AggExpr.pExpr.
30026 +** If AggExpr.pExpr==0, that means the expression is "count(*)".
30029 + int isAgg; /* if TRUE contains an aggregate function */
30030 + Expr *pExpr; /* The expression */
30031 + FuncDef *pFunc; /* Information about the aggregate function */
30035 +** An SQL parser context. A copy of this structure is passed through
30036 +** the parser and down into all the parser action routine in order to
30037 +** carry around information that is global to the entire parse.
30040 + sqlite *db; /* The main database structure */
30041 + int rc; /* Return code from execution */
30042 + char *zErrMsg; /* An error message */
30043 + Token sErrToken; /* The token at which the error occurred */
30044 + Token sFirstToken; /* The first token parsed */
30045 + Token sLastToken; /* The last token parsed */
30046 + const char *zTail; /* All SQL text past the last semicolon parsed */
30047 + Table *pNewTable; /* A table being constructed by CREATE TABLE */
30048 + Vdbe *pVdbe; /* An engine for executing database bytecode */
30049 + u8 colNamesSet; /* TRUE after OP_ColumnName has been issued to pVdbe */
30050 + u8 explain; /* True if the EXPLAIN flag is found on the query */
30051 + u8 nameClash; /* A permanent table name clashes with temp table name */
30052 + u8 useAgg; /* If true, extract field values from the aggregator
30053 + ** while generating expressions. Normally false */
30054 + int nErr; /* Number of errors seen */
30055 + int nTab; /* Number of previously allocated VDBE cursors */
30056 + int nMem; /* Number of memory cells used so far */
30057 + int nSet; /* Number of sets used so far */
30058 + int nAgg; /* Number of aggregate expressions */
30059 + int nVar; /* Number of '?' variables seen in the SQL so far */
30060 + AggExpr *aAgg; /* An array of aggregate expressions */
30061 + const char *zAuthContext; /* The 6th parameter to db->xAuth callbacks */
30062 + Trigger *pNewTrigger; /* Trigger under construct by a CREATE TRIGGER */
30063 + TriggerStack *trigStack; /* Trigger actions being coded */
30067 +** An instance of the following structure can be declared on a stack and used
30068 +** to save the Parse.zAuthContext value so that it can be restored later.
30070 +struct AuthContext {
30071 + const char *zAuthContext; /* Put saved Parse.zAuthContext here */
30072 + Parse *pParse; /* The Parse structure */
30076 +** Bitfield flags for P2 value in OP_PutIntKey and OP_Delete
30078 +#define OPFLAG_NCHANGE 1 /* Set to update db->nChange */
30079 +#define OPFLAG_LASTROWID 2 /* Set to update db->lastRowid */
30080 +#define OPFLAG_CSCHANGE 4 /* Set to update db->csChange */
30083 + * Each trigger present in the database schema is stored as an instance of
30084 + * struct Trigger.
30086 + * Pointers to instances of struct Trigger are stored in two ways.
30087 + * 1. In the "trigHash" hash table (part of the sqlite* that represents the
30088 + * database). This allows Trigger structures to be retrieved by name.
30089 + * 2. All triggers associated with a single table form a linked list, using the
30090 + * pNext member of struct Trigger. A pointer to the first element of the
30091 + * linked list is stored as the "pTrigger" member of the associated
30094 + * The "step_list" member points to the first element of a linked list
30095 + * containing the SQL statements specified as the trigger program.
30098 + char *name; /* The name of the trigger */
30099 + char *table; /* The table or view to which the trigger applies */
30100 + u8 iDb; /* Database containing this trigger */
30101 + u8 iTabDb; /* Database containing Trigger.table */
30102 + u8 op; /* One of TK_DELETE, TK_UPDATE, TK_INSERT */
30103 + u8 tr_tm; /* One of TK_BEFORE, TK_AFTER */
30104 + Expr *pWhen; /* The WHEN clause of the expresion (may be NULL) */
30105 + IdList *pColumns; /* If this is an UPDATE OF <column-list> trigger,
30106 + the <column-list> is stored here */
30107 + int foreach; /* One of TK_ROW or TK_STATEMENT */
30108 + Token nameToken; /* Token containing zName. Use during parsing only */
30110 + TriggerStep *step_list; /* Link list of trigger program steps */
30111 + Trigger *pNext; /* Next trigger associated with the table */
30115 + * An instance of struct TriggerStep is used to store a single SQL statement
30116 + * that is a part of a trigger-program.
30118 + * Instances of struct TriggerStep are stored in a singly linked list (linked
30119 + * using the "pNext" member) referenced by the "step_list" member of the
30120 + * associated struct Trigger instance. The first element of the linked list is
30121 + * the first step of the trigger-program.
30123 + * The "op" member indicates whether this is a "DELETE", "INSERT", "UPDATE" or
30124 + * "SELECT" statement. The meanings of the other members is determined by the
30125 + * value of "op" as follows:
30127 + * (op == TK_INSERT)
30128 + * orconf -> stores the ON CONFLICT algorithm
30129 + * pSelect -> If this is an INSERT INTO ... SELECT ... statement, then
30130 + * this stores a pointer to the SELECT statement. Otherwise NULL.
30131 + * target -> A token holding the name of the table to insert into.
30132 + * pExprList -> If this is an INSERT INTO ... VALUES ... statement, then
30133 + * this stores values to be inserted. Otherwise NULL.
30134 + * pIdList -> If this is an INSERT INTO ... (<column-names>) VALUES ...
30135 + * statement, then this stores the column-names to be
30138 + * (op == TK_DELETE)
30139 + * target -> A token holding the name of the table to delete from.
30140 + * pWhere -> The WHERE clause of the DELETE statement if one is specified.
30141 + * Otherwise NULL.
30143 + * (op == TK_UPDATE)
30144 + * target -> A token holding the name of the table to update rows of.
30145 + * pWhere -> The WHERE clause of the UPDATE statement if one is specified.
30146 + * Otherwise NULL.
30147 + * pExprList -> A list of the columns to update and the expressions to update
30148 + * them to. See sqliteUpdate() documentation of "pChanges"
30152 +struct TriggerStep {
30153 + int op; /* One of TK_DELETE, TK_UPDATE, TK_INSERT, TK_SELECT */
30154 + int orconf; /* OE_Rollback etc. */
30155 + Trigger *pTrig; /* The trigger that this step is a part of */
30157 + Select *pSelect; /* Valid for SELECT and sometimes
30158 + INSERT steps (when pExprList == 0) */
30159 + Token target; /* Valid for DELETE, UPDATE, INSERT steps */
30160 + Expr *pWhere; /* Valid for DELETE, UPDATE steps */
30161 + ExprList *pExprList; /* Valid for UPDATE statements and sometimes
30162 + INSERT steps (when pSelect == 0) */
30163 + IdList *pIdList; /* Valid for INSERT statements only */
30165 + TriggerStep * pNext; /* Next in the link-list */
30169 + * An instance of struct TriggerStack stores information required during code
30170 + * generation of a single trigger program. While the trigger program is being
30171 + * coded, its associated TriggerStack instance is pointed to by the
30172 + * "pTriggerStack" member of the Parse structure.
30174 + * The pTab member points to the table that triggers are being coded on. The
30175 + * newIdx member contains the index of the vdbe cursor that points at the temp
30176 + * table that stores the new.* references. If new.* references are not valid
30177 + * for the trigger being coded (for example an ON DELETE trigger), then newIdx
30178 + * is set to -1. The oldIdx member is analogous to newIdx, for old.* references.
30180 + * The ON CONFLICT policy to be used for the trigger program steps is stored
30181 + * as the orconf member. If this is OE_Default, then the ON CONFLICT clause
30182 + * specified for individual triggers steps is used.
30184 + * struct TriggerStack has a "pNext" member, to allow linked lists to be
30185 + * constructed. When coding nested triggers (triggers fired by other triggers)
30186 + * each nested trigger stores its parent trigger's TriggerStack as the "pNext"
30187 + * pointer. Once the nested trigger has been coded, the pNext value is restored
30188 + * to the pTriggerStack member of the Parse stucture and coding of the parent
30189 + * trigger continues.
30191 + * Before a nested trigger is coded, the linked list pointed to by the
30192 + * pTriggerStack is scanned to ensure that the trigger is not about to be coded
30193 + * recursively. If this condition is detected, the nested trigger is not coded.
30195 +struct TriggerStack {
30196 + Table *pTab; /* Table that triggers are currently being coded on */
30197 + int newIdx; /* Index of vdbe cursor to "new" temp table */
30198 + int oldIdx; /* Index of vdbe cursor to "old" temp table */
30199 + int orconf; /* Current orconf policy */
30200 + int ignoreJump; /* where to jump to for a RAISE(IGNORE) */
30201 + Trigger *pTrigger; /* The trigger currently being coded */
30202 + TriggerStack *pNext; /* Next trigger down on the trigger stack */
30206 +** The following structure contains information used by the sqliteFix...
30207 +** routines as they walk the parse tree to make database references
30210 +typedef struct DbFixer DbFixer;
30212 + Parse *pParse; /* The parsing context. Error messages written here */
30213 + const char *zDb; /* Make sure all objects are contained in this database */
30214 + const char *zType; /* Type of the container - used for error messages */
30215 + const Token *pName; /* Name of the container - used for error messages */
30219 + * This global flag is set for performance testing of triggers. When it is set
30220 + * SQLite will perform the overhead of building new and old trigger references
30221 + * even when no triggers exist
30223 +extern int always_code_trigger_setup;
30226 +** Internal function prototypes
30228 +int sqliteStrICmp(const char *, const char *);
30229 +int sqliteStrNICmp(const char *, const char *, int);
30230 +int sqliteHashNoCase(const char *, int);
30231 +int sqliteIsNumber(const char*);
30232 +int sqliteCompare(const char *, const char *);
30233 +int sqliteSortCompare(const char *, const char *);
30234 +void sqliteRealToSortable(double r, char *);
30235 +#ifdef MEMORY_DEBUG
30236 + void *sqliteMalloc_(int,int,char*,int);
30237 + void sqliteFree_(void*,char*,int);
30238 + void *sqliteRealloc_(void*,int,char*,int);
30239 + char *sqliteStrDup_(const char*,char*,int);
30240 + char *sqliteStrNDup_(const char*, int,char*,int);
30241 + void sqliteCheckMemory(void*,int);
30243 + void *sqliteMalloc(int);
30244 + void *sqliteMallocRaw(int);
30245 + void sqliteFree(void*);
30246 + void *sqliteRealloc(void*,int);
30247 + char *sqliteStrDup(const char*);
30248 + char *sqliteStrNDup(const char*, int);
30249 +# define sqliteCheckMemory(a,b)
30251 +char *sqliteMPrintf(const char*, ...);
30252 +char *sqliteVMPrintf(const char*, va_list);
30253 +void sqliteSetString(char **, ...);
30254 +void sqliteSetNString(char **, ...);
30255 +void sqliteErrorMsg(Parse*, const char*, ...);
30256 +void sqliteDequote(char*);
30257 +int sqliteKeywordCode(const char*, int);
30258 +int sqliteRunParser(Parse*, const char*, char **);
30259 +void sqliteExec(Parse*);
30260 +Expr *sqliteExpr(int, Expr*, Expr*, Token*);
30261 +void sqliteExprSpan(Expr*,Token*,Token*);
30262 +Expr *sqliteExprFunction(ExprList*, Token*);
30263 +void sqliteExprDelete(Expr*);
30264 +ExprList *sqliteExprListAppend(ExprList*,Expr*,Token*);
30265 +void sqliteExprListDelete(ExprList*);
30266 +int sqliteInit(sqlite*, char**);
30267 +void sqlitePragma(Parse*,Token*,Token*,int);
30268 +void sqliteResetInternalSchema(sqlite*, int);
30269 +void sqliteBeginParse(Parse*,int);
30270 +void sqliteRollbackInternalChanges(sqlite*);
30271 +void sqliteCommitInternalChanges(sqlite*);
30272 +Table *sqliteResultSetOfSelect(Parse*,char*,Select*);
30273 +void sqliteOpenMasterTable(Vdbe *v, int);
30274 +void sqliteStartTable(Parse*,Token*,Token*,int,int);
30275 +void sqliteAddColumn(Parse*,Token*);
30276 +void sqliteAddNotNull(Parse*, int);
30277 +void sqliteAddPrimaryKey(Parse*, IdList*, int);
30278 +void sqliteAddColumnType(Parse*,Token*,Token*);
30279 +void sqliteAddDefaultValue(Parse*,Token*,int);
30280 +int sqliteCollateType(const char*, int);
30281 +void sqliteAddCollateType(Parse*, int);
30282 +void sqliteEndTable(Parse*,Token*,Select*);
30283 +void sqliteCreateView(Parse*,Token*,Token*,Select*,int);
30284 +int sqliteViewGetColumnNames(Parse*,Table*);
30285 +void sqliteDropTable(Parse*, Token*, int);
30286 +void sqliteDeleteTable(sqlite*, Table*);
30287 +void sqliteInsert(Parse*, SrcList*, ExprList*, Select*, IdList*, int);
30288 +IdList *sqliteIdListAppend(IdList*, Token*);
30289 +int sqliteIdListIndex(IdList*,const char*);
30290 +SrcList *sqliteSrcListAppend(SrcList*, Token*, Token*);
30291 +void sqliteSrcListAddAlias(SrcList*, Token*);
30292 +void sqliteSrcListAssignCursors(Parse*, SrcList*);
30293 +void sqliteIdListDelete(IdList*);
30294 +void sqliteSrcListDelete(SrcList*);
30295 +void sqliteCreateIndex(Parse*,Token*,SrcList*,IdList*,int,Token*,Token*);
30296 +void sqliteDropIndex(Parse*, SrcList*);
30297 +void sqliteAddKeyType(Vdbe*, ExprList*);
30298 +void sqliteAddIdxKeyType(Vdbe*, Index*);
30299 +int sqliteSelect(Parse*, Select*, int, int, Select*, int, int*);
30300 +Select *sqliteSelectNew(ExprList*,SrcList*,Expr*,ExprList*,Expr*,ExprList*,
30302 +void sqliteSelectDelete(Select*);
30303 +void sqliteSelectUnbind(Select*);
30304 +Table *sqliteSrcListLookup(Parse*, SrcList*);
30305 +int sqliteIsReadOnly(Parse*, Table*, int);
30306 +void sqliteDeleteFrom(Parse*, SrcList*, Expr*);
30307 +void sqliteUpdate(Parse*, SrcList*, ExprList*, Expr*, int);
30308 +WhereInfo *sqliteWhereBegin(Parse*, SrcList*, Expr*, int, ExprList**);
30309 +void sqliteWhereEnd(WhereInfo*);
30310 +void sqliteExprCode(Parse*, Expr*);
30311 +int sqliteExprCodeExprList(Parse*, ExprList*, int);
30312 +void sqliteExprIfTrue(Parse*, Expr*, int, int);
30313 +void sqliteExprIfFalse(Parse*, Expr*, int, int);
30314 +Table *sqliteFindTable(sqlite*,const char*, const char*);
30315 +Table *sqliteLocateTable(Parse*,const char*, const char*);
30316 +Index *sqliteFindIndex(sqlite*,const char*, const char*);
30317 +void sqliteUnlinkAndDeleteIndex(sqlite*,Index*);
30318 +void sqliteCopy(Parse*, SrcList*, Token*, Token*, int);
30319 +void sqliteVacuum(Parse*, Token*);
30320 +int sqliteRunVacuum(char**, sqlite*);
30321 +int sqliteGlobCompare(const unsigned char*,const unsigned char*);
30322 +int sqliteLikeCompare(const unsigned char*,const unsigned char*);
30323 +char *sqliteTableNameFromToken(Token*);
30324 +int sqliteExprCheck(Parse*, Expr*, int, int*);
30325 +int sqliteExprType(Expr*);
30326 +int sqliteExprCompare(Expr*, Expr*);
30327 +int sqliteFuncId(Token*);
30328 +int sqliteExprResolveIds(Parse*, SrcList*, ExprList*, Expr*);
30329 +int sqliteExprAnalyzeAggregates(Parse*, Expr*);
30330 +Vdbe *sqliteGetVdbe(Parse*);
30331 +void sqliteRandomness(int, void*);
30332 +void sqliteRollbackAll(sqlite*);
30333 +void sqliteCodeVerifySchema(Parse*, int);
30334 +void sqliteBeginTransaction(Parse*, int);
30335 +void sqliteCommitTransaction(Parse*);
30336 +void sqliteRollbackTransaction(Parse*);
30337 +int sqliteExprIsConstant(Expr*);
30338 +int sqliteExprIsInteger(Expr*, int*);
30339 +int sqliteIsRowid(const char*);
30340 +void sqliteGenerateRowDelete(sqlite*, Vdbe*, Table*, int, int);
30341 +void sqliteGenerateRowIndexDelete(sqlite*, Vdbe*, Table*, int, char*);
30342 +void sqliteGenerateConstraintChecks(Parse*,Table*,int,char*,int,int,int,int);
30343 +void sqliteCompleteInsertion(Parse*, Table*, int, char*, int, int, int);
30344 +int sqliteOpenTableAndIndices(Parse*, Table*, int);
30345 +void sqliteBeginWriteOperation(Parse*, int, int);
30346 +void sqliteEndWriteOperation(Parse*);
30347 +Expr *sqliteExprDup(Expr*);
30348 +void sqliteTokenCopy(Token*, Token*);
30349 +ExprList *sqliteExprListDup(ExprList*);
30350 +SrcList *sqliteSrcListDup(SrcList*);
30351 +IdList *sqliteIdListDup(IdList*);
30352 +Select *sqliteSelectDup(Select*);
30353 +FuncDef *sqliteFindFunction(sqlite*,const char*,int,int,int);
30354 +void sqliteRegisterBuiltinFunctions(sqlite*);
30355 +void sqliteRegisterDateTimeFunctions(sqlite*);
30356 +int sqliteSafetyOn(sqlite*);
30357 +int sqliteSafetyOff(sqlite*);
30358 +int sqliteSafetyCheck(sqlite*);
30359 +void sqliteChangeCookie(sqlite*, Vdbe*);
30360 +void sqliteBeginTrigger(Parse*, Token*,int,int,IdList*,SrcList*,int,Expr*,int);
30361 +void sqliteFinishTrigger(Parse*, TriggerStep*, Token*);
30362 +void sqliteDropTrigger(Parse*, SrcList*);
30363 +void sqliteDropTriggerPtr(Parse*, Trigger*, int);
30364 +int sqliteTriggersExist(Parse* , Trigger* , int , int , int, ExprList*);
30365 +int sqliteCodeRowTrigger(Parse*, int, ExprList*, int, Table *, int, int,
30367 +void sqliteViewTriggers(Parse*, Table*, Expr*, int, ExprList*);
30368 +void sqliteDeleteTriggerStep(TriggerStep*);
30369 +TriggerStep *sqliteTriggerSelectStep(Select*);
30370 +TriggerStep *sqliteTriggerInsertStep(Token*, IdList*, ExprList*, Select*, int);
30371 +TriggerStep *sqliteTriggerUpdateStep(Token*, ExprList*, Expr*, int);
30372 +TriggerStep *sqliteTriggerDeleteStep(Token*, Expr*);
30373 +void sqliteDeleteTrigger(Trigger*);
30374 +int sqliteJoinType(Parse*, Token*, Token*, Token*);
30375 +void sqliteCreateForeignKey(Parse*, IdList*, Token*, IdList*, int);
30376 +void sqliteDeferForeignKey(Parse*, int);
30377 +#ifndef SQLITE_OMIT_AUTHORIZATION
30378 + void sqliteAuthRead(Parse*,Expr*,SrcList*);
30379 + int sqliteAuthCheck(Parse*,int, const char*, const char*, const char*);
30380 + void sqliteAuthContextPush(Parse*, AuthContext*, const char*);
30381 + void sqliteAuthContextPop(AuthContext*);
30383 +# define sqliteAuthRead(a,b,c)
30384 +# define sqliteAuthCheck(a,b,c,d,e) SQLITE_OK
30385 +# define sqliteAuthContextPush(a,b,c)
30386 +# define sqliteAuthContextPop(a) ((void)(a))
30388 +void sqliteAttach(Parse*, Token*, Token*, Token*);
30389 +void sqliteDetach(Parse*, Token*);
30390 +int sqliteBtreeFactory(const sqlite *db, const char *zFilename,
30391 + int mode, int nPg, Btree **ppBtree);
30392 +int sqliteFixInit(DbFixer*, Parse*, int, const char*, const Token*);
30393 +int sqliteFixSrcList(DbFixer*, SrcList*);
30394 +int sqliteFixSelect(DbFixer*, Select*);
30395 +int sqliteFixExpr(DbFixer*, Expr*);
30396 +int sqliteFixExprList(DbFixer*, ExprList*);
30397 +int sqliteFixTriggerStep(DbFixer*, TriggerStep*);
30398 +double sqliteAtoF(const char *z, const char **);
30399 +char *sqlite_snprintf(int,char*,const char*,...);
30400 +int sqliteFitsIn32Bits(const char *);
30402 +++ b/ext/sqlite/libsqlite/src/sqlite.w32.h
30405 +** 2001 September 15
30407 +** The author disclaims copyright to this source code. In place of
30408 +** a legal notice, here is a blessing:
30410 +** May you do good and not evil.
30411 +** May you find forgiveness for yourself and forgive others.
30412 +** May you share freely, never taking more than you give.
30414 +*************************************************************************
30415 +** This header file defines the interface that the SQLite library
30416 +** presents to client programs.
30420 +#ifndef _SQLITE_H_
30421 +#define _SQLITE_H_
30422 +#include <stdarg.h> /* Needed for the definition of va_list */
30425 +** Make sure we can call this stuff from C++.
30427 +#ifdef __cplusplus
30432 +** The version of the SQLite library.
30434 +#define SQLITE_VERSION "2.8.17"
30437 +** The version string is also compiled into the library so that a program
30438 +** can check to make sure that the lib*.a file and the *.h file are from
30439 +** the same version.
30441 +extern const char sqlite_version[];
30444 +** The SQLITE_UTF8 macro is defined if the library expects to see
30445 +** UTF-8 encoded data. The SQLITE_ISO8859 macro is defined if the
30446 +** iso8859 encoded should be used.
30448 +#define SQLITE_ISO8859 1
30451 +** The following constant holds one of two strings, "UTF-8" or "iso8859",
30452 +** depending on which character encoding the SQLite library expects to
30453 +** see. The character encoding makes a difference for the LIKE and GLOB
30454 +** operators and for the LENGTH() and SUBSTR() functions.
30456 +extern const char sqlite_encoding[];
30459 +** Each open sqlite database is represented by an instance of the
30460 +** following opaque structure.
30462 +typedef struct sqlite sqlite;
30465 +** A function to open a new sqlite database.
30467 +** If the database does not exist and mode indicates write
30468 +** permission, then a new database is created. If the database
30469 +** does not exist and mode does not indicate write permission,
30470 +** then the open fails, an error message generated (if errmsg!=0)
30471 +** and the function returns 0.
30473 +** If mode does not indicates user write permission, then the
30474 +** database is opened read-only.
30476 +** The Truth: As currently implemented, all databases are opened
30477 +** for writing all the time. Maybe someday we will provide the
30478 +** ability to open a database readonly. The mode parameters is
30479 +** provided in anticipation of that enhancement.
30481 +sqlite *sqlite_open(const char *filename, int mode, char **errmsg);
30484 +** A function to close the database.
30486 +** Call this function with a pointer to a structure that was previously
30487 +** returned from sqlite_open() and the corresponding database will by closed.
30489 +void sqlite_close(sqlite *);
30492 +** The type for a callback function.
30494 +typedef int (*sqlite_callback)(void*,int,char**, char**);
30497 +** A function to executes one or more statements of SQL.
30499 +** If one or more of the SQL statements are queries, then
30500 +** the callback function specified by the 3rd parameter is
30501 +** invoked once for each row of the query result. This callback
30502 +** should normally return 0. If the callback returns a non-zero
30503 +** value then the query is aborted, all subsequent SQL statements
30504 +** are skipped and the sqlite_exec() function returns the SQLITE_ABORT.
30506 +** The 4th parameter is an arbitrary pointer that is passed
30507 +** to the callback function as its first parameter.
30509 +** The 2nd parameter to the callback function is the number of
30510 +** columns in the query result. The 3rd parameter to the callback
30511 +** is an array of strings holding the values for each column.
30512 +** The 4th parameter to the callback is an array of strings holding
30513 +** the names of each column.
30515 +** The callback function may be NULL, even for queries. A NULL
30516 +** callback is not an error. It just means that no callback
30517 +** will be invoked.
30519 +** If an error occurs while parsing or evaluating the SQL (but
30520 +** not while executing the callback) then an appropriate error
30521 +** message is written into memory obtained from malloc() and
30522 +** *errmsg is made to point to that message. The calling function
30523 +** is responsible for freeing the memory that holds the error
30524 +** message. Use sqlite_freemem() for this. If errmsg==NULL,
30525 +** then no error message is ever written.
30527 +** The return value is is SQLITE_OK if there are no errors and
30528 +** some other return code if there is an error. The particular
30529 +** return value depends on the type of error.
30531 +** If the query could not be executed because a database file is
30532 +** locked or busy, then this function returns SQLITE_BUSY. (This
30533 +** behavior can be modified somewhat using the sqlite_busy_handler()
30534 +** and sqlite_busy_timeout() functions below.)
30537 + sqlite*, /* An open database */
30538 + const char *sql, /* SQL to be executed */
30539 + sqlite_callback, /* Callback function */
30540 + void *, /* 1st argument to callback function */
30541 + char **errmsg /* Error msg written here */
30545 +** Return values for sqlite_exec() and sqlite_step()
30547 +#define SQLITE_OK 0 /* Successful result */
30548 +#define SQLITE_ERROR 1 /* SQL error or missing database */
30549 +#define SQLITE_INTERNAL 2 /* An internal logic error in SQLite */
30550 +#define SQLITE_PERM 3 /* Access permission denied */
30551 +#define SQLITE_ABORT 4 /* Callback routine requested an abort */
30552 +#define SQLITE_BUSY 5 /* The database file is locked */
30553 +#define SQLITE_LOCKED 6 /* A table in the database is locked */
30554 +#define SQLITE_NOMEM 7 /* A malloc() failed */
30555 +#define SQLITE_READONLY 8 /* Attempt to write a readonly database */
30556 +#define SQLITE_INTERRUPT 9 /* Operation terminated by sqlite_interrupt() */
30557 +#define SQLITE_IOERR 10 /* Some kind of disk I/O error occurred */
30558 +#define SQLITE_CORRUPT 11 /* The database disk image is malformed */
30559 +#define SQLITE_NOTFOUND 12 /* (Internal Only) Table or record not found */
30560 +#define SQLITE_FULL 13 /* Insertion failed because database is full */
30561 +#define SQLITE_CANTOPEN 14 /* Unable to open the database file */
30562 +#define SQLITE_PROTOCOL 15 /* Database lock protocol error */
30563 +#define SQLITE_EMPTY 16 /* (Internal Only) Database table is empty */
30564 +#define SQLITE_SCHEMA 17 /* The database schema changed */
30565 +#define SQLITE_TOOBIG 18 /* Too much data for one row of a table */
30566 +#define SQLITE_CONSTRAINT 19 /* Abort due to contraint violation */
30567 +#define SQLITE_MISMATCH 20 /* Data type mismatch */
30568 +#define SQLITE_MISUSE 21 /* Library used incorrectly */
30569 +#define SQLITE_NOLFS 22 /* Uses OS features not supported on host */
30570 +#define SQLITE_AUTH 23 /* Authorization denied */
30571 +#define SQLITE_FORMAT 24 /* Auxiliary database format error */
30572 +#define SQLITE_RANGE 25 /* 2nd parameter to sqlite_bind out of range */
30573 +#define SQLITE_NOTADB 26 /* File opened that is not a database file */
30574 +#define SQLITE_ROW 100 /* sqlite_step() has another row ready */
30575 +#define SQLITE_DONE 101 /* sqlite_step() has finished executing */
30578 +** Each entry in an SQLite table has a unique integer key. (The key is
30579 +** the value of the INTEGER PRIMARY KEY column if there is such a column,
30580 +** otherwise the key is generated at random. The unique key is always
30581 +** available as the ROWID, OID, or _ROWID_ column.) The following routine
30582 +** returns the integer key of the most recent insert in the database.
30584 +** This function is similar to the mysql_insert_id() function from MySQL.
30586 +int sqlite_last_insert_rowid(sqlite*);
30589 +** This function returns the number of database rows that were changed
30590 +** (or inserted or deleted) by the most recent called sqlite_exec().
30592 +** All changes are counted, even if they were later undone by a
30593 +** ROLLBACK or ABORT. Except, changes associated with creating and
30594 +** dropping tables are not counted.
30596 +** If a callback invokes sqlite_exec() recursively, then the changes
30597 +** in the inner, recursive call are counted together with the changes
30598 +** in the outer call.
30600 +** SQLite implements the command "DELETE FROM table" without a WHERE clause
30601 +** by dropping and recreating the table. (This is much faster than going
30602 +** through and deleting individual elements form the table.) Because of
30603 +** this optimization, the change count for "DELETE FROM table" will be
30604 +** zero regardless of the number of elements that were originally in the
30605 +** table. To get an accurate count of the number of rows deleted, use
30606 +** "DELETE FROM table WHERE 1" instead.
30608 +int sqlite_changes(sqlite*);
30610 +/* If the parameter to this routine is one of the return value constants
30611 +** defined above, then this routine returns a constant text string which
30612 +** descripts (in English) the meaning of the return value.
30614 +const char *sqlite_error_string(int);
30615 +#define sqliteErrStr sqlite_error_string /* Legacy. Do not use in new code. */
30617 +/* This function causes any pending database operation to abort and
30618 +** return at its earliest opportunity. This routine is typically
30619 +** called in response to a user action such as pressing "Cancel"
30620 +** or Ctrl-C where the user wants a long query operation to halt
30623 +void sqlite_interrupt(sqlite*);
30626 +/* This function returns true if the given input string comprises
30627 +** one or more complete SQL statements.
30629 +** The algorithm is simple. If the last token other than spaces
30630 +** and comments is a semicolon, then return true. otherwise return
30633 +int sqlite_complete(const char *sql);
30636 +** This routine identifies a callback function that is invoked
30637 +** whenever an attempt is made to open a database table that is
30638 +** currently locked by another process or thread. If the busy callback
30639 +** is NULL, then sqlite_exec() returns SQLITE_BUSY immediately if
30640 +** it finds a locked table. If the busy callback is not NULL, then
30641 +** sqlite_exec() invokes the callback with three arguments. The
30642 +** second argument is the name of the locked table and the third
30643 +** argument is the number of times the table has been busy. If the
30644 +** busy callback returns 0, then sqlite_exec() immediately returns
30645 +** SQLITE_BUSY. If the callback returns non-zero, then sqlite_exec()
30646 +** tries to open the table again and the cycle repeats.
30648 +** The default busy callback is NULL.
30650 +** Sqlite is re-entrant, so the busy handler may start a new query.
30651 +** (It is not clear why anyone would every want to do this, but it
30652 +** is allowed, in theory.) But the busy handler may not close the
30653 +** database. Closing the database from a busy handler will delete
30654 +** data structures out from under the executing query and will
30655 +** probably result in a coredump.
30657 +void sqlite_busy_handler(sqlite*, int(*)(void*,const char*,int), void*);
30660 +** This routine sets a busy handler that sleeps for a while when a
30661 +** table is locked. The handler will sleep multiple times until
30662 +** at least "ms" milleseconds of sleeping have been done. After
30663 +** "ms" milleseconds of sleeping, the handler returns 0 which
30664 +** causes sqlite_exec() to return SQLITE_BUSY.
30666 +** Calling this routine with an argument less than or equal to zero
30667 +** turns off all busy handlers.
30669 +void sqlite_busy_timeout(sqlite*, int ms);
30672 +** This next routine is really just a wrapper around sqlite_exec().
30673 +** Instead of invoking a user-supplied callback for each row of the
30674 +** result, this routine remembers each row of the result in memory
30675 +** obtained from malloc(), then returns all of the result after the
30676 +** query has finished.
30678 +** As an example, suppose the query result where this table:
30681 +** -----------------------
30686 +** If the 3rd argument were &azResult then after the function returns
30687 +** azResult will contain the following data:
30689 +** azResult[0] = "Name";
30690 +** azResult[1] = "Age";
30691 +** azResult[2] = "Alice";
30692 +** azResult[3] = "43";
30693 +** azResult[4] = "Bob";
30694 +** azResult[5] = "28";
30695 +** azResult[6] = "Cindy";
30696 +** azResult[7] = "21";
30698 +** Notice that there is an extra row of data containing the column
30699 +** headers. But the *nrow return value is still 3. *ncolumn is
30700 +** set to 2. In general, the number of values inserted into azResult
30701 +** will be ((*nrow) + 1)*(*ncolumn).
30703 +** After the calling function has finished using the result, it should
30704 +** pass the result data pointer to sqlite_free_table() in order to
30705 +** release the memory that was malloc-ed. Because of the way the
30706 +** malloc() happens, the calling function must not try to call
30707 +** malloc() directly. Only sqlite_free_table() is able to release
30708 +** the memory properly and safely.
30710 +** The return value of this routine is the same as from sqlite_exec().
30712 +int sqlite_get_table(
30713 + sqlite*, /* An open database */
30714 + const char *sql, /* SQL to be executed */
30715 + char ***resultp, /* Result written to a char *[] that this points to */
30716 + int *nrow, /* Number of result rows written here */
30717 + int *ncolumn, /* Number of result columns written here */
30718 + char **errmsg /* Error msg written here */
30722 +** Call this routine to free the memory that sqlite_get_table() allocated.
30724 +void sqlite_free_table(char **result);
30727 +** The following routines are wrappers around sqlite_exec() and
30728 +** sqlite_get_table(). The only difference between the routines that
30729 +** follow and the originals is that the second argument to the
30730 +** routines that follow is really a printf()-style format
30731 +** string describing the SQL to be executed. Arguments to the format
30732 +** string appear at the end of the argument list.
30734 +** All of the usual printf formatting options apply. In addition, there
30735 +** is a "%q" option. %q works like %s in that it substitutes a null-terminated
30736 +** string from the argument list. But %q also doubles every '\'' character.
30737 +** %q is designed for use inside a string literal. By doubling each '\''
30738 +** character it escapes that character and allows it to be inserted into
30741 +** For example, so some string variable contains text as follows:
30743 +** char *zText = "It's a happy day!";
30745 +** We can use this text in an SQL statement as follows:
30747 +** sqlite_exec_printf(db, "INSERT INTO table VALUES('%q')",
30748 +** callback1, 0, 0, zText);
30750 +** Because the %q format string is used, the '\'' character in zText
30751 +** is escaped and the SQL generated is as follows:
30753 +** INSERT INTO table1 VALUES('It''s a happy day!')
30755 +** This is correct. Had we used %s instead of %q, the generated SQL
30756 +** would have looked like this:
30758 +** INSERT INTO table1 VALUES('It's a happy day!');
30760 +** This second example is an SQL syntax error. As a general rule you
30761 +** should always use %q instead of %s when inserting text into a string
30764 +int sqlite_exec_printf(
30765 + sqlite*, /* An open database */
30766 + const char *sqlFormat, /* printf-style format string for the SQL */
30767 + sqlite_callback, /* Callback function */
30768 + void *, /* 1st argument to callback function */
30769 + char **errmsg, /* Error msg written here */
30770 + ... /* Arguments to the format string. */
30772 +int sqlite_exec_vprintf(
30773 + sqlite*, /* An open database */
30774 + const char *sqlFormat, /* printf-style format string for the SQL */
30775 + sqlite_callback, /* Callback function */
30776 + void *, /* 1st argument to callback function */
30777 + char **errmsg, /* Error msg written here */
30778 + va_list ap /* Arguments to the format string. */
30780 +int sqlite_get_table_printf(
30781 + sqlite*, /* An open database */
30782 + const char *sqlFormat, /* printf-style format string for the SQL */
30783 + char ***resultp, /* Result written to a char *[] that this points to */
30784 + int *nrow, /* Number of result rows written here */
30785 + int *ncolumn, /* Number of result columns written here */
30786 + char **errmsg, /* Error msg written here */
30787 + ... /* Arguments to the format string */
30789 +int sqlite_get_table_vprintf(
30790 + sqlite*, /* An open database */
30791 + const char *sqlFormat, /* printf-style format string for the SQL */
30792 + char ***resultp, /* Result written to a char *[] that this points to */
30793 + int *nrow, /* Number of result rows written here */
30794 + int *ncolumn, /* Number of result columns written here */
30795 + char **errmsg, /* Error msg written here */
30796 + va_list ap /* Arguments to the format string */
30798 +char *sqlite_mprintf(const char*,...);
30799 +char *sqlite_vmprintf(const char*, va_list);
30802 +** Windows systems should call this routine to free memory that
30803 +** is returned in the in the errmsg parameter of sqlite_open() when
30804 +** SQLite is a DLL. For some reason, it does not work to call free()
30807 +void sqlite_freemem(void *p);
30810 +** Windows systems need functions to call to return the sqlite_version
30811 +** and sqlite_encoding strings.
30813 +const char *sqlite_libversion(void);
30814 +const char *sqlite_libencoding(void);
30817 +** A pointer to the following structure is used to communicate with
30818 +** the implementations of user-defined functions.
30820 +typedef struct sqlite_func sqlite_func;
30823 +** Use the following routines to create new user-defined functions. See
30824 +** the documentation for details.
30826 +int sqlite_create_function(
30827 + sqlite*, /* Database where the new function is registered */
30828 + const char *zName, /* Name of the new function */
30829 + int nArg, /* Number of arguments. -1 means any number */
30830 + void (*xFunc)(sqlite_func*,int,const char**), /* C code to implement */
30831 + void *pUserData /* Available via the sqlite_user_data() call */
30833 +int sqlite_create_aggregate(
30834 + sqlite*, /* Database where the new function is registered */
30835 + const char *zName, /* Name of the function */
30836 + int nArg, /* Number of arguments */
30837 + void (*xStep)(sqlite_func*,int,const char**), /* Called for each row */
30838 + void (*xFinalize)(sqlite_func*), /* Called once to get final result */
30839 + void *pUserData /* Available via the sqlite_user_data() call */
30843 +** Use the following routine to define the datatype returned by a
30844 +** user-defined function. The second argument can be one of the
30845 +** constants SQLITE_NUMERIC, SQLITE_TEXT, or SQLITE_ARGS or it
30846 +** can be an integer greater than or equal to zero. The datatype
30847 +** will be numeric or text (the only two types supported) if the
30848 +** argument is SQLITE_NUMERIC or SQLITE_TEXT. If the argument is
30849 +** SQLITE_ARGS, then the datatype is numeric if any argument to the
30850 +** function is numeric and is text otherwise. If the second argument
30851 +** is an integer, then the datatype of the result is the same as the
30852 +** parameter to the function that corresponds to that integer.
30854 +int sqlite_function_type(
30855 + sqlite *db, /* The database there the function is registered */
30856 + const char *zName, /* Name of the function */
30857 + int datatype /* The datatype for this function */
30859 +#define SQLITE_NUMERIC (-1)
30860 +#define SQLITE_TEXT (-2)
30861 +#define SQLITE_ARGS (-3)
30864 +** The user function implementations call one of the following four routines
30865 +** in order to return their results. The first parameter to each of these
30866 +** routines is a copy of the first argument to xFunc() or xFinialize().
30867 +** The second parameter to these routines is the result to be returned.
30868 +** A NULL can be passed as the second parameter to sqlite_set_result_string()
30869 +** in order to return a NULL result.
30871 +** The 3rd argument to _string and _error is the number of characters to
30872 +** take from the string. If this argument is negative, then all characters
30873 +** up to and including the first '\000' are used.
30875 +** The sqlite_set_result_string() function allocates a buffer to hold the
30876 +** result and returns a pointer to this buffer. The calling routine
30877 +** (that is, the implmentation of a user function) can alter the content
30878 +** of this buffer if desired.
30880 +char *sqlite_set_result_string(sqlite_func*,const char*,int);
30881 +void sqlite_set_result_int(sqlite_func*,int);
30882 +void sqlite_set_result_double(sqlite_func*,double);
30883 +void sqlite_set_result_error(sqlite_func*,const char*,int);
30886 +** The pUserData parameter to the sqlite_create_function() and
30887 +** sqlite_create_aggregate() routines used to register user functions
30888 +** is available to the implementation of the function using this
30891 +void *sqlite_user_data(sqlite_func*);
30894 +** Aggregate functions use the following routine to allocate
30895 +** a structure for storing their state. The first time this routine
30896 +** is called for a particular aggregate, a new structure of size nBytes
30897 +** is allocated, zeroed, and returned. On subsequent calls (for the
30898 +** same aggregate instance) the same buffer is returned. The implementation
30899 +** of the aggregate can use the returned buffer to accumulate data.
30901 +** The buffer allocated is freed automatically be SQLite.
30903 +void *sqlite_aggregate_context(sqlite_func*, int nBytes);
30906 +** The next routine returns the number of calls to xStep for a particular
30907 +** aggregate function instance. The current call to xStep counts so this
30908 +** routine always returns at least 1.
30910 +int sqlite_aggregate_count(sqlite_func*);
30913 +** This routine registers a callback with the SQLite library. The
30914 +** callback is invoked (at compile-time, not at run-time) for each
30915 +** attempt to access a column of a table in the database. The callback
30916 +** returns SQLITE_OK if access is allowed, SQLITE_DENY if the entire
30917 +** SQL statement should be aborted with an error and SQLITE_IGNORE
30918 +** if the column should be treated as a NULL value.
30920 +int sqlite_set_authorizer(
30922 + int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
30927 +** The second parameter to the access authorization function above will
30928 +** be one of the values below. These values signify what kind of operation
30929 +** is to be authorized. The 3rd and 4th parameters to the authorization
30930 +** function will be parameters or NULL depending on which of the following
30931 +** codes is used as the second parameter. The 5th parameter is the name
30932 +** of the database ("main", "temp", etc.) if applicable. The 6th parameter
30933 +** is the name of the inner-most trigger or view that is responsible for
30934 +** the access attempt or NULL if this access attempt is directly from
30935 +** input SQL code.
30939 +#define SQLITE_COPY 0 /* Table Name File Name */
30940 +#define SQLITE_CREATE_INDEX 1 /* Index Name Table Name */
30941 +#define SQLITE_CREATE_TABLE 2 /* Table Name NULL */
30942 +#define SQLITE_CREATE_TEMP_INDEX 3 /* Index Name Table Name */
30943 +#define SQLITE_CREATE_TEMP_TABLE 4 /* Table Name NULL */
30944 +#define SQLITE_CREATE_TEMP_TRIGGER 5 /* Trigger Name Table Name */
30945 +#define SQLITE_CREATE_TEMP_VIEW 6 /* View Name NULL */
30946 +#define SQLITE_CREATE_TRIGGER 7 /* Trigger Name Table Name */
30947 +#define SQLITE_CREATE_VIEW 8 /* View Name NULL */
30948 +#define SQLITE_DELETE 9 /* Table Name NULL */
30949 +#define SQLITE_DROP_INDEX 10 /* Index Name Table Name */
30950 +#define SQLITE_DROP_TABLE 11 /* Table Name NULL */
30951 +#define SQLITE_DROP_TEMP_INDEX 12 /* Index Name Table Name */
30952 +#define SQLITE_DROP_TEMP_TABLE 13 /* Table Name NULL */
30953 +#define SQLITE_DROP_TEMP_TRIGGER 14 /* Trigger Name Table Name */
30954 +#define SQLITE_DROP_TEMP_VIEW 15 /* View Name NULL */
30955 +#define SQLITE_DROP_TRIGGER 16 /* Trigger Name Table Name */
30956 +#define SQLITE_DROP_VIEW 17 /* View Name NULL */
30957 +#define SQLITE_INSERT 18 /* Table Name NULL */
30958 +#define SQLITE_PRAGMA 19 /* Pragma Name 1st arg or NULL */
30959 +#define SQLITE_READ 20 /* Table Name Column Name */
30960 +#define SQLITE_SELECT 21 /* NULL NULL */
30961 +#define SQLITE_TRANSACTION 22 /* NULL NULL */
30962 +#define SQLITE_UPDATE 23 /* Table Name Column Name */
30963 +#define SQLITE_ATTACH 24 /* Filename NULL */
30964 +#define SQLITE_DETACH 25 /* Database Name NULL */
30968 +** The return value of the authorization function should be one of the
30969 +** following constants:
30971 +/* #define SQLITE_OK 0 // Allow access (This is actually defined above) */
30972 +#define SQLITE_DENY 1 /* Abort the SQL statement with an error */
30973 +#define SQLITE_IGNORE 2 /* Don't allow access, but don't generate an error */
30976 +** Register a function that is called at every invocation of sqlite_exec()
30977 +** or sqlite_compile(). This function can be used (for example) to generate
30978 +** a log file of all SQL executed against a database.
30980 +void *sqlite_trace(sqlite*, void(*xTrace)(void*,const char*), void*);
30982 +/*** The Callback-Free API
30984 +** The following routines implement a new way to access SQLite that does not
30985 +** involve the use of callbacks.
30987 +** An sqlite_vm is an opaque object that represents a single SQL statement
30988 +** that is ready to be executed.
30990 +typedef struct sqlite_vm sqlite_vm;
30993 +** To execute an SQLite query without the use of callbacks, you first have
30994 +** to compile the SQL using this routine. The 1st parameter "db" is a pointer
30995 +** to an sqlite object obtained from sqlite_open(). The 2nd parameter
30996 +** "zSql" is the text of the SQL to be compiled. The remaining parameters
30997 +** are all outputs.
30999 +** *pzTail is made to point to the first character past the end of the first
31000 +** SQL statement in zSql. This routine only compiles the first statement
31001 +** in zSql, so *pzTail is left pointing to what remains uncompiled.
31003 +** *ppVm is left pointing to a "virtual machine" that can be used to execute
31004 +** the compiled statement. Or if there is an error, *ppVm may be set to NULL.
31005 +** If the input text contained no SQL (if the input is and empty string or
31006 +** a comment) then *ppVm is set to NULL.
31008 +** If any errors are detected during compilation, an error message is written
31009 +** into space obtained from malloc() and *pzErrMsg is made to point to that
31010 +** error message. The calling routine is responsible for freeing the text
31011 +** of this message when it has finished with it. Use sqlite_freemem() to
31012 +** free the message. pzErrMsg may be NULL in which case no error message
31013 +** will be generated.
31015 +** On success, SQLITE_OK is returned. Otherwise and error code is returned.
31017 +int sqlite_compile(
31018 + sqlite *db, /* The open database */
31019 + const char *zSql, /* SQL statement to be compiled */
31020 + const char **pzTail, /* OUT: uncompiled tail of zSql */
31021 + sqlite_vm **ppVm, /* OUT: the virtual machine to execute zSql */
31022 + char **pzErrmsg /* OUT: Error message. */
31026 +** After an SQL statement has been compiled, it is handed to this routine
31027 +** to be executed. This routine executes the statement as far as it can
31028 +** go then returns. The return value will be one of SQLITE_DONE,
31029 +** SQLITE_ERROR, SQLITE_BUSY, SQLITE_ROW, or SQLITE_MISUSE.
31031 +** SQLITE_DONE means that the execute of the SQL statement is complete
31032 +** an no errors have occurred. sqlite_step() should not be called again
31033 +** for the same virtual machine. *pN is set to the number of columns in
31034 +** the result set and *pazColName is set to an array of strings that
31035 +** describe the column names and datatypes. The name of the i-th column
31036 +** is (*pazColName)[i] and the datatype of the i-th column is
31037 +** (*pazColName)[i+*pN]. *pazValue is set to NULL.
31039 +** SQLITE_ERROR means that the virtual machine encountered a run-time
31040 +** error. sqlite_step() should not be called again for the same
31041 +** virtual machine. *pN is set to 0 and *pazColName and *pazValue are set
31042 +** to NULL. Use sqlite_finalize() to obtain the specific error code
31043 +** and the error message text for the error.
31045 +** SQLITE_BUSY means that an attempt to open the database failed because
31046 +** another thread or process is holding a lock. The calling routine
31047 +** can try again to open the database by calling sqlite_step() again.
31048 +** The return code will only be SQLITE_BUSY if no busy handler is registered
31049 +** using the sqlite_busy_handler() or sqlite_busy_timeout() routines. If
31050 +** a busy handler callback has been registered but returns 0, then this
31051 +** routine will return SQLITE_ERROR and sqltie_finalize() will return
31052 +** SQLITE_BUSY when it is called.
31054 +** SQLITE_ROW means that a single row of the result is now available.
31055 +** The data is contained in *pazValue. The value of the i-th column is
31056 +** (*azValue)[i]. *pN and *pazColName are set as described in SQLITE_DONE.
31057 +** Invoke sqlite_step() again to advance to the next row.
31059 +** SQLITE_MISUSE is returned if sqlite_step() is called incorrectly.
31060 +** For example, if you call sqlite_step() after the virtual machine
31061 +** has halted (after a prior call to sqlite_step() has returned SQLITE_DONE)
31062 +** or if you call sqlite_step() with an incorrectly initialized virtual
31063 +** machine or a virtual machine that has been deleted or that is associated
31064 +** with an sqlite structure that has been closed.
31067 + sqlite_vm *pVm, /* The virtual machine to execute */
31068 + int *pN, /* OUT: Number of columns in result */
31069 + const char ***pazValue, /* OUT: Column data */
31070 + const char ***pazColName /* OUT: Column names and datatypes */
31074 +** This routine is called to delete a virtual machine after it has finished
31075 +** executing. The return value is the result code. SQLITE_OK is returned
31076 +** if the statement executed successfully and some other value is returned if
31077 +** there was any kind of error. If an error occurred and pzErrMsg is not
31078 +** NULL, then an error message is written into memory obtained from malloc()
31079 +** and *pzErrMsg is made to point to that error message. The calling routine
31080 +** should use sqlite_freemem() to delete this message when it has finished
31083 +** This routine can be called at any point during the execution of the
31084 +** virtual machine. If the virtual machine has not completed execution
31085 +** when this routine is called, that is like encountering an error or
31086 +** an interrupt. (See sqlite_interrupt().) Incomplete updates may be
31087 +** rolled back and transactions cancelled, depending on the circumstances,
31088 +** and the result code returned will be SQLITE_ABORT.
31090 +int sqlite_finalize(sqlite_vm*, char **pzErrMsg);
31093 +** This routine deletes the virtual machine, writes any error message to
31094 +** *pzErrMsg and returns an SQLite return code in the same way as the
31095 +** sqlite_finalize() function.
31097 +** Additionally, if ppVm is not NULL, *ppVm is left pointing to a new virtual
31098 +** machine loaded with the compiled version of the original query ready for
31101 +** If sqlite_reset() returns SQLITE_SCHEMA, then *ppVm is set to NULL.
31103 +******* THIS IS AN EXPERIMENTAL API AND IS SUBJECT TO CHANGE ******
31105 +int sqlite_reset(sqlite_vm*, char **pzErrMsg);
31108 +** If the SQL that was handed to sqlite_compile contains variables that
31109 +** are represeted in the SQL text by a question mark ('?'). This routine
31110 +** is used to assign values to those variables.
31112 +** The first parameter is a virtual machine obtained from sqlite_compile().
31113 +** The 2nd "idx" parameter determines which variable in the SQL statement
31114 +** to bind the value to. The left most '?' is 1. The 3rd parameter is
31115 +** the value to assign to that variable. The 4th parameter is the number
31116 +** of bytes in the value, including the terminating \000 for strings.
31117 +** Finally, the 5th "copy" parameter is TRUE if SQLite should make its
31118 +** own private copy of this value, or false if the space that the 3rd
31119 +** parameter points to will be unchanging and can be used directly by
31122 +** Unbound variables are treated as having a value of NULL. To explicitly
31123 +** set a variable to NULL, call this routine with the 3rd parameter as a
31126 +** If the 4th "len" parameter is -1, then strlen() is used to find the
31129 +** This routine can only be called immediately after sqlite_compile()
31130 +** or sqlite_reset() and before any calls to sqlite_step().
31132 +******* THIS IS AN EXPERIMENTAL API AND IS SUBJECT TO CHANGE ******
31134 +int sqlite_bind(sqlite_vm*, int idx, const char *value, int len, int copy);
31137 +** This routine configures a callback function - the progress callback - that
31138 +** is invoked periodically during long running calls to sqlite_exec(),
31139 +** sqlite_step() and sqlite_get_table(). An example use for this API is to keep
31140 +** a GUI updated during a large query.
31142 +** The progress callback is invoked once for every N virtual machine opcodes,
31143 +** where N is the second argument to this function. The progress callback
31144 +** itself is identified by the third argument to this function. The fourth
31145 +** argument to this function is a void pointer passed to the progress callback
31146 +** function each time it is invoked.
31148 +** If a call to sqlite_exec(), sqlite_step() or sqlite_get_table() results
31149 +** in less than N opcodes being executed, then the progress callback is not
31152 +** Calling this routine overwrites any previously installed progress callback.
31153 +** To remove the progress callback altogether, pass NULL as the third
31154 +** argument to this function.
31156 +** If the progress callback returns a result other than 0, then the current
31157 +** query is immediately terminated and any database changes rolled back. If the
31158 +** query was part of a larger transaction, then the transaction is not rolled
31159 +** back and remains active. The sqlite_exec() call returns SQLITE_ABORT.
31161 +void sqlite_progress_handler(sqlite*, int, int(*)(void*), void*);
31163 +#ifdef __cplusplus
31164 +} /* End of the 'extern "C"' block */
31167 +#endif /* _SQLITE_H_ */
31169 +++ b/ext/sqlite/libsqlite/src/table.c
31172 +** 2001 September 15
31174 +** The author disclaims copyright to this source code. In place of
31175 +** a legal notice, here is a blessing:
31177 +** May you do good and not evil.
31178 +** May you find forgiveness for yourself and forgive others.
31179 +** May you share freely, never taking more than you give.
31181 +*************************************************************************
31182 +** This file contains the sqlite_get_table() and sqlite_free_table()
31183 +** interface routines. These are just wrappers around the main
31184 +** interface routine of sqlite_exec().
31186 +** These routines are in a separate files so that they will not be linked
31187 +** if they are not used.
31189 +#include <stdlib.h>
31190 +#include <string.h>
31191 +#include "sqliteInt.h"
31194 +** This structure is used to pass data from sqlite_get_table() through
31195 +** to the callback function is uses to build the result.
31197 +typedef struct TabResult {
31209 +** This routine is called once for each row in the result table. Its job
31210 +** is to fill in the TabResult structure appropriately, allocating new
31211 +** memory as necessary.
31213 +static int sqlite_get_table_cb(void *pArg, int nCol, char **argv, char **colv){
31214 + TabResult *p = (TabResult*)pArg;
31219 + /* Make sure there is enough space in p->azResult to hold everything
31220 + ** we need to remember from this invocation of the callback.
31222 + if( p->nRow==0 && argv!=0 ){
31227 + if( p->nData + need >= p->nAlloc ){
31229 + p->nAlloc = p->nAlloc*2 + need + 1;
31230 + azNew = realloc( p->azResult, sizeof(char*)*p->nAlloc );
31232 + p->rc = SQLITE_NOMEM;
31235 + p->azResult = azNew;
31238 + /* If this is the first row, then generate an extra row containing
31239 + ** the names of all columns.
31241 + if( p->nRow==0 ){
31242 + p->nColumn = nCol;
31243 + for(i=0; i<nCol; i++){
31244 + if( colv[i]==0 ){
31247 + z = malloc( strlen(colv[i])+1 );
31249 + p->rc = SQLITE_NOMEM;
31252 + strcpy(z, colv[i]);
31254 + p->azResult[p->nData++] = z;
31256 + }else if( p->nColumn!=nCol ){
31257 + sqliteSetString(&p->zErrMsg,
31258 + "sqlite_get_table() called with two or more incompatible queries",
31260 + p->rc = SQLITE_ERROR;
31264 + /* Copy over the row data
31267 + for(i=0; i<nCol; i++){
31268 + if( argv[i]==0 ){
31271 + z = malloc( strlen(argv[i])+1 );
31273 + p->rc = SQLITE_NOMEM;
31276 + strcpy(z, argv[i]);
31278 + p->azResult[p->nData++] = z;
31286 +** Query the database. But instead of invoking a callback for each row,
31287 +** malloc() for space to hold the result and return the entire results
31288 +** at the conclusion of the call.
31290 +** The result that is written to ***pazResult is held in memory obtained
31291 +** from malloc(). But the caller cannot free this memory directly.
31292 +** Instead, the entire table should be passed to sqlite_free_table() when
31293 +** the calling procedure is finished using it.
31295 +int sqlite_get_table(
31296 + sqlite *db, /* The database on which the SQL executes */
31297 + const char *zSql, /* The SQL to be executed */
31298 + char ***pazResult, /* Write the result table here */
31299 + int *pnRow, /* Write the number of rows in the result here */
31300 + int *pnColumn, /* Write the number of columns of result here */
31301 + char **pzErrMsg /* Write error messages here */
31305 + if( pazResult==0 ){ return SQLITE_ERROR; }
31307 + if( pnColumn ) *pnColumn = 0;
31308 + if( pnRow ) *pnRow = 0;
31315 + res.rc = SQLITE_OK;
31316 + res.azResult = malloc( sizeof(char*)*res.nAlloc );
31317 + if( res.azResult==0 ){
31318 + return SQLITE_NOMEM;
31320 + res.azResult[0] = 0;
31321 + rc = sqlite_exec(db, zSql, sqlite_get_table_cb, &res, pzErrMsg);
31322 + if( res.azResult ){
31323 + res.azResult[0] = (char*)res.nData;
31325 + if( rc==SQLITE_ABORT ){
31326 + sqlite_free_table(&res.azResult[1]);
31327 + if( res.zErrMsg ){
31330 + *pzErrMsg = res.zErrMsg;
31331 + sqliteStrRealloc(pzErrMsg);
31333 + sqliteFree(res.zErrMsg);
31338 + sqliteFree(res.zErrMsg);
31339 + if( rc!=SQLITE_OK ){
31340 + sqlite_free_table(&res.azResult[1]);
31343 + if( res.nAlloc>res.nData ){
31345 + azNew = realloc( res.azResult, sizeof(char*)*(res.nData+1) );
31347 + sqlite_free_table(&res.azResult[1]);
31348 + return SQLITE_NOMEM;
31350 + res.nAlloc = res.nData+1;
31351 + res.azResult = azNew;
31353 + *pazResult = &res.azResult[1];
31354 + if( pnColumn ) *pnColumn = res.nColumn;
31355 + if( pnRow ) *pnRow = res.nRow;
31360 +** This routine frees the space the sqlite_get_table() malloced.
31362 +void sqlite_free_table(
31363 + char **azResult /* Result returned from from sqlite_get_table() */
31368 + if( azResult==0 ) return;
31369 + n = (int)(long)azResult[0];
31370 + for(i=1; i<n; i++){ if( azResult[i] ) free(azResult[i]); }
31375 +++ b/ext/sqlite/libsqlite/src/tokenize.c
31378 +** 2001 September 15
31380 +** The author disclaims copyright to this source code. In place of
31381 +** a legal notice, here is a blessing:
31383 +** May you do good and not evil.
31384 +** May you find forgiveness for yourself and forgive others.
31385 +** May you share freely, never taking more than you give.
31387 +*************************************************************************
31388 +** An tokenizer for SQL
31390 +** This file contains C code that splits an SQL input string up into
31391 +** individual tokens and sends those tokens one-by-one over to the
31392 +** parser for analysis.
31396 +#include "sqliteInt.h"
31398 +#include <ctype.h>
31399 +#include <stdlib.h>
31402 +** All the keywords of the SQL language are stored as in a hash
31403 +** table composed of instances of the following structure.
31405 +typedef struct Keyword Keyword;
31407 + char *zName; /* The keyword name */
31408 + u8 tokenType; /* Token value for this keyword */
31409 + u8 len; /* Length of this keyword */
31410 + u8 iNext; /* Index in aKeywordTable[] of next with same hash */
31414 +** These are the keywords
31416 +static Keyword aKeywordTable[] = {
31417 + { "ABORT", TK_ABORT, },
31418 + { "AFTER", TK_AFTER, },
31419 + { "ALL", TK_ALL, },
31420 + { "AND", TK_AND, },
31421 + { "AS", TK_AS, },
31422 + { "ASC", TK_ASC, },
31423 + { "ATTACH", TK_ATTACH, },
31424 + { "BEFORE", TK_BEFORE, },
31425 + { "BEGIN", TK_BEGIN, },
31426 + { "BETWEEN", TK_BETWEEN, },
31427 + { "BY", TK_BY, },
31428 + { "CASCADE", TK_CASCADE, },
31429 + { "CASE", TK_CASE, },
31430 + { "CHECK", TK_CHECK, },
31431 + { "CLUSTER", TK_CLUSTER, },
31432 + { "COLLATE", TK_COLLATE, },
31433 + { "COMMIT", TK_COMMIT, },
31434 + { "CONFLICT", TK_CONFLICT, },
31435 + { "CONSTRAINT", TK_CONSTRAINT, },
31436 + { "COPY", TK_COPY, },
31437 + { "CREATE", TK_CREATE, },
31438 + { "CROSS", TK_JOIN_KW, },
31439 + { "DATABASE", TK_DATABASE, },
31440 + { "DEFAULT", TK_DEFAULT, },
31441 + { "DEFERRED", TK_DEFERRED, },
31442 + { "DEFERRABLE", TK_DEFERRABLE, },
31443 + { "DELETE", TK_DELETE, },
31444 + { "DELIMITERS", TK_DELIMITERS, },
31445 + { "DESC", TK_DESC, },
31446 + { "DETACH", TK_DETACH, },
31447 + { "DISTINCT", TK_DISTINCT, },
31448 + { "DROP", TK_DROP, },
31449 + { "END", TK_END, },
31450 + { "EACH", TK_EACH, },
31451 + { "ELSE", TK_ELSE, },
31452 + { "EXCEPT", TK_EXCEPT, },
31453 + { "EXPLAIN", TK_EXPLAIN, },
31454 + { "FAIL", TK_FAIL, },
31455 + { "FOR", TK_FOR, },
31456 + { "FOREIGN", TK_FOREIGN, },
31457 + { "FROM", TK_FROM, },
31458 + { "FULL", TK_JOIN_KW, },
31459 + { "GLOB", TK_GLOB, },
31460 + { "GROUP", TK_GROUP, },
31461 + { "HAVING", TK_HAVING, },
31462 + { "IGNORE", TK_IGNORE, },
31463 + { "IMMEDIATE", TK_IMMEDIATE, },
31464 + { "IN", TK_IN, },
31465 + { "INDEX", TK_INDEX, },
31466 + { "INITIALLY", TK_INITIALLY, },
31467 + { "INNER", TK_JOIN_KW, },
31468 + { "INSERT", TK_INSERT, },
31469 + { "INSTEAD", TK_INSTEAD, },
31470 + { "INTERSECT", TK_INTERSECT, },
31471 + { "INTO", TK_INTO, },
31472 + { "IS", TK_IS, },
31473 + { "ISNULL", TK_ISNULL, },
31474 + { "JOIN", TK_JOIN, },
31475 + { "KEY", TK_KEY, },
31476 + { "LEFT", TK_JOIN_KW, },
31477 + { "LIKE", TK_LIKE, },
31478 + { "LIMIT", TK_LIMIT, },
31479 + { "MATCH", TK_MATCH, },
31480 + { "NATURAL", TK_JOIN_KW, },
31481 + { "NOT", TK_NOT, },
31482 + { "NOTNULL", TK_NOTNULL, },
31483 + { "NULL", TK_NULL, },
31484 + { "OF", TK_OF, },
31485 + { "OFFSET", TK_OFFSET, },
31486 + { "ON", TK_ON, },
31487 + { "OR", TK_OR, },
31488 + { "ORDER", TK_ORDER, },
31489 + { "OUTER", TK_JOIN_KW, },
31490 + { "PRAGMA", TK_PRAGMA, },
31491 + { "PRIMARY", TK_PRIMARY, },
31492 + { "RAISE", TK_RAISE, },
31493 + { "REFERENCES", TK_REFERENCES, },
31494 + { "REPLACE", TK_REPLACE, },
31495 + { "RESTRICT", TK_RESTRICT, },
31496 + { "RIGHT", TK_JOIN_KW, },
31497 + { "ROLLBACK", TK_ROLLBACK, },
31498 + { "ROW", TK_ROW, },
31499 + { "SELECT", TK_SELECT, },
31500 + { "SET", TK_SET, },
31501 + { "STATEMENT", TK_STATEMENT, },
31502 + { "TABLE", TK_TABLE, },
31503 + { "TEMP", TK_TEMP, },
31504 + { "TEMPORARY", TK_TEMP, },
31505 + { "THEN", TK_THEN, },
31506 + { "TRANSACTION", TK_TRANSACTION, },
31507 + { "TRIGGER", TK_TRIGGER, },
31508 + { "UNION", TK_UNION, },
31509 + { "UNIQUE", TK_UNIQUE, },
31510 + { "UPDATE", TK_UPDATE, },
31511 + { "USING", TK_USING, },
31512 + { "VACUUM", TK_VACUUM, },
31513 + { "VALUES", TK_VALUES, },
31514 + { "VIEW", TK_VIEW, },
31515 + { "WHEN", TK_WHEN, },
31516 + { "WHERE", TK_WHERE, },
31520 +** This is the hash table
31522 +#define KEY_HASH_SIZE 101
31523 +static u8 aiHashTable[KEY_HASH_SIZE];
31527 +** This function looks up an identifier to determine if it is a
31528 +** keyword. If it is a keyword, the token code of that keyword is
31529 +** returned. If the input is not a keyword, TK_ID is returned.
31531 +int sqliteKeywordCode(const char *z, int n){
31534 + static char needInit = 1;
31536 + /* Initialize the keyword hash table */
31537 + sqliteOsEnterMutex();
31540 + nk = sizeof(aKeywordTable)/sizeof(aKeywordTable[0]);
31541 + for(i=0; i<nk; i++){
31542 + aKeywordTable[i].len = strlen(aKeywordTable[i].zName);
31543 + h = sqliteHashNoCase(aKeywordTable[i].zName, aKeywordTable[i].len);
31544 + h %= KEY_HASH_SIZE;
31545 + aKeywordTable[i].iNext = aiHashTable[h];
31546 + aiHashTable[h] = i+1;
31550 + sqliteOsLeaveMutex();
31552 + h = sqliteHashNoCase(z, n) % KEY_HASH_SIZE;
31553 + for(i=aiHashTable[h]; i; i=p->iNext){
31554 + p = &aKeywordTable[i-1];
31555 + if( p->len==n && sqliteStrNICmp(p->zName, z, n)==0 ){
31556 + return p->tokenType;
31564 +** If X is a character that can be used in an identifier and
31565 +** X&0x80==0 then isIdChar[X] will be 1. If X&0x80==0x80 then
31566 +** X is always an identifier character. (Hence all UTF-8
31567 +** characters can be part of an identifier). isIdChar[X] will
31568 +** be 0 for every character in the lower 128 ASCII characters
31569 +** that cannot be used as part of an identifier.
31571 +** In this implementation, an identifier can be a string of
31572 +** alphabetic characters, digits, and "_" plus any character
31573 +** with the high-order bit set. The latter rule means that
31574 +** any sequence of UTF-8 characters or characters taken from
31575 +** an extended ISO8859 character set can form an identifier.
31577 +static const char isIdChar[] = {
31578 +/* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
31579 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x */
31580 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 1x */
31581 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 2x */
31582 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 3x */
31583 + 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 4x */
31584 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, /* 5x */
31585 + 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 6x */
31586 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, /* 7x */
31591 +** Return the length of the token that begins at z[0].
31592 +** Store the token type in *tokenType before returning.
31594 +static int sqliteGetToken(const unsigned char *z, int *tokenType){
31597 + case ' ': case '\t': case '\n': case '\f': case '\r': {
31598 + for(i=1; isspace(z[i]); i++){}
31599 + *tokenType = TK_SPACE;
31604 + for(i=2; z[i] && z[i]!='\n'; i++){}
31605 + *tokenType = TK_COMMENT;
31608 + *tokenType = TK_MINUS;
31612 + *tokenType = TK_LP;
31616 + *tokenType = TK_RP;
31620 + *tokenType = TK_SEMI;
31624 + *tokenType = TK_PLUS;
31628 + *tokenType = TK_STAR;
31632 + if( z[1]!='*' || z[2]==0 ){
31633 + *tokenType = TK_SLASH;
31636 + for(i=3; z[i] && (z[i]!='/' || z[i-1]!='*'); i++){}
31638 + *tokenType = TK_COMMENT;
31642 + *tokenType = TK_REM;
31646 + *tokenType = TK_EQ;
31647 + return 1 + (z[1]=='=');
31651 + *tokenType = TK_LE;
31653 + }else if( z[1]=='>' ){
31654 + *tokenType = TK_NE;
31656 + }else if( z[1]=='<' ){
31657 + *tokenType = TK_LSHIFT;
31660 + *tokenType = TK_LT;
31666 + *tokenType = TK_GE;
31668 + }else if( z[1]=='>' ){
31669 + *tokenType = TK_RSHIFT;
31672 + *tokenType = TK_GT;
31678 + *tokenType = TK_ILLEGAL;
31681 + *tokenType = TK_NE;
31687 + *tokenType = TK_BITOR;
31690 + *tokenType = TK_CONCAT;
31695 + *tokenType = TK_COMMA;
31699 + *tokenType = TK_BITAND;
31703 + *tokenType = TK_BITNOT;
31706 + case '\'': case '"': {
31707 + int delim = z[0];
31708 + for(i=1; z[i]; i++){
31709 + if( z[i]==delim ){
31710 + if( z[i+1]==delim ){
31718 + *tokenType = TK_STRING;
31722 + *tokenType = TK_DOT;
31725 + case '0': case '1': case '2': case '3': case '4':
31726 + case '5': case '6': case '7': case '8': case '9': {
31727 + *tokenType = TK_INTEGER;
31728 + for(i=1; isdigit(z[i]); i++){}
31729 + if( z[i]=='.' && isdigit(z[i+1]) ){
31731 + while( isdigit(z[i]) ){ i++; }
31732 + *tokenType = TK_FLOAT;
31734 + if( (z[i]=='e' || z[i]=='E') &&
31735 + ( isdigit(z[i+1])
31736 + || ((z[i+1]=='+' || z[i+1]=='-') && isdigit(z[i+2]))
31740 + while( isdigit(z[i]) ){ i++; }
31741 + *tokenType = TK_FLOAT;
31746 + for(i=1; z[i] && z[i-1]!=']'; i++){}
31747 + *tokenType = TK_ID;
31751 + *tokenType = TK_VARIABLE;
31755 + if( (*z&0x80)==0 && !isIdChar[*z] ){
31758 + for(i=1; (z[i]&0x80)!=0 || isIdChar[z[i]]; i++){}
31759 + *tokenType = sqliteKeywordCode((char*)z, i);
31763 + *tokenType = TK_ILLEGAL;
31768 +** Run the parser on the given SQL string. The parser structure is
31769 +** passed in. An SQLITE_ status code is returned. If an error occurs
31770 +** and pzErrMsg!=NULL then an error message might be written into
31771 +** memory obtained from malloc() and *pzErrMsg made to point to that
31772 +** error message. Or maybe not.
31774 +int sqliteRunParser(Parse *pParse, const char *zSql, char **pzErrMsg){
31779 + int lastTokenParsed = -1;
31780 + sqlite *db = pParse->db;
31781 + extern void *sqliteParserAlloc(void*(*)(int));
31782 + extern void sqliteParserFree(void*, void(*)(void*));
31783 + extern int sqliteParser(void*, int, Token, Parse*);
31785 + db->flags &= ~SQLITE_Interrupt;
31786 + pParse->rc = SQLITE_OK;
31788 + pEngine = sqliteParserAlloc((void*(*)(int))malloc);
31789 + if( pEngine==0 ){
31790 + sqliteSetString(pzErrMsg, "out of memory", (char*)0);
31793 + pParse->sLastToken.dyn = 0;
31794 + pParse->zTail = zSql;
31795 + while( sqlite_malloc_failed==0 && zSql[i]!=0 ){
31797 + pParse->sLastToken.z = &zSql[i];
31798 + assert( pParse->sLastToken.dyn==0 );
31799 + pParse->sLastToken.n = sqliteGetToken((unsigned char*)&zSql[i], &tokenType);
31800 + i += pParse->sLastToken.n;
31801 + switch( tokenType ){
31803 + case TK_COMMENT: {
31804 + if( (db->flags & SQLITE_Interrupt)!=0 ){
31805 + pParse->rc = SQLITE_INTERRUPT;
31806 + sqliteSetString(pzErrMsg, "interrupt", (char*)0);
31807 + goto abort_parse;
31811 + case TK_ILLEGAL: {
31812 + sqliteSetNString(pzErrMsg, "unrecognized token: \"", -1,
31813 + pParse->sLastToken.z, pParse->sLastToken.n, "\"", 1, 0);
31815 + goto abort_parse;
31818 + pParse->zTail = &zSql[i];
31819 + /* Fall thru into the default case */
31822 + sqliteParser(pEngine, tokenType, pParse->sLastToken, pParse);
31823 + lastTokenParsed = tokenType;
31824 + if( pParse->rc!=SQLITE_OK ){
31825 + goto abort_parse;
31832 + if( zSql[i]==0 && nErr==0 && pParse->rc==SQLITE_OK ){
31833 + if( lastTokenParsed!=TK_SEMI ){
31834 + sqliteParser(pEngine, TK_SEMI, pParse->sLastToken, pParse);
31835 + pParse->zTail = &zSql[i];
31837 + sqliteParser(pEngine, 0, pParse->sLastToken, pParse);
31839 + sqliteParserFree(pEngine, free);
31840 + if( pParse->rc!=SQLITE_OK && pParse->rc!=SQLITE_DONE && pParse->zErrMsg==0 ){
31841 + sqliteSetString(&pParse->zErrMsg, sqlite_error_string(pParse->rc),
31844 + if( pParse->zErrMsg ){
31845 + if( pzErrMsg && *pzErrMsg==0 ){
31846 + *pzErrMsg = pParse->zErrMsg;
31848 + sqliteFree(pParse->zErrMsg);
31850 + pParse->zErrMsg = 0;
31851 + if( !nErr ) nErr++;
31853 + if( pParse->pVdbe && pParse->nErr>0 ){
31854 + sqliteVdbeDelete(pParse->pVdbe);
31855 + pParse->pVdbe = 0;
31857 + if( pParse->pNewTable ){
31858 + sqliteDeleteTable(pParse->db, pParse->pNewTable);
31859 + pParse->pNewTable = 0;
31861 + if( pParse->pNewTrigger ){
31862 + sqliteDeleteTrigger(pParse->pNewTrigger);
31863 + pParse->pNewTrigger = 0;
31865 + if( nErr>0 && (pParse->rc==SQLITE_OK || pParse->rc==SQLITE_DONE) ){
31866 + pParse->rc = SQLITE_ERROR;
31872 +** Token types used by the sqlite_complete() routine. See the header
31873 +** comments on that procedure for additional information.
31875 +#define tkEXPLAIN 0
31876 +#define tkCREATE 1
31878 +#define tkTRIGGER 3
31885 +** Return TRUE if the given SQL string ends in a semicolon.
31887 +** Special handling is require for CREATE TRIGGER statements.
31888 +** Whenever the CREATE TRIGGER keywords are seen, the statement
31889 +** must end with ";END;".
31891 +** This implementation uses a state machine with 7 states:
31893 +** (0) START At the beginning or end of an SQL statement. This routine
31894 +** returns 1 if it ends in the START state and 0 if it ends
31895 +** in any other state.
31897 +** (1) EXPLAIN The keyword EXPLAIN has been seen at the beginning of
31900 +** (2) CREATE The keyword CREATE has been seen at the beginning of a
31901 +** statement, possibly preceeded by EXPLAIN and/or followed by
31902 +** TEMP or TEMPORARY
31904 +** (3) NORMAL We are in the middle of statement which ends with a single
31907 +** (4) TRIGGER We are in the middle of a trigger definition that must be
31908 +** ended by a semicolon, the keyword END, and another semicolon.
31910 +** (5) SEMI We've seen the first semicolon in the ";END;" that occurs at
31911 +** the end of a trigger definition.
31913 +** (6) END We've seen the ";END" of the ";END;" that occurs at the end
31914 +** of a trigger difinition.
31916 +** Transitions between states above are determined by tokens extracted
31917 +** from the input. The following tokens are significant:
31919 +** (0) tkEXPLAIN The "explain" keyword.
31920 +** (1) tkCREATE The "create" keyword.
31921 +** (2) tkTEMP The "temp" or "temporary" keyword.
31922 +** (3) tkTRIGGER The "trigger" keyword.
31923 +** (4) tkEND The "end" keyword.
31924 +** (5) tkSEMI A semicolon.
31925 +** (6) tkWS Whitespace
31926 +** (7) tkOTHER Any other SQL token.
31928 +** Whitespace never causes a state transition and is always ignored.
31930 +int sqlite_complete(const char *zSql){
31931 + u8 state = 0; /* Current state, using numbers defined in header comment */
31932 + u8 token; /* Value of the next token */
31934 + /* The following matrix defines the transition from one state to another
31935 + ** according to what token is seen. trans[state][token] returns the
31938 + static const u8 trans[7][8] = {
31940 + /* State: ** EXPLAIN CREATE TEMP TRIGGER END SEMI WS OTHER */
31941 + /* 0 START: */ { 1, 2, 3, 3, 3, 0, 0, 3, },
31942 + /* 1 EXPLAIN: */ { 3, 2, 3, 3, 3, 0, 1, 3, },
31943 + /* 2 CREATE: */ { 3, 3, 2, 4, 3, 0, 2, 3, },
31944 + /* 3 NORMAL: */ { 3, 3, 3, 3, 3, 0, 3, 3, },
31945 + /* 4 TRIGGER: */ { 4, 4, 4, 4, 4, 5, 4, 4, },
31946 + /* 5 SEMI: */ { 4, 4, 4, 4, 6, 5, 5, 4, },
31947 + /* 6 END: */ { 4, 4, 4, 4, 4, 0, 6, 4, },
31952 + case ';': { /* A semicolon */
31960 + case '\f': { /* White space is ignored */
31964 + case '/': { /* C-style comments */
31965 + if( zSql[1]!='*' ){
31970 + while( zSql[0] && (zSql[0]!='*' || zSql[1]!='/') ){ zSql++; }
31971 + if( zSql[0]==0 ) return 0;
31976 + case '-': { /* SQL-style comments from "--" to end of line */
31977 + if( zSql[1]!='-' ){
31981 + while( *zSql && *zSql!='\n' ){ zSql++; }
31982 + if( *zSql==0 ) return state==0;
31986 + case '[': { /* Microsoft-style identifiers in [...] */
31988 + while( *zSql && *zSql!=']' ){ zSql++; }
31989 + if( *zSql==0 ) return 0;
31993 + case '"': /* single- and double-quoted strings */
31997 + while( *zSql && *zSql!=c ){ zSql++; }
31998 + if( *zSql==0 ) return 0;
32003 + if( isIdChar[(u8)*zSql] ){
32004 + /* Keywords and unquoted identifiers */
32006 + for(nId=1; isIdChar[(u8)zSql[nId]]; nId++){}
32008 + case 'c': case 'C': {
32009 + if( nId==6 && sqliteStrNICmp(zSql, "create", 6)==0 ){
32010 + token = tkCREATE;
32016 + case 't': case 'T': {
32017 + if( nId==7 && sqliteStrNICmp(zSql, "trigger", 7)==0 ){
32018 + token = tkTRIGGER;
32019 + }else if( nId==4 && sqliteStrNICmp(zSql, "temp", 4)==0 ){
32021 + }else if( nId==9 && sqliteStrNICmp(zSql, "temporary", 9)==0 ){
32028 + case 'e': case 'E': {
32029 + if( nId==3 && sqliteStrNICmp(zSql, "end", 3)==0 ){
32031 + }else if( nId==7 && sqliteStrNICmp(zSql, "explain", 7)==0 ){
32032 + token = tkEXPLAIN;
32045 + /* Operators and special symbols */
32051 + state = trans[state][token];
32057 +++ b/ext/sqlite/libsqlite/src/trigger.c
32061 +** The author disclaims copyright to this source code. In place of
32062 +** a legal notice, here is a blessing:
32064 +** May you do good and not evil.
32065 +** May you find forgiveness for yourself and forgive others.
32066 +** May you share freely, never taking more than you give.
32068 +*************************************************************************
32071 +#include "sqliteInt.h"
32074 +** Delete a linked list of TriggerStep structures.
32076 +void sqliteDeleteTriggerStep(TriggerStep *pTriggerStep){
32077 + while( pTriggerStep ){
32078 + TriggerStep * pTmp = pTriggerStep;
32079 + pTriggerStep = pTriggerStep->pNext;
32081 + if( pTmp->target.dyn ) sqliteFree((char*)pTmp->target.z);
32082 + sqliteExprDelete(pTmp->pWhere);
32083 + sqliteExprListDelete(pTmp->pExprList);
32084 + sqliteSelectDelete(pTmp->pSelect);
32085 + sqliteIdListDelete(pTmp->pIdList);
32087 + sqliteFree(pTmp);
32092 +** This is called by the parser when it sees a CREATE TRIGGER statement
32093 +** up to the point of the BEGIN before the trigger actions. A Trigger
32094 +** structure is generated based on the information available and stored
32095 +** in pParse->pNewTrigger. After the trigger actions have been parsed, the
32096 +** sqliteFinishTrigger() function is called to complete the trigger
32097 +** construction process.
32099 +void sqliteBeginTrigger(
32100 + Parse *pParse, /* The parse context of the CREATE TRIGGER statement */
32101 + Token *pName, /* The name of the trigger */
32102 + int tr_tm, /* One of TK_BEFORE, TK_AFTER, TK_INSTEAD */
32103 + int op, /* One of TK_INSERT, TK_UPDATE, TK_DELETE */
32104 + IdList *pColumns, /* column list if this is an UPDATE OF trigger */
32105 + SrcList *pTableName,/* The name of the table/view the trigger applies to */
32106 + int foreach, /* One of TK_ROW or TK_STATEMENT */
32107 + Expr *pWhen, /* WHEN clause */
32108 + int isTemp /* True if the TEMPORARY keyword is present */
32112 + char *zName = 0; /* Name of the trigger */
32113 + sqlite *db = pParse->db;
32114 + int iDb; /* When database to store the trigger in */
32118 + ** 1. the trigger name does not already exist.
32119 + ** 2. the table (or view) does exist in the same database as the trigger.
32120 + ** 3. that we are not trying to create a trigger on the sqlite_master table
32121 + ** 4. That we are not trying to create an INSTEAD OF trigger on a table.
32122 + ** 5. That we are not trying to create a BEFORE or AFTER trigger on a view.
32124 + if( sqlite_malloc_failed ) goto trigger_cleanup;
32125 + assert( pTableName->nSrc==1 );
32126 + if( db->init.busy
32127 + && sqliteFixInit(&sFix, pParse, db->init.iDb, "trigger", pName)
32128 + && sqliteFixSrcList(&sFix, pTableName)
32130 + goto trigger_cleanup;
32132 + tab = sqliteSrcListLookup(pParse, pTableName);
32134 + goto trigger_cleanup;
32136 + iDb = isTemp ? 1 : tab->iDb;
32137 + if( iDb>=2 && !db->init.busy ){
32138 + sqliteErrorMsg(pParse, "triggers may not be added to auxiliary "
32139 + "database %s", db->aDb[tab->iDb].zName);
32140 + goto trigger_cleanup;
32143 + zName = sqliteStrNDup(pName->z, pName->n);
32144 + sqliteDequote(zName);
32145 + if( sqliteHashFind(&(db->aDb[iDb].trigHash), zName,pName->n+1) ){
32146 + sqliteErrorMsg(pParse, "trigger %T already exists", pName);
32147 + goto trigger_cleanup;
32149 + if( sqliteStrNICmp(tab->zName, "sqlite_", 7)==0 ){
32150 + sqliteErrorMsg(pParse, "cannot create trigger on system table");
32152 + goto trigger_cleanup;
32154 + if( tab->pSelect && tr_tm != TK_INSTEAD ){
32155 + sqliteErrorMsg(pParse, "cannot create %s trigger on view: %S",
32156 + (tr_tm == TK_BEFORE)?"BEFORE":"AFTER", pTableName, 0);
32157 + goto trigger_cleanup;
32159 + if( !tab->pSelect && tr_tm == TK_INSTEAD ){
32160 + sqliteErrorMsg(pParse, "cannot create INSTEAD OF"
32161 + " trigger on table: %S", pTableName, 0);
32162 + goto trigger_cleanup;
32164 +#ifndef SQLITE_OMIT_AUTHORIZATION
32166 + int code = SQLITE_CREATE_TRIGGER;
32167 + const char *zDb = db->aDb[tab->iDb].zName;
32168 + const char *zDbTrig = isTemp ? db->aDb[1].zName : zDb;
32169 + if( tab->iDb==1 || isTemp ) code = SQLITE_CREATE_TEMP_TRIGGER;
32170 + if( sqliteAuthCheck(pParse, code, zName, tab->zName, zDbTrig) ){
32171 + goto trigger_cleanup;
32173 + if( sqliteAuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(tab->iDb), 0, zDb)){
32174 + goto trigger_cleanup;
32179 + /* INSTEAD OF triggers can only appear on views and BEGIN triggers
32180 + ** cannot appear on views. So we might as well translate every
32181 + ** INSTEAD OF trigger into a BEFORE trigger. It simplifies code
32184 + if (tr_tm == TK_INSTEAD){
32185 + tr_tm = TK_BEFORE;
32188 + /* Build the Trigger object */
32189 + nt = (Trigger*)sqliteMalloc(sizeof(Trigger));
32190 + if( nt==0 ) goto trigger_cleanup;
32191 + nt->name = zName;
32193 + nt->table = sqliteStrDup(pTableName->a[0].zName);
32194 + if( sqlite_malloc_failed ) goto trigger_cleanup;
32196 + nt->iTabDb = tab->iDb;
32198 + nt->tr_tm = tr_tm;
32199 + nt->pWhen = sqliteExprDup(pWhen);
32200 + nt->pColumns = sqliteIdListDup(pColumns);
32201 + nt->foreach = foreach;
32202 + sqliteTokenCopy(&nt->nameToken,pName);
32203 + assert( pParse->pNewTrigger==0 );
32204 + pParse->pNewTrigger = nt;
32207 + sqliteFree(zName);
32208 + sqliteSrcListDelete(pTableName);
32209 + sqliteIdListDelete(pColumns);
32210 + sqliteExprDelete(pWhen);
32214 +** This routine is called after all of the trigger actions have been parsed
32215 +** in order to complete the process of building the trigger.
32217 +void sqliteFinishTrigger(
32218 + Parse *pParse, /* Parser context */
32219 + TriggerStep *pStepList, /* The triggered program */
32220 + Token *pAll /* Token that describes the complete CREATE TRIGGER */
32222 + Trigger *nt = 0; /* The trigger whose construction is finishing up */
32223 + sqlite *db = pParse->db; /* The database */
32226 + if( pParse->nErr || pParse->pNewTrigger==0 ) goto triggerfinish_cleanup;
32227 + nt = pParse->pNewTrigger;
32228 + pParse->pNewTrigger = 0;
32229 + nt->step_list = pStepList;
32230 + while( pStepList ){
32231 + pStepList->pTrig = nt;
32232 + pStepList = pStepList->pNext;
32234 + if( sqliteFixInit(&sFix, pParse, nt->iDb, "trigger", &nt->nameToken)
32235 + && sqliteFixTriggerStep(&sFix, nt->step_list) ){
32236 + goto triggerfinish_cleanup;
32239 + /* if we are not initializing, and this trigger is not on a TEMP table,
32240 + ** build the sqlite_master entry
32242 + if( !db->init.busy ){
32243 + static VdbeOpList insertTrig[] = {
32244 + { OP_NewRecno, 0, 0, 0 },
32245 + { OP_String, 0, 0, "trigger" },
32246 + { OP_String, 0, 0, 0 }, /* 2: trigger name */
32247 + { OP_String, 0, 0, 0 }, /* 3: table name */
32248 + { OP_Integer, 0, 0, 0 },
32249 + { OP_String, 0, 0, 0 }, /* 5: SQL */
32250 + { OP_MakeRecord, 5, 0, 0 },
32251 + { OP_PutIntKey, 0, 0, 0 },
32256 + /* Make an entry in the sqlite_master table */
32257 + v = sqliteGetVdbe(pParse);
32258 + if( v==0 ) goto triggerfinish_cleanup;
32259 + sqliteBeginWriteOperation(pParse, 0, 0);
32260 + sqliteOpenMasterTable(v, nt->iDb);
32261 + addr = sqliteVdbeAddOpList(v, ArraySize(insertTrig), insertTrig);
32262 + sqliteVdbeChangeP3(v, addr+2, nt->name, 0);
32263 + sqliteVdbeChangeP3(v, addr+3, nt->table, 0);
32264 + sqliteVdbeChangeP3(v, addr+5, pAll->z, pAll->n);
32265 + if( nt->iDb==0 ){
32266 + sqliteChangeCookie(db, v);
32268 + sqliteVdbeAddOp(v, OP_Close, 0, 0);
32269 + sqliteEndWriteOperation(pParse);
32272 + if( !pParse->explain ){
32274 + sqliteHashInsert(&db->aDb[nt->iDb].trigHash,
32275 + nt->name, strlen(nt->name)+1, nt);
32276 + pTab = sqliteLocateTable(pParse, nt->table, db->aDb[nt->iTabDb].zName);
32277 + assert( pTab!=0 );
32278 + nt->pNext = pTab->pTrigger;
32279 + pTab->pTrigger = nt;
32283 +triggerfinish_cleanup:
32284 + sqliteDeleteTrigger(nt);
32285 + sqliteDeleteTrigger(pParse->pNewTrigger);
32286 + pParse->pNewTrigger = 0;
32287 + sqliteDeleteTriggerStep(pStepList);
32291 +** Make a copy of all components of the given trigger step. This has
32292 +** the effect of copying all Expr.token.z values into memory obtained
32293 +** from sqliteMalloc(). As initially created, the Expr.token.z values
32294 +** all point to the input string that was fed to the parser. But that
32295 +** string is ephemeral - it will go away as soon as the sqlite_exec()
32296 +** call that started the parser exits. This routine makes a persistent
32297 +** copy of all the Expr.token.z strings so that the TriggerStep structure
32298 +** will be valid even after the sqlite_exec() call returns.
32300 +static void sqlitePersistTriggerStep(TriggerStep *p){
32301 + if( p->target.z ){
32302 + p->target.z = sqliteStrNDup(p->target.z, p->target.n);
32303 + p->target.dyn = 1;
32305 + if( p->pSelect ){
32306 + Select *pNew = sqliteSelectDup(p->pSelect);
32307 + sqliteSelectDelete(p->pSelect);
32308 + p->pSelect = pNew;
32311 + Expr *pNew = sqliteExprDup(p->pWhere);
32312 + sqliteExprDelete(p->pWhere);
32313 + p->pWhere = pNew;
32315 + if( p->pExprList ){
32316 + ExprList *pNew = sqliteExprListDup(p->pExprList);
32317 + sqliteExprListDelete(p->pExprList);
32318 + p->pExprList = pNew;
32320 + if( p->pIdList ){
32321 + IdList *pNew = sqliteIdListDup(p->pIdList);
32322 + sqliteIdListDelete(p->pIdList);
32323 + p->pIdList = pNew;
32328 +** Turn a SELECT statement (that the pSelect parameter points to) into
32329 +** a trigger step. Return a pointer to a TriggerStep structure.
32331 +** The parser calls this routine when it finds a SELECT statement in
32332 +** body of a TRIGGER.
32334 +TriggerStep *sqliteTriggerSelectStep(Select *pSelect){
32335 + TriggerStep *pTriggerStep = sqliteMalloc(sizeof(TriggerStep));
32336 + if( pTriggerStep==0 ) return 0;
32338 + pTriggerStep->op = TK_SELECT;
32339 + pTriggerStep->pSelect = pSelect;
32340 + pTriggerStep->orconf = OE_Default;
32341 + sqlitePersistTriggerStep(pTriggerStep);
32343 + return pTriggerStep;
32347 +** Build a trigger step out of an INSERT statement. Return a pointer
32348 +** to the new trigger step.
32350 +** The parser calls this routine when it sees an INSERT inside the
32351 +** body of a trigger.
32353 +TriggerStep *sqliteTriggerInsertStep(
32354 + Token *pTableName, /* Name of the table into which we insert */
32355 + IdList *pColumn, /* List of columns in pTableName to insert into */
32356 + ExprList *pEList, /* The VALUE clause: a list of values to be inserted */
32357 + Select *pSelect, /* A SELECT statement that supplies values */
32358 + int orconf /* The conflict algorithm (OE_Abort, OE_Replace, etc.) */
32360 + TriggerStep *pTriggerStep = sqliteMalloc(sizeof(TriggerStep));
32361 + if( pTriggerStep==0 ) return 0;
32363 + assert(pEList == 0 || pSelect == 0);
32364 + assert(pEList != 0 || pSelect != 0);
32366 + pTriggerStep->op = TK_INSERT;
32367 + pTriggerStep->pSelect = pSelect;
32368 + pTriggerStep->target = *pTableName;
32369 + pTriggerStep->pIdList = pColumn;
32370 + pTriggerStep->pExprList = pEList;
32371 + pTriggerStep->orconf = orconf;
32372 + sqlitePersistTriggerStep(pTriggerStep);
32374 + return pTriggerStep;
32378 +** Construct a trigger step that implements an UPDATE statement and return
32379 +** a pointer to that trigger step. The parser calls this routine when it
32380 +** sees an UPDATE statement inside the body of a CREATE TRIGGER.
32382 +TriggerStep *sqliteTriggerUpdateStep(
32383 + Token *pTableName, /* Name of the table to be updated */
32384 + ExprList *pEList, /* The SET clause: list of column and new values */
32385 + Expr *pWhere, /* The WHERE clause */
32386 + int orconf /* The conflict algorithm. (OE_Abort, OE_Ignore, etc) */
32388 + TriggerStep *pTriggerStep = sqliteMalloc(sizeof(TriggerStep));
32389 + if( pTriggerStep==0 ) return 0;
32391 + pTriggerStep->op = TK_UPDATE;
32392 + pTriggerStep->target = *pTableName;
32393 + pTriggerStep->pExprList = pEList;
32394 + pTriggerStep->pWhere = pWhere;
32395 + pTriggerStep->orconf = orconf;
32396 + sqlitePersistTriggerStep(pTriggerStep);
32398 + return pTriggerStep;
32402 +** Construct a trigger step that implements a DELETE statement and return
32403 +** a pointer to that trigger step. The parser calls this routine when it
32404 +** sees a DELETE statement inside the body of a CREATE TRIGGER.
32406 +TriggerStep *sqliteTriggerDeleteStep(Token *pTableName, Expr *pWhere){
32407 + TriggerStep *pTriggerStep = sqliteMalloc(sizeof(TriggerStep));
32408 + if( pTriggerStep==0 ) return 0;
32410 + pTriggerStep->op = TK_DELETE;
32411 + pTriggerStep->target = *pTableName;
32412 + pTriggerStep->pWhere = pWhere;
32413 + pTriggerStep->orconf = OE_Default;
32414 + sqlitePersistTriggerStep(pTriggerStep);
32416 + return pTriggerStep;
32420 +** Recursively delete a Trigger structure
32422 +void sqliteDeleteTrigger(Trigger *pTrigger){
32423 + if( pTrigger==0 ) return;
32424 + sqliteDeleteTriggerStep(pTrigger->step_list);
32425 + sqliteFree(pTrigger->name);
32426 + sqliteFree(pTrigger->table);
32427 + sqliteExprDelete(pTrigger->pWhen);
32428 + sqliteIdListDelete(pTrigger->pColumns);
32429 + if( pTrigger->nameToken.dyn ) sqliteFree((char*)pTrigger->nameToken.z);
32430 + sqliteFree(pTrigger);
32434 + * This function is called to drop a trigger from the database schema.
32436 + * This may be called directly from the parser and therefore identifies
32437 + * the trigger by name. The sqliteDropTriggerPtr() routine does the
32438 + * same job as this routine except it take a spointer to the trigger
32439 + * instead of the trigger name.
32441 + * Note that this function does not delete the trigger entirely. Instead it
32442 + * removes it from the internal schema and places it in the trigDrop hash
32443 + * table. This is so that the trigger can be restored into the database schema
32444 + * if the transaction is rolled back.
32446 +void sqliteDropTrigger(Parse *pParse, SrcList *pName){
32447 + Trigger *pTrigger;
32450 + const char *zName;
32452 + sqlite *db = pParse->db;
32454 + if( sqlite_malloc_failed ) goto drop_trigger_cleanup;
32455 + assert( pName->nSrc==1 );
32456 + zDb = pName->a[0].zDatabase;
32457 + zName = pName->a[0].zName;
32458 + nName = strlen(zName);
32459 + for(i=0; i<db->nDb; i++){
32460 + int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
32461 + if( zDb && sqliteStrICmp(db->aDb[j].zName, zDb) ) continue;
32462 + pTrigger = sqliteHashFind(&(db->aDb[j].trigHash), zName, nName+1);
32463 + if( pTrigger ) break;
32466 + sqliteErrorMsg(pParse, "no such trigger: %S", pName, 0);
32467 + goto drop_trigger_cleanup;
32469 + sqliteDropTriggerPtr(pParse, pTrigger, 0);
32471 +drop_trigger_cleanup:
32472 + sqliteSrcListDelete(pName);
32476 +** Drop a trigger given a pointer to that trigger. If nested is false,
32477 +** then also generate code to remove the trigger from the SQLITE_MASTER
32480 +void sqliteDropTriggerPtr(Parse *pParse, Trigger *pTrigger, int nested){
32483 + sqlite *db = pParse->db;
32485 + assert( pTrigger->iDb<db->nDb );
32486 + if( pTrigger->iDb>=2 ){
32487 + sqliteErrorMsg(pParse, "triggers may not be removed from "
32488 + "auxiliary database %s", db->aDb[pTrigger->iDb].zName);
32491 + pTable = sqliteFindTable(db, pTrigger->table,db->aDb[pTrigger->iTabDb].zName);
32493 + assert( pTable->iDb==pTrigger->iDb || pTrigger->iDb==1 );
32494 +#ifndef SQLITE_OMIT_AUTHORIZATION
32496 + int code = SQLITE_DROP_TRIGGER;
32497 + const char *zDb = db->aDb[pTrigger->iDb].zName;
32498 + const char *zTab = SCHEMA_TABLE(pTrigger->iDb);
32499 + if( pTrigger->iDb ) code = SQLITE_DROP_TEMP_TRIGGER;
32500 + if( sqliteAuthCheck(pParse, code, pTrigger->name, pTable->zName, zDb) ||
32501 + sqliteAuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
32507 + /* Generate code to destroy the database record of the trigger.
32509 + if( pTable!=0 && !nested && (v = sqliteGetVdbe(pParse))!=0 ){
32511 + static VdbeOpList dropTrigger[] = {
32512 + { OP_Rewind, 0, ADDR(9), 0},
32513 + { OP_String, 0, 0, 0}, /* 1 */
32514 + { OP_Column, 0, 1, 0},
32515 + { OP_Ne, 0, ADDR(8), 0},
32516 + { OP_String, 0, 0, "trigger"},
32517 + { OP_Column, 0, 0, 0},
32518 + { OP_Ne, 0, ADDR(8), 0},
32519 + { OP_Delete, 0, 0, 0},
32520 + { OP_Next, 0, ADDR(1), 0}, /* 8 */
32523 + sqliteBeginWriteOperation(pParse, 0, 0);
32524 + sqliteOpenMasterTable(v, pTrigger->iDb);
32525 + base = sqliteVdbeAddOpList(v, ArraySize(dropTrigger), dropTrigger);
32526 + sqliteVdbeChangeP3(v, base+1, pTrigger->name, 0);
32527 + if( pTrigger->iDb==0 ){
32528 + sqliteChangeCookie(db, v);
32530 + sqliteVdbeAddOp(v, OP_Close, 0, 0);
32531 + sqliteEndWriteOperation(pParse);
32535 + * If this is not an "explain", then delete the trigger structure.
32537 + if( !pParse->explain ){
32538 + const char *zName = pTrigger->name;
32539 + int nName = strlen(zName);
32540 + if( pTable->pTrigger == pTrigger ){
32541 + pTable->pTrigger = pTrigger->pNext;
32543 + Trigger *cc = pTable->pTrigger;
32545 + if( cc->pNext == pTrigger ){
32546 + cc->pNext = cc->pNext->pNext;
32553 + sqliteHashInsert(&(db->aDb[pTrigger->iDb].trigHash), zName, nName+1, 0);
32554 + sqliteDeleteTrigger(pTrigger);
32559 +** pEList is the SET clause of an UPDATE statement. Each entry
32560 +** in pEList is of the format <id>=<expr>. If any of the entries
32561 +** in pEList have an <id> which matches an identifier in pIdList,
32562 +** then return TRUE. If pIdList==NULL, then it is considered a
32563 +** wildcard that matches anything. Likewise if pEList==NULL then
32564 +** it matches anything so always return true. Return false only
32565 +** if there is no match.
32567 +static int checkColumnOverLap(IdList *pIdList, ExprList *pEList){
32569 + if( !pIdList || !pEList ) return 1;
32570 + for(e=0; e<pEList->nExpr; e++){
32571 + if( sqliteIdListIndex(pIdList, pEList->a[e].zName)>=0 ) return 1;
32576 +/* A global variable that is TRUE if we should always set up temp tables for
32577 + * for triggers, even if there are no triggers to code. This is used to test
32578 + * how much overhead the triggers algorithm is causing.
32580 + * This flag can be set or cleared using the "trigger_overhead_test" pragma.
32581 + * The pragma is not documented since it is not really part of the interface
32582 + * to SQLite, just the test procedure.
32584 +int always_code_trigger_setup = 0;
32587 + * Returns true if a trigger matching op, tr_tm and foreach that is NOT already
32588 + * on the Parse objects trigger-stack (to prevent recursive trigger firing) is
32589 + * found in the list specified as pTrigger.
32591 +int sqliteTriggersExist(
32592 + Parse *pParse, /* Used to check for recursive triggers */
32593 + Trigger *pTrigger, /* A list of triggers associated with a table */
32594 + int op, /* one of TK_DELETE, TK_INSERT, TK_UPDATE */
32595 + int tr_tm, /* one of TK_BEFORE, TK_AFTER */
32596 + int foreach, /* one of TK_ROW or TK_STATEMENT */
32597 + ExprList *pChanges /* Columns that change in an UPDATE statement */
32599 + Trigger * pTriggerCursor;
32601 + if( always_code_trigger_setup ){
32605 + pTriggerCursor = pTrigger;
32606 + while( pTriggerCursor ){
32607 + if( pTriggerCursor->op == op &&
32608 + pTriggerCursor->tr_tm == tr_tm &&
32609 + pTriggerCursor->foreach == foreach &&
32610 + checkColumnOverLap(pTriggerCursor->pColumns, pChanges) ){
32611 + TriggerStack * ss;
32612 + ss = pParse->trigStack;
32613 + while( ss && ss->pTrigger != pTrigger ){
32616 + if( !ss )return 1;
32618 + pTriggerCursor = pTriggerCursor->pNext;
32625 +** Convert the pStep->target token into a SrcList and return a pointer
32626 +** to that SrcList.
32628 +** This routine adds a specific database name, if needed, to the target when
32629 +** forming the SrcList. This prevents a trigger in one database from
32630 +** referring to a target in another database. An exception is when the
32631 +** trigger is in TEMP in which case it can refer to any other database it
32634 +static SrcList *targetSrcList(
32635 + Parse *pParse, /* The parsing context */
32636 + TriggerStep *pStep /* The trigger containing the target token */
32638 + Token sDb; /* Dummy database name token */
32639 + int iDb; /* Index of the database to use */
32640 + SrcList *pSrc; /* SrcList to be returned */
32642 + iDb = pStep->pTrig->iDb;
32643 + if( iDb==0 || iDb>=2 ){
32644 + assert( iDb<pParse->db->nDb );
32645 + sDb.z = pParse->db->aDb[iDb].zName;
32646 + sDb.n = strlen(sDb.z);
32647 + pSrc = sqliteSrcListAppend(0, &sDb, &pStep->target);
32649 + pSrc = sqliteSrcListAppend(0, &pStep->target, 0);
32655 +** Generate VDBE code for zero or more statements inside the body of a
32658 +static int codeTriggerProgram(
32659 + Parse *pParse, /* The parser context */
32660 + TriggerStep *pStepList, /* List of statements inside the trigger body */
32661 + int orconfin /* Conflict algorithm. (OE_Abort, etc) */
32663 + TriggerStep * pTriggerStep = pStepList;
32666 + while( pTriggerStep ){
32667 + int saveNTab = pParse->nTab;
32669 + orconf = (orconfin == OE_Default)?pTriggerStep->orconf:orconfin;
32670 + pParse->trigStack->orconf = orconf;
32671 + switch( pTriggerStep->op ){
32672 + case TK_SELECT: {
32673 + Select * ss = sqliteSelectDup(pTriggerStep->pSelect);
32675 + assert(ss->pSrc);
32676 + sqliteSelect(pParse, ss, SRT_Discard, 0, 0, 0, 0);
32677 + sqliteSelectDelete(ss);
32680 + case TK_UPDATE: {
32682 + pSrc = targetSrcList(pParse, pTriggerStep);
32683 + sqliteVdbeAddOp(pParse->pVdbe, OP_ListPush, 0, 0);
32684 + sqliteUpdate(pParse, pSrc,
32685 + sqliteExprListDup(pTriggerStep->pExprList),
32686 + sqliteExprDup(pTriggerStep->pWhere), orconf);
32687 + sqliteVdbeAddOp(pParse->pVdbe, OP_ListPop, 0, 0);
32690 + case TK_INSERT: {
32692 + pSrc = targetSrcList(pParse, pTriggerStep);
32693 + sqliteInsert(pParse, pSrc,
32694 + sqliteExprListDup(pTriggerStep->pExprList),
32695 + sqliteSelectDup(pTriggerStep->pSelect),
32696 + sqliteIdListDup(pTriggerStep->pIdList), orconf);
32699 + case TK_DELETE: {
32701 + sqliteVdbeAddOp(pParse->pVdbe, OP_ListPush, 0, 0);
32702 + pSrc = targetSrcList(pParse, pTriggerStep);
32703 + sqliteDeleteFrom(pParse, pSrc, sqliteExprDup(pTriggerStep->pWhere));
32704 + sqliteVdbeAddOp(pParse->pVdbe, OP_ListPop, 0, 0);
32710 + pParse->nTab = saveNTab;
32711 + pTriggerStep = pTriggerStep->pNext;
32718 +** This is called to code FOR EACH ROW triggers.
32720 +** When the code that this function generates is executed, the following
32723 +** 1. No cursors may be open in the main database. (But newIdx and oldIdx
32724 +** can be indices of cursors in temporary tables. See below.)
32726 +** 2. If the triggers being coded are ON INSERT or ON UPDATE triggers, then
32727 +** a temporary vdbe cursor (index newIdx) must be open and pointing at
32728 +** a row containing values to be substituted for new.* expressions in the
32729 +** trigger program(s).
32731 +** 3. If the triggers being coded are ON DELETE or ON UPDATE triggers, then
32732 +** a temporary vdbe cursor (index oldIdx) must be open and pointing at
32733 +** a row containing values to be substituted for old.* expressions in the
32734 +** trigger program(s).
32737 +int sqliteCodeRowTrigger(
32738 + Parse *pParse, /* Parse context */
32739 + int op, /* One of TK_UPDATE, TK_INSERT, TK_DELETE */
32740 + ExprList *pChanges, /* Changes list for any UPDATE OF triggers */
32741 + int tr_tm, /* One of TK_BEFORE, TK_AFTER */
32742 + Table *pTab, /* The table to code triggers from */
32743 + int newIdx, /* The indice of the "new" row to access */
32744 + int oldIdx, /* The indice of the "old" row to access */
32745 + int orconf, /* ON CONFLICT policy */
32746 + int ignoreJump /* Instruction to jump to for RAISE(IGNORE) */
32748 + Trigger * pTrigger;
32749 + TriggerStack * pTriggerStack;
32751 + assert(op == TK_UPDATE || op == TK_INSERT || op == TK_DELETE);
32752 + assert(tr_tm == TK_BEFORE || tr_tm == TK_AFTER );
32754 + assert(newIdx != -1 || oldIdx != -1);
32756 + pTrigger = pTab->pTrigger;
32757 + while( pTrigger ){
32758 + int fire_this = 0;
32760 + /* determine whether we should code this trigger */
32761 + if( pTrigger->op == op && pTrigger->tr_tm == tr_tm &&
32762 + pTrigger->foreach == TK_ROW ){
32764 + pTriggerStack = pParse->trigStack;
32765 + while( pTriggerStack ){
32766 + if( pTriggerStack->pTrigger == pTrigger ){
32769 + pTriggerStack = pTriggerStack->pNext;
32771 + if( op == TK_UPDATE && pTrigger->pColumns &&
32772 + !checkColumnOverLap(pTrigger->pColumns, pChanges) ){
32777 + if( fire_this && (pTriggerStack = sqliteMalloc(sizeof(TriggerStack)))!=0 ){
32779 + SrcList dummyTablist;
32781 + AuthContext sContext;
32783 + dummyTablist.nSrc = 0;
32785 + /* Push an entry on to the trigger stack */
32786 + pTriggerStack->pTrigger = pTrigger;
32787 + pTriggerStack->newIdx = newIdx;
32788 + pTriggerStack->oldIdx = oldIdx;
32789 + pTriggerStack->pTab = pTab;
32790 + pTriggerStack->pNext = pParse->trigStack;
32791 + pTriggerStack->ignoreJump = ignoreJump;
32792 + pParse->trigStack = pTriggerStack;
32793 + sqliteAuthContextPush(pParse, &sContext, pTrigger->name);
32795 + /* code the WHEN clause */
32796 + endTrigger = sqliteVdbeMakeLabel(pParse->pVdbe);
32797 + whenExpr = sqliteExprDup(pTrigger->pWhen);
32798 + if( sqliteExprResolveIds(pParse, &dummyTablist, 0, whenExpr) ){
32799 + pParse->trigStack = pParse->trigStack->pNext;
32800 + sqliteFree(pTriggerStack);
32801 + sqliteExprDelete(whenExpr);
32804 + sqliteExprIfFalse(pParse, whenExpr, endTrigger, 1);
32805 + sqliteExprDelete(whenExpr);
32807 + sqliteVdbeAddOp(pParse->pVdbe, OP_ContextPush, 0, 0);
32808 + codeTriggerProgram(pParse, pTrigger->step_list, orconf);
32809 + sqliteVdbeAddOp(pParse->pVdbe, OP_ContextPop, 0, 0);
32811 + /* Pop the entry off the trigger stack */
32812 + pParse->trigStack = pParse->trigStack->pNext;
32813 + sqliteAuthContextPop(&sContext);
32814 + sqliteFree(pTriggerStack);
32816 + sqliteVdbeResolveLabel(pParse->pVdbe, endTrigger);
32818 + pTrigger = pTrigger->pNext;
32824 +++ b/ext/sqlite/libsqlite/src/update.c
32827 +** 2001 September 15
32829 +** The author disclaims copyright to this source code. In place of
32830 +** a legal notice, here is a blessing:
32832 +** May you do good and not evil.
32833 +** May you find forgiveness for yourself and forgive others.
32834 +** May you share freely, never taking more than you give.
32836 +*************************************************************************
32837 +** This file contains C code routines that are called by the parser
32838 +** to handle UPDATE statements.
32842 +#include "sqliteInt.h"
32845 +** Process an UPDATE statement.
32847 +** UPDATE OR IGNORE table_wxyz SET a=b, c=d WHERE e<5 AND f NOT NULL;
32848 +** \_______/ \________/ \______/ \________________/
32849 +* onError pTabList pChanges pWhere
32851 +void sqliteUpdate(
32852 + Parse *pParse, /* The parser context */
32853 + SrcList *pTabList, /* The table in which we should change things */
32854 + ExprList *pChanges, /* Things to be changed */
32855 + Expr *pWhere, /* The WHERE clause. May be null */
32856 + int onError /* How to handle constraint errors */
32858 + int i, j; /* Loop counters */
32859 + Table *pTab; /* The table to be updated */
32860 + int loopStart; /* VDBE instruction address of the start of the loop */
32861 + int jumpInst; /* Addr of VDBE instruction to jump out of loop */
32862 + WhereInfo *pWInfo; /* Information about the WHERE clause */
32863 + Vdbe *v; /* The virtual database engine */
32864 + Index *pIdx; /* For looping over indices */
32865 + int nIdx; /* Number of indices that need updating */
32866 + int nIdxTotal; /* Total number of indices */
32867 + int iCur; /* VDBE Cursor number of pTab */
32868 + sqlite *db; /* The database structure */
32869 + Index **apIdx = 0; /* An array of indices that need updating too */
32870 + char *aIdxUsed = 0; /* aIdxUsed[i]==1 if the i-th index is used */
32871 + int *aXRef = 0; /* aXRef[i] is the index in pChanges->a[] of the
32872 + ** an expression for the i-th column of the table.
32873 + ** aXRef[i]==-1 if the i-th column is not changed. */
32874 + int chngRecno; /* True if the record number is being changed */
32875 + Expr *pRecnoExpr; /* Expression defining the new record number */
32876 + int openAll; /* True if all indices need to be opened */
32877 + int isView; /* Trying to update a view */
32878 + int iStackDepth; /* Index of memory cell holding stack depth */
32879 + AuthContext sContext; /* The authorization context */
32881 + int before_triggers; /* True if there are any BEFORE triggers */
32882 + int after_triggers; /* True if there are any AFTER triggers */
32883 + int row_triggers_exist = 0; /* True if any row triggers exist */
32885 + int newIdx = -1; /* index of trigger "new" temp table */
32886 + int oldIdx = -1; /* index of trigger "old" temp table */
32888 + sContext.pParse = 0;
32889 + if( pParse->nErr || sqlite_malloc_failed ) goto update_cleanup;
32891 + assert( pTabList->nSrc==1 );
32892 + iStackDepth = pParse->nMem++;
32894 + /* Locate the table which we want to update.
32896 + pTab = sqliteSrcListLookup(pParse, pTabList);
32897 + if( pTab==0 ) goto update_cleanup;
32898 + before_triggers = sqliteTriggersExist(pParse, pTab->pTrigger,
32899 + TK_UPDATE, TK_BEFORE, TK_ROW, pChanges);
32900 + after_triggers = sqliteTriggersExist(pParse, pTab->pTrigger,
32901 + TK_UPDATE, TK_AFTER, TK_ROW, pChanges);
32902 + row_triggers_exist = before_triggers || after_triggers;
32903 + isView = pTab->pSelect!=0;
32904 + if( sqliteIsReadOnly(pParse, pTab, before_triggers) ){
32905 + goto update_cleanup;
32908 + if( sqliteViewGetColumnNames(pParse, pTab) ){
32909 + goto update_cleanup;
32912 + aXRef = sqliteMalloc( sizeof(int) * pTab->nCol );
32913 + if( aXRef==0 ) goto update_cleanup;
32914 + for(i=0; i<pTab->nCol; i++) aXRef[i] = -1;
32916 + /* If there are FOR EACH ROW triggers, allocate cursors for the
32917 + ** special OLD and NEW tables
32919 + if( row_triggers_exist ){
32920 + newIdx = pParse->nTab++;
32921 + oldIdx = pParse->nTab++;
32924 + /* Allocate a cursors for the main database table and for all indices.
32925 + ** The index cursors might not be used, but if they are used they
32926 + ** need to occur right after the database cursor. So go ahead and
32927 + ** allocate enough space, just in case.
32929 + pTabList->a[0].iCursor = iCur = pParse->nTab++;
32930 + for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
32934 + /* Resolve the column names in all the expressions of the
32935 + ** of the UPDATE statement. Also find the column index
32936 + ** for each column to be updated in the pChanges array. For each
32937 + ** column to be updated, make sure we have authorization to change
32941 + for(i=0; i<pChanges->nExpr; i++){
32942 + if( sqliteExprResolveIds(pParse, pTabList, 0, pChanges->a[i].pExpr) ){
32943 + goto update_cleanup;
32945 + if( sqliteExprCheck(pParse, pChanges->a[i].pExpr, 0, 0) ){
32946 + goto update_cleanup;
32948 + for(j=0; j<pTab->nCol; j++){
32949 + if( sqliteStrICmp(pTab->aCol[j].zName, pChanges->a[i].zName)==0 ){
32950 + if( j==pTab->iPKey ){
32952 + pRecnoExpr = pChanges->a[i].pExpr;
32958 + if( j>=pTab->nCol ){
32959 + if( sqliteIsRowid(pChanges->a[i].zName) ){
32961 + pRecnoExpr = pChanges->a[i].pExpr;
32963 + sqliteErrorMsg(pParse, "no such column: %s", pChanges->a[i].zName);
32964 + goto update_cleanup;
32967 +#ifndef SQLITE_OMIT_AUTHORIZATION
32970 + rc = sqliteAuthCheck(pParse, SQLITE_UPDATE, pTab->zName,
32971 + pTab->aCol[j].zName, db->aDb[pTab->iDb].zName);
32972 + if( rc==SQLITE_DENY ){
32973 + goto update_cleanup;
32974 + }else if( rc==SQLITE_IGNORE ){
32981 + /* Allocate memory for the array apIdx[] and fill it with pointers to every
32982 + ** index that needs to be updated. Indices only need updating if their
32983 + ** key includes one of the columns named in pChanges or if the record
32984 + ** number of the original table entry is changing.
32986 + for(nIdx=nIdxTotal=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdxTotal++){
32990 + for(i=0; i<pIdx->nColumn; i++){
32991 + if( aXRef[pIdx->aiColumn[i]]>=0 ) break;
32994 + if( i<pIdx->nColumn ) nIdx++;
32996 + if( nIdxTotal>0 ){
32997 + apIdx = sqliteMalloc( sizeof(Index*) * nIdx + nIdxTotal );
32998 + if( apIdx==0 ) goto update_cleanup;
32999 + aIdxUsed = (char*)&apIdx[nIdx];
33001 + for(nIdx=j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
33005 + for(i=0; i<pIdx->nColumn; i++){
33006 + if( aXRef[pIdx->aiColumn[i]]>=0 ) break;
33009 + if( i<pIdx->nColumn ){
33010 + apIdx[nIdx++] = pIdx;
33017 + /* Resolve the column names in all the expressions in the
33021 + if( sqliteExprResolveIds(pParse, pTabList, 0, pWhere) ){
33022 + goto update_cleanup;
33024 + if( sqliteExprCheck(pParse, pWhere, 0, 0) ){
33025 + goto update_cleanup;
33029 + /* Start the view context
33032 + sqliteAuthContextPush(pParse, &sContext, pTab->zName);
33035 + /* Begin generating code.
33037 + v = sqliteGetVdbe(pParse);
33038 + if( v==0 ) goto update_cleanup;
33039 + sqliteBeginWriteOperation(pParse, 1, pTab->iDb);
33041 + /* If we are trying to update a view, construct that view into
33042 + ** a temporary table.
33046 + pView = sqliteSelectDup(pTab->pSelect);
33047 + sqliteSelect(pParse, pView, SRT_TempTable, iCur, 0, 0, 0);
33048 + sqliteSelectDelete(pView);
33051 + /* Begin the database scan
33053 + pWInfo = sqliteWhereBegin(pParse, pTabList, pWhere, 1, 0);
33054 + if( pWInfo==0 ) goto update_cleanup;
33056 + /* Remember the index of every item to be updated.
33058 + sqliteVdbeAddOp(v, OP_ListWrite, 0, 0);
33060 + /* End the database scan loop.
33062 + sqliteWhereEnd(pWInfo);
33064 + /* Initialize the count of updated rows
33066 + if( db->flags & SQLITE_CountRows && !pParse->trigStack ){
33067 + sqliteVdbeAddOp(v, OP_Integer, 0, 0);
33070 + if( row_triggers_exist ){
33071 + /* Create pseudo-tables for NEW and OLD
33073 + sqliteVdbeAddOp(v, OP_OpenPseudo, oldIdx, 0);
33074 + sqliteVdbeAddOp(v, OP_OpenPseudo, newIdx, 0);
33076 + /* The top of the update loop for when there are triggers.
33078 + sqliteVdbeAddOp(v, OP_ListRewind, 0, 0);
33079 + sqliteVdbeAddOp(v, OP_StackDepth, 0, 0);
33080 + sqliteVdbeAddOp(v, OP_MemStore, iStackDepth, 1);
33081 + loopStart = sqliteVdbeAddOp(v, OP_MemLoad, iStackDepth, 0);
33082 + sqliteVdbeAddOp(v, OP_StackReset, 0, 0);
33083 + jumpInst = sqliteVdbeAddOp(v, OP_ListRead, 0, 0);
33084 + sqliteVdbeAddOp(v, OP_Dup, 0, 0);
33086 + /* Open a cursor and make it point to the record that is
33087 + ** being updated.
33089 + sqliteVdbeAddOp(v, OP_Dup, 0, 0);
33091 + sqliteVdbeAddOp(v, OP_Integer, pTab->iDb, 0);
33092 + sqliteVdbeAddOp(v, OP_OpenRead, iCur, pTab->tnum);
33094 + sqliteVdbeAddOp(v, OP_MoveTo, iCur, 0);
33096 + /* Generate the OLD table
33098 + sqliteVdbeAddOp(v, OP_Recno, iCur, 0);
33099 + sqliteVdbeAddOp(v, OP_RowData, iCur, 0);
33100 + sqliteVdbeAddOp(v, OP_PutIntKey, oldIdx, 0);
33102 + /* Generate the NEW table
33105 + sqliteExprCode(pParse, pRecnoExpr);
33107 + sqliteVdbeAddOp(v, OP_Recno, iCur, 0);
33109 + for(i=0; i<pTab->nCol; i++){
33110 + if( i==pTab->iPKey ){
33111 + sqliteVdbeAddOp(v, OP_String, 0, 0);
33116 + sqliteVdbeAddOp(v, OP_Column, iCur, i);
33118 + sqliteExprCode(pParse, pChanges->a[j].pExpr);
33121 + sqliteVdbeAddOp(v, OP_MakeRecord, pTab->nCol, 0);
33122 + sqliteVdbeAddOp(v, OP_PutIntKey, newIdx, 0);
33124 + sqliteVdbeAddOp(v, OP_Close, iCur, 0);
33127 + /* Fire the BEFORE and INSTEAD OF triggers
33129 + if( sqliteCodeRowTrigger(pParse, TK_UPDATE, pChanges, TK_BEFORE, pTab,
33130 + newIdx, oldIdx, onError, loopStart) ){
33131 + goto update_cleanup;
33137 + ** Open every index that needs updating. Note that if any
33138 + ** index could potentially invoke a REPLACE conflict resolution
33139 + ** action, then we need to open all indices because we might need
33140 + ** to be deleting some records.
33142 + sqliteVdbeAddOp(v, OP_Integer, pTab->iDb, 0);
33143 + sqliteVdbeAddOp(v, OP_OpenWrite, iCur, pTab->tnum);
33144 + if( onError==OE_Replace ){
33148 + for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
33149 + if( pIdx->onError==OE_Replace ){
33155 + for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
33156 + if( openAll || aIdxUsed[i] ){
33157 + sqliteVdbeAddOp(v, OP_Integer, pIdx->iDb, 0);
33158 + sqliteVdbeAddOp(v, OP_OpenWrite, iCur+i+1, pIdx->tnum);
33159 + assert( pParse->nTab>iCur+i+1 );
33163 + /* Loop over every record that needs updating. We have to load
33164 + ** the old data for each record to be updated because some columns
33165 + ** might not change and we will need to copy the old value.
33166 + ** Also, the old data is needed to delete the old index entires.
33167 + ** So make the cursor point at the old record.
33169 + if( !row_triggers_exist ){
33170 + sqliteVdbeAddOp(v, OP_ListRewind, 0, 0);
33171 + jumpInst = loopStart = sqliteVdbeAddOp(v, OP_ListRead, 0, 0);
33172 + sqliteVdbeAddOp(v, OP_Dup, 0, 0);
33174 + sqliteVdbeAddOp(v, OP_NotExists, iCur, loopStart);
33176 + /* If the record number will change, push the record number as it
33177 + ** will be after the update. (The old record number is currently
33178 + ** on top of the stack.)
33181 + sqliteExprCode(pParse, pRecnoExpr);
33182 + sqliteVdbeAddOp(v, OP_MustBeInt, 0, 0);
33185 + /* Compute new data for this record.
33187 + for(i=0; i<pTab->nCol; i++){
33188 + if( i==pTab->iPKey ){
33189 + sqliteVdbeAddOp(v, OP_String, 0, 0);
33194 + sqliteVdbeAddOp(v, OP_Column, iCur, i);
33196 + sqliteExprCode(pParse, pChanges->a[j].pExpr);
33200 + /* Do constraint checks
33202 + sqliteGenerateConstraintChecks(pParse, pTab, iCur, aIdxUsed, chngRecno, 1,
33203 + onError, loopStart);
33205 + /* Delete the old indices for the current record.
33207 + sqliteGenerateRowIndexDelete(db, v, pTab, iCur, aIdxUsed);
33209 + /* If changing the record number, delete the old record.
33212 + sqliteVdbeAddOp(v, OP_Delete, iCur, 0);
33215 + /* Create the new index entries and the new record.
33217 + sqliteCompleteInsertion(pParse, pTab, iCur, aIdxUsed, chngRecno, 1, -1);
33220 + /* Increment the row counter
33222 + if( db->flags & SQLITE_CountRows && !pParse->trigStack){
33223 + sqliteVdbeAddOp(v, OP_AddImm, 1, 0);
33226 + /* If there are triggers, close all the cursors after each iteration
33227 + ** through the loop. The fire the after triggers.
33229 + if( row_triggers_exist ){
33231 + for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
33232 + if( openAll || aIdxUsed[i] )
33233 + sqliteVdbeAddOp(v, OP_Close, iCur+i+1, 0);
33235 + sqliteVdbeAddOp(v, OP_Close, iCur, 0);
33236 + pParse->nTab = iCur;
33238 + if( sqliteCodeRowTrigger(pParse, TK_UPDATE, pChanges, TK_AFTER, pTab,
33239 + newIdx, oldIdx, onError, loopStart) ){
33240 + goto update_cleanup;
33244 + /* Repeat the above with the next record to be updated, until
33245 + ** all record selected by the WHERE clause have been updated.
33247 + sqliteVdbeAddOp(v, OP_Goto, 0, loopStart);
33248 + sqliteVdbeChangeP2(v, jumpInst, sqliteVdbeCurrentAddr(v));
33249 + sqliteVdbeAddOp(v, OP_ListReset, 0, 0);
33251 + /* Close all tables if there were no FOR EACH ROW triggers */
33252 + if( !row_triggers_exist ){
33253 + for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
33254 + if( openAll || aIdxUsed[i] ){
33255 + sqliteVdbeAddOp(v, OP_Close, iCur+i+1, 0);
33258 + sqliteVdbeAddOp(v, OP_Close, iCur, 0);
33259 + pParse->nTab = iCur;
33261 + sqliteVdbeAddOp(v, OP_Close, newIdx, 0);
33262 + sqliteVdbeAddOp(v, OP_Close, oldIdx, 0);
33265 + sqliteVdbeAddOp(v, OP_SetCounts, 0, 0);
33266 + sqliteEndWriteOperation(pParse);
33269 + ** Return the number of rows that were changed.
33271 + if( db->flags & SQLITE_CountRows && !pParse->trigStack ){
33272 + sqliteVdbeOp3(v, OP_ColumnName, 0, 1, "rows updated", P3_STATIC);
33273 + sqliteVdbeAddOp(v, OP_Callback, 1, 0);
33277 + sqliteAuthContextPop(&sContext);
33278 + sqliteFree(apIdx);
33279 + sqliteFree(aXRef);
33280 + sqliteSrcListDelete(pTabList);
33281 + sqliteExprListDelete(pChanges);
33282 + sqliteExprDelete(pWhere);
33286 +++ b/ext/sqlite/libsqlite/src/util.c
33289 +** 2001 September 15
33291 +** The author disclaims copyright to this source code. In place of
33292 +** a legal notice, here is a blessing:
33294 +** May you do good and not evil.
33295 +** May you find forgiveness for yourself and forgive others.
33296 +** May you share freely, never taking more than you give.
33298 +*************************************************************************
33299 +** Utility functions used throughout sqlite.
33301 +** This file contains functions for allocating memory, comparing
33302 +** strings, and stuff like that.
33306 +#include "sqliteInt.h"
33307 +#include <stdarg.h>
33308 +#include <ctype.h>
33311 +** If malloc() ever fails, this global variable gets set to 1.
33312 +** This causes the library to abort and never again function.
33314 +int sqlite_malloc_failed = 0;
33317 +** If MEMORY_DEBUG is defined, then use versions of malloc() and
33318 +** free() that track memory usage and check for buffer overruns.
33320 +#ifdef MEMORY_DEBUG
33323 +** For keeping track of the number of mallocs and frees. This
33324 +** is used to check for memory leaks.
33326 +int sqlite_nMalloc; /* Number of sqliteMalloc() calls */
33327 +int sqlite_nFree; /* Number of sqliteFree() calls */
33328 +int sqlite_iMallocFail; /* Fail sqliteMalloc() after this many calls */
33329 +#if MEMORY_DEBUG>1
33330 +static int memcnt = 0;
33334 +** Number of 32-bit guard words
33339 +** Allocate new memory and set it to zero. Return NULL if
33340 +** no memory is available.
33342 +void *sqliteMalloc_(int n, int bZero, char *zFile, int line){
33346 + if( sqlite_iMallocFail>=0 ){
33347 + sqlite_iMallocFail--;
33348 + if( sqlite_iMallocFail==0 ){
33349 + sqlite_malloc_failed++;
33350 +#if MEMORY_DEBUG>1
33351 + fprintf(stderr,"**** failed to allocate %d bytes at %s:%d\n",
33354 + sqlite_iMallocFail--;
33358 + if( n==0 ) return 0;
33359 + k = (n+sizeof(int)-1)/sizeof(int);
33360 + pi = malloc( (N_GUARD*2+1+k)*sizeof(int));
33362 + sqlite_malloc_failed++;
33365 + sqlite_nMalloc++;
33366 + for(i=0; i<N_GUARD; i++) pi[i] = 0xdead1122;
33368 + for(i=0; i<N_GUARD; i++) pi[k+1+N_GUARD+i] = 0xdead3344;
33369 + p = &pi[N_GUARD+1];
33370 + memset(p, bZero==0, n);
33371 +#if MEMORY_DEBUG>1
33372 + fprintf(stderr,"%06d malloc %d bytes at 0x%x from %s:%d\n",
33373 + ++memcnt, n, (int)p, zFile,line);
33379 +** Check to see if the given pointer was obtained from sqliteMalloc()
33380 +** and is able to hold at least N bytes. Raise an exception if this
33381 +** is not the case.
33383 +** This routine is used for testing purposes only.
33385 +void sqliteCheckMemory(void *p, int N){
33389 + for(i=0; i<N_GUARD; i++){
33390 + assert( pi[i]==0xdead1122 );
33393 + assert( N>=0 && N<n );
33394 + k = (n+sizeof(int)-1)/sizeof(int);
33395 + for(i=0; i<N_GUARD; i++){
33396 + assert( pi[k+N_GUARD+1+i]==0xdead3344 );
33401 +** Free memory previously obtained from sqliteMalloc()
33403 +void sqliteFree_(void *p, char *zFile, int line){
33405 + int *pi, i, k, n;
33409 + for(i=0; i<N_GUARD; i++){
33410 + if( pi[i]!=0xdead1122 ){
33411 + fprintf(stderr,"Low-end memory corruption at 0x%x\n", (int)p);
33416 + k = (n+sizeof(int)-1)/sizeof(int);
33417 + for(i=0; i<N_GUARD; i++){
33418 + if( pi[k+N_GUARD+1+i]!=0xdead3344 ){
33419 + fprintf(stderr,"High-end memory corruption at 0x%x\n", (int)p);
33423 + memset(pi, 0xff, (k+N_GUARD*2+1)*sizeof(int));
33424 +#if MEMORY_DEBUG>1
33425 + fprintf(stderr,"%06d free %d bytes at 0x%x from %s:%d\n",
33426 + ++memcnt, n, (int)p, zFile,line);
33433 +** Resize a prior allocation. If p==0, then this routine
33434 +** works just like sqliteMalloc(). If n==0, then this routine
33435 +** works just like sqliteFree().
33437 +void *sqliteRealloc_(void *oldP, int n, char *zFile, int line){
33438 + int *oldPi, *pi, i, k, oldN, oldK;
33441 + return sqliteMalloc_(n,1,zFile,line);
33444 + sqliteFree_(oldP,zFile,line);
33448 + oldPi -= N_GUARD+1;
33449 + if( oldPi[0]!=0xdead1122 ){
33450 + fprintf(stderr,"Low-end memory corruption in realloc at 0x%x\n", (int)oldP);
33453 + oldN = oldPi[N_GUARD];
33454 + oldK = (oldN+sizeof(int)-1)/sizeof(int);
33455 + for(i=0; i<N_GUARD; i++){
33456 + if( oldPi[oldK+N_GUARD+1+i]!=0xdead3344 ){
33457 + fprintf(stderr,"High-end memory corruption in realloc at 0x%x\n",
33462 + k = (n + sizeof(int) - 1)/sizeof(int);
33463 + pi = malloc( (k+N_GUARD*2+1)*sizeof(int) );
33465 + sqlite_malloc_failed++;
33468 + for(i=0; i<N_GUARD; i++) pi[i] = 0xdead1122;
33470 + for(i=0; i<N_GUARD; i++) pi[k+N_GUARD+1+i] = 0xdead3344;
33471 + p = &pi[N_GUARD+1];
33472 + memcpy(p, oldP, n>oldN ? oldN : n);
33474 + memset(&((char*)p)[oldN], 0, n-oldN);
33476 + memset(oldPi, 0xab, (oldK+N_GUARD+2)*sizeof(int));
33478 +#if MEMORY_DEBUG>1
33479 + fprintf(stderr,"%06d realloc %d to %d bytes at 0x%x to 0x%x at %s:%d\n",
33480 + ++memcnt, oldN, n, (int)oldP, (int)p, zFile, line);
33486 +** Make a duplicate of a string into memory obtained from malloc()
33487 +** Free the original string using sqliteFree().
33489 +** This routine is called on all strings that are passed outside of
33490 +** the SQLite library. That way clients can free the string using free()
33491 +** rather than having to call sqliteFree().
33493 +void sqliteStrRealloc(char **pz){
33495 + if( pz==0 || *pz==0 ) return;
33496 + zNew = malloc( strlen(*pz) + 1 );
33498 + sqlite_malloc_failed++;
33502 + strcpy(zNew, *pz);
33508 +** Make a copy of a string in memory obtained from sqliteMalloc()
33510 +char *sqliteStrDup_(const char *z, char *zFile, int line){
33512 + if( z==0 ) return 0;
33513 + zNew = sqliteMalloc_(strlen(z)+1, 0, zFile, line);
33514 + if( zNew ) strcpy(zNew, z);
33517 +char *sqliteStrNDup_(const char *z, int n, char *zFile, int line){
33519 + if( z==0 ) return 0;
33520 + zNew = sqliteMalloc_(n+1, 0, zFile, line);
33522 + memcpy(zNew, z, n);
33527 +#endif /* MEMORY_DEBUG */
33530 +** The following versions of malloc() and free() are for use in a
33533 +#if !defined(MEMORY_DEBUG)
33536 +** Allocate new memory and set it to zero. Return NULL if
33537 +** no memory is available. See also sqliteMallocRaw().
33539 +void *sqliteMalloc(int n){
33541 + if( (p = malloc(n))==0 ){
33542 + if( n>0 ) sqlite_malloc_failed++;
33550 +** Allocate new memory but do not set it to zero. Return NULL if
33551 +** no memory is available. See also sqliteMalloc().
33553 +void *sqliteMallocRaw(int n){
33555 + if( (p = malloc(n))==0 ){
33556 + if( n>0 ) sqlite_malloc_failed++;
33562 +** Free memory previously obtained from sqliteMalloc()
33564 +void sqliteFree(void *p){
33571 +** Resize a prior allocation. If p==0, then this routine
33572 +** works just like sqliteMalloc(). If n==0, then this routine
33573 +** works just like sqliteFree().
33575 +void *sqliteRealloc(void *p, int n){
33578 + return sqliteMalloc(n);
33584 + p2 = realloc(p, n);
33586 + sqlite_malloc_failed++;
33592 +** Make a copy of a string in memory obtained from sqliteMalloc()
33594 +char *sqliteStrDup(const char *z){
33596 + if( z==0 ) return 0;
33597 + zNew = sqliteMallocRaw(strlen(z)+1);
33598 + if( zNew ) strcpy(zNew, z);
33601 +char *sqliteStrNDup(const char *z, int n){
33603 + if( z==0 ) return 0;
33604 + zNew = sqliteMallocRaw(n+1);
33606 + memcpy(zNew, z, n);
33611 +#endif /* !defined(MEMORY_DEBUG) */
33614 +** Create a string from the 2nd and subsequent arguments (up to the
33615 +** first NULL argument), store the string in memory obtained from
33616 +** sqliteMalloc() and make the pointer indicated by the 1st argument
33617 +** point to that string. The 1st argument must either be NULL or
33618 +** point to memory obtained from sqliteMalloc().
33620 +void sqliteSetString(char **pz, ...){
33626 + if( pz==0 ) return;
33628 + va_start(ap, pz);
33629 + while( (z = va_arg(ap, const char*))!=0 ){
33630 + nByte += strlen(z);
33634 + *pz = zResult = sqliteMallocRaw( nByte );
33635 + if( zResult==0 ){
33639 + va_start(ap, pz);
33640 + while( (z = va_arg(ap, const char*))!=0 ){
33641 + strcpy(zResult, z);
33642 + zResult += strlen(zResult);
33645 +#ifdef MEMORY_DEBUG
33646 +#if MEMORY_DEBUG>1
33647 + fprintf(stderr,"string at 0x%x is %s\n", (int)*pz, *pz);
33653 +** Works like sqliteSetString, but each string is now followed by
33654 +** a length integer which specifies how much of the source string
33655 +** to copy (in bytes). -1 means use the whole string. The 1st
33656 +** argument must either be NULL or point to memory obtained from
33657 +** sqliteMalloc().
33659 +void sqliteSetNString(char **pz, ...){
33666 + if( pz==0 ) return;
33668 + va_start(ap, pz);
33669 + while( (z = va_arg(ap, const char*))!=0 ){
33670 + n = va_arg(ap, int);
33671 + if( n<=0 ) n = strlen(z);
33676 + *pz = zResult = sqliteMallocRaw( nByte + 1 );
33677 + if( zResult==0 ) return;
33678 + va_start(ap, pz);
33679 + while( (z = va_arg(ap, const char*))!=0 ){
33680 + n = va_arg(ap, int);
33681 + if( n<=0 ) n = strlen(z);
33682 + strncpy(zResult, z, n);
33686 +#ifdef MEMORY_DEBUG
33687 +#if MEMORY_DEBUG>1
33688 + fprintf(stderr,"string at 0x%x is %s\n", (int)*pz, *pz);
33695 +** Add an error message to pParse->zErrMsg and increment pParse->nErr.
33696 +** The following formatting characters are allowed:
33698 +** %s Insert a string
33699 +** %z A string that should be freed after use
33700 +** %d Insert an integer
33701 +** %T Insert a token
33702 +** %S Insert the first element of a SrcList
33704 +void sqliteErrorMsg(Parse *pParse, const char *zFormat, ...){
33707 + sqliteFree(pParse->zErrMsg);
33708 + va_start(ap, zFormat);
33709 + pParse->zErrMsg = sqliteVMPrintf(zFormat, ap);
33714 +** Convert an SQL-style quoted string into a normal string by removing
33715 +** the quote characters. The conversion is done in-place. If the
33716 +** input does not begin with a quote character, then this routine
33719 +** 2002-Feb-14: This routine is extended to remove MS-Access style
33720 +** brackets from around identifers. For example: "[a-b-c]" becomes
33723 +void sqliteDequote(char *z){
33726 + if( z==0 ) return;
33729 + case '\'': break;
33731 + case '[': quote = ']'; break;
33734 + for(i=1, j=0; z[i]; i++){
33735 + if( z[i]==quote ){
33736 + if( z[i+1]==quote ){
33749 +/* An array to map all upper-case characters into their corresponding
33750 +** lower-case character.
33752 +static unsigned char UpperToLower[] = {
33753 + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17,
33754 + 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
33755 + 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
33756 + 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99,100,101,102,103,
33757 + 104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,
33758 + 122, 91, 92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103,104,105,106,107,
33759 + 108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,
33760 + 126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
33761 + 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,
33762 + 162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,
33763 + 180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,
33764 + 198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,
33765 + 216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,
33766 + 234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,
33771 +** This function computes a hash on the name of a keyword.
33772 +** Case is not significant.
33774 +int sqliteHashNoCase(const char *z, int n){
33776 + if( n<=0 ) n = strlen(z);
33778 + h = (h<<3) ^ h ^ UpperToLower[(unsigned char)*z++];
33781 + return h & 0x7fffffff;
33785 +** Some systems have stricmp(). Others have strcasecmp(). Because
33786 +** there is no consistency, we will define our own.
33788 +int sqliteStrICmp(const char *zLeft, const char *zRight){
33789 + register unsigned char *a, *b;
33790 + a = (unsigned char *)zLeft;
33791 + b = (unsigned char *)zRight;
33792 + while( *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
33793 + return UpperToLower[*a] - UpperToLower[*b];
33795 +int sqliteStrNICmp(const char *zLeft, const char *zRight, int N){
33796 + register unsigned char *a, *b;
33797 + a = (unsigned char *)zLeft;
33798 + b = (unsigned char *)zRight;
33799 + while( N-- > 0 && *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
33800 + return N<0 ? 0 : UpperToLower[*a] - UpperToLower[*b];
33804 +** Return TRUE if z is a pure numeric string. Return FALSE if the
33805 +** string contains any character which is not part of a number.
33807 +** Am empty string is considered non-numeric.
33809 +int sqliteIsNumber(const char *z){
33810 + if( *z=='-' || *z=='+' ) z++;
33811 + if( !isdigit(*z) ){
33815 + while( isdigit(*z) ){ z++; }
33818 + if( !isdigit(*z) ) return 0;
33819 + while( isdigit(*z) ){ z++; }
33821 + if( *z=='e' || *z=='E' ){
33823 + if( *z=='+' || *z=='-' ) z++;
33824 + if( !isdigit(*z) ) return 0;
33825 + while( isdigit(*z) ){ z++; }
33831 +** The string z[] is an ascii representation of a real number.
33832 +** Convert this string to a double.
33834 +** This routine assumes that z[] really is a valid number. If it
33835 +** is not, the result is undefined.
33837 +** This routine is used instead of the library atof() function because
33838 +** the library atof() might want to use "," as the decimal point instead
33839 +** of "." depending on how locale is set. But that would cause problems
33840 +** for SQL. So this routine always uses "." regardless of locale.
33842 +double sqliteAtoF(const char *z, const char **pzEnd){
33844 + LONGDOUBLE_TYPE v1 = 0.0;
33848 + }else if( *z=='+' ){
33851 + while( isdigit(*z) ){
33852 + v1 = v1*10.0 + (*z - '0');
33856 + LONGDOUBLE_TYPE divisor = 1.0;
33858 + while( isdigit(*z) ){
33859 + v1 = v1*10.0 + (*z - '0');
33865 + if( *z=='e' || *z=='E' ){
33868 + LONGDOUBLE_TYPE scale = 1.0;
33873 + }else if( *z=='+' ){
33876 + while( isdigit(*z) ){
33877 + eval = eval*10 + *z - '0';
33880 + while( eval>=64 ){ scale *= 1.0e+64; eval -= 64; }
33881 + while( eval>=16 ){ scale *= 1.0e+16; eval -= 16; }
33882 + while( eval>=4 ){ scale *= 1.0e+4; eval -= 4; }
33883 + while( eval>=1 ){ scale *= 1.0e+1; eval -= 1; }
33890 + if( pzEnd ) *pzEnd = z;
33891 + return sign<0 ? -v1 : v1;
33895 +** The string zNum represents an integer. There might be some other
33896 +** information following the integer too, but that part is ignored.
33897 +** If the integer that the prefix of zNum represents will fit in a
33898 +** 32-bit signed integer, return TRUE. Otherwise return FALSE.
33900 +** This routine returns FALSE for the string -2147483648 even that
33901 +** that number will, in theory fit in a 32-bit integer. But positive
33902 +** 2147483648 will not fit in 32 bits. So it seems safer to return
33905 +int sqliteFitsIn32Bits(const char *zNum){
33907 + if( *zNum=='-' || *zNum=='+' ) zNum++;
33908 + for(i=0; (c=zNum[i])>='0' && c<='9'; i++){}
33909 + return i<10 || (i==10 && memcmp(zNum,"2147483647",10)<=0);
33912 +/* This comparison routine is what we use for comparison operations
33913 +** between numeric values in an SQL expression. "Numeric" is a little
33914 +** bit misleading here. What we mean is that the strings have a
33915 +** type of "numeric" from the point of view of SQL. The strings
33916 +** do not necessarily contain numbers. They could contain text.
33918 +** If the input strings both look like actual numbers then they
33919 +** compare in numerical order. Numerical strings are always less
33920 +** than non-numeric strings so if one input string looks like a
33921 +** number and the other does not, then the one that looks like
33922 +** a number is the smaller. Non-numeric strings compare in
33923 +** lexigraphical order (the same order as strcmp()).
33925 +int sqliteCompare(const char *atext, const char *btext){
33927 + int isNumA, isNumB;
33930 + }else if( btext==0 ){
33933 + isNumA = sqliteIsNumber(atext);
33934 + isNumB = sqliteIsNumber(btext);
33940 + rA = sqliteAtoF(atext, 0);
33941 + rB = sqliteAtoF(btext, 0);
33944 + }else if( rA>rB ){
33950 + }else if( isNumB ){
33953 + result = strcmp(atext, btext);
33959 +** This routine is used for sorting. Each key is a list of one or more
33960 +** null-terminated elements. The list is terminated by two nulls in
33961 +** a row. For example, the following text is a key with three elements
33963 +** Aone\000Dtwo\000Athree\000\000
33965 +** All elements begin with one of the characters "+-AD" and end with "\000"
33966 +** with zero or more text elements in between. Except, NULL elements
33967 +** consist of the special two-character sequence "N\000".
33969 +** Both arguments will have the same number of elements. This routine
33970 +** returns negative, zero, or positive if the first argument is less
33971 +** than, equal to, or greater than the first. (Result is a-b).
33973 +** Each element begins with one of the characters "+", "-", "A", "D".
33974 +** This character determines the sort order and collating sequence:
33976 +** + Sort numerically in ascending order
33977 +** - Sort numerically in descending order
33978 +** A Sort as strings in ascending order
33979 +** D Sort as strings in descending order.
33981 +** For the "+" and "-" sorting, pure numeric strings (strings for which the
33982 +** isNum() function above returns TRUE) always compare less than strings
33983 +** that are not pure numerics. Non-numeric strings compare in memcmp()
33984 +** order. This is the same sort order as the sqliteCompare() function
33985 +** above generates.
33987 +** The last point is a change from version 2.6.3 to version 2.7.0. In
33988 +** version 2.6.3 and earlier, substrings of digits compare in numerical
33989 +** and case was used only to break a tie.
33991 +** Elements that begin with 'A' or 'D' compare in memcmp() order regardless
33992 +** of whether or not they look like a number.
33994 +** Note that the sort order imposed by the rules above is the same
33995 +** from the ordering defined by the "<", "<=", ">", and ">=" operators
33996 +** of expressions and for indices. This was not the case for version
33997 +** 2.6.3 and earlier.
33999 +int sqliteSortCompare(const char *a, const char *b){
34001 + int isNumA, isNumB;
34004 + while( res==0 && *a && *b ){
34005 + if( a[0]=='N' || b[0]=='N' ){
34006 + if( a[0]==b[0] ){
34020 + assert( a[0]==b[0] );
34021 + if( (dir=a[0])=='A' || a[0]=='D' ){
34022 + res = strcmp(&a[1],&b[1]);
34025 + isNumA = sqliteIsNumber(&a[1]);
34026 + isNumB = sqliteIsNumber(&b[1]);
34033 + rA = sqliteAtoF(&a[1], 0);
34034 + rB = sqliteAtoF(&b[1], 0);
34043 + }else if( isNumB ){
34047 + res = strcmp(&a[1],&b[1]);
34051 + a += strlen(&a[1]) + 2;
34052 + b += strlen(&b[1]) + 2;
34054 + if( dir=='-' || dir=='D' ) res = -res;
34059 +** Some powers of 64. These constants are needed in the
34060 +** sqliteRealToSortable() routine below.
34062 +#define _64e3 (64.0 * 64.0 * 64.0)
34063 +#define _64e4 (64.0 * 64.0 * 64.0 * 64.0)
34064 +#define _64e15 (_64e3 * _64e4 * _64e4 * _64e4)
34065 +#define _64e16 (_64e4 * _64e4 * _64e4 * _64e4)
34066 +#define _64e63 (_64e15 * _64e16 * _64e16 * _64e16)
34067 +#define _64e64 (_64e16 * _64e16 * _64e16 * _64e16)
34070 +** The following procedure converts a double-precision floating point
34071 +** number into a string. The resulting string has the property that
34072 +** two such strings comparied using strcmp() or memcmp() will give the
34073 +** same results as a numeric comparison of the original floating point
34076 +** This routine is used to generate database keys from floating point
34077 +** numbers such that the keys sort in the same order as the original
34078 +** floating point numbers even though the keys are compared using
34081 +** The calling function should have allocated at least 14 characters
34082 +** of space for the buffer z[].
34084 +void sqliteRealToSortable(double r, char *z){
34089 + /* This array maps integers between 0 and 63 into base-64 digits.
34090 + ** The digits must be chosen such at their ASCII codes are increasing.
34091 + ** This means we can not use the traditional base-64 digit set. */
34092 + static const char zDigit[] =
34094 + "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
34095 + "abcdefghijklmnopqrstuvwxyz"
34109 + }else if( r<(0.5/64.0) ){
34110 + while( r < 0.5/_64e64 && exp > -961 ){ r *= _64e64; exp -= 64; }
34111 + while( r < 0.5/_64e16 && exp > -1009 ){ r *= _64e16; exp -= 16; }
34112 + while( r < 0.5/_64e4 && exp > -1021 ){ r *= _64e4; exp -= 4; }
34113 + while( r < 0.5/64.0 && exp > -1024 ){ r *= 64.0; exp -= 1; }
34114 + }else if( r>=0.5 ){
34115 + while( r >= 0.5*_64e63 && exp < 960 ){ r *= 1.0/_64e64; exp += 64; }
34116 + while( r >= 0.5*_64e15 && exp < 1008 ){ r *= 1.0/_64e16; exp += 16; }
34117 + while( r >= 0.5*_64e3 && exp < 1020 ){ r *= 1.0/_64e4; exp += 4; }
34118 + while( r >= 0.5 && exp < 1023 ){ r *= 1.0/64.0; exp += 1; }
34126 + if( exp<0 ) return;
34127 + if( exp>=2048 || r>=1.0 ){
34128 + strcpy(z, "~~~~~~~~~~~~");
34131 + *z++ = zDigit[(exp>>6)&0x3f];
34132 + *z++ = zDigit[exp & 0x3f];
34133 + while( r>0.0 && cnt<10 ){
34137 + assert( digit>=0 && digit<64 );
34138 + *z++ = zDigit[digit & 0x3f];
34145 +#ifdef SQLITE_UTF8
34147 +** X is a pointer to the first byte of a UTF-8 character. Increment
34148 +** X so that it points to the next character. This only works right
34149 +** if X points to a well-formed UTF-8 string.
34151 +#define sqliteNextChar(X) while( (0xc0&*++(X))==0x80 ){}
34152 +#define sqliteCharVal(X) sqlite_utf8_to_int(X)
34154 +#else /* !defined(SQLITE_UTF8) */
34156 +** For iso8859 encoding, the next character is just the next byte.
34158 +#define sqliteNextChar(X) (++(X));
34159 +#define sqliteCharVal(X) ((int)*(X))
34161 +#endif /* defined(SQLITE_UTF8) */
34164 +#ifdef SQLITE_UTF8
34166 +** Convert the UTF-8 character to which z points into a 31-bit
34167 +** UCS character. This only works right if z points to a well-formed
34170 +static int sqlite_utf8_to_int(const unsigned char *z){
34172 + static const int initVal[] = {
34173 + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
34174 + 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29,
34175 + 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44,
34176 + 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59,
34177 + 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74,
34178 + 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89,
34179 + 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104,
34180 + 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119,
34181 + 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134,
34182 + 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149,
34183 + 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164,
34184 + 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179,
34185 + 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 0, 1, 2,
34186 + 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17,
34187 + 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 0,
34188 + 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
34189 + 0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 0, 1, 254,
34192 + c = initVal[*(z++)];
34193 + while( (0xc0&*z)==0x80 ){
34194 + c = (c<<6) | (0x3f&*(z++));
34201 +** Compare two UTF-8 strings for equality where the first string can
34202 +** potentially be a "glob" expression. Return true (1) if they
34203 +** are the same and false (0) if they are different.
34205 +** Globbing rules:
34207 +** '*' Matches any sequence of zero or more characters.
34209 +** '?' Matches exactly one character.
34211 +** [...] Matches one character from the enclosed list of
34214 +** [^...] Matches one character not in the enclosed list.
34216 +** With the [...] and [^...] matching, a ']' character can be included
34217 +** in the list by making it the first character after '[' or '^'. A
34218 +** range of characters can be specified using '-'. Example:
34219 +** "[a-z]" matches any single lower-case letter. To match a '-', make
34220 +** it the last character in the list.
34222 +** This routine is usually quick, but can be N**2 in the worst case.
34224 +** Hints: to match '*' or '?', put them in "[]". Like this:
34226 +** abc[*]xyz Matches "abc*xyz" only
34229 +sqliteGlobCompare(const unsigned char *zPattern, const unsigned char *zString){
34235 + while( (c = *zPattern)!=0 ){
34238 + while( (c=zPattern[1]) == '*' || c == '?' ){
34240 + if( *zString==0 ) return 0;
34241 + sqliteNextChar(zString);
34245 + if( c==0 ) return 1;
34247 + while( *zString && sqliteGlobCompare(&zPattern[1],zString)==0 ){
34248 + sqliteNextChar(zString);
34250 + return *zString!=0;
34252 + while( (c2 = *zString)!=0 ){
34253 + while( c2 != 0 && c2 != c ){ c2 = *++zString; }
34254 + if( c2==0 ) return 0;
34255 + if( sqliteGlobCompare(&zPattern[1],zString) ) return 1;
34256 + sqliteNextChar(zString);
34261 + if( *zString==0 ) return 0;
34262 + sqliteNextChar(zString);
34270 + c = sqliteCharVal(zString);
34271 + if( c==0 ) return 0;
34272 + c2 = *++zPattern;
34273 + if( c2=='^' ){ invert = 1; c2 = *++zPattern; }
34275 + if( c==']' ) seen = 1;
34276 + c2 = *++zPattern;
34278 + while( (c2 = sqliteCharVal(zPattern))!=0 && c2!=']' ){
34279 + if( c2=='-' && zPattern[1]!=']' && zPattern[1]!=0 && prior_c>0 ){
34281 + c2 = sqliteCharVal(zPattern);
34282 + if( c>=prior_c && c<=c2 ) seen = 1;
34284 + }else if( c==c2 ){
34290 + sqliteNextChar(zPattern);
34292 + if( c2==0 || (seen ^ invert)==0 ) return 0;
34293 + sqliteNextChar(zString);
34298 + if( c != *zString ) return 0;
34305 + return *zString==0;
34309 +** Compare two UTF-8 strings for equality using the "LIKE" operator of
34310 +** SQL. The '%' character matches any sequence of 0 or more
34311 +** characters and '_' matches any single character. Case is
34312 +** not significant.
34314 +** This routine is just an adaptation of the sqliteGlobCompare()
34318 +sqliteLikeCompare(const unsigned char *zPattern, const unsigned char *zString){
34322 + while( (c = UpperToLower[*zPattern])!=0 ){
34325 + while( (c=zPattern[1]) == '%' || c == '_' ){
34327 + if( *zString==0 ) return 0;
34328 + sqliteNextChar(zString);
34332 + if( c==0 ) return 1;
34333 + c = UpperToLower[c];
34334 + while( (c2=UpperToLower[*zString])!=0 ){
34335 + while( c2 != 0 && c2 != c ){ c2 = UpperToLower[*++zString]; }
34336 + if( c2==0 ) return 0;
34337 + if( sqliteLikeCompare(&zPattern[1],zString) ) return 1;
34338 + sqliteNextChar(zString);
34343 + if( *zString==0 ) return 0;
34344 + sqliteNextChar(zString);
34349 + if( c != UpperToLower[*zString] ) return 0;
34356 + return *zString==0;
34360 +** Change the sqlite.magic from SQLITE_MAGIC_OPEN to SQLITE_MAGIC_BUSY.
34361 +** Return an error (non-zero) if the magic was not SQLITE_MAGIC_OPEN
34362 +** when this routine is called.
34364 +** This routine is a attempt to detect if two threads use the
34365 +** same sqlite* pointer at the same time. There is a race
34366 +** condition so it is possible that the error is not detected.
34367 +** But usually the problem will be seen. The result will be an
34368 +** error which can be used to debug the application that is
34369 +** using SQLite incorrectly.
34371 +** Ticket #202: If db->magic is not a valid open value, take care not
34372 +** to modify the db structure at all. It could be that db is a stale
34373 +** pointer. In other words, it could be that there has been a prior
34374 +** call to sqlite_close(db) and db has been deallocated. And we do
34375 +** not want to write into deallocated memory.
34377 +int sqliteSafetyOn(sqlite *db){
34378 + if( db->magic==SQLITE_MAGIC_OPEN ){
34379 + db->magic = SQLITE_MAGIC_BUSY;
34381 + }else if( db->magic==SQLITE_MAGIC_BUSY || db->magic==SQLITE_MAGIC_ERROR
34382 + || db->want_to_close ){
34383 + db->magic = SQLITE_MAGIC_ERROR;
34384 + db->flags |= SQLITE_Interrupt;
34390 +** Change the magic from SQLITE_MAGIC_BUSY to SQLITE_MAGIC_OPEN.
34391 +** Return an error (non-zero) if the magic was not SQLITE_MAGIC_BUSY
34392 +** when this routine is called.
34394 +int sqliteSafetyOff(sqlite *db){
34395 + if( db->magic==SQLITE_MAGIC_BUSY ){
34396 + db->magic = SQLITE_MAGIC_OPEN;
34398 + }else if( db->magic==SQLITE_MAGIC_OPEN || db->magic==SQLITE_MAGIC_ERROR
34399 + || db->want_to_close ){
34400 + db->magic = SQLITE_MAGIC_ERROR;
34401 + db->flags |= SQLITE_Interrupt;
34407 +** Check to make sure we are not currently executing an sqlite_exec().
34408 +** If we are currently in an sqlite_exec(), return true and set
34409 +** sqlite.magic to SQLITE_MAGIC_ERROR. This will cause a complete
34410 +** shutdown of the database.
34412 +** This routine is used to try to detect when API routines are called
34413 +** at the wrong time or in the wrong sequence.
34415 +int sqliteSafetyCheck(sqlite *db){
34416 + if( db->pVdbe!=0 ){
34417 + db->magic = SQLITE_MAGIC_ERROR;
34423 +++ b/ext/sqlite/libsqlite/src/vacuum.c
34428 +** The author disclaims copyright to this source code. In place of
34429 +** a legal notice, here is a blessing:
34431 +** May you do good and not evil.
34432 +** May you find forgiveness for yourself and forgive others.
34433 +** May you share freely, never taking more than you give.
34435 +*************************************************************************
34436 +** This file contains code used to implement the VACUUM command.
34438 +** Most of the code in this file may be omitted by defining the
34439 +** SQLITE_OMIT_VACUUM macro.
34443 +#include "sqliteInt.h"
34447 +** A structure for holding a dynamic string - a string that can grow
34450 +typedef struct dynStr dynStr;
34452 + char *z; /* Text of the string in space obtained from sqliteMalloc() */
34453 + int nAlloc; /* Amount of space allocated to z[] */
34454 + int nUsed; /* Next unused slot in z[] */
34458 +** A structure that holds the vacuum context
34460 +typedef struct vacuumStruct vacuumStruct;
34461 +struct vacuumStruct {
34462 + sqlite *dbOld; /* Original database */
34463 + sqlite *dbNew; /* New database */
34464 + char **pzErrMsg; /* Write errors here */
34465 + int rc; /* Set to non-zero on an error */
34466 + const char *zTable; /* Name of a table being copied */
34467 + const char *zPragma; /* Pragma to execute with results */
34468 + dynStr s1, s2; /* Two dynamic strings */
34471 +#if !defined(SQLITE_OMIT_VACUUM) || SQLITE_OMIT_VACUUM
34473 +** Append text to a dynamic string
34475 +static void appendText(dynStr *p, const char *zText, int nText){
34476 + if( nText<0 ) nText = strlen(zText);
34477 + if( p->z==0 || p->nUsed + nText + 1 >= p->nAlloc ){
34479 + p->nAlloc = p->nUsed + nText + 1000;
34480 + zNew = sqliteRealloc(p->z, p->nAlloc);
34482 + sqliteFree(p->z);
34483 + memset(p, 0, sizeof(*p));
34488 + memcpy(&p->z[p->nUsed], zText, nText+1);
34489 + p->nUsed += nText;
34493 +** Append text to a dynamic string, having first put the text in quotes.
34495 +static void appendQuoted(dynStr *p, const char *zText){
34497 + appendText(p, "'", 1);
34498 + for(i=j=0; zText[i]; i++){
34499 + if( zText[i]=='\'' ){
34500 + appendText(p, &zText[j], i-j+1);
34502 + appendText(p, "'", 1);
34506 + appendText(p, &zText[j], i-j);
34508 + appendText(p, "'", 1);
34512 +** Execute statements of SQL. If an error occurs, write the error
34513 +** message into *pzErrMsg and return non-zero.
34515 +static int execsql(char **pzErrMsg, sqlite *db, const char *zSql){
34516 + char *zErrMsg = 0;
34519 + /* printf("***** executing *****\n%s\n", zSql); */
34520 + rc = sqlite_exec(db, zSql, 0, 0, &zErrMsg);
34522 + sqliteSetString(pzErrMsg, zErrMsg, (char*)0);
34523 + sqlite_freemem(zErrMsg);
34529 +** This is the second stage callback. Each invocation contains all the
34530 +** data for a single row of a single table in the original database. This
34531 +** routine must write that information into the new database.
34533 +static int vacuumCallback2(void *pArg, int argc, char **argv, char **NotUsed){
34534 + vacuumStruct *p = (vacuumStruct*)pArg;
34535 + const char *zSep = "(";
34538 + if( argv==0 ) return 0;
34540 + appendText(&p->s2, "INSERT INTO ", -1);
34541 + appendQuoted(&p->s2, p->zTable);
34542 + appendText(&p->s2, " VALUES", -1);
34543 + for(i=0; i<argc; i++){
34544 + appendText(&p->s2, zSep, 1);
34546 + if( argv[i]==0 ){
34547 + appendText(&p->s2, "NULL", 4);
34549 + appendQuoted(&p->s2, argv[i]);
34552 + appendText(&p->s2,")", 1);
34553 + p->rc = execsql(p->pzErrMsg, p->dbNew, p->s2.z);
34558 +** This is the first stage callback. Each invocation contains three
34559 +** arguments where are taken from the SQLITE_MASTER table of the original
34560 +** database: (1) the entry type, (2) the entry name, and (3) the SQL for
34561 +** the entry. In all cases, execute the SQL of the third argument.
34562 +** For tables, run a query to select all entries in that table and
34563 +** transfer them to the second-stage callback.
34565 +static int vacuumCallback1(void *pArg, int argc, char **argv, char **NotUsed){
34566 + vacuumStruct *p = (vacuumStruct*)pArg;
34568 + assert( argc==3 );
34569 + if( argv==0 ) return 0;
34570 + assert( argv[0]!=0 );
34571 + assert( argv[1]!=0 );
34572 + assert( argv[2]!=0 );
34573 + rc = execsql(p->pzErrMsg, p->dbNew, argv[2]);
34574 + if( rc==SQLITE_OK && strcmp(argv[0],"table")==0 ){
34575 + char *zErrMsg = 0;
34577 + appendText(&p->s1, "SELECT * FROM ", -1);
34578 + appendQuoted(&p->s1, argv[1]);
34579 + p->zTable = argv[1];
34580 + rc = sqlite_exec(p->dbOld, p->s1.z, vacuumCallback2, p, &zErrMsg);
34582 + sqliteSetString(p->pzErrMsg, zErrMsg, (char*)0);
34583 + sqlite_freemem(zErrMsg);
34586 + if( rc!=SQLITE_ABORT ) p->rc = rc;
34591 +** Generate a random name of 20 character in length.
34593 +static void randomName(unsigned char *zBuf){
34594 + static const unsigned char zChars[] =
34595 + "abcdefghijklmnopqrstuvwxyz"
34598 + sqliteRandomness(20, zBuf);
34599 + for(i=0; i<20; i++){
34600 + zBuf[i] = zChars[ zBuf[i]%(sizeof(zChars)-1) ];
34606 +** The non-standard VACUUM command is used to clean up the database,
34607 +** collapse free space, etc. It is modelled after the VACUUM command
34610 +** In version 1.0.x of SQLite, the VACUUM command would call
34611 +** gdbm_reorganize() on all the database tables. But beginning
34612 +** with 2.0.0, SQLite no longer uses GDBM so this command has
34613 +** become a no-op.
34615 +void sqliteVacuum(Parse *pParse, Token *pTableName){
34616 + Vdbe *v = sqliteGetVdbe(pParse);
34617 + sqliteVdbeAddOp(v, OP_Vacuum, 0, 0);
34622 +** This routine implements the OP_Vacuum opcode of the VDBE.
34624 +int sqliteRunVacuum(char **pzErrMsg, sqlite *db){
34625 +#if !defined(SQLITE_OMIT_VACUUM) || SQLITE_OMIT_VACUUM
34626 + const char *zFilename; /* full pathname of the database file */
34627 + int nFilename; /* number of characters in zFilename[] */
34628 + char *zTemp = 0; /* a temporary file in same directory as zFilename */
34629 + sqlite *dbNew = 0; /* The new vacuumed database */
34630 + int rc = SQLITE_OK; /* Return code from service routines */
34631 + int i; /* Loop counter */
34632 + char *zErrMsg; /* Error message */
34633 + vacuumStruct sVac; /* Information passed to callbacks */
34635 + if( db->flags & SQLITE_InTrans ){
34636 + sqliteSetString(pzErrMsg, "cannot VACUUM from within a transaction",
34638 + return SQLITE_ERROR;
34640 + if( db->flags & SQLITE_Interrupt ){
34641 + return SQLITE_INTERRUPT;
34643 + memset(&sVac, 0, sizeof(sVac));
34645 + /* Get the full pathname of the database file and create two
34646 + ** temporary filenames in the same directory as the original file.
34648 + zFilename = sqliteBtreeGetFilename(db->aDb[0].pBt);
34649 + if( zFilename==0 ){
34650 + /* This only happens with the in-memory database. VACUUM is a no-op
34651 + ** there, so just return */
34652 + return SQLITE_OK;
34654 + nFilename = strlen(zFilename);
34655 + zTemp = sqliteMalloc( nFilename+100 );
34656 + if( zTemp==0 ) return SQLITE_NOMEM;
34657 + strcpy(zTemp, zFilename);
34658 + for(i=0; i<10; i++){
34659 + zTemp[nFilename] = '-';
34660 + randomName((unsigned char*)&zTemp[nFilename+1]);
34661 + if( !sqliteOsFileExists(zTemp) ) break;
34664 + sqliteSetString(pzErrMsg, "unable to create a temporary database file "
34665 + "in the same directory as the original database", (char*)0);
34666 + goto end_of_vacuum;
34670 + dbNew = sqlite_open(zTemp, 0, &zErrMsg);
34672 + sqliteSetString(pzErrMsg, "unable to open a temporary database at ",
34673 + zTemp, " - ", zErrMsg, (char*)0);
34674 + goto end_of_vacuum;
34676 + if( (rc = execsql(pzErrMsg, db, "BEGIN"))!=0 ) goto end_of_vacuum;
34677 + if( (rc = execsql(pzErrMsg, dbNew, "PRAGMA synchronous=off; BEGIN"))!=0 ){
34678 + goto end_of_vacuum;
34682 + sVac.dbNew = dbNew;
34683 + sVac.pzErrMsg = pzErrMsg;
34684 + if( rc==SQLITE_OK ){
34685 + rc = sqlite_exec(db,
34686 + "SELECT type, name, sql FROM sqlite_master "
34687 + "WHERE sql NOT NULL AND type!='view' "
34689 + "SELECT type, name, sql FROM sqlite_master "
34690 + "WHERE sql NOT NULL AND type=='view'",
34691 + vacuumCallback1, &sVac, &zErrMsg);
34693 + if( rc==SQLITE_OK ){
34694 + int meta1[SQLITE_N_BTREE_META];
34695 + int meta2[SQLITE_N_BTREE_META];
34696 + sqliteBtreeGetMeta(db->aDb[0].pBt, meta1);
34697 + sqliteBtreeGetMeta(dbNew->aDb[0].pBt, meta2);
34698 + meta2[1] = meta1[1]+1;
34699 + meta2[3] = meta1[3];
34700 + meta2[4] = meta1[4];
34701 + meta2[6] = meta1[6];
34702 + rc = sqliteBtreeUpdateMeta(dbNew->aDb[0].pBt, meta2);
34704 + if( rc==SQLITE_OK ){
34705 + rc = sqliteBtreeCopyFile(db->aDb[0].pBt, dbNew->aDb[0].pBt);
34706 + sqlite_exec(db, "COMMIT", 0, 0, 0);
34707 + sqliteResetInternalSchema(db, 0);
34711 + if( rc && zErrMsg!=0 ){
34712 + sqliteSetString(pzErrMsg, "unable to vacuum database - ",
34713 + zErrMsg, (char*)0);
34715 + sqlite_exec(db, "ROLLBACK", 0, 0, 0);
34716 + if( (dbNew && (dbNew->flags & SQLITE_Interrupt))
34717 + || (db->flags & SQLITE_Interrupt) ){
34718 + rc = SQLITE_INTERRUPT;
34720 + if( dbNew ) sqlite_close(dbNew);
34721 + sqliteOsDelete(zTemp);
34722 + sqliteFree(zTemp);
34723 + sqliteFree(sVac.s1.z);
34724 + sqliteFree(sVac.s2.z);
34725 + if( zErrMsg ) sqlite_freemem(zErrMsg);
34726 + if( rc==SQLITE_ABORT && sVac.rc!=SQLITE_INTERRUPT ) sVac.rc = SQLITE_ERROR;
34731 +++ b/ext/sqlite/libsqlite/src/vdbeaux.c
34734 +** 2003 September 6
34736 +** The author disclaims copyright to this source code. In place of
34737 +** a legal notice, here is a blessing:
34739 +** May you do good and not evil.
34740 +** May you find forgiveness for yourself and forgive others.
34741 +** May you share freely, never taking more than you give.
34743 +*************************************************************************
34744 +** This file contains code used for creating, destroying, and populating
34745 +** a VDBE (or an "sqlite_vm" as it is known to the outside world.) Prior
34746 +** to version 2.8.7, all this code was combined into the vdbe.c source file.
34747 +** But that file was getting too big so this subroutines were split out.
34749 +#include "sqliteInt.h"
34751 +#include <ctype.h>
34752 +#include "vdbeInt.h"
34756 +** When debugging the code generator in a symbolic debugger, one can
34757 +** set the sqlite_vdbe_addop_trace to 1 and all opcodes will be printed
34758 +** as they are added to the instruction stream.
34761 +int sqlite_vdbe_addop_trace = 0;
34766 +** Create a new virtual database engine.
34768 +Vdbe *sqliteVdbeCreate(sqlite *db){
34770 + p = sqliteMalloc( sizeof(Vdbe) );
34771 + if( p==0 ) return 0;
34774 + db->pVdbe->pPrev = p;
34776 + p->pNext = db->pVdbe;
34779 + p->magic = VDBE_MAGIC_INIT;
34784 +** Turn tracing on or off
34786 +void sqliteVdbeTrace(Vdbe *p, FILE *trace){
34787 + p->trace = trace;
34791 +** Add a new instruction to the list of instructions current in the
34792 +** VDBE. Return the address of the new instruction.
34796 +** p Pointer to the VDBE
34798 +** op The opcode for this instruction
34800 +** p1, p2 First two of the three possible operands.
34802 +** Use the sqliteVdbeResolveLabel() function to fix an address and
34803 +** the sqliteVdbeChangeP3() function to change the value of the P3
34806 +int sqliteVdbeAddOp(Vdbe *p, int op, int p1, int p2){
34812 + assert( p->magic==VDBE_MAGIC_INIT );
34813 + if( i>=p->nOpAlloc ){
34814 + int oldSize = p->nOpAlloc;
34816 + p->nOpAlloc = p->nOpAlloc*2 + 100;
34817 + aNew = sqliteRealloc(p->aOp, p->nOpAlloc*sizeof(Op));
34819 + p->nOpAlloc = oldSize;
34823 + memset(&p->aOp[oldSize], 0, (p->nOpAlloc-oldSize)*sizeof(Op));
34825 + pOp = &p->aOp[i];
34826 + pOp->opcode = op;
34828 + if( p2<0 && (-1-p2)<p->nLabel && p->aLabel[-1-p2]>=0 ){
34829 + p2 = p->aLabel[-1-p2];
34833 + pOp->p3type = P3_NOTUSED;
34835 + if( sqlite_vdbe_addop_trace ) sqliteVdbePrintOp(0, i, &p->aOp[i]);
34841 +** Add an opcode that includes the p3 value.
34843 +int sqliteVdbeOp3(Vdbe *p, int op, int p1, int p2, const char *zP3, int p3type){
34844 + int addr = sqliteVdbeAddOp(p, op, p1, p2);
34845 + sqliteVdbeChangeP3(p, addr, zP3, p3type);
34850 +** Add multiple opcodes. The list is terminated by an opcode of 0.
34852 +int sqliteVdbeCode(Vdbe *p, ...){
34855 + int opcode, p1, p2;
34858 + while( (opcode = va_arg(ap,int))!=0 ){
34859 + p1 = va_arg(ap,int);
34860 + p2 = va_arg(ap,int);
34861 + sqliteVdbeAddOp(p, opcode, p1, p2);
34870 +** Create a new symbolic label for an instruction that has yet to be
34871 +** coded. The symbolic label is really just a negative number. The
34872 +** label can be used as the P2 value of an operation. Later, when
34873 +** the label is resolved to a specific address, the VDBE will scan
34874 +** through its operation list and change all values of P2 which match
34875 +** the label into the resolved address.
34877 +** The VDBE knows that a P2 value is a label because labels are
34878 +** always negative and P2 values are suppose to be non-negative.
34879 +** Hence, a negative P2 value is a label that has yet to be resolved.
34881 +int sqliteVdbeMakeLabel(Vdbe *p){
34884 + assert( p->magic==VDBE_MAGIC_INIT );
34885 + if( i>=p->nLabelAlloc ){
34887 + p->nLabelAlloc = p->nLabelAlloc*2 + 10;
34888 + aNew = sqliteRealloc( p->aLabel, p->nLabelAlloc*sizeof(p->aLabel[0]));
34890 + sqliteFree(p->aLabel);
34892 + p->aLabel = aNew;
34894 + if( p->aLabel==0 ){
34896 + p->nLabelAlloc = 0;
34899 + p->aLabel[i] = -1;
34904 +** Resolve label "x" to be the address of the next instruction to
34905 +** be inserted. The parameter "x" must have been obtained from
34906 +** a prior call to sqliteVdbeMakeLabel().
34908 +void sqliteVdbeResolveLabel(Vdbe *p, int x){
34910 + assert( p->magic==VDBE_MAGIC_INIT );
34911 + if( x<0 && (-x)<=p->nLabel && p->aOp ){
34912 + if( p->aLabel[-1-x]==p->nOp ) return;
34913 + assert( p->aLabel[-1-x]<0 );
34914 + p->aLabel[-1-x] = p->nOp;
34915 + for(j=0; j<p->nOp; j++){
34916 + if( p->aOp[j].p2==x ) p->aOp[j].p2 = p->nOp;
34922 +** Return the address of the next instruction to be inserted.
34924 +int sqliteVdbeCurrentAddr(Vdbe *p){
34925 + assert( p->magic==VDBE_MAGIC_INIT );
34930 +** Add a whole list of operations to the operation stack. Return the
34931 +** address of the first operation added.
34933 +int sqliteVdbeAddOpList(Vdbe *p, int nOp, VdbeOpList const *aOp){
34935 + assert( p->magic==VDBE_MAGIC_INIT );
34936 + if( p->nOp + nOp >= p->nOpAlloc ){
34937 + int oldSize = p->nOpAlloc;
34939 + p->nOpAlloc = p->nOpAlloc*2 + nOp + 10;
34940 + aNew = sqliteRealloc(p->aOp, p->nOpAlloc*sizeof(Op));
34942 + p->nOpAlloc = oldSize;
34946 + memset(&p->aOp[oldSize], 0, (p->nOpAlloc-oldSize)*sizeof(Op));
34951 + VdbeOpList const *pIn = aOp;
34952 + for(i=0; i<nOp; i++, pIn++){
34953 + int p2 = pIn->p2;
34954 + VdbeOp *pOut = &p->aOp[i+addr];
34955 + pOut->opcode = pIn->opcode;
34956 + pOut->p1 = pIn->p1;
34957 + pOut->p2 = p2<0 ? addr + ADDR(p2) : p2;
34958 + pOut->p3 = pIn->p3;
34959 + pOut->p3type = pIn->p3 ? P3_STATIC : P3_NOTUSED;
34961 + if( sqlite_vdbe_addop_trace ){
34962 + sqliteVdbePrintOp(0, i+addr, &p->aOp[i+addr]);
34972 +** Change the value of the P1 operand for a specific instruction.
34973 +** This routine is useful when a large program is loaded from a
34974 +** static array using sqliteVdbeAddOpList but we want to make a
34975 +** few minor changes to the program.
34977 +void sqliteVdbeChangeP1(Vdbe *p, int addr, int val){
34978 + assert( p->magic==VDBE_MAGIC_INIT );
34979 + if( p && addr>=0 && p->nOp>addr && p->aOp ){
34980 + p->aOp[addr].p1 = val;
34985 +** Change the value of the P2 operand for a specific instruction.
34986 +** This routine is useful for setting a jump destination.
34988 +void sqliteVdbeChangeP2(Vdbe *p, int addr, int val){
34989 + assert( val>=0 );
34990 + assert( p->magic==VDBE_MAGIC_INIT );
34991 + if( p && addr>=0 && p->nOp>addr && p->aOp ){
34992 + p->aOp[addr].p2 = val;
34997 +** Change the value of the P3 operand for a specific instruction.
34998 +** This routine is useful when a large program is loaded from a
34999 +** static array using sqliteVdbeAddOpList but we want to make a
35000 +** few minor changes to the program.
35002 +** If n>=0 then the P3 operand is dynamic, meaning that a copy of
35003 +** the string is made into memory obtained from sqliteMalloc().
35004 +** A value of n==0 means copy bytes of zP3 up to and including the
35005 +** first null byte. If n>0 then copy n+1 bytes of zP3.
35007 +** If n==P3_STATIC it means that zP3 is a pointer to a constant static
35008 +** string and we can just copy the pointer. n==P3_POINTER means zP3 is
35009 +** a pointer to some object other than a string.
35011 +** If addr<0 then change P3 on the most recently inserted instruction.
35013 +void sqliteVdbeChangeP3(Vdbe *p, int addr, const char *zP3, int n){
35015 + assert( p->magic==VDBE_MAGIC_INIT );
35016 + if( p==0 || p->aOp==0 ) return;
35017 + if( addr<0 || addr>=p->nOp ){
35018 + addr = p->nOp - 1;
35019 + if( addr<0 ) return;
35021 + pOp = &p->aOp[addr];
35022 + if( pOp->p3 && pOp->p3type==P3_DYNAMIC ){
35023 + sqliteFree(pOp->p3);
35028 + pOp->p3type = P3_NOTUSED;
35030 + pOp->p3 = (char*)zP3;
35033 + sqliteSetNString(&pOp->p3, zP3, n, 0);
35034 + pOp->p3type = P3_DYNAMIC;
35039 +** If the P3 operand to the specified instruction appears
35040 +** to be a quoted string token, then this procedure removes
35043 +** The quoting operator can be either a grave ascent (ASCII 0x27)
35044 +** or a double quote character (ASCII 0x22). Two quotes in a row
35045 +** resolve to be a single actual quote character within the string.
35047 +void sqliteVdbeDequoteP3(Vdbe *p, int addr){
35049 + assert( p->magic==VDBE_MAGIC_INIT );
35050 + if( p->aOp==0 ) return;
35051 + if( addr<0 || addr>=p->nOp ){
35052 + addr = p->nOp - 1;
35053 + if( addr<0 ) return;
35055 + pOp = &p->aOp[addr];
35056 + if( pOp->p3==0 || pOp->p3[0]==0 ) return;
35057 + if( pOp->p3type==P3_POINTER ) return;
35058 + if( pOp->p3type!=P3_DYNAMIC ){
35059 + pOp->p3 = sqliteStrDup(pOp->p3);
35060 + pOp->p3type = P3_DYNAMIC;
35062 + sqliteDequote(pOp->p3);
35066 +** On the P3 argument of the given instruction, change all
35067 +** strings of whitespace characters into a single space and
35068 +** delete leading and trailing whitespace.
35070 +void sqliteVdbeCompressSpace(Vdbe *p, int addr){
35071 + unsigned char *z;
35074 + assert( p->magic==VDBE_MAGIC_INIT );
35075 + if( p->aOp==0 || addr<0 || addr>=p->nOp ) return;
35076 + pOp = &p->aOp[addr];
35077 + if( pOp->p3type==P3_POINTER ){
35080 + if( pOp->p3type!=P3_DYNAMIC ){
35081 + pOp->p3 = sqliteStrDup(pOp->p3);
35082 + pOp->p3type = P3_DYNAMIC;
35084 + z = (unsigned char*)pOp->p3;
35085 + if( z==0 ) return;
35087 + while( isspace(z[i]) ){ i++; }
35089 + if( isspace(z[i]) ){
35091 + while( isspace(z[++i]) ){}
35096 + while( j>0 && isspace(z[j-1]) ){ j--; }
35101 +** Search for the current program for the given opcode and P2
35102 +** value. Return the address plus 1 if found and 0 if not found.
35104 +int sqliteVdbeFindOp(Vdbe *p, int op, int p2){
35106 + assert( p->magic==VDBE_MAGIC_INIT );
35107 + for(i=0; i<p->nOp; i++){
35108 + if( p->aOp[i].opcode==op && p->aOp[i].p2==p2 ) return i+1;
35114 +** Return the opcode for a given address.
35116 +VdbeOp *sqliteVdbeGetOp(Vdbe *p, int addr){
35117 + assert( p->magic==VDBE_MAGIC_INIT );
35118 + assert( addr>=0 && addr<p->nOp );
35119 + return &p->aOp[addr];
35123 +** The following group or routines are employed by installable functions
35124 +** to return their results.
35126 +** The sqlite_set_result_string() routine can be used to return a string
35127 +** value or to return a NULL. To return a NULL, pass in NULL for zResult.
35128 +** A copy is made of the string before this routine returns so it is safe
35129 +** to pass in an ephemeral string.
35131 +** sqlite_set_result_error() works like sqlite_set_result_string() except
35132 +** that it signals a fatal error. The string argument, if any, is the
35133 +** error message. If the argument is NULL a generic substitute error message
35136 +** The sqlite_set_result_int() and sqlite_set_result_double() set the return
35137 +** value of the user function to an integer or a double.
35139 +** These routines are defined here in vdbe.c because they depend on knowing
35140 +** the internals of the sqlite_func structure which is only defined in
35141 +** this source file.
35143 +char *sqlite_set_result_string(sqlite_func *p, const char *zResult, int n){
35144 + assert( !p->isStep );
35145 + if( p->s.flags & MEM_Dyn ){
35146 + sqliteFree(p->s.z);
35148 + if( zResult==0 ){
35149 + p->s.flags = MEM_Null;
35154 + if( n<0 ) n = strlen(zResult);
35156 + memcpy(p->s.zShort, zResult, n);
35157 + p->s.zShort[n] = 0;
35158 + p->s.flags = MEM_Str | MEM_Short;
35159 + p->s.z = p->s.zShort;
35161 + p->s.z = sqliteMallocRaw( n+1 );
35163 + memcpy(p->s.z, zResult, n);
35166 + p->s.flags = MEM_Str | MEM_Dyn;
35172 +void sqlite_set_result_int(sqlite_func *p, int iResult){
35173 + assert( !p->isStep );
35174 + if( p->s.flags & MEM_Dyn ){
35175 + sqliteFree(p->s.z);
35177 + p->s.i = iResult;
35178 + p->s.flags = MEM_Int;
35180 +void sqlite_set_result_double(sqlite_func *p, double rResult){
35181 + assert( !p->isStep );
35182 + if( p->s.flags & MEM_Dyn ){
35183 + sqliteFree(p->s.z);
35185 + p->s.r = rResult;
35186 + p->s.flags = MEM_Real;
35188 +void sqlite_set_result_error(sqlite_func *p, const char *zMsg, int n){
35189 + assert( !p->isStep );
35190 + sqlite_set_result_string(p, zMsg, n);
35195 +** Extract the user data from a sqlite_func structure and return a
35198 +void *sqlite_user_data(sqlite_func *p){
35199 + assert( p && p->pFunc );
35200 + return p->pFunc->pUserData;
35204 +** Allocate or return the aggregate context for a user function. A new
35205 +** context is allocated on the first call. Subsequent calls return the
35206 +** same context that was returned on prior calls.
35208 +** This routine is defined here in vdbe.c because it depends on knowing
35209 +** the internals of the sqlite_func structure which is only defined in
35210 +** this source file.
35212 +void *sqlite_aggregate_context(sqlite_func *p, int nByte){
35213 + assert( p && p->pFunc && p->pFunc->xStep );
35214 + if( p->pAgg==0 ){
35215 + if( nByte<=NBFS ){
35216 + p->pAgg = (void*)p->s.z;
35217 + memset(p->pAgg, 0, nByte);
35219 + p->pAgg = sqliteMalloc( nByte );
35226 +** Return the number of times the Step function of a aggregate has been
35229 +** This routine is defined here in vdbe.c because it depends on knowing
35230 +** the internals of the sqlite_func structure which is only defined in
35231 +** this source file.
35233 +int sqlite_aggregate_count(sqlite_func *p){
35234 + assert( p && p->pFunc && p->pFunc->xStep );
35238 +#if !defined(NDEBUG) || defined(VDBE_PROFILE)
35240 +** Print a single opcode. This routine is used for debugging only.
35242 +void sqliteVdbePrintOp(FILE *pOut, int pc, Op *pOp){
35245 + if( pOp->p3type==P3_POINTER ){
35246 + sprintf(zPtr, "ptr(%#lx)", (long)pOp->p3);
35251 + if( pOut==0 ) pOut = stdout;
35252 + fprintf(pOut,"%4d %-12s %4d %4d %s\n",
35253 + pc, sqliteOpcodeNames[pOp->opcode], pOp->p1, pOp->p2, zP3 ? zP3 : "");
35259 +** Give a listing of the program in the virtual machine.
35261 +** The interface is the same as sqliteVdbeExec(). But instead of
35262 +** running the code, it invokes the callback once for each instruction.
35263 +** This feature is used to implement "EXPLAIN".
35265 +int sqliteVdbeList(
35266 + Vdbe *p /* The VDBE */
35268 + sqlite *db = p->db;
35270 + int rc = SQLITE_OK;
35271 + static char *azColumnNames[] = {
35272 + "addr", "opcode", "p1", "p2", "p3",
35273 + "int", "text", "int", "int", "text",
35277 + assert( p->popStack==0 );
35278 + assert( p->explain );
35279 + p->azColName = azColumnNames;
35280 + p->azResColumn = p->zArgv;
35281 + for(i=0; i<5; i++) p->zArgv[i] = p->aStack[i].zShort;
35284 + p->rc = SQLITE_OK;
35285 + rc = SQLITE_DONE;
35286 + }else if( db->flags & SQLITE_Interrupt ){
35287 + db->flags &= ~SQLITE_Interrupt;
35288 + if( db->magic!=SQLITE_MAGIC_BUSY ){
35289 + p->rc = SQLITE_MISUSE;
35291 + p->rc = SQLITE_INTERRUPT;
35293 + rc = SQLITE_ERROR;
35294 + sqliteSetString(&p->zErrMsg, sqlite_error_string(p->rc), (char*)0);
35296 + sprintf(p->zArgv[0],"%d",i);
35297 + sprintf(p->zArgv[2],"%d", p->aOp[i].p1);
35298 + sprintf(p->zArgv[3],"%d", p->aOp[i].p2);
35299 + if( p->aOp[i].p3type==P3_POINTER ){
35300 + sprintf(p->aStack[4].zShort, "ptr(%#lx)", (long)p->aOp[i].p3);
35301 + p->zArgv[4] = p->aStack[4].zShort;
35303 + p->zArgv[4] = p->aOp[i].p3;
35305 + p->zArgv[1] = sqliteOpcodeNames[p->aOp[i].opcode];
35307 + p->azResColumn = p->zArgv;
35308 + p->nResColumn = 5;
35309 + p->rc = SQLITE_OK;
35316 +** Prepare a virtual machine for execution. This involves things such
35317 +** as allocating stack space and initializing the program counter.
35318 +** After the VDBE has be prepped, it can be executed by one or more
35319 +** calls to sqliteVdbeExec().
35321 +void sqliteVdbeMakeReady(
35322 + Vdbe *p, /* The VDBE */
35323 + int nVar, /* Number of '?' see in the SQL statement */
35324 + int isExplain /* True if the EXPLAIN keywords is present */
35329 + assert( p->magic==VDBE_MAGIC_INIT );
35331 + /* Add a HALT instruction to the very end of the program.
35333 + if( p->nOp==0 || (p->aOp && p->aOp[p->nOp-1].opcode!=OP_Halt) ){
35334 + sqliteVdbeAddOp(p, OP_Halt, 0, 0);
35337 + /* No instruction ever pushes more than a single element onto the
35338 + ** stack. And the stack never grows on successive executions of the
35339 + ** same loop. So the total number of instructions is an upper bound
35340 + ** on the maximum stack depth required.
35342 + ** Allocation all the stack space we will ever need.
35344 + if( p->aStack==0 ){
35346 + assert( nVar>=0 );
35347 + n = isExplain ? 10 : p->nOp;
35348 + p->aStack = sqliteMalloc(
35349 + n*(sizeof(p->aStack[0]) + 2*sizeof(char*)) /* aStack and zArgv */
35350 + + p->nVar*(sizeof(char*)+sizeof(int)+1) /* azVar, anVar, abVar */
35352 + p->zArgv = (char**)&p->aStack[n];
35353 + p->azColName = (char**)&p->zArgv[n];
35354 + p->azVar = (char**)&p->azColName[n];
35355 + p->anVar = (int*)&p->azVar[p->nVar];
35356 + p->abVar = (u8*)&p->anVar[p->nVar];
35359 + sqliteHashInit(&p->agg.hash, SQLITE_HASH_BINARY, 0);
35360 + p->agg.pSearch = 0;
35361 +#ifdef MEMORY_DEBUG
35362 + if( sqliteOsFileExists("vdbe_trace") ){
35363 + p->trace = stdout;
35366 + p->pTos = &p->aStack[-1];
35368 + p->rc = SQLITE_OK;
35369 + p->uniqueCnt = 0;
35370 + p->returnDepth = 0;
35371 + p->errorAction = OE_Abort;
35372 + p->undoTransOnError = 0;
35374 + p->explain |= isExplain;
35375 + p->magic = VDBE_MAGIC_RUN;
35376 +#ifdef VDBE_PROFILE
35379 + for(i=0; i<p->nOp; i++){
35380 + p->aOp[i].cnt = 0;
35381 + p->aOp[i].cycles = 0;
35389 +** Remove any elements that remain on the sorter for the VDBE given.
35391 +void sqliteVdbeSorterReset(Vdbe *p){
35392 + while( p->pSort ){
35393 + Sorter *pSorter = p->pSort;
35394 + p->pSort = pSorter->pNext;
35395 + sqliteFree(pSorter->zKey);
35396 + sqliteFree(pSorter->pData);
35397 + sqliteFree(pSorter);
35402 +** Reset an Agg structure. Delete all its contents.
35404 +** For installable aggregate functions, if the step function has been
35405 +** called, make sure the finalizer function has also been called. The
35406 +** finalizer might need to free memory that was allocated as part of its
35407 +** private context. If the finalizer has not been called yet, call it
35410 +void sqliteVdbeAggReset(Agg *pAgg){
35413 + for(p = sqliteHashFirst(&pAgg->hash); p; p = sqliteHashNext(p)){
35414 + AggElem *pElem = sqliteHashData(p);
35415 + assert( pAgg->apFunc!=0 );
35416 + for(i=0; i<pAgg->nMem; i++){
35417 + Mem *pMem = &pElem->aMem[i];
35418 + if( pAgg->apFunc[i] && (pMem->flags & MEM_AggCtx)!=0 ){
35420 + ctx.pFunc = pAgg->apFunc[i];
35421 + ctx.s.flags = MEM_Null;
35422 + ctx.pAgg = pMem->z;
35423 + ctx.cnt = pMem->i;
35426 + (*pAgg->apFunc[i]->xFinalize)(&ctx);
35427 + if( pMem->z!=0 && pMem->z!=pMem->zShort ){
35428 + sqliteFree(pMem->z);
35430 + if( ctx.s.flags & MEM_Dyn ){
35431 + sqliteFree(ctx.s.z);
35433 + }else if( pMem->flags & MEM_Dyn ){
35434 + sqliteFree(pMem->z);
35437 + sqliteFree(pElem);
35439 + sqliteHashClear(&pAgg->hash);
35440 + sqliteFree(pAgg->apFunc);
35441 + pAgg->apFunc = 0;
35442 + pAgg->pCurrent = 0;
35443 + pAgg->pSearch = 0;
35448 +** Delete a keylist
35450 +void sqliteVdbeKeylistFree(Keylist *p){
35452 + Keylist *pNext = p->pNext;
35459 +** Close a cursor and release all the resources that cursor happens
35462 +void sqliteVdbeCleanupCursor(Cursor *pCx){
35463 + if( pCx->pCursor ){
35464 + sqliteBtreeCloseCursor(pCx->pCursor);
35467 + sqliteBtreeClose(pCx->pBt);
35469 + sqliteFree(pCx->pData);
35470 + memset(pCx, 0, sizeof(Cursor));
35474 +** Close all cursors
35476 +static void closeAllCursors(Vdbe *p){
35478 + for(i=0; i<p->nCursor; i++){
35479 + sqliteVdbeCleanupCursor(&p->aCsr[i]);
35481 + sqliteFree(p->aCsr);
35487 +** Clean up the VM after execution.
35489 +** This routine will automatically close any cursors, lists, and/or
35490 +** sorters that were left open. It also deletes the values of
35491 +** variables in the azVariable[] array.
35493 +static void Cleanup(Vdbe *p){
35496 + Mem *pTos = p->pTos;
35497 + while( pTos>=p->aStack ){
35498 + if( pTos->flags & MEM_Dyn ){
35499 + sqliteFree(pTos->z);
35505 + closeAllCursors(p);
35507 + for(i=0; i<p->nMem; i++){
35508 + if( p->aMem[i].flags & MEM_Dyn ){
35509 + sqliteFree(p->aMem[i].z);
35513 + sqliteFree(p->aMem);
35517 + sqliteVdbeKeylistFree(p->pList);
35520 + sqliteVdbeSorterReset(p);
35522 + if( p->pFile!=stdin ) fclose(p->pFile);
35525 + if( p->azField ){
35526 + sqliteFree(p->azField);
35531 + sqliteFree(p->zLine);
35534 + p->nLineAlloc = 0;
35535 + sqliteVdbeAggReset(&p->agg);
35537 + for(i=0; i<p->nSet; i++){
35538 + sqliteHashClear(&p->aSet[i].hash);
35541 + sqliteFree(p->aSet);
35544 + if( p->keylistStack ){
35546 + for(ii = 0; ii < p->keylistStackDepth; ii++){
35547 + sqliteVdbeKeylistFree(p->keylistStack[ii]);
35549 + sqliteFree(p->keylistStack);
35550 + p->keylistStackDepth = 0;
35551 + p->keylistStack = 0;
35553 + sqliteFree(p->contextStack);
35554 + p->contextStack = 0;
35555 + sqliteFree(p->zErrMsg);
35560 +** Clean up a VDBE after execution but do not delete the VDBE just yet.
35561 +** Write any error messages into *pzErrMsg. Return the result code.
35563 +** After this routine is run, the VDBE should be ready to be executed
35566 +int sqliteVdbeReset(Vdbe *p, char **pzErrMsg){
35567 + sqlite *db = p->db;
35570 + if( p->magic!=VDBE_MAGIC_RUN && p->magic!=VDBE_MAGIC_HALT ){
35571 + sqliteSetString(pzErrMsg, sqlite_error_string(SQLITE_MISUSE), (char*)0);
35572 + return SQLITE_MISUSE;
35574 + if( p->zErrMsg ){
35575 + if( pzErrMsg && *pzErrMsg==0 ){
35576 + *pzErrMsg = p->zErrMsg;
35578 + sqliteFree(p->zErrMsg);
35581 + }else if( p->rc ){
35582 + sqliteSetString(pzErrMsg, sqlite_error_string(p->rc), (char*)0);
35585 + if( p->rc!=SQLITE_OK ){
35586 + switch( p->errorAction ){
35588 + if( !p->undoTransOnError ){
35589 + for(i=0; i<db->nDb; i++){
35590 + if( db->aDb[i].pBt ){
35591 + sqliteBtreeRollbackCkpt(db->aDb[i].pBt);
35596 + /* Fall through to ROLLBACK */
35598 + case OE_Rollback: {
35599 + sqliteRollbackAll(db);
35600 + db->flags &= ~SQLITE_InTrans;
35601 + db->onError = OE_Default;
35605 + if( p->undoTransOnError ){
35606 + sqliteRollbackAll(db);
35607 + db->flags &= ~SQLITE_InTrans;
35608 + db->onError = OE_Default;
35613 + sqliteRollbackInternalChanges(db);
35615 + for(i=0; i<db->nDb; i++){
35616 + if( db->aDb[i].pBt && db->aDb[i].inTrans==2 ){
35617 + sqliteBtreeCommitCkpt(db->aDb[i].pBt);
35618 + db->aDb[i].inTrans = 1;
35621 + assert( p->pTos<&p->aStack[p->pc] || sqlite_malloc_failed==1 );
35622 +#ifdef VDBE_PROFILE
35624 + FILE *out = fopen("vdbe_profile.out", "a");
35627 + fprintf(out, "---- ");
35628 + for(i=0; i<p->nOp; i++){
35629 + fprintf(out, "%02x", p->aOp[i].opcode);
35631 + fprintf(out, "\n");
35632 + for(i=0; i<p->nOp; i++){
35633 + fprintf(out, "%6d %10lld %8lld ",
35635 + p->aOp[i].cycles,
35636 + p->aOp[i].cnt>0 ? p->aOp[i].cycles/p->aOp[i].cnt : 0
35638 + sqliteVdbePrintOp(out, i, &p->aOp[i]);
35644 + p->magic = VDBE_MAGIC_INIT;
35649 +** Clean up and delete a VDBE after execution. Return an integer which is
35650 +** the result code. Write any error message text into *pzErrMsg.
35652 +int sqliteVdbeFinalize(Vdbe *p, char **pzErrMsg){
35656 + if( p->magic!=VDBE_MAGIC_RUN && p->magic!=VDBE_MAGIC_HALT ){
35657 + sqliteSetString(pzErrMsg, sqlite_error_string(SQLITE_MISUSE), (char*)0);
35658 + return SQLITE_MISUSE;
35661 + rc = sqliteVdbeReset(p, pzErrMsg);
35662 + sqliteVdbeDelete(p);
35663 + if( db->want_to_close && db->pVdbe==0 ){
35664 + sqlite_close(db);
35666 + if( rc==SQLITE_SCHEMA ){
35667 + sqliteResetInternalSchema(db, 0);
35673 +** Set the values of all variables. Variable $1 in the original SQL will
35674 +** be the string azValue[0]. $2 will have the value azValue[1]. And
35675 +** so forth. If a value is out of range (for example $3 when nValue==2)
35676 +** then its value will be NULL.
35678 +** This routine overrides any prior call.
35680 +int sqlite_bind(sqlite_vm *pVm, int i, const char *zVal, int len, int copy){
35681 + Vdbe *p = (Vdbe*)pVm;
35682 + if( p->magic!=VDBE_MAGIC_RUN || p->pc!=0 ){
35683 + return SQLITE_MISUSE;
35685 + if( i<1 || i>p->nVar ){
35686 + return SQLITE_RANGE;
35689 + if( p->abVar[i] ){
35690 + sqliteFree(p->azVar[i]);
35697 + len = strlen(zVal)+1;
35700 + p->azVar[i] = sqliteMalloc( len );
35701 + if( p->azVar[i] ) memcpy(p->azVar[i], zVal, len);
35703 + p->azVar[i] = (char*)zVal;
35705 + p->abVar[i] = copy;
35706 + p->anVar[i] = len;
35707 + return SQLITE_OK;
35712 +** Delete an entire VDBE.
35714 +void sqliteVdbeDelete(Vdbe *p){
35716 + if( p==0 ) return;
35719 + p->pPrev->pNext = p->pNext;
35721 + assert( p->db->pVdbe==p );
35722 + p->db->pVdbe = p->pNext;
35725 + p->pNext->pPrev = p->pPrev;
35727 + p->pPrev = p->pNext = 0;
35728 + if( p->nOpAlloc==0 ){
35732 + for(i=0; i<p->nOp; i++){
35733 + if( p->aOp[i].p3type==P3_DYNAMIC ){
35734 + sqliteFree(p->aOp[i].p3);
35737 + for(i=0; i<p->nVar; i++){
35738 + if( p->abVar[i] ) sqliteFree(p->azVar[i]);
35740 + sqliteFree(p->aOp);
35741 + sqliteFree(p->aLabel);
35742 + sqliteFree(p->aStack);
35743 + p->magic = VDBE_MAGIC_DEAD;
35748 +** Convert an integer in between the native integer format and
35749 +** the bigEndian format used as the record number for tables.
35751 +** The bigEndian format (most significant byte first) is used for
35752 +** record numbers so that records will sort into the correct order
35753 +** even though memcmp() is used to compare the keys. On machines
35754 +** whose native integer format is little endian (ex: i486) the
35755 +** order of bytes is reversed. On native big-endian machines
35756 +** (ex: Alpha, Sparc, Motorola) the byte order is the same.
35758 +** This function is its own inverse. In other words
35760 +** X == byteSwap(byteSwap(X))
35762 +int sqliteVdbeByteSwap(int x){
35764 + char zBuf[sizeof(int)];
35767 + ux.zBuf[3] = x&0xff;
35768 + ux.zBuf[2] = (x>>8)&0xff;
35769 + ux.zBuf[1] = (x>>16)&0xff;
35770 + ux.zBuf[0] = (x>>24)&0xff;
35775 +** If a MoveTo operation is pending on the given cursor, then do that
35776 +** MoveTo now. Return an error code. If no MoveTo is pending, this
35777 +** routine does nothing and returns SQLITE_OK.
35779 +int sqliteVdbeCursorMoveto(Cursor *p){
35780 + if( p->deferredMoveto ){
35782 + extern int sqlite_search_count;
35783 + sqliteBtreeMoveto(p->pCursor, (char*)&p->movetoTarget, sizeof(int), &res);
35784 + p->lastRecno = keyToInt(p->movetoTarget);
35785 + p->recnoIsValid = res==0;
35787 + sqliteBtreeNext(p->pCursor, &res);
35789 + sqlite_search_count++;
35790 + p->deferredMoveto = 0;
35792 + return SQLITE_OK;
35795 +++ b/ext/sqlite/libsqlite/src/vdbe.c
35798 +** 2001 September 15
35800 +** The author disclaims copyright to this source code. In place of
35801 +** a legal notice, here is a blessing:
35803 +** May you do good and not evil.
35804 +** May you find forgiveness for yourself and forgive others.
35805 +** May you share freely, never taking more than you give.
35807 +*************************************************************************
35808 +** The code in this file implements execution method of the
35809 +** Virtual Database Engine (VDBE). A separate file ("vdbeaux.c")
35810 +** handles housekeeping details such as creating and deleting
35811 +** VDBE instances. This file is solely interested in executing
35812 +** the VDBE program.
35814 +** In the external interface, an "sqlite_vm*" is an opaque pointer
35817 +** The SQL parser generates a program which is then executed by
35818 +** the VDBE to do the work of the SQL statement. VDBE programs are
35819 +** similar in form to assembly language. The program consists of
35820 +** a linear sequence of operations. Each operation has an opcode
35821 +** and 3 operands. Operands P1 and P2 are integers. Operand P3
35822 +** is a null-terminated string. The P2 operand must be non-negative.
35823 +** Opcodes will typically ignore one or more operands. Many opcodes
35824 +** ignore all three operands.
35826 +** Computation results are stored on a stack. Each entry on the
35827 +** stack is either an integer, a null-terminated string, a floating point
35828 +** number, or the SQL "NULL" value. An inplicit conversion from one
35829 +** type to the other occurs as necessary.
35831 +** Most of the code in this file is taken up by the sqliteVdbeExec()
35832 +** function which does the work of interpreting a VDBE program.
35833 +** But other routines are also provided to help in building up
35834 +** a program instruction by instruction.
35836 +** Various scripts scan this source file in order to generate HTML
35837 +** documentation, headers files, or other derived files. The formatting
35838 +** of the code in this file is, therefore, important. See other comments
35839 +** in this file for details. If in doubt, do not deviate from existing
35840 +** commenting and indentation practices when changing or adding code.
35844 +#include "sqliteInt.h"
35846 +#include <ctype.h>
35847 +#include "vdbeInt.h"
35850 +** The following global variable is incremented every time a cursor
35851 +** moves, either by the OP_MoveTo or the OP_Next opcode. The test
35852 +** procedures use this information to make sure that indices are
35853 +** working correctly. This variable has no function other than to
35854 +** help verify the correct operation of the library.
35856 +int sqlite_search_count = 0;
35859 +** When this global variable is positive, it gets decremented once before
35860 +** each instruction in the VDBE. When reaches zero, the SQLITE_Interrupt
35861 +** of the db.flags field is set in order to simulate an interrupt.
35863 +** This facility is used for testing purposes only. It does not function
35864 +** in an ordinary build.
35866 +int sqlite_interrupt_count = 0;
35869 +** Advance the virtual machine to the next output row.
35871 +** The return vale will be either SQLITE_BUSY, SQLITE_DONE,
35872 +** SQLITE_ROW, SQLITE_ERROR, or SQLITE_MISUSE.
35874 +** SQLITE_BUSY means that the virtual machine attempted to open
35875 +** a locked database and there is no busy callback registered.
35876 +** Call sqlite_step() again to retry the open. *pN is set to 0
35877 +** and *pazColName and *pazValue are both set to NULL.
35879 +** SQLITE_DONE means that the virtual machine has finished
35880 +** executing. sqlite_step() should not be called again on this
35881 +** virtual machine. *pN and *pazColName are set appropriately
35882 +** but *pazValue is set to NULL.
35884 +** SQLITE_ROW means that the virtual machine has generated another
35885 +** row of the result set. *pN is set to the number of columns in
35886 +** the row. *pazColName is set to the names of the columns followed
35887 +** by the column datatypes. *pazValue is set to the values of each
35888 +** column in the row. The value of the i-th column is (*pazValue)[i].
35889 +** The name of the i-th column is (*pazColName)[i] and the datatype
35890 +** of the i-th column is (*pazColName)[i+*pN].
35892 +** SQLITE_ERROR means that a run-time error (such as a constraint
35893 +** violation) has occurred. The details of the error will be returned
35894 +** by the next call to sqlite_finalize(). sqlite_step() should not
35895 +** be called again on the VM.
35897 +** SQLITE_MISUSE means that the this routine was called inappropriately.
35898 +** Perhaps it was called on a virtual machine that had already been
35899 +** finalized or on one that had previously returned SQLITE_ERROR or
35900 +** SQLITE_DONE. Or it could be the case the the same database connection
35901 +** is being used simulataneously by two or more threads.
35904 + sqlite_vm *pVm, /* The virtual machine to execute */
35905 + int *pN, /* OUT: Number of columns in result */
35906 + const char ***pazValue, /* OUT: Column data */
35907 + const char ***pazColName /* OUT: Column names and datatypes */
35909 + Vdbe *p = (Vdbe*)pVm;
35913 + if( !p || p->magic!=VDBE_MAGIC_RUN ){
35914 + return SQLITE_MISUSE;
35917 + if( sqliteSafetyOn(db) ){
35918 + p->rc = SQLITE_MISUSE;
35919 + return SQLITE_MISUSE;
35921 + if( p->explain ){
35922 + rc = sqliteVdbeList(p);
35924 + rc = sqliteVdbeExec(p);
35926 + if( rc==SQLITE_DONE || rc==SQLITE_ROW ){
35927 + if( pazColName ) *pazColName = (const char**)p->azColName;
35928 + if( pN ) *pN = p->nResColumn;
35930 + if( pazColName) *pazColName = 0;
35931 + if( pN ) *pN = 0;
35934 + if( rc==SQLITE_ROW ){
35935 + *pazValue = (const char**)p->azResColumn;
35940 + if( sqliteSafetyOff(db) ){
35941 + return SQLITE_MISUSE;
35947 +** Insert a new aggregate element and make it the element that
35950 +** Return 0 on success and 1 if memory is exhausted.
35952 +static int AggInsert(Agg *p, char *zKey, int nKey){
35953 + AggElem *pElem, *pOld;
35956 + pElem = sqliteMalloc( sizeof(AggElem) + nKey +
35957 + (p->nMem-1)*sizeof(pElem->aMem[0]) );
35958 + if( pElem==0 ) return 1;
35959 + pElem->zKey = (char*)&pElem->aMem[p->nMem];
35960 + memcpy(pElem->zKey, zKey, nKey);
35961 + pElem->nKey = nKey;
35962 + pOld = sqliteHashInsert(&p->hash, pElem->zKey, pElem->nKey, pElem);
35964 + assert( pOld==pElem ); /* Malloc failed on insert */
35965 + sqliteFree(pOld);
35968 + for(i=0, pMem=pElem->aMem; i<p->nMem; i++, pMem++){
35969 + pMem->flags = MEM_Null;
35971 + p->pCurrent = pElem;
35976 +** Get the AggElem currently in focus
35978 +#define AggInFocus(P) ((P).pCurrent ? (P).pCurrent : _AggInFocus(&(P)))
35979 +static AggElem *_AggInFocus(Agg *p){
35980 + HashElem *pElem = sqliteHashFirst(&p->hash);
35982 + AggInsert(p,"",1);
35983 + pElem = sqliteHashFirst(&p->hash);
35985 + return pElem ? sqliteHashData(pElem) : 0;
35989 +** Convert the given stack entity into a string if it isn't one
35992 +#define Stringify(P) if(((P)->flags & MEM_Str)==0){hardStringify(P);}
35993 +static int hardStringify(Mem *pStack){
35994 + int fg = pStack->flags;
35995 + if( fg & MEM_Real ){
35996 + sqlite_snprintf(sizeof(pStack->zShort),pStack->zShort,"%.15g",pStack->r);
35997 + }else if( fg & MEM_Int ){
35998 + sqlite_snprintf(sizeof(pStack->zShort),pStack->zShort,"%d",pStack->i);
36000 + pStack->zShort[0] = 0;
36002 + pStack->z = pStack->zShort;
36003 + pStack->n = strlen(pStack->zShort)+1;
36004 + pStack->flags = MEM_Str | MEM_Short;
36009 +** Convert the given stack entity into a string that has been obtained
36010 +** from sqliteMalloc(). This is different from Stringify() above in that
36011 +** Stringify() will use the NBFS bytes of static string space if the string
36012 +** will fit but this routine always mallocs for space.
36013 +** Return non-zero if we run out of memory.
36015 +#define Dynamicify(P) (((P)->flags & MEM_Dyn)==0 ? hardDynamicify(P):0)
36016 +static int hardDynamicify(Mem *pStack){
36017 + int fg = pStack->flags;
36019 + if( (fg & MEM_Str)==0 ){
36020 + hardStringify(pStack);
36022 + assert( (fg & MEM_Dyn)==0 );
36023 + z = sqliteMallocRaw( pStack->n );
36024 + if( z==0 ) return 1;
36025 + memcpy(z, pStack->z, pStack->n);
36027 + pStack->flags |= MEM_Dyn;
36032 +** An ephemeral string value (signified by the MEM_Ephem flag) contains
36033 +** a pointer to a dynamically allocated string where some other entity
36034 +** is responsible for deallocating that string. Because the stack entry
36035 +** does not control the string, it might be deleted without the stack
36036 +** entry knowing it.
36038 +** This routine converts an ephemeral string into a dynamically allocated
36039 +** string that the stack entry itself controls. In other words, it
36040 +** converts an MEM_Ephem string into an MEM_Dyn string.
36042 +#define Deephemeralize(P) \
36043 + if( ((P)->flags&MEM_Ephem)!=0 && hardDeephem(P) ){ goto no_mem;}
36044 +static int hardDeephem(Mem *pStack){
36046 + assert( (pStack->flags & MEM_Ephem)!=0 );
36047 + z = sqliteMallocRaw( pStack->n );
36048 + if( z==0 ) return 1;
36049 + memcpy(z, pStack->z, pStack->n);
36051 + pStack->flags &= ~MEM_Ephem;
36052 + pStack->flags |= MEM_Dyn;
36057 +** Release the memory associated with the given stack level. This
36058 +** leaves the Mem.flags field in an inconsistent state.
36060 +#define Release(P) if((P)->flags&MEM_Dyn){ sqliteFree((P)->z); }
36063 +** Pop the stack N times.
36065 +static void popStack(Mem **ppTos, int N){
36066 + Mem *pTos = *ppTos;
36076 +** Return TRUE if zNum is a 32-bit signed integer and write
36077 +** the value of the integer into *pNum. If zNum is not an integer
36078 +** or is an integer that is too large to be expressed with just 32
36079 +** bits, then return false.
36081 +** Under Linux (RedHat 7.2) this routine is much faster than atoi()
36082 +** for converting strings into integers.
36084 +static int toInt(const char *zNum, int *pNum){
36088 + if( *zNum=='-' ){
36091 + }else if( *zNum=='+' ){
36097 + for(i=0; (c=zNum[i])>='0' && c<='9'; i++){
36098 + v = v*10 + c - '0';
36100 + *pNum = neg ? -v : v;
36101 + return c==0 && i>0 && (i<10 || (i==10 && memcmp(zNum,"2147483647",10)<=0));
36105 +** Convert the given stack entity into a integer if it isn't one
36108 +** Any prior string or real representation is invalidated.
36109 +** NULLs are converted into 0.
36111 +#define Integerify(P) if(((P)->flags&MEM_Int)==0){ hardIntegerify(P); }
36112 +static void hardIntegerify(Mem *pStack){
36113 + if( pStack->flags & MEM_Real ){
36114 + pStack->i = (int)pStack->r;
36116 + }else if( pStack->flags & MEM_Str ){
36117 + toInt(pStack->z, &pStack->i);
36122 + pStack->flags = MEM_Int;
36126 +** Get a valid Real representation for the given stack element.
36128 +** Any prior string or integer representation is retained.
36129 +** NULLs are converted into 0.0.
36131 +#define Realify(P) if(((P)->flags&MEM_Real)==0){ hardRealify(P); }
36132 +static void hardRealify(Mem *pStack){
36133 + if( pStack->flags & MEM_Str ){
36134 + pStack->r = sqliteAtoF(pStack->z, 0);
36135 + }else if( pStack->flags & MEM_Int ){
36136 + pStack->r = pStack->i;
36140 + pStack->flags |= MEM_Real;
36144 +** The parameters are pointers to the head of two sorted lists
36145 +** of Sorter structures. Merge these two lists together and return
36146 +** a single sorted list. This routine forms the core of the merge-sort
36149 +** In the case of a tie, left sorts in front of right.
36151 +static Sorter *Merge(Sorter *pLeft, Sorter *pRight){
36155 + pTail->pNext = 0;
36156 + while( pLeft && pRight ){
36157 + int c = sqliteSortCompare(pLeft->zKey, pRight->zKey);
36159 + pTail->pNext = pLeft;
36160 + pLeft = pLeft->pNext;
36162 + pTail->pNext = pRight;
36163 + pRight = pRight->pNext;
36165 + pTail = pTail->pNext;
36168 + pTail->pNext = pLeft;
36169 + }else if( pRight ){
36170 + pTail->pNext = pRight;
36172 + return sHead.pNext;
36176 +** The following routine works like a replacement for the standard
36177 +** library routine fgets(). The difference is in how end-of-line (EOL)
36178 +** is handled. Standard fgets() uses LF for EOL under unix, CRLF
36179 +** under windows, and CR under mac. This routine accepts any of these
36180 +** character sequences as an EOL mark. The EOL mark is replaced by
36181 +** a single LF character in zBuf.
36183 +static char *vdbe_fgets(char *zBuf, int nBuf, FILE *in){
36185 + for(i=0; i<nBuf-1 && (c=getc(in))!=EOF; i++){
36187 + if( c=='\r' || c=='\n' ){
36191 + if( c!=EOF && c!='\n' ) ungetc(c, in);
36198 + return i>0 ? zBuf : 0;
36202 +** Make sure there is space in the Vdbe structure to hold at least
36203 +** mxCursor cursors. If there is not currently enough space, then
36206 +** If a memory allocation error occurs, return 1. Return 0 if
36207 +** everything works.
36209 +static int expandCursorArraySize(Vdbe *p, int mxCursor){
36210 + if( mxCursor>=p->nCursor ){
36211 + Cursor *aCsr = sqliteRealloc( p->aCsr, (mxCursor+1)*sizeof(Cursor) );
36212 + if( aCsr==0 ) return 1;
36214 + memset(&p->aCsr[p->nCursor], 0, sizeof(Cursor)*(mxCursor+1-p->nCursor));
36215 + p->nCursor = mxCursor+1;
36220 +#ifdef VDBE_PROFILE
36222 +** The following routine only works on pentium-class processors.
36223 +** It uses the RDTSC opcode to read cycle count value out of the
36224 +** processor and returns that value. This can be used for high-res
36227 +__inline__ unsigned long long int hwtime(void){
36228 + unsigned long long int x;
36229 + __asm__("rdtsc\n\t"
36230 + "mov %%edx, %%ecx\n\t"
36237 +** The CHECK_FOR_INTERRUPT macro defined here looks to see if the
36238 +** sqlite_interrupt() routine has been called. If it has been, then
36239 +** processing of the VDBE program is interrupted.
36241 +** This macro added to every instruction that does a jump in order to
36242 +** implement a loop. This test used to be on every single instruction,
36243 +** but that meant we more testing that we needed. By only testing the
36244 +** flag on jump instructions, we get a (small) speed improvement.
36246 +#define CHECK_FOR_INTERRUPT \
36247 + if( db->flags & SQLITE_Interrupt ) goto abort_due_to_interrupt;
36251 +** Execute as much of a VDBE program as we can then return.
36253 +** sqliteVdbeMakeReady() must be called before this routine in order to
36254 +** close the program with a final OP_Halt and to set up the callbacks
36255 +** and the error message pointer.
36257 +** Whenever a row or result data is available, this routine will either
36258 +** invoke the result callback (if there is one) or return with
36261 +** If an attempt is made to open a locked database, then this routine
36262 +** will either invoke the busy callback (if there is one) or it will
36263 +** return SQLITE_BUSY.
36265 +** If an error occurs, an error message is written to memory obtained
36266 +** from sqliteMalloc() and p->zErrMsg is made to point to that memory.
36267 +** The error code is stored in p->rc and this routine returns SQLITE_ERROR.
36269 +** If the callback ever returns non-zero, then the program exits
36270 +** immediately. There will be no error message but the p->rc field is
36271 +** set to SQLITE_ABORT and this routine will return SQLITE_ERROR.
36273 +** A memory allocation error causes p->rc to be set to SQLITE_NOMEM and this
36274 +** routine to return SQLITE_ERROR.
36276 +** Other fatal errors return SQLITE_ERROR.
36278 +** After this routine has finished, sqliteVdbeFinalize() should be
36279 +** used to clean up the mess that was left behind.
36281 +int sqliteVdbeExec(
36282 + Vdbe *p /* The VDBE */
36284 + int pc; /* The program counter */
36285 + Op *pOp; /* Current operation */
36286 + int rc = SQLITE_OK; /* Value to return */
36287 + sqlite *db = p->db; /* The database */
36288 + Mem *pTos; /* Top entry in the operand stack */
36289 + char zBuf[100]; /* Space to sprintf() an integer */
36290 +#ifdef VDBE_PROFILE
36291 + unsigned long long start; /* CPU clock count at start of opcode */
36292 + int origPc; /* Program counter at start of opcode */
36294 +#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
36295 + int nProgressOps = 0; /* Opcodes executed since progress callback. */
36298 + if( p->magic!=VDBE_MAGIC_RUN ) return SQLITE_MISUSE;
36299 + assert( db->magic==SQLITE_MAGIC_BUSY );
36300 + assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY );
36301 + p->rc = SQLITE_OK;
36302 + assert( p->explain==0 );
36303 + if( sqlite_malloc_failed ) goto no_mem;
36305 + if( p->popStack ){
36306 + popStack(&pTos, p->popStack);
36309 + CHECK_FOR_INTERRUPT;
36310 + for(pc=p->pc; rc==SQLITE_OK; pc++){
36311 + assert( pc>=0 && pc<p->nOp );
36312 + assert( pTos<=&p->aStack[pc] );
36313 +#ifdef VDBE_PROFILE
36315 + start = hwtime();
36317 + pOp = &p->aOp[pc];
36319 + /* Only allow tracing if NDEBUG is not defined.
36323 + sqliteVdbePrintOp(p->trace, pc, pOp);
36327 + /* Check to see if we need to simulate an interrupt. This only happens
36328 + ** if we have a special test build.
36330 +#ifdef SQLITE_TEST
36331 + if( sqlite_interrupt_count>0 ){
36332 + sqlite_interrupt_count--;
36333 + if( sqlite_interrupt_count==0 ){
36334 + sqlite_interrupt(db);
36339 +#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
36340 + /* Call the progress callback if it is configured and the required number
36341 + ** of VDBE ops have been executed (either since this invocation of
36342 + ** sqliteVdbeExec() or since last time the progress callback was called).
36343 + ** If the progress callback returns non-zero, exit the virtual machine with
36344 + ** a return code SQLITE_ABORT.
36346 + if( db->xProgress ){
36347 + if( db->nProgressOps==nProgressOps ){
36348 + if( db->xProgress(db->pProgressArg)!=0 ){
36349 + rc = SQLITE_ABORT;
36350 + continue; /* skip to the next iteration of the for loop */
36352 + nProgressOps = 0;
36358 + switch( pOp->opcode ){
36360 +/*****************************************************************************
36361 +** What follows is a massive switch statement where each case implements a
36362 +** separate instruction in the virtual machine. If we follow the usual
36363 +** indentation conventions, each case should be indented by 6 spaces. But
36364 +** that is a lot of wasted space on the left margin. So the code within
36365 +** the switch statement will break with convention and be flush-left. Another
36366 +** big comment (similar to this one) will mark the point in the code where
36367 +** we transition back to normal indentation.
36369 +** The formatting of each case is important. The makefile for SQLite
36370 +** generates two C files "opcodes.h" and "opcodes.c" by scanning this
36371 +** file looking for lines that begin with "case OP_". The opcodes.h files
36372 +** will be filled with #defines that give unique integer values to each
36373 +** opcode and the opcodes.c file is filled with an array of strings where
36374 +** each string is the symbolic name for the corresponding opcode.
36376 +** Documentation about VDBE opcodes is generated by scanning this file
36377 +** for lines of that contain "Opcode:". That line and all subsequent
36378 +** comment lines are used in the generation of the opcode.html documentation
36383 +** Formatting is important to scripts that scan this file.
36384 +** Do not deviate from the formatting style currently in use.
36386 +*****************************************************************************/
36388 +/* Opcode: Goto * P2 *
36390 +** An unconditional jump to address P2.
36391 +** The next instruction executed will be
36392 +** the one at index P2 from the beginning of
36396 + CHECK_FOR_INTERRUPT;
36397 + pc = pOp->p2 - 1;
36401 +/* Opcode: Gosub * P2 *
36403 +** Push the current address plus 1 onto the return address stack
36404 +** and then jump to address P2.
36406 +** The return address stack is of limited depth. If too many
36407 +** OP_Gosub operations occur without intervening OP_Returns, then
36408 +** the return address stack will fill up and processing will abort
36409 +** with a fatal error.
36412 + if( p->returnDepth>=sizeof(p->returnStack)/sizeof(p->returnStack[0]) ){
36413 + sqliteSetString(&p->zErrMsg, "return address stack overflow", (char*)0);
36414 + p->rc = SQLITE_INTERNAL;
36415 + return SQLITE_ERROR;
36417 + p->returnStack[p->returnDepth++] = pc+1;
36418 + pc = pOp->p2 - 1;
36422 +/* Opcode: Return * * *
36424 +** Jump immediately to the next instruction after the last unreturned
36425 +** OP_Gosub. If an OP_Return has occurred for all OP_Gosubs, then
36426 +** processing aborts with a fatal error.
36429 + if( p->returnDepth<=0 ){
36430 + sqliteSetString(&p->zErrMsg, "return address stack underflow", (char*)0);
36431 + p->rc = SQLITE_INTERNAL;
36432 + return SQLITE_ERROR;
36434 + p->returnDepth--;
36435 + pc = p->returnStack[p->returnDepth] - 1;
36439 +/* Opcode: Halt P1 P2 *
36441 +** Exit immediately. All open cursors, Lists, Sorts, etc are closed
36444 +** P1 is the result code returned by sqlite_exec(). For a normal
36445 +** halt, this should be SQLITE_OK (0). For errors, it can be some
36446 +** other value. If P1!=0 then P2 will determine whether or not to
36447 +** rollback the current transaction. Do not rollback if P2==OE_Fail.
36448 +** Do the rollback if P2==OE_Rollback. If P2==OE_Abort, then back
36449 +** out all changes that have occurred during this execution of the
36450 +** VDBE, but do not rollback the transaction.
36452 +** There is an implied "Halt 0 0 0" instruction inserted at the very end of
36453 +** every program. So a jump past the last instruction of the program
36454 +** is the same as executing Halt.
36457 + p->magic = VDBE_MAGIC_HALT;
36459 + if( pOp->p1!=SQLITE_OK ){
36461 + p->errorAction = pOp->p2;
36463 + sqliteSetString(&p->zErrMsg, pOp->p3, (char*)0);
36465 + return SQLITE_ERROR;
36467 + p->rc = SQLITE_OK;
36468 + return SQLITE_DONE;
36472 +/* Opcode: Integer P1 * P3
36474 +** The integer value P1 is pushed onto the stack. If P3 is not zero
36475 +** then it is assumed to be a string representation of the same integer.
36477 +case OP_Integer: {
36479 + pTos->i = pOp->p1;
36480 + pTos->flags = MEM_Int;
36482 + pTos->z = pOp->p3;
36483 + pTos->flags |= MEM_Str | MEM_Static;
36484 + pTos->n = strlen(pOp->p3)+1;
36489 +/* Opcode: String * * P3
36491 +** The string value P3 is pushed onto the stack. If P3==0 then a
36492 +** NULL is pushed onto the stack.
36495 + char *z = pOp->p3;
36498 + pTos->flags = MEM_Null;
36501 + pTos->n = strlen(z) + 1;
36502 + pTos->flags = MEM_Str | MEM_Static;
36507 +/* Opcode: Variable P1 * *
36509 +** Push the value of variable P1 onto the stack. A variable is
36510 +** an unknown in the original SQL string as handed to sqlite_compile().
36511 +** Any occurance of the '?' character in the original SQL is considered
36512 +** a variable. Variables in the SQL string are number from left to
36513 +** right beginning with 1. The values of variables are set using the
36514 +** sqlite_bind() API.
36516 +case OP_Variable: {
36517 + int j = pOp->p1 - 1;
36519 + if( j>=0 && j<p->nVar && p->azVar[j]!=0 ){
36520 + pTos->z = p->azVar[j];
36521 + pTos->n = p->anVar[j];
36522 + pTos->flags = MEM_Str | MEM_Static;
36524 + pTos->flags = MEM_Null;
36529 +/* Opcode: Pop P1 * *
36531 +** P1 elements are popped off of the top of stack and discarded.
36534 + assert( pOp->p1>=0 );
36535 + popStack(&pTos, pOp->p1);
36536 + assert( pTos>=&p->aStack[-1] );
36540 +/* Opcode: Dup P1 P2 *
36542 +** A copy of the P1-th element of the stack
36543 +** is made and pushed onto the top of the stack.
36544 +** The top of the stack is element 0. So the
36545 +** instruction "Dup 0 0 0" will make a copy of the
36546 +** top of the stack.
36548 +** If the content of the P1-th element is a dynamically
36549 +** allocated string, then a new copy of that string
36550 +** is made if P2==0. If P2!=0, then just a pointer
36551 +** to the string is copied.
36553 +** Also see the Pull instruction.
36556 + Mem *pFrom = &pTos[-pOp->p1];
36557 + assert( pFrom<=pTos && pFrom>=p->aStack );
36559 + memcpy(pTos, pFrom, sizeof(*pFrom)-NBFS);
36560 + if( pTos->flags & MEM_Str ){
36561 + if( pOp->p2 && (pTos->flags & (MEM_Dyn|MEM_Ephem)) ){
36562 + pTos->flags &= ~MEM_Dyn;
36563 + pTos->flags |= MEM_Ephem;
36564 + }else if( pTos->flags & MEM_Short ){
36565 + memcpy(pTos->zShort, pFrom->zShort, pTos->n);
36566 + pTos->z = pTos->zShort;
36567 + }else if( (pTos->flags & MEM_Static)==0 ){
36568 + pTos->z = sqliteMallocRaw(pFrom->n);
36569 + if( sqlite_malloc_failed ) goto no_mem;
36570 + memcpy(pTos->z, pFrom->z, pFrom->n);
36571 + pTos->flags &= ~(MEM_Static|MEM_Ephem|MEM_Short);
36572 + pTos->flags |= MEM_Dyn;
36578 +/* Opcode: Pull P1 * *
36580 +** The P1-th element is removed from its current location on
36581 +** the stack and pushed back on top of the stack. The
36582 +** top of the stack is element 0, so "Pull 0 0 0" is
36583 +** a no-op. "Pull 1 0 0" swaps the top two elements of
36586 +** See also the Dup instruction.
36589 + Mem *pFrom = &pTos[-pOp->p1];
36594 + Deephemeralize(pTos);
36595 + for(i=0; i<pOp->p1; i++, pFrom++){
36596 + Deephemeralize(&pFrom[1]);
36597 + *pFrom = pFrom[1];
36598 + assert( (pFrom->flags & MEM_Ephem)==0 );
36599 + if( pFrom->flags & MEM_Short ){
36600 + assert( pFrom->flags & MEM_Str );
36601 + assert( pFrom->z==pFrom[1].zShort );
36602 + pFrom->z = pFrom->zShort;
36606 + if( pTos->flags & MEM_Short ){
36607 + assert( pTos->flags & MEM_Str );
36608 + assert( pTos->z==pTos[-pOp->p1].zShort );
36609 + pTos->z = pTos->zShort;
36614 +/* Opcode: Push P1 * *
36616 +** Overwrite the value of the P1-th element down on the
36617 +** stack (P1==0 is the top of the stack) with the value
36618 +** of the top of the stack. Then pop the top of the stack.
36621 + Mem *pTo = &pTos[-pOp->p1];
36623 + assert( pTo>=p->aStack );
36624 + Deephemeralize(pTos);
36627 + if( pTo->flags & MEM_Short ){
36628 + assert( pTo->z==pTos->zShort );
36629 + pTo->z = pTo->zShort;
36636 +/* Opcode: ColumnName P1 P2 P3
36638 +** P3 becomes the P1-th column name (first is 0). An array of pointers
36639 +** to all column names is passed as the 4th parameter to the callback.
36640 +** If P2==1 then this is the last column in the result set and thus the
36641 +** number of columns in the result set will be P1. There must be at least
36642 +** one OP_ColumnName with a P2==1 before invoking OP_Callback and the
36643 +** number of columns specified in OP_Callback must one more than the P1
36644 +** value of the OP_ColumnName that has P2==1.
36646 +case OP_ColumnName: {
36647 + assert( pOp->p1>=0 && pOp->p1<p->nOp );
36648 + p->azColName[pOp->p1] = pOp->p3;
36649 + p->nCallback = 0;
36650 + if( pOp->p2 ) p->nResColumn = pOp->p1+1;
36654 +/* Opcode: Callback P1 * *
36656 +** Pop P1 values off the stack and form them into an array. Then
36657 +** invoke the callback function using the newly formed array as the
36660 +case OP_Callback: {
36662 + char **azArgv = p->zArgv;
36665 + pCol = &pTos[1-pOp->p1];
36666 + assert( pCol>=p->aStack );
36667 + for(i=0; i<pOp->p1; i++, pCol++){
36668 + if( pCol->flags & MEM_Null ){
36672 + azArgv[i] = pCol->z;
36677 + p->azResColumn = azArgv;
36678 + assert( p->nResColumn==pOp->p1 );
36679 + p->popStack = pOp->p1;
36682 + return SQLITE_ROW;
36685 +/* Opcode: Concat P1 P2 P3
36687 +** Look at the first P1 elements of the stack. Append them all
36688 +** together with the lowest element first. Use P3 as a separator.
36689 +** Put the result on the top of the stack. The original P1 elements
36690 +** are popped from the stack if P2==0 and retained if P2==1. If
36691 +** any element of the stack is NULL, then the result is NULL.
36693 +** If P3 is NULL, then use no separator. When P1==1, this routine
36694 +** makes a copy of the top stack element into memory obtained
36695 +** from sqliteMalloc().
36706 + nField = pOp->p1;
36708 + if( zSep==0 ) zSep = "";
36709 + nSep = strlen(zSep);
36710 + assert( &pTos[1-nField] >= p->aStack );
36711 + nByte = 1 - nSep;
36712 + pTerm = &pTos[1-nField];
36713 + for(i=0; i<nField; i++, pTerm++){
36714 + if( pTerm->flags & MEM_Null ){
36718 + Stringify(pTerm);
36719 + nByte += pTerm->n - 1 + nSep;
36723 + if( pOp->p2==0 ){
36724 + popStack(&pTos, nField);
36727 + pTos->flags = MEM_Null;
36730 + zNew = sqliteMallocRaw( nByte );
36731 + if( zNew==0 ) goto no_mem;
36733 + pTerm = &pTos[1-nField];
36734 + for(i=j=0; i<nField; i++, pTerm++){
36735 + assert( pTerm->flags & MEM_Str );
36736 + memcpy(&zNew[j], pTerm->z, pTerm->n-1);
36738 + if( nSep>0 && i<nField-1 ){
36739 + memcpy(&zNew[j], zSep, nSep);
36744 + if( pOp->p2==0 ){
36745 + popStack(&pTos, nField);
36749 + pTos->flags = MEM_Str|MEM_Dyn;
36754 +/* Opcode: Add * * *
36756 +** Pop the top two elements from the stack, add them together,
36757 +** and push the result back onto the stack. If either element
36758 +** is a string then it is converted to a double using the atof()
36759 +** function before the addition.
36760 +** If either operand is NULL, the result is NULL.
36762 +/* Opcode: Multiply * * *
36764 +** Pop the top two elements from the stack, multiply them together,
36765 +** and push the result back onto the stack. If either element
36766 +** is a string then it is converted to a double using the atof()
36767 +** function before the multiplication.
36768 +** If either operand is NULL, the result is NULL.
36770 +/* Opcode: Subtract * * *
36772 +** Pop the top two elements from the stack, subtract the
36773 +** first (what was on top of the stack) from the second (the
36775 +** and push the result back onto the stack. If either element
36776 +** is a string then it is converted to a double using the atof()
36777 +** function before the subtraction.
36778 +** If either operand is NULL, the result is NULL.
36780 +/* Opcode: Divide * * *
36782 +** Pop the top two elements from the stack, divide the
36783 +** first (what was on top of the stack) from the second (the
36785 +** and push the result back onto the stack. If either element
36786 +** is a string then it is converted to a double using the atof()
36787 +** function before the division. Division by zero returns NULL.
36788 +** If either operand is NULL, the result is NULL.
36790 +/* Opcode: Remainder * * *
36792 +** Pop the top two elements from the stack, divide the
36793 +** first (what was on top of the stack) from the second (the
36795 +** and push the remainder after division onto the stack. If either element
36796 +** is a string then it is converted to a double using the atof()
36797 +** function before the division. Division by zero returns NULL.
36798 +** If either operand is NULL, the result is NULL.
36804 +case OP_Remainder: {
36805 + Mem *pNos = &pTos[-1];
36806 + assert( pNos>=p->aStack );
36807 + if( ((pTos->flags | pNos->flags) & MEM_Null)!=0 ){
36811 + pTos->flags = MEM_Null;
36812 + }else if( (pTos->flags & pNos->flags & MEM_Int)==MEM_Int ){
36816 + switch( pOp->opcode ){
36817 + case OP_Add: b += a; break;
36818 + case OP_Subtract: b -= a; break;
36819 + case OP_Multiply: b *= a; break;
36820 + case OP_Divide: {
36821 + if( a==0 ) goto divide_by_zero;
36826 + if( a==0 ) goto divide_by_zero;
36835 + pTos->flags = MEM_Int;
36842 + switch( pOp->opcode ){
36843 + case OP_Add: b += a; break;
36844 + case OP_Subtract: b -= a; break;
36845 + case OP_Multiply: b *= a; break;
36846 + case OP_Divide: {
36847 + if( a==0.0 ) goto divide_by_zero;
36854 + if( ia==0.0 ) goto divide_by_zero;
36863 + pTos->flags = MEM_Real;
36871 + pTos->flags = MEM_Null;
36875 +/* Opcode: Function P1 * P3
36877 +** Invoke a user function (P3 is a pointer to a Function structure that
36878 +** defines the function) with P1 string arguments taken from the stack.
36879 +** Pop all arguments from the stack and push back the result.
36881 +** See also: AggFunc
36883 +case OP_Function: {
36890 + pArg = &pTos[1-n];
36891 + azArgv = p->zArgv;
36892 + for(i=0; i<n; i++, pArg++){
36893 + if( pArg->flags & MEM_Null ){
36897 + azArgv[i] = pArg->z;
36900 + ctx.pFunc = (FuncDef*)pOp->p3;
36901 + ctx.s.flags = MEM_Null;
36905 + if( sqliteSafetyOff(db) ) goto abort_due_to_misuse;
36906 + (*ctx.pFunc->xFunc)(&ctx, n, (const char**)azArgv);
36907 + if( sqliteSafetyOn(db) ) goto abort_due_to_misuse;
36908 + popStack(&pTos, n);
36911 + if( pTos->flags & MEM_Short ){
36912 + pTos->z = pTos->zShort;
36914 + if( ctx.isError ){
36915 + sqliteSetString(&p->zErrMsg,
36916 + (pTos->flags & MEM_Str)!=0 ? pTos->z : "user function error", (char*)0);
36917 + rc = SQLITE_ERROR;
36922 +/* Opcode: BitAnd * * *
36924 +** Pop the top two elements from the stack. Convert both elements
36925 +** to integers. Push back onto the stack the bit-wise AND of the
36927 +** If either operand is NULL, the result is NULL.
36929 +/* Opcode: BitOr * * *
36931 +** Pop the top two elements from the stack. Convert both elements
36932 +** to integers. Push back onto the stack the bit-wise OR of the
36934 +** If either operand is NULL, the result is NULL.
36936 +/* Opcode: ShiftLeft * * *
36938 +** Pop the top two elements from the stack. Convert both elements
36939 +** to integers. Push back onto the stack the top element shifted
36940 +** left by N bits where N is the second element on the stack.
36941 +** If either operand is NULL, the result is NULL.
36943 +/* Opcode: ShiftRight * * *
36945 +** Pop the top two elements from the stack. Convert both elements
36946 +** to integers. Push back onto the stack the top element shifted
36947 +** right by N bits where N is the second element on the stack.
36948 +** If either operand is NULL, the result is NULL.
36952 +case OP_ShiftLeft:
36953 +case OP_ShiftRight: {
36954 + Mem *pNos = &pTos[-1];
36957 + assert( pNos>=p->aStack );
36958 + if( (pTos->flags | pNos->flags) & MEM_Null ){
36959 + popStack(&pTos, 2);
36961 + pTos->flags = MEM_Null;
36964 + Integerify(pTos);
36965 + Integerify(pNos);
36968 + switch( pOp->opcode ){
36969 + case OP_BitAnd: a &= b; break;
36970 + case OP_BitOr: a |= b; break;
36971 + case OP_ShiftLeft: a <<= b; break;
36972 + case OP_ShiftRight: a >>= b; break;
36973 + default: /* CANT HAPPEN */ break;
36975 + assert( (pTos->flags & MEM_Dyn)==0 );
36976 + assert( (pNos->flags & MEM_Dyn)==0 );
36980 + pTos->flags = MEM_Int;
36984 +/* Opcode: AddImm P1 * *
36986 +** Add the value P1 to whatever is on top of the stack. The result
36987 +** is always an integer.
36989 +** To force the top of the stack to be an integer, just add 0.
36992 + assert( pTos>=p->aStack );
36993 + Integerify(pTos);
36994 + pTos->i += pOp->p1;
36998 +/* Opcode: ForceInt P1 P2 *
37000 +** Convert the top of the stack into an integer. If the current top of
37001 +** the stack is not numeric (meaning that is is a NULL or a string that
37002 +** does not look like an integer or floating point number) then pop the
37003 +** stack and jump to P2. If the top of the stack is numeric then
37004 +** convert it into the least integer that is greater than or equal to its
37005 +** current value if P1==0, or to the least integer that is strictly
37006 +** greater than its current value if P1==1.
37008 +case OP_ForceInt: {
37010 + assert( pTos>=p->aStack );
37011 + if( (pTos->flags & (MEM_Int|MEM_Real))==0
37012 + && ((pTos->flags & MEM_Str)==0 || sqliteIsNumber(pTos->z)==0) ){
37015 + pc = pOp->p2 - 1;
37018 + if( pTos->flags & MEM_Int ){
37019 + v = pTos->i + (pOp->p1!=0);
37022 + v = (int)pTos->r;
37023 + if( pTos->r>(double)v ) v++;
37024 + if( pOp->p1 && pTos->r==(double)v ) v++;
37028 + pTos->flags = MEM_Int;
37032 +/* Opcode: MustBeInt P1 P2 *
37034 +** Force the top of the stack to be an integer. If the top of the
37035 +** stack is not an integer and cannot be converted into an integer
37036 +** with out data loss, then jump immediately to P2, or if P2==0
37037 +** raise an SQLITE_MISMATCH exception.
37039 +** If the top of the stack is not an integer and P2 is not zero and
37040 +** P1 is 1, then the stack is popped. In all other cases, the depth
37041 +** of the stack is unchanged.
37043 +case OP_MustBeInt: {
37044 + assert( pTos>=p->aStack );
37045 + if( pTos->flags & MEM_Int ){
37047 + }else if( pTos->flags & MEM_Real ){
37048 + int i = (int)pTos->r;
37049 + double r = (double)i;
37050 + if( r!=pTos->r ){
37054 + }else if( pTos->flags & MEM_Str ){
37056 + if( !toInt(pTos->z, &v) ){
37058 + if( !sqliteIsNumber(pTos->z) ){
37062 + v = (int)pTos->r;
37064 + if( r!=pTos->r ){
37073 + pTos->flags = MEM_Int;
37077 + if( pOp->p2==0 ){
37078 + rc = SQLITE_MISMATCH;
37079 + goto abort_due_to_error;
37081 + if( pOp->p1 ) popStack(&pTos, 1);
37082 + pc = pOp->p2 - 1;
37087 +/* Opcode: Eq P1 P2 *
37089 +** Pop the top two elements from the stack. If they are equal, then
37090 +** jump to instruction P2. Otherwise, continue to the next instruction.
37092 +** If either operand is NULL (and thus if the result is unknown) then
37093 +** take the jump if P1 is true.
37095 +** If both values are numeric, they are converted to doubles using atof()
37096 +** and compared for equality that way. Otherwise the strcmp() library
37097 +** routine is used for the comparison. For a pure text comparison
37100 +** If P2 is zero, do not jump. Instead, push an integer 1 onto the
37101 +** stack if the jump would have been taken, or a 0 if not. Push a
37102 +** NULL if either operand was NULL.
37104 +/* Opcode: Ne P1 P2 *
37106 +** Pop the top two elements from the stack. If they are not equal, then
37107 +** jump to instruction P2. Otherwise, continue to the next instruction.
37109 +** If either operand is NULL (and thus if the result is unknown) then
37110 +** take the jump if P1 is true.
37112 +** If both values are numeric, they are converted to doubles using atof()
37113 +** and compared in that format. Otherwise the strcmp() library
37114 +** routine is used for the comparison. For a pure text comparison
37117 +** If P2 is zero, do not jump. Instead, push an integer 1 onto the
37118 +** stack if the jump would have been taken, or a 0 if not. Push a
37119 +** NULL if either operand was NULL.
37121 +/* Opcode: Lt P1 P2 *
37123 +** Pop the top two elements from the stack. If second element (the
37124 +** next on stack) is less than the first (the top of stack), then
37125 +** jump to instruction P2. Otherwise, continue to the next instruction.
37126 +** In other words, jump if NOS<TOS.
37128 +** If either operand is NULL (and thus if the result is unknown) then
37129 +** take the jump if P1 is true.
37131 +** If both values are numeric, they are converted to doubles using atof()
37132 +** and compared in that format. Numeric values are always less than
37133 +** non-numeric values. If both operands are non-numeric, the strcmp() library
37134 +** routine is used for the comparison. For a pure text comparison
37137 +** If P2 is zero, do not jump. Instead, push an integer 1 onto the
37138 +** stack if the jump would have been taken, or a 0 if not. Push a
37139 +** NULL if either operand was NULL.
37141 +/* Opcode: Le P1 P2 *
37143 +** Pop the top two elements from the stack. If second element (the
37144 +** next on stack) is less than or equal to the first (the top of stack),
37145 +** then jump to instruction P2. In other words, jump if NOS<=TOS.
37147 +** If either operand is NULL (and thus if the result is unknown) then
37148 +** take the jump if P1 is true.
37150 +** If both values are numeric, they are converted to doubles using atof()
37151 +** and compared in that format. Numeric values are always less than
37152 +** non-numeric values. If both operands are non-numeric, the strcmp() library
37153 +** routine is used for the comparison. For a pure text comparison
37156 +** If P2 is zero, do not jump. Instead, push an integer 1 onto the
37157 +** stack if the jump would have been taken, or a 0 if not. Push a
37158 +** NULL if either operand was NULL.
37160 +/* Opcode: Gt P1 P2 *
37162 +** Pop the top two elements from the stack. If second element (the
37163 +** next on stack) is greater than the first (the top of stack),
37164 +** then jump to instruction P2. In other words, jump if NOS>TOS.
37166 +** If either operand is NULL (and thus if the result is unknown) then
37167 +** take the jump if P1 is true.
37169 +** If both values are numeric, they are converted to doubles using atof()
37170 +** and compared in that format. Numeric values are always less than
37171 +** non-numeric values. If both operands are non-numeric, the strcmp() library
37172 +** routine is used for the comparison. For a pure text comparison
37175 +** If P2 is zero, do not jump. Instead, push an integer 1 onto the
37176 +** stack if the jump would have been taken, or a 0 if not. Push a
37177 +** NULL if either operand was NULL.
37179 +/* Opcode: Ge P1 P2 *
37181 +** Pop the top two elements from the stack. If second element (the next
37182 +** on stack) is greater than or equal to the first (the top of stack),
37183 +** then jump to instruction P2. In other words, jump if NOS>=TOS.
37185 +** If either operand is NULL (and thus if the result is unknown) then
37186 +** take the jump if P1 is true.
37188 +** If both values are numeric, they are converted to doubles using atof()
37189 +** and compared in that format. Numeric values are always less than
37190 +** non-numeric values. If both operands are non-numeric, the strcmp() library
37191 +** routine is used for the comparison. For a pure text comparison
37194 +** If P2 is zero, do not jump. Instead, push an integer 1 onto the
37195 +** stack if the jump would have been taken, or a 0 if not. Push a
37196 +** NULL if either operand was NULL.
37204 + Mem *pNos = &pTos[-1];
37207 + assert( pNos>=p->aStack );
37208 + ft = pTos->flags;
37209 + fn = pNos->flags;
37210 + if( (ft | fn) & MEM_Null ){
37211 + popStack(&pTos, 2);
37213 + if( pOp->p1 ) pc = pOp->p2-1;
37216 + pTos->flags = MEM_Null;
37219 + }else if( (ft & fn & MEM_Int)==MEM_Int ){
37220 + c = pNos->i - pTos->i;
37221 + }else if( (ft & MEM_Int)!=0 && (fn & MEM_Str)!=0 && toInt(pNos->z,&v) ){
37223 + }else if( (fn & MEM_Int)!=0 && (ft & MEM_Str)!=0 && toInt(pTos->z,&v) ){
37228 + c = sqliteCompare(pNos->z, pTos->z);
37230 + switch( pOp->opcode ){
37231 + case OP_Eq: c = c==0; break;
37232 + case OP_Ne: c = c!=0; break;
37233 + case OP_Lt: c = c<0; break;
37234 + case OP_Le: c = c<=0; break;
37235 + case OP_Gt: c = c>0; break;
37236 + default: c = c>=0; break;
37238 + popStack(&pTos, 2);
37240 + if( c ) pc = pOp->p2-1;
37244 + pTos->flags = MEM_Int;
37248 +/* INSERT NO CODE HERE!
37250 +** The opcode numbers are extracted from this source file by doing
37252 +** grep '^case OP_' vdbe.c | ... >opcodes.h
37254 +** The opcodes are numbered in the order that they appear in this file.
37255 +** But in order for the expression generating code to work right, the
37256 +** string comparison operators that follow must be numbered exactly 6
37257 +** greater than the numeric comparison opcodes above. So no other
37258 +** cases can appear between the two.
37260 +/* Opcode: StrEq P1 P2 *
37262 +** Pop the top two elements from the stack. If they are equal, then
37263 +** jump to instruction P2. Otherwise, continue to the next instruction.
37265 +** If either operand is NULL (and thus if the result is unknown) then
37266 +** take the jump if P1 is true.
37268 +** The strcmp() library routine is used for the comparison. For a
37269 +** numeric comparison, use OP_Eq.
37271 +** If P2 is zero, do not jump. Instead, push an integer 1 onto the
37272 +** stack if the jump would have been taken, or a 0 if not. Push a
37273 +** NULL if either operand was NULL.
37275 +/* Opcode: StrNe P1 P2 *
37277 +** Pop the top two elements from the stack. If they are not equal, then
37278 +** jump to instruction P2. Otherwise, continue to the next instruction.
37280 +** If either operand is NULL (and thus if the result is unknown) then
37281 +** take the jump if P1 is true.
37283 +** The strcmp() library routine is used for the comparison. For a
37284 +** numeric comparison, use OP_Ne.
37286 +** If P2 is zero, do not jump. Instead, push an integer 1 onto the
37287 +** stack if the jump would have been taken, or a 0 if not. Push a
37288 +** NULL if either operand was NULL.
37290 +/* Opcode: StrLt P1 P2 *
37292 +** Pop the top two elements from the stack. If second element (the
37293 +** next on stack) is less than the first (the top of stack), then
37294 +** jump to instruction P2. Otherwise, continue to the next instruction.
37295 +** In other words, jump if NOS<TOS.
37297 +** If either operand is NULL (and thus if the result is unknown) then
37298 +** take the jump if P1 is true.
37300 +** The strcmp() library routine is used for the comparison. For a
37301 +** numeric comparison, use OP_Lt.
37303 +** If P2 is zero, do not jump. Instead, push an integer 1 onto the
37304 +** stack if the jump would have been taken, or a 0 if not. Push a
37305 +** NULL if either operand was NULL.
37307 +/* Opcode: StrLe P1 P2 *
37309 +** Pop the top two elements from the stack. If second element (the
37310 +** next on stack) is less than or equal to the first (the top of stack),
37311 +** then jump to instruction P2. In other words, jump if NOS<=TOS.
37313 +** If either operand is NULL (and thus if the result is unknown) then
37314 +** take the jump if P1 is true.
37316 +** The strcmp() library routine is used for the comparison. For a
37317 +** numeric comparison, use OP_Le.
37319 +** If P2 is zero, do not jump. Instead, push an integer 1 onto the
37320 +** stack if the jump would have been taken, or a 0 if not. Push a
37321 +** NULL if either operand was NULL.
37323 +/* Opcode: StrGt P1 P2 *
37325 +** Pop the top two elements from the stack. If second element (the
37326 +** next on stack) is greater than the first (the top of stack),
37327 +** then jump to instruction P2. In other words, jump if NOS>TOS.
37329 +** If either operand is NULL (and thus if the result is unknown) then
37330 +** take the jump if P1 is true.
37332 +** The strcmp() library routine is used for the comparison. For a
37333 +** numeric comparison, use OP_Gt.
37335 +** If P2 is zero, do not jump. Instead, push an integer 1 onto the
37336 +** stack if the jump would have been taken, or a 0 if not. Push a
37337 +** NULL if either operand was NULL.
37339 +/* Opcode: StrGe P1 P2 *
37341 +** Pop the top two elements from the stack. If second element (the next
37342 +** on stack) is greater than or equal to the first (the top of stack),
37343 +** then jump to instruction P2. In other words, jump if NOS>=TOS.
37345 +** If either operand is NULL (and thus if the result is unknown) then
37346 +** take the jump if P1 is true.
37348 +** The strcmp() library routine is used for the comparison. For a
37349 +** numeric comparison, use OP_Ge.
37351 +** If P2 is zero, do not jump. Instead, push an integer 1 onto the
37352 +** stack if the jump would have been taken, or a 0 if not. Push a
37353 +** NULL if either operand was NULL.
37361 + Mem *pNos = &pTos[-1];
37363 + assert( pNos>=p->aStack );
37364 + if( (pNos->flags | pTos->flags) & MEM_Null ){
37365 + popStack(&pTos, 2);
37367 + if( pOp->p1 ) pc = pOp->p2-1;
37370 + pTos->flags = MEM_Null;
37376 + c = strcmp(pNos->z, pTos->z);
37378 + /* The asserts on each case of the following switch are there to verify
37379 + ** that string comparison opcodes are always exactly 6 greater than the
37380 + ** corresponding numeric comparison opcodes. The code generator depends
37383 + switch( pOp->opcode ){
37384 + case OP_StrEq: c = c==0; assert( pOp->opcode-6==OP_Eq ); break;
37385 + case OP_StrNe: c = c!=0; assert( pOp->opcode-6==OP_Ne ); break;
37386 + case OP_StrLt: c = c<0; assert( pOp->opcode-6==OP_Lt ); break;
37387 + case OP_StrLe: c = c<=0; assert( pOp->opcode-6==OP_Le ); break;
37388 + case OP_StrGt: c = c>0; assert( pOp->opcode-6==OP_Gt ); break;
37389 + default: c = c>=0; assert( pOp->opcode-6==OP_Ge ); break;
37391 + popStack(&pTos, 2);
37393 + if( c ) pc = pOp->p2-1;
37396 + pTos->flags = MEM_Int;
37402 +/* Opcode: And * * *
37404 +** Pop two values off the stack. Take the logical AND of the
37405 +** two values and push the resulting boolean value back onto the
37408 +/* Opcode: Or * * *
37410 +** Pop two values off the stack. Take the logical OR of the
37411 +** two values and push the resulting boolean value back onto the
37416 + Mem *pNos = &pTos[-1];
37417 + int v1, v2; /* 0==TRUE, 1==FALSE, 2==UNKNOWN or NULL */
37419 + assert( pNos>=p->aStack );
37420 + if( pTos->flags & MEM_Null ){
37423 + Integerify(pTos);
37426 + if( pNos->flags & MEM_Null ){
37429 + Integerify(pNos);
37432 + if( pOp->opcode==OP_And ){
37433 + static const unsigned char and_logic[] = { 0, 1, 2, 1, 1, 1, 2, 1, 2 };
37434 + v1 = and_logic[v1*3+v2];
37436 + static const unsigned char or_logic[] = { 0, 0, 0, 0, 1, 2, 0, 2, 2 };
37437 + v1 = or_logic[v1*3+v2];
37439 + popStack(&pTos, 2);
37442 + pTos->flags = MEM_Null;
37445 + pTos->flags = MEM_Int;
37450 +/* Opcode: Negative * * *
37452 +** Treat the top of the stack as a numeric quantity. Replace it
37453 +** with its additive inverse. If the top of the stack is NULL
37454 +** its value is unchanged.
37456 +/* Opcode: AbsValue * * *
37458 +** Treat the top of the stack as a numeric quantity. Replace it
37459 +** with its absolute value. If the top of the stack is NULL
37460 +** its value is unchanged.
37463 +case OP_AbsValue: {
37464 + assert( pTos>=p->aStack );
37465 + if( pTos->flags & MEM_Real ){
37467 + if( pOp->opcode==OP_Negative || pTos->r<0.0 ){
37468 + pTos->r = -pTos->r;
37470 + pTos->flags = MEM_Real;
37471 + }else if( pTos->flags & MEM_Int ){
37473 + if( pOp->opcode==OP_Negative || pTos->i<0 ){
37474 + pTos->i = -pTos->i;
37476 + pTos->flags = MEM_Int;
37477 + }else if( pTos->flags & MEM_Null ){
37482 + if( pOp->opcode==OP_Negative || pTos->r<0.0 ){
37483 + pTos->r = -pTos->r;
37485 + pTos->flags = MEM_Real;
37490 +/* Opcode: Not * * *
37492 +** Interpret the top of the stack as a boolean value. Replace it
37493 +** with its complement. If the top of the stack is NULL its value
37497 + assert( pTos>=p->aStack );
37498 + if( pTos->flags & MEM_Null ) break; /* Do nothing to NULLs */
37499 + Integerify(pTos);
37501 + pTos->i = !pTos->i;
37502 + pTos->flags = MEM_Int;
37506 +/* Opcode: BitNot * * *
37508 +** Interpret the top of the stack as an value. Replace it
37509 +** with its ones-complement. If the top of the stack is NULL its
37510 +** value is unchanged.
37513 + assert( pTos>=p->aStack );
37514 + if( pTos->flags & MEM_Null ) break; /* Do nothing to NULLs */
37515 + Integerify(pTos);
37517 + pTos->i = ~pTos->i;
37518 + pTos->flags = MEM_Int;
37522 +/* Opcode: Noop * * *
37524 +** Do nothing. This instruction is often useful as a jump
37531 +/* Opcode: If P1 P2 *
37533 +** Pop a single boolean from the stack. If the boolean popped is
37534 +** true, then jump to p2. Otherwise continue to the next instruction.
37535 +** An integer is false if zero and true otherwise. A string is
37536 +** false if it has zero length and true otherwise.
37538 +** If the value popped of the stack is NULL, then take the jump if P1
37539 +** is true and fall through if P1 is false.
37541 +/* Opcode: IfNot P1 P2 *
37543 +** Pop a single boolean from the stack. If the boolean popped is
37544 +** false, then jump to p2. Otherwise continue to the next instruction.
37545 +** An integer is false if zero and true otherwise. A string is
37546 +** false if it has zero length and true otherwise.
37548 +** If the value popped of the stack is NULL, then take the jump if P1
37549 +** is true and fall through if P1 is false.
37554 + assert( pTos>=p->aStack );
37555 + if( pTos->flags & MEM_Null ){
37558 + Integerify(pTos);
37560 + if( pOp->opcode==OP_IfNot ) c = !c;
37562 + assert( (pTos->flags & MEM_Dyn)==0 );
37564 + if( c ) pc = pOp->p2-1;
37568 +/* Opcode: IsNull P1 P2 *
37570 +** If any of the top abs(P1) values on the stack are NULL, then jump
37571 +** to P2. Pop the stack P1 times if P1>0. If P1<0 leave the stack
37578 + if( cnt<0 ) cnt = -cnt;
37579 + pTerm = &pTos[1-cnt];
37580 + assert( pTerm>=p->aStack );
37581 + for(i=0; i<cnt; i++, pTerm++){
37582 + if( pTerm->flags & MEM_Null ){
37587 + if( pOp->p1>0 ) popStack(&pTos, cnt);
37591 +/* Opcode: NotNull P1 P2 *
37593 +** Jump to P2 if the top P1 values on the stack are all not NULL. Pop the
37594 +** stack if P1 times if P1 is greater than zero. If P1 is less than
37595 +** zero then leave the stack unchanged.
37597 +case OP_NotNull: {
37600 + if( cnt<0 ) cnt = -cnt;
37601 + assert( &pTos[1-cnt] >= p->aStack );
37602 + for(i=0; i<cnt && (pTos[1+i-cnt].flags & MEM_Null)==0; i++){}
37603 + if( i>=cnt ) pc = pOp->p2-1;
37604 + if( pOp->p1>0 ) popStack(&pTos, cnt);
37608 +/* Opcode: MakeRecord P1 P2 *
37610 +** Convert the top P1 entries of the stack into a single entry
37611 +** suitable for use as a data record in a database table. The
37612 +** details of the format are irrelavant as long as the OP_Column
37613 +** opcode can decode the record later. Refer to source code
37614 +** comments for the details of the record format.
37616 +** If P2 is true (non-zero) and one or more of the P1 entries
37617 +** that go into building the record is NULL, then add some extra
37618 +** bytes to the record to make it distinct for other entries created
37619 +** during the same run of the VDBE. The extra bytes added are a
37620 +** counter that is reset with each run of the VDBE, so records
37621 +** created this way will not necessarily be distinct across runs.
37622 +** But they should be distinct for transient tables (created using
37623 +** OP_OpenTemp) which is what they are intended for.
37625 +** (Later:) The P2==1 option was intended to make NULLs distinct
37626 +** for the UNION operator. But I have since discovered that NULLs
37627 +** are indistinct for UNION. So this option is never used.
37629 +case OP_MakeRecord: {
37630 + char *zNewRecord;
37637 + int addUnique = 0; /* True to cause bytes to be added to make the
37638 + ** generated record distinct */
37639 + char zTemp[NBFS]; /* Temp space for small records */
37641 + /* Assuming the record contains N fields, the record format looks
37644 + ** -------------------------------------------------------------------
37645 + ** | idx0 | idx1 | ... | idx(N-1) | idx(N) | data0 | ... | data(N-1) |
37646 + ** -------------------------------------------------------------------
37648 + ** All data fields are converted to strings before being stored and
37649 + ** are stored with their null terminators. NULL entries omit the
37650 + ** null terminator. Thus an empty string uses 1 byte and a NULL uses
37651 + ** zero bytes. Data(0) is taken from the lowest element of the stack
37652 + ** and data(N-1) is the top of the stack.
37654 + ** Each of the idx() entries is either 1, 2, or 3 bytes depending on
37655 + ** how big the total record is. Idx(0) contains the offset to the start
37656 + ** of data(0). Idx(k) contains the offset to the start of data(k).
37657 + ** Idx(N) contains the total number of bytes in the record.
37659 + nField = pOp->p1;
37660 + pRec = &pTos[1-nField];
37661 + assert( pRec>=p->aStack );
37663 + for(i=0; i<nField; i++, pRec++){
37664 + if( pRec->flags & MEM_Null ){
37665 + addUnique = pOp->p2;
37668 + nByte += pRec->n;
37671 + if( addUnique ) nByte += sizeof(p->uniqueCnt);
37672 + if( nByte + nField + 1 < 256 ){
37674 + }else if( nByte + 2*nField + 2 < 65536 ){
37679 + nByte += idxWidth*(nField + 1);
37680 + if( nByte>MAX_BYTES_PER_ROW ){
37681 + rc = SQLITE_TOOBIG;
37682 + goto abort_due_to_error;
37684 + if( nByte<=NBFS ){
37685 + zNewRecord = zTemp;
37687 + zNewRecord = sqliteMallocRaw( nByte );
37688 + if( zNewRecord==0 ) goto no_mem;
37691 + addr = idxWidth*(nField+1) + addUnique*sizeof(p->uniqueCnt);
37692 + for(i=0, pRec=&pTos[1-nField]; i<nField; i++, pRec++){
37693 + zNewRecord[j++] = addr & 0xff;
37694 + if( idxWidth>1 ){
37695 + zNewRecord[j++] = (addr>>8)&0xff;
37696 + if( idxWidth>2 ){
37697 + zNewRecord[j++] = (addr>>16)&0xff;
37700 + if( (pRec->flags & MEM_Null)==0 ){
37704 + zNewRecord[j++] = addr & 0xff;
37705 + if( idxWidth>1 ){
37706 + zNewRecord[j++] = (addr>>8)&0xff;
37707 + if( idxWidth>2 ){
37708 + zNewRecord[j++] = (addr>>16)&0xff;
37712 + memcpy(&zNewRecord[j], &p->uniqueCnt, sizeof(p->uniqueCnt));
37714 + j += sizeof(p->uniqueCnt);
37716 + for(i=0, pRec=&pTos[1-nField]; i<nField; i++, pRec++){
37717 + if( (pRec->flags & MEM_Null)==0 ){
37718 + memcpy(&zNewRecord[j], pRec->z, pRec->n);
37722 + popStack(&pTos, nField);
37725 + if( nByte<=NBFS ){
37726 + assert( zNewRecord==zTemp );
37727 + memcpy(pTos->zShort, zTemp, nByte);
37728 + pTos->z = pTos->zShort;
37729 + pTos->flags = MEM_Str | MEM_Short;
37731 + assert( zNewRecord!=zTemp );
37732 + pTos->z = zNewRecord;
37733 + pTos->flags = MEM_Str | MEM_Dyn;
37738 +/* Opcode: MakeKey P1 P2 P3
37740 +** Convert the top P1 entries of the stack into a single entry suitable
37741 +** for use as the key in an index. The top P1 records are
37742 +** converted to strings and merged. The null-terminators
37743 +** are retained and used as separators.
37744 +** The lowest entry in the stack is the first field and the top of the
37745 +** stack becomes the last.
37747 +** If P2 is not zero, then the original entries remain on the stack
37748 +** and the new key is pushed on top. If P2 is zero, the original
37749 +** data is popped off the stack first then the new key is pushed
37750 +** back in its place.
37752 +** P3 is a string that is P1 characters long. Each character is either
37753 +** an 'n' or a 't' to indicates if the argument should be intepreted as
37754 +** numeric or text type. The first character of P3 corresponds to the
37755 +** lowest element on the stack. If P3 is NULL then all arguments are
37756 +** assumed to be of the numeric type.
37758 +** The type makes a difference in that text-type fields may not be
37759 +** introduced by 'b' (as described in the next paragraph). The
37760 +** first character of a text-type field must be either 'a' (if it is NULL)
37761 +** or 'c'. Numeric fields will be introduced by 'b' if their content
37762 +** looks like a well-formed number. Otherwise the 'a' or 'c' will be
37765 +** The key is a concatenation of fields. Each field is terminated by
37766 +** a single 0x00 character. A NULL field is introduced by an 'a' and
37767 +** is followed immediately by its 0x00 terminator. A numeric field is
37768 +** introduced by a single character 'b' and is followed by a sequence
37769 +** of characters that represent the number such that a comparison of
37770 +** the character string using memcpy() sorts the numbers in numerical
37771 +** order. The character strings for numbers are generated using the
37772 +** sqliteRealToSortable() function. A text field is introduced by a
37773 +** 'c' character and is followed by the exact text of the field. The
37774 +** use of an 'a', 'b', or 'c' character at the beginning of each field
37775 +** guarantees that NULLs sort before numbers and that numbers sort
37776 +** before text. 0x00 characters do not occur except as separators
37777 +** between fields.
37779 +** See also: MakeIdxKey, SortMakeKey
37781 +/* Opcode: MakeIdxKey P1 P2 P3
37783 +** Convert the top P1 entries of the stack into a single entry suitable
37784 +** for use as the key in an index. In addition, take one additional integer
37785 +** off of the stack, treat that integer as a four-byte record number, and
37786 +** append the four bytes to the key. Thus a total of P1+1 entries are
37787 +** popped from the stack for this instruction and a single entry is pushed
37788 +** back. The first P1 entries that are popped are strings and the last
37789 +** entry (the lowest on the stack) is an integer record number.
37791 +** The converstion of the first P1 string entries occurs just like in
37792 +** MakeKey. Each entry is separated from the others by a null.
37793 +** The entire concatenation is null-terminated. The lowest entry
37794 +** in the stack is the first field and the top of the stack becomes the
37797 +** If P2 is not zero and one or more of the P1 entries that go into the
37798 +** generated key is NULL, then jump to P2 after the new key has been
37799 +** pushed on the stack. In other words, jump to P2 if the key is
37800 +** guaranteed to be unique. This jump can be used to skip a subsequent
37801 +** uniqueness test.
37803 +** P3 is a string that is P1 characters long. Each character is either
37804 +** an 'n' or a 't' to indicates if the argument should be numeric or
37805 +** text. The first character corresponds to the lowest element on the
37806 +** stack. If P3 is null then all arguments are assumed to be numeric.
37808 +** See also: MakeKey, SortMakeKey
37810 +case OP_MakeIdxKey:
37811 +case OP_MakeKey: {
37817 + int containsNull = 0;
37819 + char zTemp[NBFS];
37821 + addRowid = pOp->opcode==OP_MakeIdxKey;
37822 + nField = pOp->p1;
37823 + pRec = &pTos[1-nField];
37824 + assert( pRec>=p->aStack );
37826 + for(j=0, i=0; i<nField; i++, j++, pRec++){
37827 + int flags = pRec->flags;
37830 + if( flags & MEM_Null ){
37832 + containsNull = 1;
37833 + }else if( pOp->p3 && pOp->p3[j]=='t' ){
37835 + pRec->flags &= ~(MEM_Int|MEM_Real);
37836 + nByte += pRec->n+1;
37837 + }else if( (flags & (MEM_Real|MEM_Int))!=0 || sqliteIsNumber(pRec->z) ){
37838 + if( (flags & (MEM_Real|MEM_Int))==MEM_Int ){
37839 + pRec->r = pRec->i;
37840 + }else if( (flags & (MEM_Real|MEM_Int))==0 ){
37841 + pRec->r = sqliteAtoF(pRec->z, 0);
37844 + z = pRec->zShort;
37845 + sqliteRealToSortable(pRec->r, z);
37848 + pRec->flags = MEM_Real;
37850 + nByte += pRec->n+1;
37852 + nByte += pRec->n+1;
37855 + if( nByte+sizeof(u32)>MAX_BYTES_PER_ROW ){
37856 + rc = SQLITE_TOOBIG;
37857 + goto abort_due_to_error;
37859 + if( addRowid ) nByte += sizeof(u32);
37860 + if( nByte<=NBFS ){
37863 + zNewKey = sqliteMallocRaw( nByte );
37864 + if( zNewKey==0 ) goto no_mem;
37867 + pRec = &pTos[1-nField];
37868 + for(i=0; i<nField; i++, pRec++){
37869 + if( pRec->flags & MEM_Null ){
37870 + zNewKey[j++] = 'a';
37871 + zNewKey[j++] = 0;
37872 + }else if( pRec->flags==MEM_Real ){
37873 + zNewKey[j++] = 'b';
37874 + memcpy(&zNewKey[j], pRec->zShort, pRec->n);
37877 + assert( pRec->flags & MEM_Str );
37878 + zNewKey[j++] = 'c';
37879 + memcpy(&zNewKey[j], pRec->z, pRec->n);
37885 + pRec = &pTos[-nField];
37886 + assert( pRec>=p->aStack );
37887 + Integerify(pRec);
37888 + iKey = intToKey(pRec->i);
37889 + memcpy(&zNewKey[j], &iKey, sizeof(u32));
37890 + popStack(&pTos, nField+1);
37891 + if( pOp->p2 && containsNull ) pc = pOp->p2 - 1;
37893 + if( pOp->p2==0 ) popStack(&pTos, nField);
37897 + if( nByte<=NBFS ){
37898 + assert( zNewKey==zTemp );
37899 + pTos->z = pTos->zShort;
37900 + memcpy(pTos->zShort, zTemp, nByte);
37901 + pTos->flags = MEM_Str | MEM_Short;
37903 + pTos->z = zNewKey;
37904 + pTos->flags = MEM_Str | MEM_Dyn;
37909 +/* Opcode: IncrKey * * *
37911 +** The top of the stack should contain an index key generated by
37912 +** The MakeKey opcode. This routine increases the least significant
37913 +** byte of that key by one. This is used so that the MoveTo opcode
37914 +** will move to the first entry greater than the key rather than to
37915 +** the key itself.
37917 +case OP_IncrKey: {
37918 + assert( pTos>=p->aStack );
37919 + /* The IncrKey opcode is only applied to keys generated by
37920 + ** MakeKey or MakeIdxKey and the results of those operands
37921 + ** are always dynamic strings or zShort[] strings. So we
37922 + ** are always free to modify the string in place.
37924 + assert( pTos->flags & (MEM_Dyn|MEM_Short) );
37925 + pTos->z[pTos->n-1]++;
37929 +/* Opcode: Checkpoint P1 * *
37931 +** Begin a checkpoint. A checkpoint is the beginning of a operation that
37932 +** is part of a larger transaction but which might need to be rolled back
37933 +** itself without effecting the containing transaction. A checkpoint will
37934 +** be automatically committed or rollback when the VDBE halts.
37936 +** The checkpoint is begun on the database file with index P1. The main
37937 +** database file has an index of 0 and the file used for temporary tables
37938 +** has an index of 1.
37940 +case OP_Checkpoint: {
37942 + if( i>=0 && i<db->nDb && db->aDb[i].pBt && db->aDb[i].inTrans==1 ){
37943 + rc = sqliteBtreeBeginCkpt(db->aDb[i].pBt);
37944 + if( rc==SQLITE_OK ) db->aDb[i].inTrans = 2;
37949 +/* Opcode: Transaction P1 * *
37951 +** Begin a transaction. The transaction ends when a Commit or Rollback
37952 +** opcode is encountered. Depending on the ON CONFLICT setting, the
37953 +** transaction might also be rolled back if an error is encountered.
37955 +** P1 is the index of the database file on which the transaction is
37956 +** started. Index 0 is the main database file and index 1 is the
37957 +** file used for temporary tables.
37959 +** A write lock is obtained on the database file when a transaction is
37960 +** started. No other process can read or write the file while the
37961 +** transaction is underway. Starting a transaction also creates a
37962 +** rollback journal. A transaction must be started before any changes
37963 +** can be made to the database.
37965 +case OP_Transaction: {
37968 + assert( i>=0 && i<db->nDb );
37969 + if( db->aDb[i].inTrans ) break;
37970 + while( db->aDb[i].pBt!=0 && busy ){
37971 + rc = sqliteBtreeBeginTrans(db->aDb[i].pBt);
37973 + case SQLITE_BUSY: {
37974 + if( db->xBusyCallback==0 ){
37976 + p->undoTransOnError = 1;
37977 + p->rc = SQLITE_BUSY;
37979 + return SQLITE_BUSY;
37980 + }else if( (*db->xBusyCallback)(db->pBusyArg, "", busy++)==0 ){
37981 + sqliteSetString(&p->zErrMsg, sqlite_error_string(rc), (char*)0);
37986 + case SQLITE_READONLY: {
37988 + /* Fall thru into the next case */
37990 + case SQLITE_OK: {
37991 + p->inTempTrans = 0;
37996 + goto abort_due_to_error;
38000 + db->aDb[i].inTrans = 1;
38001 + p->undoTransOnError = 1;
38005 +/* Opcode: Commit * * *
38007 +** Cause all modifications to the database that have been made since the
38008 +** last Transaction to actually take effect. No additional modifications
38009 +** are allowed until another transaction is started. The Commit instruction
38010 +** deletes the journal file and releases the write lock on the database.
38011 +** A read lock continues to be held if there are still cursors open.
38015 + if( db->xCommitCallback!=0 ){
38016 + if( sqliteSafetyOff(db) ) goto abort_due_to_misuse;
38017 + if( db->xCommitCallback(db->pCommitArg)!=0 ){
38018 + rc = SQLITE_CONSTRAINT;
38020 + if( sqliteSafetyOn(db) ) goto abort_due_to_misuse;
38022 + for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
38023 + if( db->aDb[i].inTrans ){
38024 + rc = sqliteBtreeCommit(db->aDb[i].pBt);
38025 + db->aDb[i].inTrans = 0;
38028 + if( rc==SQLITE_OK ){
38029 + sqliteCommitInternalChanges(db);
38031 + sqliteRollbackAll(db);
38036 +/* Opcode: Rollback P1 * *
38038 +** Cause all modifications to the database that have been made since the
38039 +** last Transaction to be undone. The database is restored to its state
38040 +** before the Transaction opcode was executed. No additional modifications
38041 +** are allowed until another transaction is started.
38043 +** P1 is the index of the database file that is committed. An index of 0
38044 +** is used for the main database and an index of 1 is used for the file used
38045 +** to hold temporary tables.
38047 +** This instruction automatically closes all cursors and releases both
38048 +** the read and write locks on the indicated database.
38050 +case OP_Rollback: {
38051 + sqliteRollbackAll(db);
38055 +/* Opcode: ReadCookie P1 P2 *
38057 +** Read cookie number P2 from database P1 and push it onto the stack.
38058 +** P2==0 is the schema version. P2==1 is the database format.
38059 +** P2==2 is the recommended pager cache size, and so forth. P1==0 is
38060 +** the main database file and P1==1 is the database file used to store
38061 +** temporary tables.
38063 +** There must be a read-lock on the database (either a transaction
38064 +** must be started or there must be an open cursor) before
38065 +** executing this instruction.
38067 +case OP_ReadCookie: {
38068 + int aMeta[SQLITE_N_BTREE_META];
38069 + assert( pOp->p2<SQLITE_N_BTREE_META );
38070 + assert( pOp->p1>=0 && pOp->p1<db->nDb );
38071 + assert( db->aDb[pOp->p1].pBt!=0 );
38072 + rc = sqliteBtreeGetMeta(db->aDb[pOp->p1].pBt, aMeta);
38074 + pTos->i = aMeta[1+pOp->p2];
38075 + pTos->flags = MEM_Int;
38079 +/* Opcode: SetCookie P1 P2 *
38081 +** Write the top of the stack into cookie number P2 of database P1.
38082 +** P2==0 is the schema version. P2==1 is the database format.
38083 +** P2==2 is the recommended pager cache size, and so forth. P1==0 is
38084 +** the main database file and P1==1 is the database file used to store
38085 +** temporary tables.
38087 +** A transaction must be started before executing this opcode.
38089 +case OP_SetCookie: {
38090 + int aMeta[SQLITE_N_BTREE_META];
38091 + assert( pOp->p2<SQLITE_N_BTREE_META );
38092 + assert( pOp->p1>=0 && pOp->p1<db->nDb );
38093 + assert( db->aDb[pOp->p1].pBt!=0 );
38094 + assert( pTos>=p->aStack );
38096 + rc = sqliteBtreeGetMeta(db->aDb[pOp->p1].pBt, aMeta);
38097 + if( rc==SQLITE_OK ){
38098 + aMeta[1+pOp->p2] = pTos->i;
38099 + rc = sqliteBtreeUpdateMeta(db->aDb[pOp->p1].pBt, aMeta);
38106 +/* Opcode: VerifyCookie P1 P2 *
38108 +** Check the value of global database parameter number 0 (the
38109 +** schema version) and make sure it is equal to P2.
38110 +** P1 is the database number which is 0 for the main database file
38111 +** and 1 for the file holding temporary tables and some higher number
38112 +** for auxiliary databases.
38114 +** The cookie changes its value whenever the database schema changes.
38115 +** This operation is used to detect when that the cookie has changed
38116 +** and that the current process needs to reread the schema.
38118 +** Either a transaction needs to have been started or an OP_Open needs
38119 +** to be executed (to establish a read lock) before this opcode is
38122 +case OP_VerifyCookie: {
38123 + int aMeta[SQLITE_N_BTREE_META];
38124 + assert( pOp->p1>=0 && pOp->p1<db->nDb );
38125 + rc = sqliteBtreeGetMeta(db->aDb[pOp->p1].pBt, aMeta);
38126 + if( rc==SQLITE_OK && aMeta[1]!=pOp->p2 ){
38127 + sqliteSetString(&p->zErrMsg, "database schema has changed", (char*)0);
38128 + rc = SQLITE_SCHEMA;
38133 +/* Opcode: OpenRead P1 P2 P3
38135 +** Open a read-only cursor for the database table whose root page is
38136 +** P2 in a database file. The database file is determined by an
38137 +** integer from the top of the stack. 0 means the main database and
38138 +** 1 means the database used for temporary tables. Give the new
38139 +** cursor an identifier of P1. The P1 values need not be contiguous
38140 +** but all P1 values should be small integers. It is an error for
38141 +** P1 to be negative.
38143 +** If P2==0 then take the root page number from the next of the stack.
38145 +** There will be a read lock on the database whenever there is an
38146 +** open cursor. If the database was unlocked prior to this instruction
38147 +** then a read lock is acquired as part of this instruction. A read
38148 +** lock allows other processes to read the database but prohibits
38149 +** any other process from modifying the database. The read lock is
38150 +** released when all cursors are closed. If this instruction attempts
38151 +** to get a read lock but fails, the script terminates with an
38152 +** SQLITE_BUSY error code.
38154 +** The P3 value is the name of the table or index being opened.
38155 +** The P3 value is not actually used by this opcode and may be
38156 +** omitted. But the code generator usually inserts the index or
38157 +** table name into P3 to make the code easier to read.
38159 +** See also OpenWrite.
38161 +/* Opcode: OpenWrite P1 P2 P3
38163 +** Open a read/write cursor named P1 on the table or index whose root
38164 +** page is P2. If P2==0 then take the root page number from the stack.
38166 +** The P3 value is the name of the table or index being opened.
38167 +** The P3 value is not actually used by this opcode and may be
38168 +** omitted. But the code generator usually inserts the index or
38169 +** table name into P3 to make the code easier to read.
38171 +** This instruction works just like OpenRead except that it opens the cursor
38172 +** in read/write mode. For a given table, there can be one or more read-only
38173 +** cursors or a single read/write cursor but not both.
38175 +** See also OpenRead.
38178 +case OP_OpenWrite: {
38181 + int p2 = pOp->p2;
38186 + assert( pTos>=p->aStack );
38187 + Integerify(pTos);
38190 + assert( iDb>=0 && iDb<db->nDb );
38191 + pX = db->aDb[iDb].pBt;
38193 + wrFlag = pOp->opcode==OP_OpenWrite;
38195 + assert( pTos>=p->aStack );
38196 + Integerify(pTos);
38200 + sqliteSetString(&p->zErrMsg, "root page number less than 2", (char*)0);
38201 + rc = SQLITE_INTERNAL;
38206 + if( expandCursorArraySize(p, i) ) goto no_mem;
38207 + sqliteVdbeCleanupCursor(&p->aCsr[i]);
38208 + memset(&p->aCsr[i], 0, sizeof(Cursor));
38209 + p->aCsr[i].nullRow = 1;
38210 + if( pX==0 ) break;
38212 + rc = sqliteBtreeCursor(pX, p2, wrFlag, &p->aCsr[i].pCursor);
38214 + case SQLITE_BUSY: {
38215 + if( db->xBusyCallback==0 ){
38217 + p->rc = SQLITE_BUSY;
38218 + p->pTos = &pTos[1 + (pOp->p2<=0)]; /* Operands must remain on stack */
38219 + return SQLITE_BUSY;
38220 + }else if( (*db->xBusyCallback)(db->pBusyArg, pOp->p3, ++busy)==0 ){
38221 + sqliteSetString(&p->zErrMsg, sqlite_error_string(rc), (char*)0);
38226 + case SQLITE_OK: {
38231 + goto abort_due_to_error;
38238 +/* Opcode: OpenTemp P1 P2 *
38240 +** Open a new cursor to a transient table.
38241 +** The transient cursor is always opened read/write even if
38242 +** the main database is read-only. The transient table is deleted
38243 +** automatically when the cursor is closed.
38245 +** The cursor points to a BTree table if P2==0 and to a BTree index
38246 +** if P2==1. A BTree table must have an integer key and can have arbitrary
38247 +** data. A BTree index has no data but can have an arbitrary key.
38249 +** This opcode is used for tables that exist for the duration of a single
38250 +** SQL statement only. Tables created using CREATE TEMPORARY TABLE
38251 +** are opened using OP_OpenRead or OP_OpenWrite. "Temporary" in the
38252 +** context of this opcode means for the duration of a single SQL statement
38253 +** whereas "Temporary" in the context of CREATE TABLE means for the duration
38254 +** of the connection to the database. Same word; different meanings.
38256 +case OP_OpenTemp: {
38260 + if( expandCursorArraySize(p, i) ) goto no_mem;
38261 + pCx = &p->aCsr[i];
38262 + sqliteVdbeCleanupCursor(pCx);
38263 + memset(pCx, 0, sizeof(*pCx));
38264 + pCx->nullRow = 1;
38265 + rc = sqliteBtreeFactory(db, 0, 1, TEMP_PAGES, &pCx->pBt);
38267 + if( rc==SQLITE_OK ){
38268 + rc = sqliteBtreeBeginTrans(pCx->pBt);
38270 + if( rc==SQLITE_OK ){
38273 + rc = sqliteBtreeCreateIndex(pCx->pBt, &pgno);
38274 + if( rc==SQLITE_OK ){
38275 + rc = sqliteBtreeCursor(pCx->pBt, pgno, 1, &pCx->pCursor);
38278 + rc = sqliteBtreeCursor(pCx->pBt, 2, 1, &pCx->pCursor);
38284 +/* Opcode: OpenPseudo P1 * *
38286 +** Open a new cursor that points to a fake table that contains a single
38287 +** row of data. Any attempt to write a second row of data causes the
38288 +** first row to be deleted. All data is deleted when the cursor is
38291 +** A pseudo-table created by this opcode is useful for holding the
38292 +** NEW or OLD tables in a trigger.
38294 +case OP_OpenPseudo: {
38298 + if( expandCursorArraySize(p, i) ) goto no_mem;
38299 + pCx = &p->aCsr[i];
38300 + sqliteVdbeCleanupCursor(pCx);
38301 + memset(pCx, 0, sizeof(*pCx));
38302 + pCx->nullRow = 1;
38303 + pCx->pseudoTable = 1;
38307 +/* Opcode: Close P1 * *
38309 +** Close a cursor previously opened as P1. If P1 is not
38310 +** currently open, this instruction is a no-op.
38314 + if( i>=0 && i<p->nCursor ){
38315 + sqliteVdbeCleanupCursor(&p->aCsr[i]);
38320 +/* Opcode: MoveTo P1 P2 *
38322 +** Pop the top of the stack and use its value as a key. Reposition
38323 +** cursor P1 so that it points to an entry with a matching key. If
38324 +** the table contains no record with a matching key, then the cursor
38325 +** is left pointing at the first record that is greater than the key.
38326 +** If there are no records greater than the key and P2 is not zero,
38327 +** then an immediate jump to P2 is made.
38329 +** See also: Found, NotFound, Distinct, MoveLt
38331 +/* Opcode: MoveLt P1 P2 *
38333 +** Pop the top of the stack and use its value as a key. Reposition
38334 +** cursor P1 so that it points to the entry with the largest key that is
38335 +** less than the key popped from the stack.
38336 +** If there are no records less than than the key and P2
38337 +** is not zero then an immediate jump to P2 is made.
38339 +** See also: MoveTo
38346 + assert( pTos>=p->aStack );
38347 + assert( i>=0 && i<p->nCursor );
38348 + pC = &p->aCsr[i];
38349 + if( pC->pCursor!=0 ){
38352 + if( pTos->flags & MEM_Int ){
38353 + int iKey = intToKey(pTos->i);
38354 + if( pOp->p2==0 && pOp->opcode==OP_MoveTo ){
38355 + pC->movetoTarget = iKey;
38356 + pC->deferredMoveto = 1;
38361 + sqliteBtreeMoveto(pC->pCursor, (char*)&iKey, sizeof(int), &res);
38362 + pC->lastRecno = pTos->i;
38363 + pC->recnoIsValid = res==0;
38366 + sqliteBtreeMoveto(pC->pCursor, pTos->z, pTos->n, &res);
38367 + pC->recnoIsValid = 0;
38369 + pC->deferredMoveto = 0;
38370 + sqlite_search_count++;
38371 + oc = pOp->opcode;
38372 + if( oc==OP_MoveTo && res<0 ){
38373 + sqliteBtreeNext(pC->pCursor, &res);
38374 + pC->recnoIsValid = 0;
38375 + if( res && pOp->p2>0 ){
38376 + pc = pOp->p2 - 1;
38378 + }else if( oc==OP_MoveLt ){
38380 + sqliteBtreePrevious(pC->pCursor, &res);
38381 + pC->recnoIsValid = 0;
38383 + /* res might be negative because the table is empty. Check to
38384 + ** see if this is the case.
38387 + res = sqliteBtreeKeySize(pC->pCursor,&keysize)!=0 || keysize==0;
38389 + if( res && pOp->p2>0 ){
38390 + pc = pOp->p2 - 1;
38399 +/* Opcode: Distinct P1 P2 *
38401 +** Use the top of the stack as a string key. If a record with that key does
38402 +** not exist in the table of cursor P1, then jump to P2. If the record
38403 +** does already exist, then fall thru. The cursor is left pointing
38404 +** at the record if it exists. The key is not popped from the stack.
38406 +** This operation is similar to NotFound except that this operation
38407 +** does not pop the key from the stack.
38409 +** See also: Found, NotFound, MoveTo, IsUnique, NotExists
38411 +/* Opcode: Found P1 P2 *
38413 +** Use the top of the stack as a string key. If a record with that key
38414 +** does exist in table of P1, then jump to P2. If the record
38415 +** does not exist, then fall thru. The cursor is left pointing
38416 +** to the record if it exists. The key is popped from the stack.
38418 +** See also: Distinct, NotFound, MoveTo, IsUnique, NotExists
38420 +/* Opcode: NotFound P1 P2 *
38422 +** Use the top of the stack as a string key. If a record with that key
38423 +** does not exist in table of P1, then jump to P2. If the record
38424 +** does exist, then fall thru. The cursor is left pointing to the
38425 +** record if it exists. The key is popped from the stack.
38427 +** The difference between this operation and Distinct is that
38428 +** Distinct does not pop the key from the stack.
38430 +** See also: Distinct, Found, MoveTo, NotExists, IsUnique
38436 + int alreadyExists = 0;
38438 + assert( pTos>=p->aStack );
38439 + assert( i>=0 && i<p->nCursor );
38440 + if( (pC = &p->aCsr[i])->pCursor!=0 ){
38443 + rx = sqliteBtreeMoveto(pC->pCursor, pTos->z, pTos->n, &res);
38444 + alreadyExists = rx==SQLITE_OK && res==0;
38445 + pC->deferredMoveto = 0;
38447 + if( pOp->opcode==OP_Found ){
38448 + if( alreadyExists ) pc = pOp->p2 - 1;
38450 + if( !alreadyExists ) pc = pOp->p2 - 1;
38452 + if( pOp->opcode!=OP_Distinct ){
38459 +/* Opcode: IsUnique P1 P2 *
38461 +** The top of the stack is an integer record number. Call this
38462 +** record number R. The next on the stack is an index key created
38463 +** using MakeIdxKey. Call it K. This instruction pops R from the
38464 +** stack but it leaves K unchanged.
38466 +** P1 is an index. So all but the last four bytes of K are an
38467 +** index string. The last four bytes of K are a record number.
38469 +** This instruction asks if there is an entry in P1 where the
38470 +** index string matches K but the record number is different
38471 +** from R. If there is no such entry, then there is an immediate
38472 +** jump to P2. If any entry does exist where the index string
38473 +** matches K but the record number is not R, then the record
38474 +** number for that entry is pushed onto the stack and control
38475 +** falls through to the next instruction.
38477 +** See also: Distinct, NotFound, NotExists, Found
38479 +case OP_IsUnique: {
38481 + Mem *pNos = &pTos[-1];
38485 + /* Pop the value R off the top of the stack
38487 + assert( pNos>=p->aStack );
38488 + Integerify(pTos);
38491 + assert( i>=0 && i<=p->nCursor );
38492 + if( (pCrsr = p->aCsr[i].pCursor)!=0 ){
38494 + int v; /* The record number on the P1 entry that matches K */
38495 + char *zKey; /* The value of K */
38496 + int nKey; /* Number of bytes in K */
38498 + /* Make sure K is a string and make zKey point to K
38503 + assert( nKey >= 4 );
38505 + /* Search for an entry in P1 where all but the last four bytes match K.
38506 + ** If there is no such entry, jump immediately to P2.
38508 + assert( p->aCsr[i].deferredMoveto==0 );
38509 + rc = sqliteBtreeMoveto(pCrsr, zKey, nKey-4, &res);
38510 + if( rc!=SQLITE_OK ) goto abort_due_to_error;
38512 + rc = sqliteBtreeNext(pCrsr, &res);
38514 + pc = pOp->p2 - 1;
38518 + rc = sqliteBtreeKeyCompare(pCrsr, zKey, nKey-4, 4, &res);
38519 + if( rc!=SQLITE_OK ) goto abort_due_to_error;
38521 + pc = pOp->p2 - 1;
38525 + /* At this point, pCrsr is pointing to an entry in P1 where all but
38526 + ** the last for bytes of the key match K. Check to see if the last
38527 + ** four bytes of the key are different from R. If the last four
38528 + ** bytes equal R then jump immediately to P2.
38530 + sqliteBtreeKey(pCrsr, nKey - 4, 4, (char*)&v);
38533 + pc = pOp->p2 - 1;
38537 + /* The last four bytes of the key are different from R. Convert the
38538 + ** last four bytes of the key into an integer and push it onto the
38539 + ** stack. (These bytes are the record number of an entry that
38540 + ** violates a UNIQUE constraint.)
38544 + pTos->flags = MEM_Int;
38549 +/* Opcode: NotExists P1 P2 *
38551 +** Use the top of the stack as a integer key. If a record with that key
38552 +** does not exist in table of P1, then jump to P2. If the record
38553 +** does exist, then fall thru. The cursor is left pointing to the
38554 +** record if it exists. The integer key is popped from the stack.
38556 +** The difference between this operation and NotFound is that this
38557 +** operation assumes the key is an integer and NotFound assumes it
38560 +** See also: Distinct, Found, MoveTo, NotFound, IsUnique
38562 +case OP_NotExists: {
38565 + assert( pTos>=p->aStack );
38566 + assert( i>=0 && i<p->nCursor );
38567 + if( (pCrsr = p->aCsr[i].pCursor)!=0 ){
38568 + int res, rx, iKey;
38569 + assert( pTos->flags & MEM_Int );
38570 + iKey = intToKey(pTos->i);
38571 + rx = sqliteBtreeMoveto(pCrsr, (char*)&iKey, sizeof(int), &res);
38572 + p->aCsr[i].lastRecno = pTos->i;
38573 + p->aCsr[i].recnoIsValid = res==0;
38574 + p->aCsr[i].nullRow = 0;
38575 + if( rx!=SQLITE_OK || res!=0 ){
38576 + pc = pOp->p2 - 1;
38577 + p->aCsr[i].recnoIsValid = 0;
38585 +/* Opcode: NewRecno P1 * *
38587 +** Get a new integer record number used as the key to a table.
38588 +** The record number is not previously used as a key in the database
38589 +** table that cursor P1 points to. The new record number is pushed
38590 +** onto the stack.
38592 +case OP_NewRecno: {
38596 + assert( i>=0 && i<p->nCursor );
38597 + if( (pC = &p->aCsr[i])->pCursor==0 ){
38600 + /* The next rowid or record number (different terms for the same
38601 + ** thing) is obtained in a two-step algorithm.
38603 + ** First we attempt to find the largest existing rowid and add one
38604 + ** to that. But if the largest existing rowid is already the maximum
38605 + ** positive integer, we have to fall through to the second
38606 + ** probabilistic algorithm
38608 + ** The second algorithm is to select a rowid at random and see if
38609 + ** it already exists in the table. If it does not exist, we have
38610 + ** succeeded. If the random rowid does exist, we select a new one
38611 + ** and try again, up to 1000 times.
38613 + ** For a table with less than 2 billion entries, the probability
38614 + ** of not finding a unused rowid is about 1.0e-300. This is a
38615 + ** non-zero probability, but it is still vanishingly small and should
38616 + ** never cause a problem. You are much, much more likely to have a
38617 + ** hardware failure than for this algorithm to fail.
38619 + ** The analysis in the previous paragraph assumes that you have a good
38620 + ** source of random numbers. Is a library function like lrand48()
38621 + ** good enough? Maybe. Maybe not. It's hard to know whether there
38622 + ** might be subtle bugs is some implementations of lrand48() that
38623 + ** could cause problems. To avoid uncertainty, SQLite uses its own
38624 + ** random number generator based on the RC4 algorithm.
38626 + ** To promote locality of reference for repetitive inserts, the
38627 + ** first few attempts at chosing a random rowid pick values just a little
38628 + ** larger than the previous rowid. This has been shown experimentally
38629 + ** to double the speed of the COPY operation.
38631 + int res, rx, cnt, x;
38633 + if( !pC->useRandomRowid ){
38634 + if( pC->nextRowidValid ){
38635 + v = pC->nextRowid;
38637 + rx = sqliteBtreeLast(pC->pCursor, &res);
38641 + sqliteBtreeKey(pC->pCursor, 0, sizeof(v), (void*)&v);
38643 + if( v==0x7fffffff ){
38644 + pC->useRandomRowid = 1;
38650 + if( v<0x7fffffff ){
38651 + pC->nextRowidValid = 1;
38652 + pC->nextRowid = v+1;
38654 + pC->nextRowidValid = 0;
38657 + if( pC->useRandomRowid ){
38658 + v = db->priorNewRowid;
38661 + if( v==0 || cnt>2 ){
38662 + sqliteRandomness(sizeof(v), &v);
38663 + if( cnt<5 ) v &= 0xffffff;
38666 + sqliteRandomness(1, &r);
38669 + if( v==0 ) continue;
38671 + rx = sqliteBtreeMoveto(pC->pCursor, &x, sizeof(int), &res);
38673 + }while( cnt<1000 && rx==SQLITE_OK && res==0 );
38674 + db->priorNewRowid = v;
38675 + if( rx==SQLITE_OK && res==0 ){
38676 + rc = SQLITE_FULL;
38677 + goto abort_due_to_error;
38680 + pC->recnoIsValid = 0;
38681 + pC->deferredMoveto = 0;
38685 + pTos->flags = MEM_Int;
38689 +/* Opcode: PutIntKey P1 P2 *
38691 +** Write an entry into the table of cursor P1. A new entry is
38692 +** created if it doesn't already exist or the data for an existing
38693 +** entry is overwritten. The data is the value on the top of the
38694 +** stack. The key is the next value down on the stack. The key must
38695 +** be an integer. The stack is popped twice by this instruction.
38697 +** If the OPFLAG_NCHANGE flag of P2 is set, then the row change count is
38698 +** incremented (otherwise not). If the OPFLAG_CSCHANGE flag is set,
38699 +** then the current statement change count is incremented (otherwise not).
38700 +** If the OPFLAG_LASTROWID flag of P2 is set, then rowid is
38701 +** stored for subsequent return by the sqlite_last_insert_rowid() function
38702 +** (otherwise it's unmodified).
38704 +/* Opcode: PutStrKey P1 * *
38706 +** Write an entry into the table of cursor P1. A new entry is
38707 +** created if it doesn't already exist or the data for an existing
38708 +** entry is overwritten. The data is the value on the top of the
38709 +** stack. The key is the next value down on the stack. The key must
38710 +** be a string. The stack is popped twice by this instruction.
38712 +** P1 may not be a pseudo-table opened using the OpenPseudo opcode.
38714 +case OP_PutIntKey:
38715 +case OP_PutStrKey: {
38716 + Mem *pNos = &pTos[-1];
38719 + assert( pNos>=p->aStack );
38720 + assert( i>=0 && i<p->nCursor );
38721 + if( ((pC = &p->aCsr[i])->pCursor!=0 || pC->pseudoTable) ){
38724 + if( pOp->opcode==OP_PutStrKey ){
38729 + assert( pNos->flags & MEM_Int );
38730 + nKey = sizeof(int);
38731 + iKey = intToKey(pNos->i);
38732 + zKey = (char*)&iKey;
38733 + if( pOp->p2 & OPFLAG_NCHANGE ) db->nChange++;
38734 + if( pOp->p2 & OPFLAG_LASTROWID ) db->lastRowid = pNos->i;
38735 + if( pOp->p2 & OPFLAG_CSCHANGE ) db->csChange++;
38736 + if( pC->nextRowidValid && pTos->i>=pC->nextRowid ){
38737 + pC->nextRowidValid = 0;
38740 + if( pTos->flags & MEM_Null ){
38744 + assert( pTos->flags & MEM_Str );
38746 + if( pC->pseudoTable ){
38747 + /* PutStrKey does not work for pseudo-tables.
38748 + ** The following assert makes sure we are not trying to use
38749 + ** PutStrKey on a pseudo-table
38751 + assert( pOp->opcode==OP_PutIntKey );
38752 + sqliteFree(pC->pData);
38754 + pC->nData = pTos->n;
38755 + if( pTos->flags & MEM_Dyn ){
38756 + pC->pData = pTos->z;
38757 + pTos->flags = MEM_Null;
38759 + pC->pData = sqliteMallocRaw( pC->nData );
38761 + memcpy(pC->pData, pTos->z, pC->nData);
38766 + rc = sqliteBtreeInsert(pC->pCursor, zKey, nKey, pTos->z, pTos->n);
38768 + pC->recnoIsValid = 0;
38769 + pC->deferredMoveto = 0;
38771 + popStack(&pTos, 2);
38775 +/* Opcode: Delete P1 P2 *
38777 +** Delete the record at which the P1 cursor is currently pointing.
38779 +** The cursor will be left pointing at either the next or the previous
38780 +** record in the table. If it is left pointing at the next record, then
38781 +** the next Next instruction will be a no-op. Hence it is OK to delete
38782 +** a record from within an Next loop.
38784 +** If the OPFLAG_NCHANGE flag of P2 is set, then the row change count is
38785 +** incremented (otherwise not). If OPFLAG_CSCHANGE flag is set,
38786 +** then the current statement change count is incremented (otherwise not).
38788 +** If P1 is a pseudo-table, then this instruction is a no-op.
38793 + assert( i>=0 && i<p->nCursor );
38794 + pC = &p->aCsr[i];
38795 + if( pC->pCursor!=0 ){
38796 + sqliteVdbeCursorMoveto(pC);
38797 + rc = sqliteBtreeDelete(pC->pCursor);
38798 + pC->nextRowidValid = 0;
38800 + if( pOp->p2 & OPFLAG_NCHANGE ) db->nChange++;
38801 + if( pOp->p2 & OPFLAG_CSCHANGE ) db->csChange++;
38805 +/* Opcode: SetCounts * * *
38807 +** Called at end of statement. Updates lsChange (last statement change count)
38808 +** and resets csChange (current statement change count) to 0.
38810 +case OP_SetCounts: {
38811 + db->lsChange=db->csChange;
38816 +/* Opcode: KeyAsData P1 P2 *
38818 +** Turn the key-as-data mode for cursor P1 either on (if P2==1) or
38819 +** off (if P2==0). In key-as-data mode, the OP_Column opcode pulls
38820 +** data off of the key rather than the data. This is used for
38821 +** processing compound selects.
38823 +case OP_KeyAsData: {
38825 + assert( i>=0 && i<p->nCursor );
38826 + p->aCsr[i].keyAsData = pOp->p2;
38830 +/* Opcode: RowData P1 * *
38832 +** Push onto the stack the complete row data for cursor P1.
38833 +** There is no interpretation of the data. It is just copied
38834 +** onto the stack exactly as it is found in the database file.
38836 +** If the cursor is not pointing to a valid row, a NULL is pushed
38837 +** onto the stack.
38839 +/* Opcode: RowKey P1 * *
38841 +** Push onto the stack the complete row key for cursor P1.
38842 +** There is no interpretation of the key. It is just copied
38843 +** onto the stack exactly as it is found in the database file.
38845 +** If the cursor is not pointing to a valid row, a NULL is pushed
38846 +** onto the stack.
38849 +case OP_RowData: {
38855 + assert( i>=0 && i<p->nCursor );
38856 + pC = &p->aCsr[i];
38857 + if( pC->nullRow ){
38858 + pTos->flags = MEM_Null;
38859 + }else if( pC->pCursor!=0 ){
38860 + BtCursor *pCrsr = pC->pCursor;
38861 + sqliteVdbeCursorMoveto(pC);
38862 + if( pC->nullRow ){
38863 + pTos->flags = MEM_Null;
38865 + }else if( pC->keyAsData || pOp->opcode==OP_RowKey ){
38866 + sqliteBtreeKeySize(pCrsr, &n);
38868 + sqliteBtreeDataSize(pCrsr, &n);
38872 + pTos->flags = MEM_Str | MEM_Short;
38873 + pTos->z = pTos->zShort;
38875 + char *z = sqliteMallocRaw( n );
38876 + if( z==0 ) goto no_mem;
38877 + pTos->flags = MEM_Str | MEM_Dyn;
38880 + if( pC->keyAsData || pOp->opcode==OP_RowKey ){
38881 + sqliteBtreeKey(pCrsr, 0, n, pTos->z);
38883 + sqliteBtreeData(pCrsr, 0, n, pTos->z);
38885 + }else if( pC->pseudoTable ){
38886 + pTos->n = pC->nData;
38887 + pTos->z = pC->pData;
38888 + pTos->flags = MEM_Str|MEM_Ephem;
38890 + pTos->flags = MEM_Null;
38895 +/* Opcode: Column P1 P2 *
38897 +** Interpret the data that cursor P1 points to as
38898 +** a structure built using the MakeRecord instruction.
38899 +** (See the MakeRecord opcode for additional information about
38900 +** the format of the data.)
38901 +** Push onto the stack the value of the P2-th column contained
38904 +** If the KeyAsData opcode has previously executed on this cursor,
38905 +** then the field might be extracted from the key rather than the
38908 +** If P1 is negative, then the record is stored on the stack rather
38909 +** than in a table. For P1==-1, the top of the stack is used.
38910 +** For P1==-2, the next on the stack is used. And so forth. The
38911 +** value pushed is always just a pointer into the record which is
38912 +** stored further down on the stack. The column value is not copied.
38915 + int amt, offset, end, payloadSize;
38917 + int p2 = pOp->p2;
38922 + unsigned char aHdr[10];
38924 + assert( i<p->nCursor );
38927 + assert( &pTos[i]>=p->aStack );
38928 + assert( pTos[i].flags & MEM_Str );
38929 + zRec = pTos[i].z;
38930 + payloadSize = pTos[i].n;
38931 + }else if( (pC = &p->aCsr[i])->pCursor!=0 ){
38932 + sqliteVdbeCursorMoveto(pC);
38934 + pCrsr = pC->pCursor;
38935 + if( pC->nullRow ){
38937 + }else if( pC->keyAsData ){
38938 + sqliteBtreeKeySize(pCrsr, &payloadSize);
38940 + sqliteBtreeDataSize(pCrsr, &payloadSize);
38942 + }else if( pC->pseudoTable ){
38943 + payloadSize = pC->nData;
38944 + zRec = pC->pData;
38945 + assert( payloadSize==0 || zRec!=0 );
38950 + /* Figure out how many bytes in the column data and where the column
38953 + if( payloadSize==0 ){
38954 + pTos->flags = MEM_Null;
38956 + }else if( payloadSize<256 ){
38958 + }else if( payloadSize<65536 ){
38964 + /* Figure out where the requested column is stored and how big it is.
38966 + if( payloadSize < idxWidth*(p2+1) ){
38967 + rc = SQLITE_CORRUPT;
38968 + goto abort_due_to_error;
38971 + memcpy(aHdr, &zRec[idxWidth*p2], idxWidth*2);
38972 + }else if( pC->keyAsData ){
38973 + sqliteBtreeKey(pCrsr, idxWidth*p2, idxWidth*2, (char*)aHdr);
38975 + sqliteBtreeData(pCrsr, idxWidth*p2, idxWidth*2, (char*)aHdr);
38977 + offset = aHdr[0];
38978 + end = aHdr[idxWidth];
38979 + if( idxWidth>1 ){
38980 + offset |= aHdr[1]<<8;
38981 + end |= aHdr[idxWidth+1]<<8;
38982 + if( idxWidth>2 ){
38983 + offset |= aHdr[2]<<16;
38984 + end |= aHdr[idxWidth+2]<<16;
38987 + amt = end - offset;
38988 + if( amt<0 || offset<0 || end>payloadSize ){
38989 + rc = SQLITE_CORRUPT;
38990 + goto abort_due_to_error;
38993 + /* amt and offset now hold the offset to the start of data and the
38994 + ** amount of data. Go get the data and put it on the stack.
38998 + pTos->flags = MEM_Null;
38999 + }else if( zRec ){
39000 + pTos->flags = MEM_Str | MEM_Ephem;
39001 + pTos->z = &zRec[offset];
39004 + pTos->flags = MEM_Str | MEM_Short;
39005 + pTos->z = pTos->zShort;
39007 + char *z = sqliteMallocRaw( amt );
39008 + if( z==0 ) goto no_mem;
39009 + pTos->flags = MEM_Str | MEM_Dyn;
39012 + if( pC->keyAsData ){
39013 + sqliteBtreeKey(pCrsr, offset, amt, pTos->z);
39015 + sqliteBtreeData(pCrsr, offset, amt, pTos->z);
39021 +/* Opcode: Recno P1 * *
39023 +** Push onto the stack an integer which is the first 4 bytes of the
39024 +** the key to the current entry in a sequential scan of the database
39025 +** file P1. The sequential scan should have been started using the
39033 + assert( i>=0 && i<p->nCursor );
39034 + pC = &p->aCsr[i];
39035 + sqliteVdbeCursorMoveto(pC);
39037 + if( pC->recnoIsValid ){
39038 + v = pC->lastRecno;
39039 + }else if( pC->pseudoTable ){
39040 + v = keyToInt(pC->iKey);
39041 + }else if( pC->nullRow || pC->pCursor==0 ){
39042 + pTos->flags = MEM_Null;
39045 + assert( pC->pCursor!=0 );
39046 + sqliteBtreeKey(pC->pCursor, 0, sizeof(u32), (char*)&v);
39050 + pTos->flags = MEM_Int;
39054 +/* Opcode: FullKey P1 * *
39056 +** Extract the complete key from the record that cursor P1 is currently
39057 +** pointing to and push the key onto the stack as a string.
39059 +** Compare this opcode to Recno. The Recno opcode extracts the first
39060 +** 4 bytes of the key and pushes those bytes onto the stack as an
39061 +** integer. This instruction pushes the entire key as a string.
39063 +** This opcode may not be used on a pseudo-table.
39065 +case OP_FullKey: {
39069 + assert( p->aCsr[i].keyAsData );
39070 + assert( !p->aCsr[i].pseudoTable );
39071 + assert( i>=0 && i<p->nCursor );
39073 + if( (pCrsr = p->aCsr[i].pCursor)!=0 ){
39077 + sqliteVdbeCursorMoveto(&p->aCsr[i]);
39078 + sqliteBtreeKeySize(pCrsr, &amt);
39080 + rc = SQLITE_CORRUPT;
39081 + goto abort_due_to_error;
39084 + z = sqliteMallocRaw( amt );
39085 + if( z==0 ) goto no_mem;
39086 + pTos->flags = MEM_Str | MEM_Dyn;
39088 + z = pTos->zShort;
39089 + pTos->flags = MEM_Str | MEM_Short;
39091 + sqliteBtreeKey(pCrsr, 0, amt, z);
39098 +/* Opcode: NullRow P1 * *
39100 +** Move the cursor P1 to a null row. Any OP_Column operations
39101 +** that occur while the cursor is on the null row will always push
39102 +** a NULL onto the stack.
39104 +case OP_NullRow: {
39107 + assert( i>=0 && i<p->nCursor );
39108 + p->aCsr[i].nullRow = 1;
39109 + p->aCsr[i].recnoIsValid = 0;
39113 +/* Opcode: Last P1 P2 *
39115 +** The next use of the Recno or Column or Next instruction for P1
39116 +** will refer to the last entry in the database table or index.
39117 +** If the table or index is empty and P2>0, then jump immediately to P2.
39118 +** If P2 is 0 or if the table or index is not empty, fall through
39119 +** to the following instruction.
39126 + assert( i>=0 && i<p->nCursor );
39127 + pC = &p->aCsr[i];
39128 + if( (pCrsr = pC->pCursor)!=0 ){
39130 + rc = sqliteBtreeLast(pCrsr, &res);
39131 + pC->nullRow = res;
39132 + pC->deferredMoveto = 0;
39133 + if( res && pOp->p2>0 ){
39134 + pc = pOp->p2 - 1;
39142 +/* Opcode: Rewind P1 P2 *
39144 +** The next use of the Recno or Column or Next instruction for P1
39145 +** will refer to the first entry in the database table or index.
39146 +** If the table or index is empty and P2>0, then jump immediately to P2.
39147 +** If P2 is 0 or if the table or index is not empty, fall through
39148 +** to the following instruction.
39155 + assert( i>=0 && i<p->nCursor );
39156 + pC = &p->aCsr[i];
39157 + if( (pCrsr = pC->pCursor)!=0 ){
39159 + rc = sqliteBtreeFirst(pCrsr, &res);
39160 + pC->atFirst = res==0;
39161 + pC->nullRow = res;
39162 + pC->deferredMoveto = 0;
39163 + if( res && pOp->p2>0 ){
39164 + pc = pOp->p2 - 1;
39172 +/* Opcode: Next P1 P2 *
39174 +** Advance cursor P1 so that it points to the next key/data pair in its
39175 +** table or index. If there are no more key/value pairs then fall through
39176 +** to the following instruction. But if the cursor advance was successful,
39177 +** jump immediately to P2.
39181 +/* Opcode: Prev P1 P2 *
39183 +** Back up cursor P1 so that it points to the previous key/data pair in its
39184 +** table or index. If there is no previous key/value pairs then fall through
39185 +** to the following instruction. But if the cursor backup was successful,
39186 +** jump immediately to P2.
39193 + CHECK_FOR_INTERRUPT;
39194 + assert( pOp->p1>=0 && pOp->p1<p->nCursor );
39195 + pC = &p->aCsr[pOp->p1];
39196 + if( (pCrsr = pC->pCursor)!=0 ){
39198 + if( pC->nullRow ){
39201 + assert( pC->deferredMoveto==0 );
39202 + rc = pOp->opcode==OP_Next ? sqliteBtreeNext(pCrsr, &res) :
39203 + sqliteBtreePrevious(pCrsr, &res);
39204 + pC->nullRow = res;
39207 + pc = pOp->p2 - 1;
39208 + sqlite_search_count++;
39213 + pC->recnoIsValid = 0;
39217 +/* Opcode: IdxPut P1 P2 P3
39219 +** The top of the stack holds a SQL index key made using the
39220 +** MakeIdxKey instruction. This opcode writes that key into the
39221 +** index P1. Data for the entry is nil.
39223 +** If P2==1, then the key must be unique. If the key is not unique,
39224 +** the program aborts with a SQLITE_CONSTRAINT error and the database
39225 +** is rolled back. If P3 is not null, then it becomes part of the
39226 +** error message returned with the SQLITE_CONSTRAINT.
39231 + assert( pTos>=p->aStack );
39232 + assert( i>=0 && i<p->nCursor );
39233 + assert( pTos->flags & MEM_Str );
39234 + if( (pCrsr = p->aCsr[i].pCursor)!=0 ){
39235 + int nKey = pTos->n;
39236 + const char *zKey = pTos->z;
39239 + assert( nKey >= 4 );
39240 + rc = sqliteBtreeMoveto(pCrsr, zKey, nKey-4, &res);
39241 + if( rc!=SQLITE_OK ) goto abort_due_to_error;
39244 + sqliteBtreeKeySize(pCrsr, &n);
39246 + && sqliteBtreeKeyCompare(pCrsr, zKey, nKey-4, 4, &c)==SQLITE_OK
39249 + rc = SQLITE_CONSTRAINT;
39250 + if( pOp->p3 && pOp->p3[0] ){
39251 + sqliteSetString(&p->zErrMsg, pOp->p3, (char*)0);
39253 + goto abort_due_to_error;
39256 + sqliteBtreeNext(pCrsr, &res);
39263 + rc = sqliteBtreeInsert(pCrsr, zKey, nKey, "", 0);
39264 + assert( p->aCsr[i].deferredMoveto==0 );
39271 +/* Opcode: IdxDelete P1 * *
39273 +** The top of the stack is an index key built using the MakeIdxKey opcode.
39274 +** This opcode removes that entry from the index.
39276 +case OP_IdxDelete: {
39279 + assert( pTos>=p->aStack );
39280 + assert( pTos->flags & MEM_Str );
39281 + assert( i>=0 && i<p->nCursor );
39282 + if( (pCrsr = p->aCsr[i].pCursor)!=0 ){
39284 + rx = sqliteBtreeMoveto(pCrsr, pTos->z, pTos->n, &res);
39285 + if( rx==SQLITE_OK && res==0 ){
39286 + rc = sqliteBtreeDelete(pCrsr);
39288 + assert( p->aCsr[i].deferredMoveto==0 );
39295 +/* Opcode: IdxRecno P1 * *
39297 +** Push onto the stack an integer which is the last 4 bytes of the
39298 +** the key to the current entry in index P1. These 4 bytes should
39299 +** be the record number of the table entry to which this index entry
39302 +** See also: Recno, MakeIdxKey.
39304 +case OP_IdxRecno: {
39308 + assert( i>=0 && i<p->nCursor );
39310 + if( (pCrsr = p->aCsr[i].pCursor)!=0 ){
39313 + assert( p->aCsr[i].deferredMoveto==0 );
39314 + sqliteBtreeKeySize(pCrsr, &sz);
39315 + if( sz<sizeof(u32) ){
39316 + pTos->flags = MEM_Null;
39318 + sqliteBtreeKey(pCrsr, sz - sizeof(u32), sizeof(u32), (char*)&v);
39321 + pTos->flags = MEM_Int;
39324 + pTos->flags = MEM_Null;
39329 +/* Opcode: IdxGT P1 P2 *
39331 +** Compare the top of the stack against the key on the index entry that
39332 +** cursor P1 is currently pointing to. Ignore the last 4 bytes of the
39333 +** index entry. If the index entry is greater than the top of the stack
39334 +** then jump to P2. Otherwise fall through to the next instruction.
39335 +** In either case, the stack is popped once.
39337 +/* Opcode: IdxGE P1 P2 *
39339 +** Compare the top of the stack against the key on the index entry that
39340 +** cursor P1 is currently pointing to. Ignore the last 4 bytes of the
39341 +** index entry. If the index entry is greater than or equal to
39342 +** the top of the stack
39343 +** then jump to P2. Otherwise fall through to the next instruction.
39344 +** In either case, the stack is popped once.
39346 +/* Opcode: IdxLT P1 P2 *
39348 +** Compare the top of the stack against the key on the index entry that
39349 +** cursor P1 is currently pointing to. Ignore the last 4 bytes of the
39350 +** index entry. If the index entry is less than the top of the stack
39351 +** then jump to P2. Otherwise fall through to the next instruction.
39352 +** In either case, the stack is popped once.
39360 + assert( i>=0 && i<p->nCursor );
39361 + assert( pTos>=p->aStack );
39362 + if( (pCrsr = p->aCsr[i].pCursor)!=0 ){
39366 + assert( p->aCsr[i].deferredMoveto==0 );
39367 + rc = sqliteBtreeKeyCompare(pCrsr, pTos->z, pTos->n, 4, &res);
39368 + if( rc!=SQLITE_OK ){
39371 + if( pOp->opcode==OP_IdxLT ){
39373 + }else if( pOp->opcode==OP_IdxGE ){
39377 + pc = pOp->p2 - 1 ;
39385 +/* Opcode: IdxIsNull P1 P2 *
39387 +** The top of the stack contains an index entry such as might be generated
39388 +** by the MakeIdxKey opcode. This routine looks at the first P1 fields of
39389 +** that key. If any of the first P1 fields are NULL, then a jump is made
39390 +** to address P2. Otherwise we fall straight through.
39392 +** The index entry is always popped from the stack.
39394 +case OP_IdxIsNull: {
39399 + assert( pTos>=p->aStack );
39400 + assert( pTos->flags & MEM_Str );
39403 + for(k=0; k<n && i>0; i--){
39408 + while( k<n && z[k] ){ k++; }
39416 +/* Opcode: Destroy P1 P2 *
39418 +** Delete an entire database table or index whose root page in the database
39419 +** file is given by P1.
39421 +** The table being destroyed is in the main database file if P2==0. If
39422 +** P2==1 then the table to be clear is in the auxiliary database file
39423 +** that is used to store tables create using CREATE TEMPORARY TABLE.
39425 +** See also: Clear
39427 +case OP_Destroy: {
39428 + rc = sqliteBtreeDropTable(db->aDb[pOp->p2].pBt, pOp->p1);
39432 +/* Opcode: Clear P1 P2 *
39434 +** Delete all contents of the database table or index whose root page
39435 +** in the database file is given by P1. But, unlike Destroy, do not
39436 +** remove the table or index from the database file.
39438 +** The table being clear is in the main database file if P2==0. If
39439 +** P2==1 then the table to be clear is in the auxiliary database file
39440 +** that is used to store tables create using CREATE TEMPORARY TABLE.
39442 +** See also: Destroy
39445 + rc = sqliteBtreeClearTable(db->aDb[pOp->p2].pBt, pOp->p1);
39449 +/* Opcode: CreateTable * P2 P3
39451 +** Allocate a new table in the main database file if P2==0 or in the
39452 +** auxiliary database file if P2==1. Push the page number
39453 +** for the root page of the new table onto the stack.
39455 +** The root page number is also written to a memory location that P3
39456 +** points to. This is the mechanism is used to write the root page
39457 +** number into the parser's internal data structures that describe the
39460 +** The difference between a table and an index is this: A table must
39461 +** have a 4-byte integer key and can have arbitrary data. An index
39462 +** has an arbitrary key but no data.
39464 +** See also: CreateIndex
39466 +/* Opcode: CreateIndex * P2 P3
39468 +** Allocate a new index in the main database file if P2==0 or in the
39469 +** auxiliary database file if P2==1. Push the page number of the
39470 +** root page of the new index onto the stack.
39472 +** See documentation on OP_CreateTable for additional information.
39474 +case OP_CreateIndex:
39475 +case OP_CreateTable: {
39477 + assert( pOp->p3!=0 && pOp->p3type==P3_POINTER );
39478 + assert( pOp->p2>=0 && pOp->p2<db->nDb );
39479 + assert( db->aDb[pOp->p2].pBt!=0 );
39480 + if( pOp->opcode==OP_CreateTable ){
39481 + rc = sqliteBtreeCreateTable(db->aDb[pOp->p2].pBt, &pgno);
39483 + rc = sqliteBtreeCreateIndex(db->aDb[pOp->p2].pBt, &pgno);
39486 + if( rc==SQLITE_OK ){
39488 + pTos->flags = MEM_Int;
39489 + *(u32*)pOp->p3 = pgno;
39492 + pTos->flags = MEM_Null;
39497 +/* Opcode: IntegrityCk P1 P2 *
39499 +** Do an analysis of the currently open database. Push onto the
39500 +** stack the text of an error message describing any problems.
39501 +** If there are no errors, push a "ok" onto the stack.
39503 +** P1 is the index of a set that contains the root page numbers
39504 +** for all tables and indices in the main database file. The set
39505 +** is cleared by this opcode. In other words, after this opcode
39506 +** has executed, the set will be empty.
39508 +** If P2 is not zero, the check is done on the auxiliary database
39509 +** file, not the main database file.
39511 +** This opcode is used for testing purposes only.
39513 +case OP_IntegrityCk: {
39516 + int iSet = pOp->p1;
39522 + assert( iSet>=0 && iSet<p->nSet );
39524 + pSet = &p->aSet[iSet];
39525 + nRoot = sqliteHashCount(&pSet->hash);
39526 + aRoot = sqliteMallocRaw( sizeof(int)*(nRoot+1) );
39527 + if( aRoot==0 ) goto no_mem;
39528 + for(j=0, i=sqliteHashFirst(&pSet->hash); i; i=sqliteHashNext(i), j++){
39529 + toInt((char*)sqliteHashKey(i), &aRoot[j]);
39532 + sqliteHashClear(&pSet->hash);
39534 + z = sqliteBtreeIntegrityCheck(db->aDb[pOp->p2].pBt, aRoot, nRoot);
39535 + if( z==0 || z[0]==0 ){
39536 + if( z ) sqliteFree(z);
39539 + pTos->flags = MEM_Str | MEM_Static;
39542 + pTos->n = strlen(z) + 1;
39543 + pTos->flags = MEM_Str | MEM_Dyn;
39545 + sqliteFree(aRoot);
39549 +/* Opcode: ListWrite * * *
39551 +** Write the integer on the top of the stack
39552 +** into the temporary storage list.
39554 +case OP_ListWrite: {
39555 + Keylist *pKeylist;
39556 + assert( pTos>=p->aStack );
39557 + pKeylist = p->pList;
39558 + if( pKeylist==0 || pKeylist->nUsed>=pKeylist->nKey ){
39559 + pKeylist = sqliteMallocRaw( sizeof(Keylist)+999*sizeof(pKeylist->aKey[0]) );
39560 + if( pKeylist==0 ) goto no_mem;
39561 + pKeylist->nKey = 1000;
39562 + pKeylist->nRead = 0;
39563 + pKeylist->nUsed = 0;
39564 + pKeylist->pNext = p->pList;
39565 + p->pList = pKeylist;
39567 + Integerify(pTos);
39568 + pKeylist->aKey[pKeylist->nUsed++] = pTos->i;
39574 +/* Opcode: ListRewind * * *
39576 +** Rewind the temporary buffer back to the beginning.
39578 +case OP_ListRewind: {
39579 + /* What this opcode codes, really, is reverse the order of the
39580 + ** linked list of Keylist structures so that they are read out
39581 + ** in the same order that they were read in. */
39582 + Keylist *pRev, *pTop;
39584 + while( p->pList ){
39586 + p->pList = pTop->pNext;
39587 + pTop->pNext = pRev;
39594 +/* Opcode: ListRead * P2 *
39596 +** Attempt to read an integer from the temporary storage buffer
39597 +** and push it onto the stack. If the storage buffer is empty,
39598 +** push nothing but instead jump to P2.
39600 +case OP_ListRead: {
39601 + Keylist *pKeylist;
39602 + CHECK_FOR_INTERRUPT;
39603 + pKeylist = p->pList;
39604 + if( pKeylist!=0 ){
39605 + assert( pKeylist->nRead>=0 );
39606 + assert( pKeylist->nRead<pKeylist->nUsed );
39607 + assert( pKeylist->nRead<pKeylist->nKey );
39609 + pTos->i = pKeylist->aKey[pKeylist->nRead++];
39610 + pTos->flags = MEM_Int;
39611 + if( pKeylist->nRead>=pKeylist->nUsed ){
39612 + p->pList = pKeylist->pNext;
39613 + sqliteFree(pKeylist);
39616 + pc = pOp->p2 - 1;
39621 +/* Opcode: ListReset * * *
39623 +** Reset the temporary storage buffer so that it holds nothing.
39625 +case OP_ListReset: {
39627 + sqliteVdbeKeylistFree(p->pList);
39633 +/* Opcode: ListPush * * *
39635 +** Save the current Vdbe list such that it can be restored by a ListPop
39636 +** opcode. The list is empty after this is executed.
39638 +case OP_ListPush: {
39639 + p->keylistStackDepth++;
39640 + assert(p->keylistStackDepth > 0);
39641 + p->keylistStack = sqliteRealloc(p->keylistStack,
39642 + sizeof(Keylist *) * p->keylistStackDepth);
39643 + if( p->keylistStack==0 ) goto no_mem;
39644 + p->keylistStack[p->keylistStackDepth - 1] = p->pList;
39649 +/* Opcode: ListPop * * *
39651 +** Restore the Vdbe list to the state it was in when ListPush was last
39654 +case OP_ListPop: {
39655 + assert(p->keylistStackDepth > 0);
39656 + p->keylistStackDepth--;
39657 + sqliteVdbeKeylistFree(p->pList);
39658 + p->pList = p->keylistStack[p->keylistStackDepth];
39659 + p->keylistStack[p->keylistStackDepth] = 0;
39660 + if( p->keylistStackDepth == 0 ){
39661 + sqliteFree(p->keylistStack);
39662 + p->keylistStack = 0;
39667 +/* Opcode: ContextPush * * *
39669 +** Save the current Vdbe context such that it can be restored by a ContextPop
39670 +** opcode. The context stores the last insert row id, the last statement change
39671 +** count, and the current statement change count.
39673 +case OP_ContextPush: {
39674 + p->contextStackDepth++;
39675 + assert(p->contextStackDepth > 0);
39676 + p->contextStack = sqliteRealloc(p->contextStack,
39677 + sizeof(Context) * p->contextStackDepth);
39678 + if( p->contextStack==0 ) goto no_mem;
39679 + p->contextStack[p->contextStackDepth - 1].lastRowid = p->db->lastRowid;
39680 + p->contextStack[p->contextStackDepth - 1].lsChange = p->db->lsChange;
39681 + p->contextStack[p->contextStackDepth - 1].csChange = p->db->csChange;
39685 +/* Opcode: ContextPop * * *
39687 +** Restore the Vdbe context to the state it was in when contextPush was last
39688 +** executed. The context stores the last insert row id, the last statement
39689 +** change count, and the current statement change count.
39691 +case OP_ContextPop: {
39692 + assert(p->contextStackDepth > 0);
39693 + p->contextStackDepth--;
39694 + p->db->lastRowid = p->contextStack[p->contextStackDepth].lastRowid;
39695 + p->db->lsChange = p->contextStack[p->contextStackDepth].lsChange;
39696 + p->db->csChange = p->contextStack[p->contextStackDepth].csChange;
39697 + if( p->contextStackDepth == 0 ){
39698 + sqliteFree(p->contextStack);
39699 + p->contextStack = 0;
39704 +/* Opcode: SortPut * * *
39706 +** The TOS is the key and the NOS is the data. Pop both from the stack
39707 +** and put them on the sorter. The key and data should have been
39708 +** made using SortMakeKey and SortMakeRec, respectively.
39710 +case OP_SortPut: {
39711 + Mem *pNos = &pTos[-1];
39713 + assert( pNos>=p->aStack );
39714 + if( Dynamicify(pTos) || Dynamicify(pNos) ) goto no_mem;
39715 + pSorter = sqliteMallocRaw( sizeof(Sorter) );
39716 + if( pSorter==0 ) goto no_mem;
39717 + pSorter->pNext = p->pSort;
39718 + p->pSort = pSorter;
39719 + assert( pTos->flags & MEM_Dyn );
39720 + pSorter->nKey = pTos->n;
39721 + pSorter->zKey = pTos->z;
39722 + assert( pNos->flags & MEM_Dyn );
39723 + pSorter->nData = pNos->n;
39724 + pSorter->pData = pNos->z;
39729 +/* Opcode: SortMakeRec P1 * *
39731 +** The top P1 elements are the arguments to a callback. Form these
39732 +** elements into a single data entry that can be stored on a sorter
39733 +** using SortPut and later fed to a callback using SortCallback.
39735 +case OP_SortMakeRec: {
39743 + nField = pOp->p1;
39744 + pRec = &pTos[1-nField];
39745 + assert( pRec>=p->aStack );
39747 + for(i=0; i<nField; i++, pRec++){
39748 + if( (pRec->flags & MEM_Null)==0 ){
39750 + nByte += pRec->n;
39753 + nByte += sizeof(char*)*(nField+1);
39754 + azArg = sqliteMallocRaw( nByte );
39755 + if( azArg==0 ) goto no_mem;
39756 + z = (char*)&azArg[nField+1];
39757 + for(pRec=&pTos[1-nField], i=0; i<nField; i++, pRec++){
39758 + if( pRec->flags & MEM_Null ){
39762 + memcpy(z, pRec->z, pRec->n);
39766 + popStack(&pTos, nField);
39769 + pTos->z = (char*)azArg;
39770 + pTos->flags = MEM_Str | MEM_Dyn;
39774 +/* Opcode: SortMakeKey * * P3
39776 +** Convert the top few entries of the stack into a sort key. The
39777 +** number of stack entries consumed is the number of characters in
39778 +** the string P3. One character from P3 is prepended to each entry.
39779 +** The first character of P3 is prepended to the element lowest in
39780 +** the stack and the last character of P3 is prepended to the top of
39781 +** the stack. All stack entries are separated by a \000 character
39782 +** in the result. The whole key is terminated by two \000 characters
39785 +** "N" is substituted in place of the P3 character for NULL values.
39787 +** See also the MakeKey and MakeIdxKey opcodes.
39789 +case OP_SortMakeKey: {
39796 + nField = strlen(pOp->p3);
39797 + pRec = &pTos[1-nField];
39799 + for(i=0; i<nField; i++, pRec++){
39800 + if( pRec->flags & MEM_Null ){
39804 + nByte += pRec->n+2;
39807 + zNewKey = sqliteMallocRaw( nByte );
39808 + if( zNewKey==0 ) goto no_mem;
39811 + for(pRec=&pTos[1-nField], i=0; i<nField; i++, pRec++){
39812 + if( pRec->flags & MEM_Null ){
39813 + zNewKey[j++] = 'N';
39814 + zNewKey[j++] = 0;
39817 + zNewKey[j++] = pOp->p3[k++];
39818 + memcpy(&zNewKey[j], pRec->z, pRec->n-1);
39820 + zNewKey[j++] = 0;
39824 + assert( j<nByte );
39825 + popStack(&pTos, nField);
39828 + pTos->flags = MEM_Str|MEM_Dyn;
39829 + pTos->z = zNewKey;
39833 +/* Opcode: Sort * * *
39835 +** Sort all elements on the sorter. The algorithm is a
39841 + Sorter *apSorter[NSORT];
39842 + for(i=0; i<NSORT; i++){
39845 + while( p->pSort ){
39846 + pElem = p->pSort;
39847 + p->pSort = pElem->pNext;
39848 + pElem->pNext = 0;
39849 + for(i=0; i<NSORT-1; i++){
39850 + if( apSorter[i]==0 ){
39851 + apSorter[i] = pElem;
39854 + pElem = Merge(apSorter[i], pElem);
39858 + if( i>=NSORT-1 ){
39859 + apSorter[NSORT-1] = Merge(apSorter[NSORT-1],pElem);
39863 + for(i=0; i<NSORT; i++){
39864 + pElem = Merge(apSorter[i], pElem);
39866 + p->pSort = pElem;
39870 +/* Opcode: SortNext * P2 *
39872 +** Push the data for the topmost element in the sorter onto the
39873 +** stack, then remove the element from the sorter. If the sorter
39874 +** is empty, push nothing on the stack and instead jump immediately
39875 +** to instruction P2.
39877 +case OP_SortNext: {
39878 + Sorter *pSorter = p->pSort;
39879 + CHECK_FOR_INTERRUPT;
39880 + if( pSorter!=0 ){
39881 + p->pSort = pSorter->pNext;
39883 + pTos->z = pSorter->pData;
39884 + pTos->n = pSorter->nData;
39885 + pTos->flags = MEM_Str|MEM_Dyn;
39886 + sqliteFree(pSorter->zKey);
39887 + sqliteFree(pSorter);
39889 + pc = pOp->p2 - 1;
39894 +/* Opcode: SortCallback P1 * *
39896 +** The top of the stack contains a callback record built using
39897 +** the SortMakeRec operation with the same P1 value as this
39898 +** instruction. Pop this record from the stack and invoke the
39899 +** callback on it.
39901 +case OP_SortCallback: {
39902 + assert( pTos>=p->aStack );
39903 + assert( pTos->flags & MEM_Str );
39906 + p->azResColumn = (char**)pTos->z;
39907 + assert( p->nResColumn==pOp->p1 );
39910 + return SQLITE_ROW;
39913 +/* Opcode: SortReset * * *
39915 +** Remove any elements that remain on the sorter.
39917 +case OP_SortReset: {
39918 + sqliteVdbeSorterReset(p);
39922 +/* Opcode: FileOpen * * P3
39924 +** Open the file named by P3 for reading using the FileRead opcode.
39925 +** If P3 is "stdin" then open standard input for reading.
39927 +case OP_FileOpen: {
39928 + assert( pOp->p3!=0 );
39930 + if( p->pFile!=stdin ) fclose(p->pFile);
39933 + if( sqliteStrICmp(pOp->p3,"stdin")==0 ){
39934 + p->pFile = stdin;
39936 + p->pFile = fopen(pOp->p3, "r");
39938 + if( p->pFile==0 ){
39939 + sqliteSetString(&p->zErrMsg,"unable to open file: ", pOp->p3, (char*)0);
39940 + rc = SQLITE_ERROR;
39945 +/* Opcode: FileRead P1 P2 P3
39947 +** Read a single line of input from the open file (the file opened using
39948 +** FileOpen). If we reach end-of-file, jump immediately to P2. If
39949 +** we are able to get another line, split the line apart using P3 as
39950 +** a delimiter. There should be P1 fields. If the input line contains
39951 +** more than P1 fields, ignore the excess. If the input line contains
39952 +** fewer than P1 fields, assume the remaining fields contain NULLs.
39954 +** Input ends if a line consists of just "\.". A field containing only
39955 +** "\N" is a null field. The backslash \ character can be used be used
39956 +** to escape newlines or the delimiter.
39958 +case OP_FileRead: {
39959 + int n, eol, nField, i, c, nDelim;
39960 + char *zDelim, *z;
39961 + CHECK_FOR_INTERRUPT;
39962 + if( p->pFile==0 ) goto fileread_jump;
39963 + nField = pOp->p1;
39964 + if( nField<=0 ) goto fileread_jump;
39965 + if( nField!=p->nField || p->azField==0 ){
39966 + char **azField = sqliteRealloc(p->azField, sizeof(char*)*nField+1);
39967 + if( azField==0 ){ goto no_mem; }
39968 + p->azField = azField;
39969 + p->nField = nField;
39974 + if( p->zLine==0 || n+200>p->nLineAlloc ){
39976 + p->nLineAlloc = p->nLineAlloc*2 + 300;
39977 + zLine = sqliteRealloc(p->zLine, p->nLineAlloc);
39979 + p->nLineAlloc = 0;
39980 + sqliteFree(p->zLine);
39984 + p->zLine = zLine;
39986 + if( vdbe_fgets(&p->zLine[n], p->nLineAlloc-n, p->pFile)==0 ){
39991 + while( (c = p->zLine[n])!=0 ){
39993 + if( p->zLine[n+1]==0 ) break;
39995 + }else if( c=='\n' ){
40005 + if( n==0 ) goto fileread_jump;
40007 + if( z[0]=='\\' && z[1]=='.' && z[2]==0 ){
40008 + goto fileread_jump;
40010 + zDelim = pOp->p3;
40011 + if( zDelim==0 ) zDelim = "\t";
40013 + nDelim = strlen(zDelim);
40014 + p->azField[0] = z;
40015 + for(i=1; *z!=0 && i<=nField; i++){
40018 + if( z[0]=='\\' && z[1]=='N'
40019 + && (z[2]==0 || strncmp(&z[2],zDelim,nDelim)==0) ){
40020 + if( i<=nField ) p->azField[i-1] = 0;
40022 + if( i<nField ) p->azField[i] = z;
40025 + while( z[from] ){
40026 + if( z[from]=='\\' && z[from+1]!=0 ){
40027 + int tx = z[from+1];
40029 + case 'b': tx = '\b'; break;
40030 + case 'f': tx = '\f'; break;
40031 + case 'n': tx = '\n'; break;
40032 + case 'r': tx = '\r'; break;
40033 + case 't': tx = '\t'; break;
40034 + case 'v': tx = '\v'; break;
40041 + if( z[from]==c && strncmp(&z[from],zDelim,nDelim)==0 ) break;
40042 + z[to++] = z[from++];
40046 + z += from + nDelim;
40047 + if( i<nField ) p->azField[i] = z;
40053 + while( i<nField ){
40054 + p->azField[i++] = 0;
40058 + /* If we reach end-of-file, or if anything goes wrong, jump here.
40059 + ** This code will cause a jump to P2 */
40061 + pc = pOp->p2 - 1;
40065 +/* Opcode: FileColumn P1 * *
40067 +** Push onto the stack the P1-th column of the most recently read line
40068 +** from the input file.
40070 +case OP_FileColumn: {
40073 + assert( i>=0 && i<p->nField );
40074 + if( p->azField ){
40075 + z = p->azField[i];
40081 + pTos->n = strlen(z) + 1;
40083 + pTos->flags = MEM_Str | MEM_Ephem;
40085 + pTos->flags = MEM_Null;
40090 +/* Opcode: MemStore P1 P2 *
40092 +** Write the top of the stack into memory location P1.
40093 +** P1 should be a small integer since space is allocated
40094 +** for all memory locations between 0 and P1 inclusive.
40096 +** After the data is stored in the memory location, the
40097 +** stack is popped once if P2 is 1. If P2 is zero, then
40098 +** the original data remains on the stack.
40100 +case OP_MemStore: {
40103 + assert( pTos>=p->aStack );
40104 + if( i>=p->nMem ){
40105 + int nOld = p->nMem;
40108 + aMem = sqliteRealloc(p->aMem, p->nMem*sizeof(p->aMem[0]));
40109 + if( aMem==0 ) goto no_mem;
40110 + if( aMem!=p->aMem ){
40112 + for(j=0; j<nOld; j++){
40113 + if( aMem[j].flags & MEM_Short ){
40114 + aMem[j].z = aMem[j].zShort;
40119 + if( nOld<p->nMem ){
40120 + memset(&p->aMem[nOld], 0, sizeof(p->aMem[0])*(p->nMem-nOld));
40123 + Deephemeralize(pTos);
40124 + pMem = &p->aMem[i];
40127 + if( pMem->flags & MEM_Dyn ){
40129 + pTos->flags = MEM_Null;
40131 + pMem->z = sqliteMallocRaw( pMem->n );
40132 + if( pMem->z==0 ) goto no_mem;
40133 + memcpy(pMem->z, pTos->z, pMem->n);
40135 + }else if( pMem->flags & MEM_Short ){
40136 + pMem->z = pMem->zShort;
40145 +/* Opcode: MemLoad P1 * *
40147 +** Push a copy of the value in memory location P1 onto the stack.
40149 +** If the value is a string, then the value pushed is a pointer to
40150 +** the string that is stored in the memory location. If the memory
40151 +** location is subsequently changed (using OP_MemStore) then the
40152 +** value pushed onto the stack will change too.
40154 +case OP_MemLoad: {
40156 + assert( i>=0 && i<p->nMem );
40158 + memcpy(pTos, &p->aMem[i], sizeof(pTos[0])-NBFS);;
40159 + if( pTos->flags & MEM_Str ){
40160 + pTos->flags |= MEM_Ephem;
40161 + pTos->flags &= ~(MEM_Dyn|MEM_Static|MEM_Short);
40166 +/* Opcode: MemIncr P1 P2 *
40168 +** Increment the integer valued memory cell P1 by 1. If P2 is not zero
40169 +** and the result after the increment is greater than zero, then jump
40172 +** This instruction throws an error if the memory cell is not initially
40175 +case OP_MemIncr: {
40178 + assert( i>=0 && i<p->nMem );
40179 + pMem = &p->aMem[i];
40180 + assert( pMem->flags==MEM_Int );
40182 + if( pOp->p2>0 && pMem->i>0 ){
40183 + pc = pOp->p2 - 1;
40188 +/* Opcode: AggReset * P2 *
40190 +** Reset the aggregator so that it no longer contains any data.
40191 +** Future aggregator elements will contain P2 values each.
40193 +case OP_AggReset: {
40194 + sqliteVdbeAggReset(&p->agg);
40195 + p->agg.nMem = pOp->p2;
40196 + p->agg.apFunc = sqliteMalloc( p->agg.nMem*sizeof(p->agg.apFunc[0]) );
40197 + if( p->agg.apFunc==0 ) goto no_mem;
40201 +/* Opcode: AggInit * P2 P3
40203 +** Initialize the function parameters for an aggregate function.
40204 +** The aggregate will operate out of aggregate column P2.
40205 +** P3 is a pointer to the FuncDef structure for the function.
40207 +case OP_AggInit: {
40209 + assert( i>=0 && i<p->agg.nMem );
40210 + p->agg.apFunc[i] = (FuncDef*)pOp->p3;
40214 +/* Opcode: AggFunc * P2 P3
40216 +** Execute the step function for an aggregate. The
40217 +** function has P2 arguments. P3 is a pointer to the FuncDef
40218 +** structure that specifies the function.
40220 +** The top of the stack must be an integer which is the index of
40221 +** the aggregate column that corresponds to this aggregate function.
40222 +** Ideally, this index would be another parameter, but there are
40223 +** no free parameters left. The integer is popped from the stack.
40225 +case OP_AggFunc: {
40228 + Mem *pMem, *pRec;
40229 + char **azArgv = p->zArgv;
40233 + assert( pTos->flags==MEM_Int );
40234 + pRec = &pTos[-n];
40235 + assert( pRec>=p->aStack );
40236 + for(i=0; i<n; i++, pRec++){
40237 + if( pRec->flags & MEM_Null ){
40241 + azArgv[i] = pRec->z;
40245 + assert( i>=0 && i<p->agg.nMem );
40246 + ctx.pFunc = (FuncDef*)pOp->p3;
40247 + pMem = &p->agg.pCurrent->aMem[i];
40248 + ctx.s.z = pMem->zShort; /* Space used for small aggregate contexts */
40249 + ctx.pAgg = pMem->z;
40250 + ctx.cnt = ++pMem->i;
40253 + (ctx.pFunc->xStep)(&ctx, n, (const char**)azArgv);
40254 + pMem->z = ctx.pAgg;
40255 + pMem->flags = MEM_AggCtx;
40256 + popStack(&pTos, n+1);
40257 + if( ctx.isError ){
40258 + rc = SQLITE_ERROR;
40263 +/* Opcode: AggFocus * P2 *
40265 +** Pop the top of the stack and use that as an aggregator key. If
40266 +** an aggregator with that same key already exists, then make the
40267 +** aggregator the current aggregator and jump to P2. If no aggregator
40268 +** with the given key exists, create one and make it current but
40271 +** The order of aggregator opcodes is important. The order is:
40272 +** AggReset AggFocus AggNext. In other words, you must execute
40273 +** AggReset first, then zero or more AggFocus operations, then
40274 +** zero or more AggNext operations. You must not execute an AggFocus
40275 +** in between an AggNext and an AggReset.
40277 +case OP_AggFocus: {
40282 + assert( pTos>=p->aStack );
40286 + pElem = sqliteHashFind(&p->agg.hash, zKey, nKey);
40288 + p->agg.pCurrent = pElem;
40289 + pc = pOp->p2 - 1;
40291 + AggInsert(&p->agg, zKey, nKey);
40292 + if( sqlite_malloc_failed ) goto no_mem;
40299 +/* Opcode: AggSet * P2 *
40301 +** Move the top of the stack into the P2-th field of the current
40302 +** aggregate. String values are duplicated into new memory.
40305 + AggElem *pFocus = AggInFocus(p->agg);
40308 + assert( pTos>=p->aStack );
40309 + if( pFocus==0 ) goto no_mem;
40310 + assert( i>=0 && i<p->agg.nMem );
40311 + Deephemeralize(pTos);
40312 + pMem = &pFocus->aMem[i];
40315 + if( pMem->flags & MEM_Dyn ){
40316 + pTos->flags = MEM_Null;
40317 + }else if( pMem->flags & MEM_Short ){
40318 + pMem->z = pMem->zShort;
40325 +/* Opcode: AggGet * P2 *
40327 +** Push a new entry onto the stack which is a copy of the P2-th field
40328 +** of the current aggregate. Strings are not duplicated so
40329 +** string values will be ephemeral.
40332 + AggElem *pFocus = AggInFocus(p->agg);
40335 + if( pFocus==0 ) goto no_mem;
40336 + assert( i>=0 && i<p->agg.nMem );
40338 + pMem = &pFocus->aMem[i];
40340 + if( pTos->flags & MEM_Str ){
40341 + pTos->flags &= ~(MEM_Dyn|MEM_Static|MEM_Short);
40342 + pTos->flags |= MEM_Ephem;
40344 + if( pTos->flags & MEM_AggCtx ){
40346 + pTos->flags = MEM_Null;
40351 +/* Opcode: AggNext * P2 *
40353 +** Make the next aggregate value the current aggregate. The prior
40354 +** aggregate is deleted. If all aggregate values have been consumed,
40357 +** The order of aggregator opcodes is important. The order is:
40358 +** AggReset AggFocus AggNext. In other words, you must execute
40359 +** AggReset first, then zero or more AggFocus operations, then
40360 +** zero or more AggNext operations. You must not execute an AggFocus
40361 +** in between an AggNext and an AggReset.
40363 +case OP_AggNext: {
40364 + CHECK_FOR_INTERRUPT;
40365 + if( p->agg.pSearch==0 ){
40366 + p->agg.pSearch = sqliteHashFirst(&p->agg.hash);
40368 + p->agg.pSearch = sqliteHashNext(p->agg.pSearch);
40370 + if( p->agg.pSearch==0 ){
40371 + pc = pOp->p2 - 1;
40376 + p->agg.pCurrent = sqliteHashData(p->agg.pSearch);
40377 + aMem = p->agg.pCurrent->aMem;
40378 + for(i=0; i<p->agg.nMem; i++){
40380 + if( p->agg.apFunc[i]==0 ) continue;
40381 + if( p->agg.apFunc[i]->xFinalize==0 ) continue;
40382 + ctx.s.flags = MEM_Null;
40383 + ctx.s.z = aMem[i].zShort;
40384 + ctx.pAgg = (void*)aMem[i].z;
40385 + freeCtx = aMem[i].z && aMem[i].z!=aMem[i].zShort;
40386 + ctx.cnt = aMem[i].i;
40388 + ctx.pFunc = p->agg.apFunc[i];
40389 + (*p->agg.apFunc[i]->xFinalize)(&ctx);
40391 + sqliteFree( aMem[i].z );
40394 + if( aMem[i].flags & MEM_Short ){
40395 + aMem[i].z = aMem[i].zShort;
40402 +/* Opcode: SetInsert P1 * P3
40404 +** If Set P1 does not exist then create it. Then insert value
40405 +** P3 into that set. If P3 is NULL, then insert the top of the
40406 +** stack into the set.
40408 +case OP_SetInsert: {
40410 + if( p->nSet<=i ){
40412 + Set *aSet = sqliteRealloc(p->aSet, (i+1)*sizeof(p->aSet[0]) );
40413 + if( aSet==0 ) goto no_mem;
40415 + for(k=p->nSet; k<=i; k++){
40416 + sqliteHashInit(&p->aSet[k].hash, SQLITE_HASH_BINARY, 1);
40421 + sqliteHashInsert(&p->aSet[i].hash, pOp->p3, strlen(pOp->p3)+1, p);
40423 + assert( pTos>=p->aStack );
40425 + sqliteHashInsert(&p->aSet[i].hash, pTos->z, pTos->n, p);
40429 + if( sqlite_malloc_failed ) goto no_mem;
40433 +/* Opcode: SetFound P1 P2 *
40435 +** Pop the stack once and compare the value popped off with the
40436 +** contents of set P1. If the element popped exists in set P1,
40437 +** then jump to P2. Otherwise fall through.
40439 +case OP_SetFound: {
40441 + assert( pTos>=p->aStack );
40443 + if( i>=0 && i<p->nSet && sqliteHashFind(&p->aSet[i].hash, pTos->z, pTos->n)){
40444 + pc = pOp->p2 - 1;
40451 +/* Opcode: SetNotFound P1 P2 *
40453 +** Pop the stack once and compare the value popped off with the
40454 +** contents of set P1. If the element popped does not exists in
40455 +** set P1, then jump to P2. Otherwise fall through.
40457 +case OP_SetNotFound: {
40459 + assert( pTos>=p->aStack );
40461 + if( i<0 || i>=p->nSet ||
40462 + sqliteHashFind(&p->aSet[i].hash, pTos->z, pTos->n)==0 ){
40463 + pc = pOp->p2 - 1;
40470 +/* Opcode: SetFirst P1 P2 *
40472 +** Read the first element from set P1 and push it onto the stack. If the
40473 +** set is empty, push nothing and jump immediately to P2. This opcode is
40474 +** used in combination with OP_SetNext to loop over all elements of a set.
40476 +/* Opcode: SetNext P1 P2 *
40478 +** Read the next element from set P1 and push it onto the stack. If there
40479 +** are no more elements in the set, do not do the push and fall through.
40480 +** Otherwise, jump to P2 after pushing the next set element.
40483 +case OP_SetNext: {
40485 + CHECK_FOR_INTERRUPT;
40486 + if( pOp->p1<0 || pOp->p1>=p->nSet ){
40487 + if( pOp->opcode==OP_SetFirst ) pc = pOp->p2 - 1;
40490 + pSet = &p->aSet[pOp->p1];
40491 + if( pOp->opcode==OP_SetFirst ){
40492 + pSet->prev = sqliteHashFirst(&pSet->hash);
40493 + if( pSet->prev==0 ){
40494 + pc = pOp->p2 - 1;
40498 + if( pSet->prev ){
40499 + pSet->prev = sqliteHashNext(pSet->prev);
40501 + if( pSet->prev==0 ){
40504 + pc = pOp->p2 - 1;
40508 + pTos->z = sqliteHashKey(pSet->prev);
40509 + pTos->n = sqliteHashKeysize(pSet->prev);
40510 + pTos->flags = MEM_Str | MEM_Ephem;
40514 +/* Opcode: Vacuum * * *
40516 +** Vacuum the entire database. This opcode will cause other virtual
40517 +** machines to be created and run. It may not be called from within
40521 + if( sqliteSafetyOff(db) ) goto abort_due_to_misuse;
40522 + rc = sqliteRunVacuum(&p->zErrMsg, db);
40523 + if( sqliteSafetyOn(db) ) goto abort_due_to_misuse;
40527 +/* Opcode: StackDepth * * *
40529 +** Push an integer onto the stack which is the depth of the stack prior
40530 +** to that integer being pushed.
40532 +case OP_StackDepth: {
40533 + int depth = (&pTos[1]) - p->aStack;
40536 + pTos->flags = MEM_Int;
40540 +/* Opcode: StackReset * * *
40542 +** Pop a single integer off of the stack. Then pop the stack
40543 +** as many times as necessary to get the depth of the stack down
40544 +** to the value of the integer that was popped.
40546 +case OP_StackReset: {
40548 + assert( pTos>=p->aStack );
40549 + Integerify(pTos);
40551 + depth = (&pTos[1]) - p->aStack;
40552 + assert( goal<depth );
40553 + popStack(&pTos, depth-goal);
40557 +/* An other opcode is illegal...
40560 + sqlite_snprintf(sizeof(zBuf),zBuf,"%d",pOp->opcode);
40561 + sqliteSetString(&p->zErrMsg, "unknown opcode ", zBuf, (char*)0);
40562 + rc = SQLITE_INTERNAL;
40566 +/*****************************************************************************
40567 +** The cases of the switch statement above this line should all be indented
40568 +** by 6 spaces. But the left-most 6 spaces have been removed to improve the
40569 +** readability. From this point on down, the normal indentation rules are
40571 +*****************************************************************************/
40574 +#ifdef VDBE_PROFILE
40576 + long long elapse = hwtime() - start;
40577 + pOp->cycles += elapse;
40580 + fprintf(stdout, "%10lld ", elapse);
40581 + sqliteVdbePrintOp(stdout, origPc, &p->aOp[origPc]);
40586 + /* The following code adds nothing to the actual functionality
40587 + ** of the program. It is only here for testing and debugging.
40588 + ** On the other hand, it does burn CPU cycles every time through
40589 + ** the evaluator loop. So we can leave it out when NDEBUG is defined.
40592 + /* Sanity checking on the top element of the stack */
40593 + if( pTos>=p->aStack ){
40594 + assert( pTos->flags!=0 ); /* Must define some type */
40595 + if( pTos->flags & MEM_Str ){
40596 + int x = pTos->flags & (MEM_Static|MEM_Dyn|MEM_Ephem|MEM_Short);
40597 + assert( x!=0 ); /* Strings must define a string subtype */
40598 + assert( (x & (x-1))==0 ); /* Only one string subtype can be defined */
40599 + assert( pTos->z!=0 ); /* Strings must have a value */
40600 + /* Mem.z points to Mem.zShort iff the subtype is MEM_Short */
40601 + assert( (pTos->flags & MEM_Short)==0 || pTos->z==pTos->zShort );
40602 + assert( (pTos->flags & MEM_Short)!=0 || pTos->z!=pTos->zShort );
40604 + /* Cannot define a string subtype for non-string objects */
40605 + assert( (pTos->flags & (MEM_Static|MEM_Dyn|MEM_Ephem|MEM_Short))==0 );
40607 + /* MEM_Null excludes all other types */
40608 + assert( pTos->flags==MEM_Null || (pTos->flags&MEM_Null)==0 );
40610 + if( pc<-1 || pc>=p->nOp ){
40611 + sqliteSetString(&p->zErrMsg, "jump destination out of range", (char*)0);
40612 + rc = SQLITE_INTERNAL;
40614 + if( p->trace && pTos>=p->aStack ){
40616 + fprintf(p->trace, "Stack:");
40617 + for(i=0; i>-5 && &pTos[i]>=p->aStack; i--){
40618 + if( pTos[i].flags & MEM_Null ){
40619 + fprintf(p->trace, " NULL");
40620 + }else if( (pTos[i].flags & (MEM_Int|MEM_Str))==(MEM_Int|MEM_Str) ){
40621 + fprintf(p->trace, " si:%d", pTos[i].i);
40622 + }else if( pTos[i].flags & MEM_Int ){
40623 + fprintf(p->trace, " i:%d", pTos[i].i);
40624 + }else if( pTos[i].flags & MEM_Real ){
40625 + fprintf(p->trace, " r:%g", pTos[i].r);
40626 + }else if( pTos[i].flags & MEM_Str ){
40630 + if( pTos[i].flags & MEM_Dyn ){
40632 + assert( (pTos[i].flags & (MEM_Static|MEM_Ephem))==0 );
40633 + }else if( pTos[i].flags & MEM_Static ){
40635 + assert( (pTos[i].flags & (MEM_Dyn|MEM_Ephem))==0 );
40636 + }else if( pTos[i].flags & MEM_Ephem ){
40638 + assert( (pTos[i].flags & (MEM_Static|MEM_Dyn))==0 );
40644 + for(j=0; j<20 && j<pTos[i].n; j++){
40645 + int c = pTos[i].z[j];
40646 + if( c==0 && j==pTos[i].n-1 ) break;
40647 + if( isprint(c) && !isspace(c) ){
40655 + fprintf(p->trace, "%s", zBuf);
40657 + fprintf(p->trace, " ???");
40660 + if( rc!=0 ) fprintf(p->trace," rc=%d",rc);
40661 + fprintf(p->trace,"\n");
40664 + } /* The end of the for(;;) loop the loops through opcodes */
40666 + /* If we reach this point, it means that execution is finished.
40669 + CHECK_FOR_INTERRUPT
40672 + rc = SQLITE_ERROR;
40674 + rc = SQLITE_DONE;
40676 + p->magic = VDBE_MAGIC_HALT;
40680 + /* Jump to here if a malloc() fails. It's hard to get a malloc()
40681 + ** to fail on a modern VM computer, so this code is untested.
40684 + sqliteSetString(&p->zErrMsg, "out of memory", (char*)0);
40685 + rc = SQLITE_NOMEM;
40688 + /* Jump to here for an SQLITE_MISUSE error.
40690 +abort_due_to_misuse:
40691 + rc = SQLITE_MISUSE;
40692 + /* Fall thru into abort_due_to_error */
40694 + /* Jump to here for any other kind of fatal error. The "rc" variable
40695 + ** should hold the error number.
40697 +abort_due_to_error:
40698 + if( p->zErrMsg==0 ){
40699 + if( sqlite_malloc_failed ) rc = SQLITE_NOMEM;
40700 + sqliteSetString(&p->zErrMsg, sqlite_error_string(rc), (char*)0);
40704 + /* Jump to here if the sqlite_interrupt() API sets the interrupt
40707 +abort_due_to_interrupt:
40708 + assert( db->flags & SQLITE_Interrupt );
40709 + db->flags &= ~SQLITE_Interrupt;
40710 + if( db->magic!=SQLITE_MAGIC_BUSY ){
40711 + rc = SQLITE_MISUSE;
40713 + rc = SQLITE_INTERRUPT;
40715 + sqliteSetString(&p->zErrMsg, sqlite_error_string(rc), (char*)0);
40719 +++ b/ext/sqlite/libsqlite/src/vdbe.h
40722 +** 2001 September 15
40724 +** The author disclaims copyright to this source code. In place of
40725 +** a legal notice, here is a blessing:
40727 +** May you do good and not evil.
40728 +** May you find forgiveness for yourself and forgive others.
40729 +** May you share freely, never taking more than you give.
40731 +*************************************************************************
40732 +** Header file for the Virtual DataBase Engine (VDBE)
40734 +** This header defines the interface to the virtual database engine
40735 +** or VDBE. The VDBE implements an abstract machine that runs a
40736 +** simple program to access and modify the underlying database.
40740 +#ifndef _SQLITE_VDBE_H_
40741 +#define _SQLITE_VDBE_H_
40742 +#include <stdio.h>
40745 +** A single VDBE is an opaque structure named "Vdbe". Only routines
40746 +** in the source file sqliteVdbe.c are allowed to see the insides
40747 +** of this structure.
40749 +typedef struct Vdbe Vdbe;
40752 +** A single instruction of the virtual machine has an opcode
40753 +** and as many as three operands. The instruction is recorded
40754 +** as an instance of the following structure:
40757 + u8 opcode; /* What operation to perform */
40758 + int p1; /* First operand */
40759 + int p2; /* Second parameter (often the jump destination) */
40760 + char *p3; /* Third parameter */
40761 + int p3type; /* P3_STATIC, P3_DYNAMIC or P3_POINTER */
40762 +#ifdef VDBE_PROFILE
40763 + int cnt; /* Number of times this instruction was executed */
40764 + long long cycles; /* Total time spend executing this instruction */
40767 +typedef struct VdbeOp VdbeOp;
40770 +** A smaller version of VdbeOp used for the VdbeAddOpList() function because
40771 +** it takes up less space.
40773 +struct VdbeOpList {
40774 + u8 opcode; /* What operation to perform */
40775 + signed char p1; /* First operand */
40776 + short int p2; /* Second parameter (often the jump destination) */
40777 + char *p3; /* Third parameter */
40779 +typedef struct VdbeOpList VdbeOpList;
40782 +** Allowed values of VdbeOp.p3type
40784 +#define P3_NOTUSED 0 /* The P3 parameter is not used */
40785 +#define P3_DYNAMIC (-1) /* Pointer to a string obtained from sqliteMalloc() */
40786 +#define P3_STATIC (-2) /* Pointer to a static string */
40787 +#define P3_POINTER (-3) /* P3 is a pointer to some structure or object */
40790 +** The following macro converts a relative address in the p2 field
40791 +** of a VdbeOp structure into a negative number so that
40792 +** sqliteVdbeAddOpList() knows that the address is relative. Calling
40793 +** the macro again restores the address.
40795 +#define ADDR(X) (-1-(X))
40798 +** The makefile scans the vdbe.c source file and creates the "opcodes.h"
40799 +** header file that defines a number for each opcode used by the VDBE.
40801 +#include "opcodes.h"
40804 +** Prototypes for the VDBE interface. See comments on the implementation
40805 +** for a description of what each of these routines does.
40807 +Vdbe *sqliteVdbeCreate(sqlite*);
40808 +void sqliteVdbeCreateCallback(Vdbe*, int*);
40809 +int sqliteVdbeAddOp(Vdbe*,int,int,int);
40810 +int sqliteVdbeOp3(Vdbe*,int,int,int,const char *zP3,int);
40811 +int sqliteVdbeCode(Vdbe*,...);
40812 +int sqliteVdbeAddOpList(Vdbe*, int nOp, VdbeOpList const *aOp);
40813 +void sqliteVdbeChangeP1(Vdbe*, int addr, int P1);
40814 +void sqliteVdbeChangeP2(Vdbe*, int addr, int P2);
40815 +void sqliteVdbeChangeP3(Vdbe*, int addr, const char *zP1, int N);
40816 +void sqliteVdbeDequoteP3(Vdbe*, int addr);
40817 +int sqliteVdbeFindOp(Vdbe*, int, int);
40818 +VdbeOp *sqliteVdbeGetOp(Vdbe*, int);
40819 +int sqliteVdbeMakeLabel(Vdbe*);
40820 +void sqliteVdbeDelete(Vdbe*);
40821 +void sqliteVdbeMakeReady(Vdbe*,int,int);
40822 +int sqliteVdbeExec(Vdbe*);
40823 +int sqliteVdbeList(Vdbe*);
40824 +int sqliteVdbeFinalize(Vdbe*,char**);
40825 +void sqliteVdbeResolveLabel(Vdbe*, int);
40826 +int sqliteVdbeCurrentAddr(Vdbe*);
40827 +void sqliteVdbeTrace(Vdbe*,FILE*);
40828 +void sqliteVdbeCompressSpace(Vdbe*,int);
40829 +int sqliteVdbeReset(Vdbe*,char **);
40830 +int sqliteVdbeSetVariables(Vdbe*,int,const char**);
40834 +++ b/ext/sqlite/libsqlite/src/vdbeInt.h
40837 +** 2003 September 6
40839 +** The author disclaims copyright to this source code. In place of
40840 +** a legal notice, here is a blessing:
40842 +** May you do good and not evil.
40843 +** May you find forgiveness for yourself and forgive others.
40844 +** May you share freely, never taking more than you give.
40846 +*************************************************************************
40847 +** This is the header file for information that is private to the
40848 +** VDBE. This information used to all be at the top of the single
40849 +** source code file "vdbe.c". When that file became too big (over
40850 +** 6000 lines long) it was split up into several smaller files and
40851 +** this header information was factored out.
40855 +** When converting from the native format to the key format and back
40856 +** again, in addition to changing the byte order we invert the high-order
40857 +** bit of the most significant byte. This causes negative numbers to
40858 +** sort before positive numbers in the memcmp() function.
40860 +#define keyToInt(X) (sqliteVdbeByteSwap(X) ^ 0x80000000)
40861 +#define intToKey(X) (sqliteVdbeByteSwap((X) ^ 0x80000000))
40864 +** The makefile scans this source file and creates the following
40865 +** array of string constants which are the names of all VDBE opcodes.
40866 +** This array is defined in a separate source code file named opcode.c
40867 +** which is automatically generated by the makefile.
40869 +extern char *sqliteOpcodeNames[];
40872 +** SQL is translated into a sequence of instructions to be
40873 +** executed by a virtual machine. Each instruction is an instance
40874 +** of the following structure.
40876 +typedef struct VdbeOp Op;
40881 +typedef unsigned char Bool;
40884 +** A cursor is a pointer into a single BTree within a database file.
40885 +** The cursor can seek to a BTree entry with a particular key, or
40886 +** loop over all entries of the Btree. You can also insert new BTree
40887 +** entries or retrieve the key or data from the entry that the cursor
40888 +** is currently pointing to.
40890 +** Every cursor that the virtual machine has open is represented by an
40891 +** instance of the following structure.
40893 +** If the Cursor.isTriggerRow flag is set it means that this cursor is
40894 +** really a single row that represents the NEW or OLD pseudo-table of
40895 +** a row trigger. The data for the row is stored in Cursor.pData and
40896 +** the rowid is in Cursor.iKey.
40899 + BtCursor *pCursor; /* The cursor structure of the backend */
40900 + int lastRecno; /* Last recno from a Next or NextIdx operation */
40901 + int nextRowid; /* Next rowid returned by OP_NewRowid */
40902 + Bool recnoIsValid; /* True if lastRecno is valid */
40903 + Bool keyAsData; /* The OP_Column command works on key instead of data */
40904 + Bool atFirst; /* True if pointing to first entry */
40905 + Bool useRandomRowid; /* Generate new record numbers semi-randomly */
40906 + Bool nullRow; /* True if pointing to a row with no data */
40907 + Bool nextRowidValid; /* True if the nextRowid field is valid */
40908 + Bool pseudoTable; /* This is a NEW or OLD pseudo-tables of a trigger */
40909 + Bool deferredMoveto; /* A call to sqliteBtreeMoveto() is needed */
40910 + int movetoTarget; /* Argument to the deferred sqliteBtreeMoveto() */
40911 + Btree *pBt; /* Separate file holding temporary table */
40912 + int nData; /* Number of bytes in pData */
40913 + char *pData; /* Data for a NEW or OLD pseudo-table */
40914 + int iKey; /* Key for the NEW or OLD pseudo-table row */
40916 +typedef struct Cursor Cursor;
40919 +** A sorter builds a list of elements to be sorted. Each element of
40920 +** the list is an instance of the following structure.
40922 +typedef struct Sorter Sorter;
40924 + int nKey; /* Number of bytes in the key */
40925 + char *zKey; /* The key by which we will sort */
40926 + int nData; /* Number of bytes in the data */
40927 + char *pData; /* The data associated with this key */
40928 + Sorter *pNext; /* Next in the list */
40932 +** Number of buckets used for merge-sort.
40937 +** Number of bytes of string storage space available to each stack
40938 +** layer without having to malloc. NBFS is short for Number of Bytes
40944 +** A single level of the stack or a single memory cell
40945 +** is an instance of the following structure.
40948 + int i; /* Integer value */
40949 + int n; /* Number of characters in string value, including '\0' */
40950 + int flags; /* Some combination of MEM_Null, MEM_Str, MEM_Dyn, etc. */
40951 + double r; /* Real value */
40952 + char *z; /* String value */
40953 + char zShort[NBFS]; /* Space for short strings */
40955 +typedef struct Mem Mem;
40958 +** Allowed values for Mem.flags
40960 +#define MEM_Null 0x0001 /* Value is NULL */
40961 +#define MEM_Str 0x0002 /* Value is a string */
40962 +#define MEM_Int 0x0004 /* Value is an integer */
40963 +#define MEM_Real 0x0008 /* Value is a real number */
40964 +#define MEM_Dyn 0x0010 /* Need to call sqliteFree() on Mem.z */
40965 +#define MEM_Static 0x0020 /* Mem.z points to a static string */
40966 +#define MEM_Ephem 0x0040 /* Mem.z points to an ephemeral string */
40967 +#define MEM_Short 0x0080 /* Mem.z points to Mem.zShort */
40969 +/* The following MEM_ value appears only in AggElem.aMem.s.flag fields.
40970 +** It indicates that the corresponding AggElem.aMem.z points to a
40971 +** aggregate function context that needs to be finalized.
40973 +#define MEM_AggCtx 0x0100 /* Mem.z points to an agg function context */
40976 +** The "context" argument for a installable function. A pointer to an
40977 +** instance of this structure is the first argument to the routines used
40978 +** implement the SQL functions.
40980 +** There is a typedef for this structure in sqlite.h. So all routines,
40981 +** even the public interface to SQLite, can use a pointer to this structure.
40982 +** But this file is the only place where the internal details of this
40983 +** structure are known.
40985 +** This structure is defined inside of vdbe.c because it uses substructures
40986 +** (Mem) which are only defined there.
40988 +struct sqlite_func {
40989 + FuncDef *pFunc; /* Pointer to function information. MUST BE FIRST */
40990 + Mem s; /* The return value is stored here */
40991 + void *pAgg; /* Aggregate context */
40992 + u8 isError; /* Set to true for an error */
40993 + u8 isStep; /* Current in the step function */
40994 + int cnt; /* Number of times that the step function has been called */
40998 +** An Agg structure describes an Aggregator. Each Agg consists of
40999 +** zero or more Aggregator elements (AggElem). Each AggElem contains
41000 +** a key and one or more values. The values are used in processing
41001 +** aggregate functions in a SELECT. The key is used to implement
41002 +** the GROUP BY clause of a select.
41004 +typedef struct Agg Agg;
41005 +typedef struct AggElem AggElem;
41007 + int nMem; /* Number of values stored in each AggElem */
41008 + AggElem *pCurrent; /* The AggElem currently in focus */
41009 + HashElem *pSearch; /* The hash element for pCurrent */
41010 + Hash hash; /* Hash table of all aggregate elements */
41011 + FuncDef **apFunc; /* Information about aggregate functions */
41014 + char *zKey; /* The key to this AggElem */
41015 + int nKey; /* Number of bytes in the key, including '\0' at end */
41016 + Mem aMem[1]; /* The values for this AggElem */
41020 +** A Set structure is used for quick testing to see if a value
41021 +** is part of a small set. Sets are used to implement code like
41023 +** x.y IN ('hi','hoo','hum')
41025 +typedef struct Set Set;
41027 + Hash hash; /* A set is just a hash table */
41028 + HashElem *prev; /* Previously accessed hash elemen */
41032 +** A Keylist is a bunch of keys into a table. The keylist can
41033 +** grow without bound. The keylist stores the ROWIDs of database
41034 +** records that need to be deleted or updated.
41036 +typedef struct Keylist Keylist;
41038 + int nKey; /* Number of slots in aKey[] */
41039 + int nUsed; /* Next unwritten slot in aKey[] */
41040 + int nRead; /* Next unread slot in aKey[] */
41041 + Keylist *pNext; /* Next block of keys */
41042 + int aKey[1]; /* One or more keys. Extra space allocated as needed */
41046 +** A Context stores the last insert rowid, the last statement change count,
41047 +** and the current statement change count (i.e. changes since last statement).
41048 +** Elements of Context structure type make up the ContextStack, which is
41049 +** updated by the ContextPush and ContextPop opcodes (used by triggers)
41051 +typedef struct Context Context;
41053 + int lastRowid; /* Last insert rowid (from db->lastRowid) */
41054 + int lsChange; /* Last statement change count (from db->lsChange) */
41055 + int csChange; /* Current statement change count (from db->csChange) */
41059 +** An instance of the virtual machine. This structure contains the complete
41060 +** state of the virtual machine.
41062 +** The "sqlite_vm" structure pointer that is returned by sqlite_compile()
41063 +** is really a pointer to an instance of this structure.
41066 + sqlite *db; /* The whole database */
41067 + Vdbe *pPrev,*pNext; /* Linked list of VDBEs with the same Vdbe.db */
41068 + FILE *trace; /* Write an execution trace here, if not NULL */
41069 + int nOp; /* Number of instructions in the program */
41070 + int nOpAlloc; /* Number of slots allocated for aOp[] */
41071 + Op *aOp; /* Space to hold the virtual machine's program */
41072 + int nLabel; /* Number of labels used */
41073 + int nLabelAlloc; /* Number of slots allocated in aLabel[] */
41074 + int *aLabel; /* Space to hold the labels */
41075 + Mem *aStack; /* The operand stack, except string values */
41076 + Mem *pTos; /* Top entry in the operand stack */
41077 + char **zArgv; /* Text values used by the callback */
41078 + char **azColName; /* Becomes the 4th parameter to callbacks */
41079 + int nCursor; /* Number of slots in aCsr[] */
41080 + Cursor *aCsr; /* One element of this array for each open cursor */
41081 + Sorter *pSort; /* A linked list of objects to be sorted */
41082 + FILE *pFile; /* At most one open file handler */
41083 + int nField; /* Number of file fields */
41084 + char **azField; /* Data for each file field */
41085 + int nVar; /* Number of entries in azVariable[] */
41086 + char **azVar; /* Values for the OP_Variable opcode */
41087 + int *anVar; /* Length of each value in azVariable[] */
41088 + u8 *abVar; /* TRUE if azVariable[i] needs to be sqliteFree()ed */
41089 + char *zLine; /* A single line from the input file */
41090 + int nLineAlloc; /* Number of spaces allocated for zLine */
41091 + int magic; /* Magic number for sanity checking */
41092 + int nMem; /* Number of memory locations currently allocated */
41093 + Mem *aMem; /* The memory locations */
41094 + Agg agg; /* Aggregate information */
41095 + int nSet; /* Number of sets allocated */
41096 + Set *aSet; /* An array of sets */
41097 + int nCallback; /* Number of callbacks invoked so far */
41098 + Keylist *pList; /* A list of ROWIDs */
41099 + int keylistStackDepth; /* The size of the "keylist" stack */
41100 + Keylist **keylistStack; /* The stack used by opcodes ListPush & ListPop */
41101 + int contextStackDepth; /* The size of the "context" stack */
41102 + Context *contextStack; /* Stack used by opcodes ContextPush & ContextPop*/
41103 + int pc; /* The program counter */
41104 + int rc; /* Value to return */
41105 + unsigned uniqueCnt; /* Used by OP_MakeRecord when P2!=0 */
41106 + int errorAction; /* Recovery action to do in case of an error */
41107 + int undoTransOnError; /* If error, either ROLLBACK or COMMIT */
41108 + int inTempTrans; /* True if temp database is transactioned */
41109 + int returnStack[100]; /* Return address stack for OP_Gosub & OP_Return */
41110 + int returnDepth; /* Next unused element in returnStack[] */
41111 + int nResColumn; /* Number of columns in one row of the result set */
41112 + char **azResColumn; /* Values for one row of result */
41113 + int popStack; /* Pop the stack this much on entry to VdbeExec() */
41114 + char *zErrMsg; /* Error message written here */
41115 + u8 explain; /* True if EXPLAIN present on SQL command */
41119 +** The following are allowed values for Vdbe.magic
41121 +#define VDBE_MAGIC_INIT 0x26bceaa5 /* Building a VDBE program */
41122 +#define VDBE_MAGIC_RUN 0xbdf20da3 /* VDBE is ready to execute */
41123 +#define VDBE_MAGIC_HALT 0x519c2973 /* VDBE has completed execution */
41124 +#define VDBE_MAGIC_DEAD 0xb606c3c8 /* The VDBE has been deallocated */
41127 +** Function prototypes
41129 +void sqliteVdbeCleanupCursor(Cursor*);
41130 +void sqliteVdbeSorterReset(Vdbe*);
41131 +void sqliteVdbeAggReset(Agg*);
41132 +void sqliteVdbeKeylistFree(Keylist*);
41133 +void sqliteVdbePopStack(Vdbe*,int);
41134 +int sqliteVdbeCursorMoveto(Cursor*);
41135 +int sqliteVdbeByteSwap(int);
41136 +#if !defined(NDEBUG) || defined(VDBE_PROFILE)
41137 +void sqliteVdbePrintOp(FILE*, int, Op*);
41140 +++ b/ext/sqlite/libsqlite/src/where.c
41143 +** 2001 September 15
41145 +** The author disclaims copyright to this source code. In place of
41146 +** a legal notice, here is a blessing:
41148 +** May you do good and not evil.
41149 +** May you find forgiveness for yourself and forgive others.
41150 +** May you share freely, never taking more than you give.
41152 +*************************************************************************
41153 +** This module contains C code that generates VDBE code used to process
41154 +** the WHERE clause of SQL statements.
41158 +#include "sqliteInt.h"
41161 +** The query generator uses an array of instances of this structure to
41162 +** help it analyze the subexpressions of the WHERE clause. Each WHERE
41163 +** clause subexpression is separated from the others by an AND operator.
41165 +typedef struct ExprInfo ExprInfo;
41167 + Expr *p; /* Pointer to the subexpression */
41168 + u8 indexable; /* True if this subexprssion is usable by an index */
41169 + short int idxLeft; /* p->pLeft is a column in this table number. -1 if
41170 + ** p->pLeft is not the column of any table */
41171 + short int idxRight; /* p->pRight is a column in this table number. -1 if
41172 + ** p->pRight is not the column of any table */
41173 + unsigned prereqLeft; /* Bitmask of tables referenced by p->pLeft */
41174 + unsigned prereqRight; /* Bitmask of tables referenced by p->pRight */
41175 + unsigned prereqAll; /* Bitmask of tables referenced by p */
41179 +** An instance of the following structure keeps track of a mapping
41180 +** between VDBE cursor numbers and bitmasks. The VDBE cursor numbers
41181 +** are small integers contained in SrcList_item.iCursor and Expr.iTable
41182 +** fields. For any given WHERE clause, we want to track which cursors
41183 +** are being used, so we assign a single bit in a 32-bit word to track
41184 +** that cursor. Then a 32-bit integer is able to show the set of all
41185 +** cursors being used.
41187 +typedef struct ExprMaskSet ExprMaskSet;
41188 +struct ExprMaskSet {
41189 + int n; /* Number of assigned cursor values */
41190 + int ix[31]; /* Cursor assigned to each bit */
41194 +** Determine the number of elements in an array.
41196 +#define ARRAYSIZE(X) (sizeof(X)/sizeof(X[0]))
41199 +** This routine is used to divide the WHERE expression into subexpressions
41200 +** separated by the AND operator.
41202 +** aSlot[] is an array of subexpressions structures.
41203 +** There are nSlot spaces left in this array. This routine attempts to
41204 +** split pExpr into subexpressions and fills aSlot[] with those subexpressions.
41205 +** The return value is the number of slots filled.
41207 +static int exprSplit(int nSlot, ExprInfo *aSlot, Expr *pExpr){
41209 + if( pExpr==0 || nSlot<1 ) return 0;
41210 + if( nSlot==1 || pExpr->op!=TK_AND ){
41211 + aSlot[0].p = pExpr;
41214 + if( pExpr->pLeft->op!=TK_AND ){
41215 + aSlot[0].p = pExpr->pLeft;
41216 + cnt = 1 + exprSplit(nSlot-1, &aSlot[1], pExpr->pRight);
41218 + cnt = exprSplit(nSlot, aSlot, pExpr->pLeft);
41219 + cnt += exprSplit(nSlot-cnt, &aSlot[cnt], pExpr->pRight);
41225 +** Initialize an expression mask set
41227 +#define initMaskSet(P) memset(P, 0, sizeof(*P))
41230 +** Return the bitmask for the given cursor. Assign a new bitmask
41231 +** if this is the first time the cursor has been seen.
41233 +static int getMask(ExprMaskSet *pMaskSet, int iCursor){
41235 + for(i=0; i<pMaskSet->n; i++){
41236 + if( pMaskSet->ix[i]==iCursor ) return 1<<i;
41238 + if( i==pMaskSet->n && i<ARRAYSIZE(pMaskSet->ix) ){
41240 + pMaskSet->ix[i] = iCursor;
41247 +** Destroy an expression mask set
41249 +#define freeMaskSet(P) /* NO-OP */
41252 +** This routine walks (recursively) an expression tree and generates
41253 +** a bitmask indicating which tables are used in that expression
41256 +** In order for this routine to work, the calling function must have
41257 +** previously invoked sqliteExprResolveIds() on the expression. See
41258 +** the header comment on that routine for additional information.
41259 +** The sqliteExprResolveIds() routines looks for column names and
41260 +** sets their opcodes to TK_COLUMN and their Expr.iTable fields to
41261 +** the VDBE cursor number of the table.
41263 +static int exprTableUsage(ExprMaskSet *pMaskSet, Expr *p){
41264 + unsigned int mask = 0;
41265 + if( p==0 ) return 0;
41266 + if( p->op==TK_COLUMN ){
41267 + mask = getMask(pMaskSet, p->iTable);
41268 + if( mask==0 ) mask = -1;
41272 + mask = exprTableUsage(pMaskSet, p->pRight);
41275 + mask |= exprTableUsage(pMaskSet, p->pLeft);
41279 + for(i=0; i<p->pList->nExpr; i++){
41280 + mask |= exprTableUsage(pMaskSet, p->pList->a[i].pExpr);
41287 +** Return TRUE if the given operator is one of the operators that is
41288 +** allowed for an indexable WHERE clause. The allowed operators are
41289 +** "=", "<", ">", "<=", ">=", and "IN".
41291 +static int allowedOp(int op){
41306 +** The input to this routine is an ExprInfo structure with only the
41307 +** "p" field filled in. The job of this routine is to analyze the
41308 +** subexpression and populate all the other fields of the ExprInfo
41311 +static void exprAnalyze(ExprMaskSet *pMaskSet, ExprInfo *pInfo){
41312 + Expr *pExpr = pInfo->p;
41313 + pInfo->prereqLeft = exprTableUsage(pMaskSet, pExpr->pLeft);
41314 + pInfo->prereqRight = exprTableUsage(pMaskSet, pExpr->pRight);
41315 + pInfo->prereqAll = exprTableUsage(pMaskSet, pExpr);
41316 + pInfo->indexable = 0;
41317 + pInfo->idxLeft = -1;
41318 + pInfo->idxRight = -1;
41319 + if( allowedOp(pExpr->op) && (pInfo->prereqRight & pInfo->prereqLeft)==0 ){
41320 + if( pExpr->pRight && pExpr->pRight->op==TK_COLUMN ){
41321 + pInfo->idxRight = pExpr->pRight->iTable;
41322 + pInfo->indexable = 1;
41324 + if( pExpr->pLeft->op==TK_COLUMN ){
41325 + pInfo->idxLeft = pExpr->pLeft->iTable;
41326 + pInfo->indexable = 1;
41332 +** pOrderBy is an ORDER BY clause from a SELECT statement. pTab is the
41333 +** left-most table in the FROM clause of that same SELECT statement and
41334 +** the table has a cursor number of "base".
41336 +** This routine attempts to find an index for pTab that generates the
41337 +** correct record sequence for the given ORDER BY clause. The return value
41338 +** is a pointer to an index that does the job. NULL is returned if the
41339 +** table has no index that will generate the correct sort order.
41341 +** If there are two or more indices that generate the correct sort order
41342 +** and pPreferredIdx is one of those indices, then return pPreferredIdx.
41344 +** nEqCol is the number of columns of pPreferredIdx that are used as
41345 +** equality constraints. Any index returned must have exactly this same
41346 +** set of columns. The ORDER BY clause only matches index columns beyond the
41347 +** the first nEqCol columns.
41349 +** All terms of the ORDER BY clause must be either ASC or DESC. The
41350 +** *pbRev value is set to 1 if the ORDER BY clause is all DESC and it is
41351 +** set to 0 if the ORDER BY clause is all ASC.
41353 +static Index *findSortingIndex(
41354 + Table *pTab, /* The table to be sorted */
41355 + int base, /* Cursor number for pTab */
41356 + ExprList *pOrderBy, /* The ORDER BY clause */
41357 + Index *pPreferredIdx, /* Use this index, if possible and not NULL */
41358 + int nEqCol, /* Number of index columns used with == constraints */
41359 + int *pbRev /* Set to 1 if ORDER BY is DESC */
41366 + assert( pOrderBy!=0 );
41367 + assert( pOrderBy->nExpr>0 );
41368 + sortOrder = pOrderBy->a[0].sortOrder & SQLITE_SO_DIRMASK;
41369 + for(i=0; i<pOrderBy->nExpr; i++){
41371 + if( (pOrderBy->a[i].sortOrder & SQLITE_SO_DIRMASK)!=sortOrder ){
41372 + /* Indices can only be used if all ORDER BY terms are either
41373 + ** DESC or ASC. Indices cannot be used on a mixture. */
41376 + if( (pOrderBy->a[i].sortOrder & SQLITE_SO_TYPEMASK)!=SQLITE_SO_UNK ){
41377 + /* Do not sort by index if there is a COLLATE clause */
41380 + p = pOrderBy->a[i].pExpr;
41381 + if( p->op!=TK_COLUMN || p->iTable!=base ){
41382 + /* Can not use an index sort on anything that is not a column in the
41383 + ** left-most table of the FROM clause */
41388 + /* If we get this far, it means the ORDER BY clause consists only of
41389 + ** ascending columns in the left-most table of the FROM clause. Now
41390 + ** check for a matching index.
41393 + for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
41394 + int nExpr = pOrderBy->nExpr;
41395 + if( pIdx->nColumn < nEqCol || pIdx->nColumn < nExpr ) continue;
41396 + for(i=j=0; i<nEqCol; i++){
41397 + if( pPreferredIdx->aiColumn[i]!=pIdx->aiColumn[i] ) break;
41398 + if( j<nExpr && pOrderBy->a[j].pExpr->iColumn==pIdx->aiColumn[i] ){ j++; }
41400 + if( i<nEqCol ) continue;
41401 + for(i=0; i+j<nExpr; i++){
41402 + if( pOrderBy->a[i+j].pExpr->iColumn!=pIdx->aiColumn[i+nEqCol] ) break;
41404 + if( i+j>=nExpr ){
41406 + if( pIdx==pPreferredIdx ) break;
41409 + if( pMatch && pbRev ){
41410 + *pbRev = sortOrder==SQLITE_SO_DESC;
41416 +** Disable a term in the WHERE clause. Except, do not disable the term
41417 +** if it controls a LEFT OUTER JOIN and it did not originate in the ON
41418 +** or USING clause of that join.
41420 +** Consider the term t2.z='ok' in the following queries:
41422 +** (1) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
41423 +** (2) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
41424 +** (3) SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
41426 +** The t2.z='ok' is disabled in the in (2) because it did not originate
41427 +** in the ON clause. The term is disabled in (3) because it is not part
41428 +** of a LEFT OUTER JOIN. In (1), the term is not disabled.
41430 +** Disabling a term causes that term to not be tested in the inner loop
41431 +** of the join. Disabling is an optimization. We would get the correct
41432 +** results if nothing were ever disabled, but joins might run a little
41433 +** slower. The trick is to disable as much as we can without disabling
41434 +** too much. If we disabled in (1), we'd get the wrong answer.
41435 +** See ticket #813.
41437 +static void disableTerm(WhereLevel *pLevel, Expr **ppExpr){
41438 + Expr *pExpr = *ppExpr;
41439 + if( pLevel->iLeftJoin==0 || ExprHasProperty(pExpr, EP_FromJoin) ){
41445 +** Generate the beginning of the loop used for WHERE clause processing.
41446 +** The return value is a pointer to an (opaque) structure that contains
41447 +** information needed to terminate the loop. Later, the calling routine
41448 +** should invoke sqliteWhereEnd() with the return value of this function
41449 +** in order to complete the WHERE clause processing.
41451 +** If an error occurs, this routine returns NULL.
41453 +** The basic idea is to do a nested loop, one loop for each table in
41454 +** the FROM clause of a select. (INSERT and UPDATE statements are the
41455 +** same as a SELECT with only a single table in the FROM clause.) For
41456 +** example, if the SQL is this:
41458 +** SELECT * FROM t1, t2, t3 WHERE ...;
41460 +** Then the code generated is conceptually like the following:
41462 +** foreach row1 in t1 do \ Code generated
41463 +** foreach row2 in t2 do |-- by sqliteWhereBegin()
41464 +** foreach row3 in t3 do /
41466 +** end \ Code generated
41467 +** end |-- by sqliteWhereEnd()
41470 +** There are Btree cursors associated with each table. t1 uses cursor
41471 +** number pTabList->a[0].iCursor. t2 uses the cursor pTabList->a[1].iCursor.
41472 +** And so forth. This routine generates code to open those VDBE cursors
41473 +** and sqliteWhereEnd() generates the code to close them.
41475 +** If the WHERE clause is empty, the foreach loops must each scan their
41476 +** entire tables. Thus a three-way join is an O(N^3) operation. But if
41477 +** the tables have indices and there are terms in the WHERE clause that
41478 +** refer to those indices, a complete table scan can be avoided and the
41479 +** code will run much faster. Most of the work of this routine is checking
41480 +** to see if there are indices that can be used to speed up the loop.
41482 +** Terms of the WHERE clause are also used to limit which rows actually
41483 +** make it to the "..." in the middle of the loop. After each "foreach",
41484 +** terms of the WHERE clause that use only terms in that loop and outer
41485 +** loops are evaluated and if false a jump is made around all subsequent
41486 +** inner loops (or around the "..." if the test occurs within the inner-
41491 +** An outer join of tables t1 and t2 is conceptally coded as follows:
41493 +** foreach row1 in t1 do
41495 +** foreach row2 in t2 do
41500 +** if flag==0 then
41501 +** move the row2 cursor to a null row
41506 +** ORDER BY CLAUSE PROCESSING
41508 +** *ppOrderBy is a pointer to the ORDER BY clause of a SELECT statement,
41509 +** if there is one. If there is no ORDER BY clause or if this routine
41510 +** is called from an UPDATE or DELETE statement, then ppOrderBy is NULL.
41512 +** If an index can be used so that the natural output order of the table
41513 +** scan is correct for the ORDER BY clause, then that index is used and
41514 +** *ppOrderBy is set to NULL. This is an optimization that prevents an
41515 +** unnecessary sort of the result set if an index appropriate for the
41516 +** ORDER BY clause already exists.
41518 +** If the where clause loops cannot be arranged to provide the correct
41519 +** output order, then the *ppOrderBy is unchanged.
41521 +WhereInfo *sqliteWhereBegin(
41522 + Parse *pParse, /* The parser context */
41523 + SrcList *pTabList, /* A list of all tables to be scanned */
41524 + Expr *pWhere, /* The WHERE clause */
41525 + int pushKey, /* If TRUE, leave the table key on the stack */
41526 + ExprList **ppOrderBy /* An ORDER BY clause, or NULL */
41528 + int i; /* Loop counter */
41529 + WhereInfo *pWInfo; /* Will become the return value of this function */
41530 + Vdbe *v = pParse->pVdbe; /* The virtual database engine */
41531 + int brk, cont = 0; /* Addresses used during code generation */
41532 + int nExpr; /* Number of subexpressions in the WHERE clause */
41533 + int loopMask; /* One bit set for each outer loop */
41534 + int haveKey; /* True if KEY is on the stack */
41535 + ExprMaskSet maskSet; /* The expression mask set */
41536 + int iDirectEq[32]; /* Term of the form ROWID==X for the N-th table */
41537 + int iDirectLt[32]; /* Term of the form ROWID<X or ROWID<=X */
41538 + int iDirectGt[32]; /* Term of the form ROWID>X or ROWID>=X */
41539 + ExprInfo aExpr[101]; /* The WHERE clause is divided into these expressions */
41541 + /* pushKey is only allowed if there is a single table (as in an INSERT or
41542 + ** UPDATE statement)
41544 + assert( pushKey==0 || pTabList->nSrc==1 );
41546 + /* Split the WHERE clause into separate subexpressions where each
41547 + ** subexpression is separated by an AND operator. If the aExpr[]
41548 + ** array fills up, the last entry might point to an expression which
41549 + ** contains additional unfactored AND operators.
41551 + initMaskSet(&maskSet);
41552 + memset(aExpr, 0, sizeof(aExpr));
41553 + nExpr = exprSplit(ARRAYSIZE(aExpr), aExpr, pWhere);
41554 + if( nExpr==ARRAYSIZE(aExpr) ){
41555 + sqliteErrorMsg(pParse, "WHERE clause too complex - no more "
41556 + "than %d terms allowed", (int)ARRAYSIZE(aExpr)-1);
41560 + /* Allocate and initialize the WhereInfo structure that will become the
41563 + pWInfo = sqliteMalloc( sizeof(WhereInfo) + pTabList->nSrc*sizeof(WhereLevel));
41564 + if( sqlite_malloc_failed ){
41565 + sqliteFree(pWInfo);
41568 + pWInfo->pParse = pParse;
41569 + pWInfo->pTabList = pTabList;
41570 + pWInfo->peakNTab = pWInfo->savedNTab = pParse->nTab;
41571 + pWInfo->iBreak = sqliteVdbeMakeLabel(v);
41573 + /* Special case: a WHERE clause that is constant. Evaluate the
41574 + ** expression and either jump over all of the code or fall thru.
41576 + if( pWhere && (pTabList->nSrc==0 || sqliteExprIsConstant(pWhere)) ){
41577 + sqliteExprIfFalse(pParse, pWhere, pWInfo->iBreak, 1);
41581 + /* Analyze all of the subexpressions.
41583 + for(i=0; i<nExpr; i++){
41584 + exprAnalyze(&maskSet, &aExpr[i]);
41586 + /* If we are executing a trigger body, remove all references to
41587 + ** new.* and old.* tables from the prerequisite masks.
41589 + if( pParse->trigStack ){
41591 + if( (x = pParse->trigStack->newIdx) >= 0 ){
41592 + int mask = ~getMask(&maskSet, x);
41593 + aExpr[i].prereqRight &= mask;
41594 + aExpr[i].prereqLeft &= mask;
41595 + aExpr[i].prereqAll &= mask;
41597 + if( (x = pParse->trigStack->oldIdx) >= 0 ){
41598 + int mask = ~getMask(&maskSet, x);
41599 + aExpr[i].prereqRight &= mask;
41600 + aExpr[i].prereqLeft &= mask;
41601 + aExpr[i].prereqAll &= mask;
41606 + /* Figure out what index to use (if any) for each nested loop.
41607 + ** Make pWInfo->a[i].pIdx point to the index to use for the i-th nested
41608 + ** loop where i==0 is the outer loop and i==pTabList->nSrc-1 is the inner
41611 + ** If terms exist that use the ROWID of any table, then set the
41612 + ** iDirectEq[], iDirectLt[], or iDirectGt[] elements for that table
41613 + ** to the index of the term containing the ROWID. We always prefer
41614 + ** to use a ROWID which can directly access a table rather than an
41615 + ** index which requires reading an index first to get the rowid then
41616 + ** doing a second read of the actual database table.
41618 + ** Actually, if there are more than 32 tables in the join, only the
41619 + ** first 32 tables are candidates for indices. This is (again) due
41620 + ** to the limit of 32 bits in an integer bitmask.
41623 + for(i=0; i<pTabList->nSrc && i<ARRAYSIZE(iDirectEq); i++){
41625 + int iCur = pTabList->a[i].iCursor; /* The cursor for this table */
41626 + int mask = getMask(&maskSet, iCur); /* Cursor mask for this table */
41627 + Table *pTab = pTabList->a[i].pTab;
41629 + Index *pBestIdx = 0;
41630 + int bestScore = 0;
41632 + /* Check to see if there is an expression that uses only the
41633 + ** ROWID field of this table. For terms of the form ROWID==expr
41634 + ** set iDirectEq[i] to the index of the term. For terms of the
41635 + ** form ROWID<expr or ROWID<=expr set iDirectLt[i] to the term index.
41636 + ** For terms like ROWID>expr or ROWID>=expr set iDirectGt[i].
41638 + ** (Added:) Treat ROWID IN expr like ROWID=expr.
41640 + pWInfo->a[i].iCur = -1;
41641 + iDirectEq[i] = -1;
41642 + iDirectLt[i] = -1;
41643 + iDirectGt[i] = -1;
41644 + for(j=0; j<nExpr; j++){
41645 + if( aExpr[j].idxLeft==iCur && aExpr[j].p->pLeft->iColumn<0
41646 + && (aExpr[j].prereqRight & loopMask)==aExpr[j].prereqRight ){
41647 + switch( aExpr[j].p->op ){
41649 + case TK_EQ: iDirectEq[i] = j; break;
41651 + case TK_LT: iDirectLt[i] = j; break;
41653 + case TK_GT: iDirectGt[i] = j; break;
41656 + if( aExpr[j].idxRight==iCur && aExpr[j].p->pRight->iColumn<0
41657 + && (aExpr[j].prereqLeft & loopMask)==aExpr[j].prereqLeft ){
41658 + switch( aExpr[j].p->op ){
41659 + case TK_EQ: iDirectEq[i] = j; break;
41661 + case TK_LT: iDirectGt[i] = j; break;
41663 + case TK_GT: iDirectLt[i] = j; break;
41667 + if( iDirectEq[i]>=0 ){
41668 + loopMask |= mask;
41669 + pWInfo->a[i].pIdx = 0;
41673 + /* Do a search for usable indices. Leave pBestIdx pointing to
41674 + ** the "best" index. pBestIdx is left set to NULL if no indices
41677 + ** The best index is determined as follows. For each of the
41678 + ** left-most terms that is fixed by an equality operator, add
41679 + ** 8 to the score. The right-most term of the index may be
41680 + ** constrained by an inequality. Add 1 if for an "x<..." constraint
41681 + ** and add 2 for an "x>..." constraint. Chose the index that
41682 + ** gives the best score.
41684 + ** This scoring system is designed so that the score can later be
41685 + ** used to determine how the index is used. If the score&7 is 0
41686 + ** then all constraints are equalities. If score&1 is not 0 then
41687 + ** there is an inequality used as a termination key. (ex: "x<...")
41688 + ** If score&2 is not 0 then there is an inequality used as the
41689 + ** start key. (ex: "x>..."). A score or 4 is the special case
41690 + ** of an IN operator constraint. (ex: "x IN ...").
41692 + ** The IN operator (as in "<expr> IN (...)") is treated the same as
41693 + ** an equality comparison except that it can only be used on the
41694 + ** left-most column of an index and other terms of the WHERE clause
41695 + ** cannot be used in conjunction with the IN operator to help satisfy
41696 + ** other columns of the index.
41698 + for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
41699 + int eqMask = 0; /* Index columns covered by an x=... term */
41700 + int ltMask = 0; /* Index columns covered by an x<... term */
41701 + int gtMask = 0; /* Index columns covered by an x>... term */
41702 + int inMask = 0; /* Index columns covered by an x IN .. term */
41703 + int nEq, m, score;
41705 + if( pIdx->nColumn>32 ) continue; /* Ignore indices too many columns */
41706 + for(j=0; j<nExpr; j++){
41707 + if( aExpr[j].idxLeft==iCur
41708 + && (aExpr[j].prereqRight & loopMask)==aExpr[j].prereqRight ){
41709 + int iColumn = aExpr[j].p->pLeft->iColumn;
41711 + for(k=0; k<pIdx->nColumn; k++){
41712 + if( pIdx->aiColumn[k]==iColumn ){
41713 + switch( aExpr[j].p->op ){
41715 + if( k==0 ) inMask |= 1;
41733 + /* CANT_HAPPEN */
41742 + if( aExpr[j].idxRight==iCur
41743 + && (aExpr[j].prereqLeft & loopMask)==aExpr[j].prereqLeft ){
41744 + int iColumn = aExpr[j].p->pRight->iColumn;
41746 + for(k=0; k<pIdx->nColumn; k++){
41747 + if( pIdx->aiColumn[k]==iColumn ){
41748 + switch( aExpr[j].p->op ){
41764 + /* CANT_HAPPEN */
41775 + /* The following loop ends with nEq set to the number of columns
41776 + ** on the left of the index with == constraints.
41778 + for(nEq=0; nEq<pIdx->nColumn; nEq++){
41779 + m = (1<<(nEq+1))-1;
41780 + if( (m & eqMask)!=m ) break;
41782 + score = nEq*8; /* Base score is 8 times number of == constraints */
41784 + if( m & ltMask ) score++; /* Increase score for a < constraint */
41785 + if( m & gtMask ) score+=2; /* Increase score for a > constraint */
41786 + if( score==0 && inMask ) score = 4; /* Default score for IN constraint */
41787 + if( score>bestScore ){
41789 + bestScore = score;
41792 + pWInfo->a[i].pIdx = pBestIdx;
41793 + pWInfo->a[i].score = bestScore;
41794 + pWInfo->a[i].bRev = 0;
41795 + loopMask |= mask;
41797 + pWInfo->a[i].iCur = pParse->nTab++;
41798 + pWInfo->peakNTab = pParse->nTab;
41802 + /* Check to see if the ORDER BY clause is or can be satisfied by the
41803 + ** use of an index on the first table.
41805 + if( ppOrderBy && *ppOrderBy && pTabList->nSrc>0 ){
41811 + pTab = pTabList->a[0].pTab;
41812 + pIdx = pWInfo->a[0].pIdx;
41813 + if( pIdx && pWInfo->a[0].score==4 ){
41814 + /* If there is already an IN index on the left-most table,
41815 + ** it will not give the correct sort order.
41816 + ** So, pretend that no suitable index is found.
41819 + }else if( iDirectEq[0]>=0 || iDirectLt[0]>=0 || iDirectGt[0]>=0 ){
41820 + /* If the left-most column is accessed using its ROWID, then do
41821 + ** not try to sort by index.
41825 + int nEqCol = (pWInfo->a[0].score+4)/8;
41826 + pSortIdx = findSortingIndex(pTab, pTabList->a[0].iCursor,
41827 + *ppOrderBy, pIdx, nEqCol, &bRev);
41829 + if( pSortIdx && (pIdx==0 || pIdx==pSortIdx) ){
41831 + pWInfo->a[0].pIdx = pSortIdx;
41832 + pWInfo->a[0].iCur = pParse->nTab++;
41833 + pWInfo->peakNTab = pParse->nTab;
41835 + pWInfo->a[0].bRev = bRev;
41840 + /* Open all tables in the pTabList and all indices used by those tables.
41842 + for(i=0; i<pTabList->nSrc; i++){
41846 + pTab = pTabList->a[i].pTab;
41847 + if( pTab->isTransient || pTab->pSelect ) continue;
41848 + sqliteVdbeAddOp(v, OP_Integer, pTab->iDb, 0);
41849 + sqliteVdbeOp3(v, OP_OpenRead, pTabList->a[i].iCursor, pTab->tnum,
41850 + pTab->zName, P3_STATIC);
41851 + sqliteCodeVerifySchema(pParse, pTab->iDb);
41852 + if( (pIx = pWInfo->a[i].pIdx)!=0 ){
41853 + sqliteVdbeAddOp(v, OP_Integer, pIx->iDb, 0);
41854 + sqliteVdbeOp3(v, OP_OpenRead, pWInfo->a[i].iCur, pIx->tnum, pIx->zName,0);
41858 + /* Generate the code to do the search
41861 + for(i=0; i<pTabList->nSrc; i++){
41863 + int iCur = pTabList->a[i].iCursor;
41865 + WhereLevel *pLevel = &pWInfo->a[i];
41867 + /* If this is the right table of a LEFT OUTER JOIN, allocate and
41868 + ** initialize a memory cell that records if this table matches any
41869 + ** row of the left table of the join.
41871 + if( i>0 && (pTabList->a[i-1].jointype & JT_LEFT)!=0 ){
41872 + if( !pParse->nMem ) pParse->nMem++;
41873 + pLevel->iLeftJoin = pParse->nMem++;
41874 + sqliteVdbeAddOp(v, OP_String, 0, 0);
41875 + sqliteVdbeAddOp(v, OP_MemStore, pLevel->iLeftJoin, 1);
41878 + pIdx = pLevel->pIdx;
41879 + pLevel->inOp = OP_Noop;
41880 + if( i<ARRAYSIZE(iDirectEq) && iDirectEq[i]>=0 ){
41881 + /* Case 1: We can directly reference a single row using an
41882 + ** equality comparison against the ROWID field. Or
41883 + ** we reference multiple rows using a "rowid IN (...)"
41886 + k = iDirectEq[i];
41887 + assert( k<nExpr );
41888 + assert( aExpr[k].p!=0 );
41889 + assert( aExpr[k].idxLeft==iCur || aExpr[k].idxRight==iCur );
41890 + brk = pLevel->brk = sqliteVdbeMakeLabel(v);
41891 + if( aExpr[k].idxLeft==iCur ){
41892 + Expr *pX = aExpr[k].p;
41893 + if( pX->op!=TK_IN ){
41894 + sqliteExprCode(pParse, aExpr[k].p->pRight);
41895 + }else if( pX->pList ){
41896 + sqliteVdbeAddOp(v, OP_SetFirst, pX->iTable, brk);
41897 + pLevel->inOp = OP_SetNext;
41898 + pLevel->inP1 = pX->iTable;
41899 + pLevel->inP2 = sqliteVdbeCurrentAddr(v);
41901 + assert( pX->pSelect );
41902 + sqliteVdbeAddOp(v, OP_Rewind, pX->iTable, brk);
41903 + sqliteVdbeAddOp(v, OP_KeyAsData, pX->iTable, 1);
41904 + pLevel->inP2 = sqliteVdbeAddOp(v, OP_FullKey, pX->iTable, 0);
41905 + pLevel->inOp = OP_Next;
41906 + pLevel->inP1 = pX->iTable;
41909 + sqliteExprCode(pParse, aExpr[k].p->pLeft);
41911 + disableTerm(pLevel, &aExpr[k].p);
41912 + cont = pLevel->cont = sqliteVdbeMakeLabel(v);
41913 + sqliteVdbeAddOp(v, OP_MustBeInt, 1, brk);
41915 + sqliteVdbeAddOp(v, OP_NotExists, iCur, brk);
41916 + pLevel->op = OP_Noop;
41917 + }else if( pIdx!=0 && pLevel->score>0 && pLevel->score%4==0 ){
41918 + /* Case 2: There is an index and all terms of the WHERE clause that
41919 + ** refer to the index use the "==" or "IN" operators.
41923 + int nColumn = (pLevel->score+4)/8;
41924 + brk = pLevel->brk = sqliteVdbeMakeLabel(v);
41925 + for(j=0; j<nColumn; j++){
41926 + for(k=0; k<nExpr; k++){
41927 + Expr *pX = aExpr[k].p;
41928 + if( pX==0 ) continue;
41929 + if( aExpr[k].idxLeft==iCur
41930 + && (aExpr[k].prereqRight & loopMask)==aExpr[k].prereqRight
41931 + && pX->pLeft->iColumn==pIdx->aiColumn[j]
41933 + if( pX->op==TK_EQ ){
41934 + sqliteExprCode(pParse, pX->pRight);
41935 + disableTerm(pLevel, &aExpr[k].p);
41938 + if( pX->op==TK_IN && nColumn==1 ){
41940 + sqliteVdbeAddOp(v, OP_SetFirst, pX->iTable, brk);
41941 + pLevel->inOp = OP_SetNext;
41942 + pLevel->inP1 = pX->iTable;
41943 + pLevel->inP2 = sqliteVdbeCurrentAddr(v);
41945 + assert( pX->pSelect );
41946 + sqliteVdbeAddOp(v, OP_Rewind, pX->iTable, brk);
41947 + sqliteVdbeAddOp(v, OP_KeyAsData, pX->iTable, 1);
41948 + pLevel->inP2 = sqliteVdbeAddOp(v, OP_FullKey, pX->iTable, 0);
41949 + pLevel->inOp = OP_Next;
41950 + pLevel->inP1 = pX->iTable;
41952 + disableTerm(pLevel, &aExpr[k].p);
41956 + if( aExpr[k].idxRight==iCur
41957 + && aExpr[k].p->op==TK_EQ
41958 + && (aExpr[k].prereqLeft & loopMask)==aExpr[k].prereqLeft
41959 + && aExpr[k].p->pRight->iColumn==pIdx->aiColumn[j]
41961 + sqliteExprCode(pParse, aExpr[k].p->pLeft);
41962 + disableTerm(pLevel, &aExpr[k].p);
41967 + pLevel->iMem = pParse->nMem++;
41968 + cont = pLevel->cont = sqliteVdbeMakeLabel(v);
41969 + sqliteVdbeAddOp(v, OP_NotNull, -nColumn, sqliteVdbeCurrentAddr(v)+3);
41970 + sqliteVdbeAddOp(v, OP_Pop, nColumn, 0);
41971 + sqliteVdbeAddOp(v, OP_Goto, 0, brk);
41972 + sqliteVdbeAddOp(v, OP_MakeKey, nColumn, 0);
41973 + sqliteAddIdxKeyType(v, pIdx);
41974 + if( nColumn==pIdx->nColumn || pLevel->bRev ){
41975 + sqliteVdbeAddOp(v, OP_MemStore, pLevel->iMem, 0);
41976 + testOp = OP_IdxGT;
41978 + sqliteVdbeAddOp(v, OP_Dup, 0, 0);
41979 + sqliteVdbeAddOp(v, OP_IncrKey, 0, 0);
41980 + sqliteVdbeAddOp(v, OP_MemStore, pLevel->iMem, 1);
41981 + testOp = OP_IdxGE;
41983 + if( pLevel->bRev ){
41984 + /* Scan in reverse order */
41985 + sqliteVdbeAddOp(v, OP_IncrKey, 0, 0);
41986 + sqliteVdbeAddOp(v, OP_MoveLt, pLevel->iCur, brk);
41987 + start = sqliteVdbeAddOp(v, OP_MemLoad, pLevel->iMem, 0);
41988 + sqliteVdbeAddOp(v, OP_IdxLT, pLevel->iCur, brk);
41989 + pLevel->op = OP_Prev;
41991 + /* Scan in the forward order */
41992 + sqliteVdbeAddOp(v, OP_MoveTo, pLevel->iCur, brk);
41993 + start = sqliteVdbeAddOp(v, OP_MemLoad, pLevel->iMem, 0);
41994 + sqliteVdbeAddOp(v, testOp, pLevel->iCur, brk);
41995 + pLevel->op = OP_Next;
41997 + sqliteVdbeAddOp(v, OP_RowKey, pLevel->iCur, 0);
41998 + sqliteVdbeAddOp(v, OP_IdxIsNull, nColumn, cont);
41999 + sqliteVdbeAddOp(v, OP_IdxRecno, pLevel->iCur, 0);
42000 + if( i==pTabList->nSrc-1 && pushKey ){
42003 + sqliteVdbeAddOp(v, OP_MoveTo, iCur, 0);
42006 + pLevel->p1 = pLevel->iCur;
42007 + pLevel->p2 = start;
42008 + }else if( i<ARRAYSIZE(iDirectLt) && (iDirectLt[i]>=0 || iDirectGt[i]>=0) ){
42009 + /* Case 3: We have an inequality comparison against the ROWID field.
42011 + int testOp = OP_Noop;
42014 + brk = pLevel->brk = sqliteVdbeMakeLabel(v);
42015 + cont = pLevel->cont = sqliteVdbeMakeLabel(v);
42016 + if( iDirectGt[i]>=0 ){
42017 + k = iDirectGt[i];
42018 + assert( k<nExpr );
42019 + assert( aExpr[k].p!=0 );
42020 + assert( aExpr[k].idxLeft==iCur || aExpr[k].idxRight==iCur );
42021 + if( aExpr[k].idxLeft==iCur ){
42022 + sqliteExprCode(pParse, aExpr[k].p->pRight);
42024 + sqliteExprCode(pParse, aExpr[k].p->pLeft);
42026 + sqliteVdbeAddOp(v, OP_ForceInt,
42027 + aExpr[k].p->op==TK_LT || aExpr[k].p->op==TK_GT, brk);
42028 + sqliteVdbeAddOp(v, OP_MoveTo, iCur, brk);
42029 + disableTerm(pLevel, &aExpr[k].p);
42031 + sqliteVdbeAddOp(v, OP_Rewind, iCur, brk);
42033 + if( iDirectLt[i]>=0 ){
42034 + k = iDirectLt[i];
42035 + assert( k<nExpr );
42036 + assert( aExpr[k].p!=0 );
42037 + assert( aExpr[k].idxLeft==iCur || aExpr[k].idxRight==iCur );
42038 + if( aExpr[k].idxLeft==iCur ){
42039 + sqliteExprCode(pParse, aExpr[k].p->pRight);
42041 + sqliteExprCode(pParse, aExpr[k].p->pLeft);
42043 + /* sqliteVdbeAddOp(v, OP_MustBeInt, 0, sqliteVdbeCurrentAddr(v)+1); */
42044 + pLevel->iMem = pParse->nMem++;
42045 + sqliteVdbeAddOp(v, OP_MemStore, pLevel->iMem, 1);
42046 + if( aExpr[k].p->op==TK_LT || aExpr[k].p->op==TK_GT ){
42051 + disableTerm(pLevel, &aExpr[k].p);
42053 + start = sqliteVdbeCurrentAddr(v);
42054 + pLevel->op = OP_Next;
42055 + pLevel->p1 = iCur;
42056 + pLevel->p2 = start;
42057 + if( testOp!=OP_Noop ){
42058 + sqliteVdbeAddOp(v, OP_Recno, iCur, 0);
42059 + sqliteVdbeAddOp(v, OP_MemLoad, pLevel->iMem, 0);
42060 + sqliteVdbeAddOp(v, testOp, 0, brk);
42063 + }else if( pIdx==0 ){
42064 + /* Case 4: There is no usable index. We must do a complete
42065 + ** scan of the entire database table.
42069 + brk = pLevel->brk = sqliteVdbeMakeLabel(v);
42070 + cont = pLevel->cont = sqliteVdbeMakeLabel(v);
42071 + sqliteVdbeAddOp(v, OP_Rewind, iCur, brk);
42072 + start = sqliteVdbeCurrentAddr(v);
42073 + pLevel->op = OP_Next;
42074 + pLevel->p1 = iCur;
42075 + pLevel->p2 = start;
42078 + /* Case 5: The WHERE clause term that refers to the right-most
42079 + ** column of the index is an inequality. For example, if
42080 + ** the index is on (x,y,z) and the WHERE clause is of the
42081 + ** form "x=5 AND y<10" then this case is used. Only the
42082 + ** right-most column can be an inequality - the rest must
42083 + ** use the "==" operator.
42085 + ** This case is also used when there are no WHERE clause
42086 + ** constraints but an index is selected anyway, in order
42087 + ** to force the output order to conform to an ORDER BY.
42089 + int score = pLevel->score;
42090 + int nEqColumn = score/8;
42092 + int leFlag, geFlag;
42095 + /* Evaluate the equality constraints
42097 + for(j=0; j<nEqColumn; j++){
42098 + for(k=0; k<nExpr; k++){
42099 + if( aExpr[k].p==0 ) continue;
42100 + if( aExpr[k].idxLeft==iCur
42101 + && aExpr[k].p->op==TK_EQ
42102 + && (aExpr[k].prereqRight & loopMask)==aExpr[k].prereqRight
42103 + && aExpr[k].p->pLeft->iColumn==pIdx->aiColumn[j]
42105 + sqliteExprCode(pParse, aExpr[k].p->pRight);
42106 + disableTerm(pLevel, &aExpr[k].p);
42109 + if( aExpr[k].idxRight==iCur
42110 + && aExpr[k].p->op==TK_EQ
42111 + && (aExpr[k].prereqLeft & loopMask)==aExpr[k].prereqLeft
42112 + && aExpr[k].p->pRight->iColumn==pIdx->aiColumn[j]
42114 + sqliteExprCode(pParse, aExpr[k].p->pLeft);
42115 + disableTerm(pLevel, &aExpr[k].p);
42121 + /* Duplicate the equality term values because they will all be
42122 + ** used twice: once to make the termination key and once to make the
42125 + for(j=0; j<nEqColumn; j++){
42126 + sqliteVdbeAddOp(v, OP_Dup, nEqColumn-1, 0);
42129 + /* Labels for the beginning and end of the loop
42131 + cont = pLevel->cont = sqliteVdbeMakeLabel(v);
42132 + brk = pLevel->brk = sqliteVdbeMakeLabel(v);
42134 + /* Generate the termination key. This is the key value that
42135 + ** will end the search. There is no termination key if there
42136 + ** are no equality terms and no "X<..." term.
42138 + ** 2002-Dec-04: On a reverse-order scan, the so-called "termination"
42139 + ** key computed here really ends up being the start key.
42141 + if( (score & 1)!=0 ){
42142 + for(k=0; k<nExpr; k++){
42143 + Expr *pExpr = aExpr[k].p;
42144 + if( pExpr==0 ) continue;
42145 + if( aExpr[k].idxLeft==iCur
42146 + && (pExpr->op==TK_LT || pExpr->op==TK_LE)
42147 + && (aExpr[k].prereqRight & loopMask)==aExpr[k].prereqRight
42148 + && pExpr->pLeft->iColumn==pIdx->aiColumn[j]
42150 + sqliteExprCode(pParse, pExpr->pRight);
42151 + leFlag = pExpr->op==TK_LE;
42152 + disableTerm(pLevel, &aExpr[k].p);
42155 + if( aExpr[k].idxRight==iCur
42156 + && (pExpr->op==TK_GT || pExpr->op==TK_GE)
42157 + && (aExpr[k].prereqLeft & loopMask)==aExpr[k].prereqLeft
42158 + && pExpr->pRight->iColumn==pIdx->aiColumn[j]
42160 + sqliteExprCode(pParse, pExpr->pLeft);
42161 + leFlag = pExpr->op==TK_GE;
42162 + disableTerm(pLevel, &aExpr[k].p);
42166 + testOp = OP_IdxGE;
42168 + testOp = nEqColumn>0 ? OP_IdxGE : OP_Noop;
42171 + if( testOp!=OP_Noop ){
42172 + int nCol = nEqColumn + (score & 1);
42173 + pLevel->iMem = pParse->nMem++;
42174 + sqliteVdbeAddOp(v, OP_NotNull, -nCol, sqliteVdbeCurrentAddr(v)+3);
42175 + sqliteVdbeAddOp(v, OP_Pop, nCol, 0);
42176 + sqliteVdbeAddOp(v, OP_Goto, 0, brk);
42177 + sqliteVdbeAddOp(v, OP_MakeKey, nCol, 0);
42178 + sqliteAddIdxKeyType(v, pIdx);
42180 + sqliteVdbeAddOp(v, OP_IncrKey, 0, 0);
42182 + if( pLevel->bRev ){
42183 + sqliteVdbeAddOp(v, OP_MoveLt, pLevel->iCur, brk);
42185 + sqliteVdbeAddOp(v, OP_MemStore, pLevel->iMem, 1);
42187 + }else if( pLevel->bRev ){
42188 + sqliteVdbeAddOp(v, OP_Last, pLevel->iCur, brk);
42191 + /* Generate the start key. This is the key that defines the lower
42192 + ** bound on the search. There is no start key if there are no
42193 + ** equality terms and if there is no "X>..." term. In
42194 + ** that case, generate a "Rewind" instruction in place of the
42195 + ** start key search.
42197 + ** 2002-Dec-04: In the case of a reverse-order search, the so-called
42198 + ** "start" key really ends up being used as the termination key.
42200 + if( (score & 2)!=0 ){
42201 + for(k=0; k<nExpr; k++){
42202 + Expr *pExpr = aExpr[k].p;
42203 + if( pExpr==0 ) continue;
42204 + if( aExpr[k].idxLeft==iCur
42205 + && (pExpr->op==TK_GT || pExpr->op==TK_GE)
42206 + && (aExpr[k].prereqRight & loopMask)==aExpr[k].prereqRight
42207 + && pExpr->pLeft->iColumn==pIdx->aiColumn[j]
42209 + sqliteExprCode(pParse, pExpr->pRight);
42210 + geFlag = pExpr->op==TK_GE;
42211 + disableTerm(pLevel, &aExpr[k].p);
42214 + if( aExpr[k].idxRight==iCur
42215 + && (pExpr->op==TK_LT || pExpr->op==TK_LE)
42216 + && (aExpr[k].prereqLeft & loopMask)==aExpr[k].prereqLeft
42217 + && pExpr->pRight->iColumn==pIdx->aiColumn[j]
42219 + sqliteExprCode(pParse, pExpr->pLeft);
42220 + geFlag = pExpr->op==TK_LE;
42221 + disableTerm(pLevel, &aExpr[k].p);
42228 + if( nEqColumn>0 || (score&2)!=0 ){
42229 + int nCol = nEqColumn + ((score&2)!=0);
42230 + sqliteVdbeAddOp(v, OP_NotNull, -nCol, sqliteVdbeCurrentAddr(v)+3);
42231 + sqliteVdbeAddOp(v, OP_Pop, nCol, 0);
42232 + sqliteVdbeAddOp(v, OP_Goto, 0, brk);
42233 + sqliteVdbeAddOp(v, OP_MakeKey, nCol, 0);
42234 + sqliteAddIdxKeyType(v, pIdx);
42236 + sqliteVdbeAddOp(v, OP_IncrKey, 0, 0);
42238 + if( pLevel->bRev ){
42239 + pLevel->iMem = pParse->nMem++;
42240 + sqliteVdbeAddOp(v, OP_MemStore, pLevel->iMem, 1);
42241 + testOp = OP_IdxLT;
42243 + sqliteVdbeAddOp(v, OP_MoveTo, pLevel->iCur, brk);
42245 + }else if( pLevel->bRev ){
42246 + testOp = OP_Noop;
42248 + sqliteVdbeAddOp(v, OP_Rewind, pLevel->iCur, brk);
42251 + /* Generate the the top of the loop. If there is a termination
42252 + ** key we have to test for that key and abort at the top of the
42255 + start = sqliteVdbeCurrentAddr(v);
42256 + if( testOp!=OP_Noop ){
42257 + sqliteVdbeAddOp(v, OP_MemLoad, pLevel->iMem, 0);
42258 + sqliteVdbeAddOp(v, testOp, pLevel->iCur, brk);
42260 + sqliteVdbeAddOp(v, OP_RowKey, pLevel->iCur, 0);
42261 + sqliteVdbeAddOp(v, OP_IdxIsNull, nEqColumn + (score & 1), cont);
42262 + sqliteVdbeAddOp(v, OP_IdxRecno, pLevel->iCur, 0);
42263 + if( i==pTabList->nSrc-1 && pushKey ){
42266 + sqliteVdbeAddOp(v, OP_MoveTo, iCur, 0);
42270 + /* Record the instruction used to terminate the loop.
42272 + pLevel->op = pLevel->bRev ? OP_Prev : OP_Next;
42273 + pLevel->p1 = pLevel->iCur;
42274 + pLevel->p2 = start;
42276 + loopMask |= getMask(&maskSet, iCur);
42278 + /* Insert code to test every subexpression that can be completely
42279 + ** computed using the current set of tables.
42281 + for(j=0; j<nExpr; j++){
42282 + if( aExpr[j].p==0 ) continue;
42283 + if( (aExpr[j].prereqAll & loopMask)!=aExpr[j].prereqAll ) continue;
42284 + if( pLevel->iLeftJoin && !ExprHasProperty(aExpr[j].p,EP_FromJoin) ){
42289 + sqliteVdbeAddOp(v, OP_MoveTo, iCur, 0);
42291 + sqliteExprIfFalse(pParse, aExpr[j].p, cont, 1);
42296 + /* For a LEFT OUTER JOIN, generate code that will record the fact that
42297 + ** at least one row of the right table has matched the left table.
42299 + if( pLevel->iLeftJoin ){
42300 + pLevel->top = sqliteVdbeCurrentAddr(v);
42301 + sqliteVdbeAddOp(v, OP_Integer, 1, 0);
42302 + sqliteVdbeAddOp(v, OP_MemStore, pLevel->iLeftJoin, 1);
42303 + for(j=0; j<nExpr; j++){
42304 + if( aExpr[j].p==0 ) continue;
42305 + if( (aExpr[j].prereqAll & loopMask)!=aExpr[j].prereqAll ) continue;
42307 + /* Cannot happen. "haveKey" can only be true if pushKey is true
42308 + ** an pushKey can only be true for DELETE and UPDATE and there are
42309 + ** no outer joins with DELETE and UPDATE.
42312 + sqliteVdbeAddOp(v, OP_MoveTo, iCur, 0);
42314 + sqliteExprIfFalse(pParse, aExpr[j].p, cont, 1);
42319 + pWInfo->iContinue = cont;
42320 + if( pushKey && !haveKey ){
42321 + sqliteVdbeAddOp(v, OP_Recno, pTabList->a[0].iCursor, 0);
42323 + freeMaskSet(&maskSet);
42328 +** Generate the end of the WHERE loop. See comments on
42329 +** sqliteWhereBegin() for additional information.
42331 +void sqliteWhereEnd(WhereInfo *pWInfo){
42332 + Vdbe *v = pWInfo->pParse->pVdbe;
42334 + WhereLevel *pLevel;
42335 + SrcList *pTabList = pWInfo->pTabList;
42337 + for(i=pTabList->nSrc-1; i>=0; i--){
42338 + pLevel = &pWInfo->a[i];
42339 + sqliteVdbeResolveLabel(v, pLevel->cont);
42340 + if( pLevel->op!=OP_Noop ){
42341 + sqliteVdbeAddOp(v, pLevel->op, pLevel->p1, pLevel->p2);
42343 + sqliteVdbeResolveLabel(v, pLevel->brk);
42344 + if( pLevel->inOp!=OP_Noop ){
42345 + sqliteVdbeAddOp(v, pLevel->inOp, pLevel->inP1, pLevel->inP2);
42347 + if( pLevel->iLeftJoin ){
42349 + addr = sqliteVdbeAddOp(v, OP_MemLoad, pLevel->iLeftJoin, 0);
42350 + sqliteVdbeAddOp(v, OP_NotNull, 1, addr+4 + (pLevel->iCur>=0));
42351 + sqliteVdbeAddOp(v, OP_NullRow, pTabList->a[i].iCursor, 0);
42352 + if( pLevel->iCur>=0 ){
42353 + sqliteVdbeAddOp(v, OP_NullRow, pLevel->iCur, 0);
42355 + sqliteVdbeAddOp(v, OP_Goto, 0, pLevel->top);
42358 + sqliteVdbeResolveLabel(v, pWInfo->iBreak);
42359 + for(i=0; i<pTabList->nSrc; i++){
42360 + Table *pTab = pTabList->a[i].pTab;
42361 + assert( pTab!=0 );
42362 + if( pTab->isTransient || pTab->pSelect ) continue;
42363 + pLevel = &pWInfo->a[i];
42364 + sqliteVdbeAddOp(v, OP_Close, pTabList->a[i].iCursor, 0);
42365 + if( pLevel->pIdx!=0 ){
42366 + sqliteVdbeAddOp(v, OP_Close, pLevel->iCur, 0);
42369 +#if 0 /* Never reuse a cursor */
42370 + if( pWInfo->pParse->nTab==pWInfo->peakNTab ){
42371 + pWInfo->pParse->nTab = pWInfo->savedNTab;
42374 + sqliteFree(pWInfo);
42378 +++ b/ext/sqlite/libsqlite/VERSION
42382 +++ b/ext/sqlite/Makefile.frag
42384 +$(srcdir)/libsqlite/src/parse.c: $(srcdir)/libsqlite/src/parse.y
42385 + @$(LEMON) $(srcdir)/libsqlite/src/parse.y
42387 +++ b/ext/sqlite/package.xml
42389 +<?xml version="1.0" encoding="ISO-8859-1" ?>
42390 +<!DOCTYPE package SYSTEM "../pear/package.dtd">
42392 + <name>SQLite</name>
42393 + <summary>SQLite database bindings</summary>
42397 + <name>Wez Furlong</name>
42398 + <email>wez@php.net</email>
42399 + <role>lead</role>
42403 + <name>Tal Peer</name>
42404 + <email>tal@php.net</email>
42405 + <role>developer</role>
42408 + <user>helly</user>
42409 + <name>Marcus Börger</name>
42410 + <email>helly@php.net</email>
42411 + <role>lead</role>
42414 + <user>iliaa</user>
42415 + <name>Ilia Alshanetsky</name>
42416 + <email>ilia@php.net</email>
42417 + <role>developer</role>
42421 +SQLite is a C library that implements an embeddable SQL database engine.
42422 +Programs that link with the SQLite library can have SQL database access
42423 +without running a separate RDBMS process.
42424 +This extension allows you to access SQLite databases from within PHP.
42426 +Windows binary available from:
42427 +http://snaps.php.net/win32/PECL_STABLE/php_sqlite.dll
42429 + <license>PHP</license>
42431 + <state>stable</state>
42432 + <version>2.0-dev</version>
42439 + <file role="src" name="config.m4"/>
42440 + <file role="src" name="config.w32"/>
42441 + <file role="src" name="sqlite.c"/>
42442 + <file role="src" name="sqlite.dsp"/>
42443 + <file role="src" name="php_sqlite.h"/>
42444 + <file role="src" name="php_sqlite.def"/>
42445 + <file role="doc" name="CREDITS"/>
42446 + <file role="doc" name="README"/>
42447 + <file role="doc" name="TODO"/>
42448 + <file role="doc" name="sqlite.php"/>
42449 + <file role="test" name="tests/sqlite_001.phpt"/>
42450 + <file role="test" name="tests/sqlite_002.phpt"/>
42451 + <file role="test" name="tests/sqlite_003.phpt"/>
42452 + <file role="test" name="tests/sqlite_004.phpt"/>
42453 + <file role="test" name="tests/sqlite_005.phpt"/>
42454 + <file role="test" name="tests/sqlite_006.phpt"/>
42455 + <file role="test" name="tests/sqlite_007.phpt"/>
42456 + <file role="test" name="tests/sqlite_008.phpt"/>
42457 + <file role="test" name="tests/sqlite_009.phpt"/>
42458 + <file role="test" name="tests/sqlite_010.phpt"/>
42459 + <file role="test" name="tests/sqlite_011.phpt"/>
42460 + <file role="test" name="tests/sqlite_012.phpt"/>
42461 + <file role="test" name="tests/sqlite_013.phpt"/>
42462 + <file role="test" name="tests/sqlite_014.phpt"/>
42463 + <file role="test" name="tests/sqlite_015.phpt"/>
42464 + <file role="test" name="tests/sqlite_016.phpt"/>
42465 + <file role="test" name="tests/sqlite_017.phpt"/>
42466 + <file role="test" name="tests/blankdb.inc"/>
42468 + <dir name="libsqlite">
42469 + <file role="doc" name="README"/>
42470 + <file role="src" name="VERSION"/>
42473 + <file role="src" name="attach.c"/>
42474 + <file role="src" name="auth.c"/>
42475 + <file role="src" name="btree.c"/>
42476 + <file role="src" name="btree_rb.c"/>
42477 + <file role="src" name="build.c"/>
42478 + <file role="src" name="copy.c"/>
42479 + <file role="src" name="delete.c"/>
42480 + <file role="src" name="encode.c"/>
42481 + <file role="src" name="expr.c"/>
42482 + <file role="src" name="func.c"/>
42483 + <file role="src" name="hash.c"/>
42484 + <file role="src" name="insert.c"/>
42485 + <file role="src" name="main.c"/>
42486 + <file role="src" name="opcodes.c"/>
42487 + <file role="src" name="os.c"/>
42488 + <file role="src" name="pager.c"/>
42489 + <file role="src" name="parse.c"/>
42490 + <file role="src" name="parse.y"/>
42491 + <file role="src" name="pragma.c"/>
42492 + <file role="src" name="printf.c"/>
42493 + <file role="src" name="random.c"/>
42494 + <file role="src" name="select.c"/>
42495 + <file role="src" name="table.c"/>
42496 + <file role="src" name="tokenize.c"/>
42497 + <file role="src" name="trigger.c"/>
42498 + <file role="src" name="update.c"/>
42499 + <file role="src" name="util.c"/>
42500 + <file role="src" name="vacuum.c"/>
42501 + <file role="src" name="vdbe.c"/>
42502 + <file role="src" name="where.c"/>
42503 + <file role="src" name="btree.h"/>
42504 + <file role="src" name="hash.h"/>
42505 + <file role="src" name="opcodes.h"/>
42506 + <file role="src" name="os.h"/>
42507 + <file role="src" name="pager.h"/>
42508 + <file role="src" name="parse.h"/>
42509 + <file role="src" name="sqlite_config.w32.h"/>
42510 + <file role="src" name="sqlite.h.in"/>
42511 + <file role="src" name="sqliteInt.h"/>
42512 + <file role="src" name="sqlite.w32.h"/>
42513 + <file role="src" name="vdbe.h"/>
42518 + <dep type="php" rel="ge" version="5" />
42526 +++ b/ext/sqlite/pdo_sqlite2.c
42529 + +----------------------------------------------------------------------+
42530 + | PHP Version 5 |
42531 + +----------------------------------------------------------------------+
42532 + | Copyright (c) 1997-2012 The PHP Group |
42533 + +----------------------------------------------------------------------+
42534 + | This source file is subject to version 3.01 of the PHP license, |
42535 + | that is bundled with this package in the file LICENSE, and is |
42536 + | available through the world-wide-web at the following url: |
42537 + | http://www.php.net/license/3_01.txt |
42538 + | If you did not receive a copy of the PHP license and are unable to |
42539 + | obtain it through the world-wide-web, please send a note to |
42540 + | license@php.net so we can mail you a copy immediately. |
42541 + +----------------------------------------------------------------------+
42542 + | Author: Wez Furlong <wez@php.net> |
42543 + +----------------------------------------------------------------------+
42547 +#ifdef HAVE_CONFIG_H
42548 +#include "config.h"
42552 +#ifdef PHP_SQLITE2_HAVE_PDO
42553 +#include "sqlite.h"
42554 +#include "pdo/php_pdo.h"
42555 +#include "pdo/php_pdo_driver.h"
42556 +#include "zend_exceptions.h"
42558 +#define php_sqlite_encode_binary(in, n, out) sqlite_encode_binary((const unsigned char *)in, n, (unsigned char *)out)
42559 +#define php_sqlite_decode_binary(in, out) sqlite_decode_binary((const unsigned char *)in, (unsigned char *)out)
42563 + const char *file;
42565 + unsigned int errcode;
42567 +} pdo_sqlite2_error_info;
42571 + pdo_sqlite2_error_info einfo;
42572 +} pdo_sqlite2_db_handle;
42575 + pdo_sqlite2_db_handle *H;
42577 + const char **rowdata, **colnames;
42579 + unsigned pre_fetched:1;
42581 + pdo_sqlite2_error_info einfo;
42582 +} pdo_sqlite2_stmt;
42584 +extern int _pdo_sqlite2_error(pdo_dbh_t *dbh, pdo_stmt_t *stmt, char *errmsg, const char *file, int line TSRMLS_DC);
42585 +#define pdo_sqlite2_error(msg, s) _pdo_sqlite2_error(s, NULL, msg, __FILE__, __LINE__ TSRMLS_CC)
42586 +#define pdo_sqlite2_error_stmt(msg, s) _pdo_sqlite2_error(stmt->dbh, stmt, msg, __FILE__, __LINE__ TSRMLS_CC)
42588 +extern struct pdo_stmt_methods sqlite2_stmt_methods;
42590 +static int pdo_sqlite2_stmt_dtor(pdo_stmt_t *stmt TSRMLS_DC)
42592 + pdo_sqlite2_stmt *S = (pdo_sqlite2_stmt*)stmt->driver_data;
42595 + char *errmsg = NULL;
42596 + sqlite_finalize(S->vm, &errmsg);
42598 + sqlite_freemem(errmsg);
42602 + if (S->einfo.errmsg) {
42603 + pefree(S->einfo.errmsg, stmt->dbh->is_persistent);
42609 +static int pdo_sqlite2_stmt_execute(pdo_stmt_t *stmt TSRMLS_DC)
42611 + pdo_sqlite2_stmt *S = (pdo_sqlite2_stmt*)stmt->driver_data;
42612 + char *errmsg = NULL;
42613 + const char *tail;
42615 + if (stmt->executed && !S->done) {
42616 + sqlite_finalize(S->vm, &errmsg);
42617 + pdo_sqlite2_error_stmt(errmsg, stmt);
42622 + S->einfo.errcode = sqlite_compile(S->H->db, stmt->active_query_string, &tail, &S->vm, &errmsg);
42623 + if (S->einfo.errcode != SQLITE_OK) {
42624 + pdo_sqlite2_error_stmt(errmsg, stmt);
42629 + S->einfo.errcode = sqlite_step(S->vm, &S->ncols, &S->rowdata, &S->colnames);
42630 + switch (S->einfo.errcode) {
42632 + S->pre_fetched = 1;
42633 + stmt->column_count = S->ncols;
42636 + case SQLITE_DONE:
42637 + stmt->column_count = S->ncols;
42638 + stmt->row_count = sqlite_changes(S->H->db);
42639 + S->einfo.errcode = sqlite_reset(S->vm, &errmsg);
42640 + if (S->einfo.errcode != SQLITE_OK) {
42641 + pdo_sqlite2_error_stmt(errmsg, stmt);
42646 + case SQLITE_ERROR:
42647 + case SQLITE_MISUSE:
42648 + case SQLITE_BUSY:
42650 + pdo_sqlite2_error_stmt(errmsg, stmt);
42655 +static int pdo_sqlite2_stmt_param_hook(pdo_stmt_t *stmt, struct pdo_bound_param_data *param,
42656 + enum pdo_param_event event_type TSRMLS_DC)
42661 +static int pdo_sqlite2_stmt_fetch(pdo_stmt_t *stmt,
42662 + enum pdo_fetch_orientation ori, long offset TSRMLS_DC)
42664 + pdo_sqlite2_stmt *S = (pdo_sqlite2_stmt*)stmt->driver_data;
42665 + char *errmsg = NULL;
42670 + if (S->pre_fetched) {
42671 + S->pre_fetched = 0;
42678 + S->einfo.errcode = sqlite_step(S->vm, &S->ncols, &S->rowdata, &S->colnames);
42679 + switch (S->einfo.errcode) {
42683 + case SQLITE_DONE:
42685 + S->einfo.errcode = sqlite_reset(S->vm, &errmsg);
42686 + if (S->einfo.errcode != SQLITE_OK) {
42687 + pdo_sqlite2_error_stmt(errmsg, stmt);
42693 + pdo_sqlite2_error_stmt(errmsg, stmt);
42698 +static int pdo_sqlite2_stmt_describe(pdo_stmt_t *stmt, int colno TSRMLS_DC)
42700 + pdo_sqlite2_stmt *S = (pdo_sqlite2_stmt*)stmt->driver_data;
42702 + if(colno >= S->ncols) {
42703 + /* error invalid column */
42704 + pdo_sqlite2_error_stmt(NULL, stmt);
42708 + stmt->columns[colno].name = estrdup(S->colnames[colno]);
42709 + stmt->columns[colno].namelen = strlen(stmt->columns[colno].name);
42710 + stmt->columns[colno].maxlen = 0xffffffff;
42711 + stmt->columns[colno].precision = 0;
42712 + stmt->columns[colno].param_type = PDO_PARAM_STR;
42717 +static int pdo_sqlite2_stmt_get_col(pdo_stmt_t *stmt, int colno, char **ptr, unsigned long *len, int *caller_frees TSRMLS_DC)
42719 + pdo_sqlite2_stmt *S = (pdo_sqlite2_stmt*)stmt->driver_data;
42723 + if(colno >= S->ncols) {
42724 + /* error invalid column */
42725 + pdo_sqlite2_error_stmt(NULL, stmt);
42728 + if (S->rowdata[colno]) {
42729 + if (S->rowdata[colno][0] == '\x01') {
42731 + *caller_frees = 1;
42732 + *ptr = emalloc(strlen(S->rowdata[colno]));
42733 + *len = php_sqlite_decode_binary(S->rowdata[colno]+1, *ptr);
42734 + (*(char**)ptr)[*len] = '\0';
42736 + *ptr = (char*)S->rowdata[colno];
42737 + *len = strlen(*ptr);
42746 +struct pdo_stmt_methods sqlite2_stmt_methods = {
42747 + pdo_sqlite2_stmt_dtor,
42748 + pdo_sqlite2_stmt_execute,
42749 + pdo_sqlite2_stmt_fetch,
42750 + pdo_sqlite2_stmt_describe,
42751 + pdo_sqlite2_stmt_get_col,
42752 + pdo_sqlite2_stmt_param_hook,
42753 + NULL, /* set_attr */
42754 + NULL, /* get_attr */
42759 +int _pdo_sqlite2_error(pdo_dbh_t *dbh, pdo_stmt_t *stmt, char *errmsg, const char *file, int line TSRMLS_DC) /* {{{ */
42761 + pdo_sqlite2_db_handle *H = (pdo_sqlite2_db_handle *)dbh->driver_data;
42762 + pdo_error_type *pdo_err = stmt ? &stmt->error_code : &dbh->error_code;
42763 + pdo_sqlite2_error_info *einfo = &H->einfo;
42764 + pdo_sqlite2_stmt *S;
42767 + S = stmt->driver_data;
42768 + einfo = &S->einfo;
42771 + einfo->file = file;
42772 + einfo->line = line;
42774 + if (einfo->errmsg) {
42775 + pefree(einfo->errmsg, dbh->is_persistent);
42776 + einfo->errmsg = NULL;
42779 + if (einfo->errcode != SQLITE_OK) {
42781 + einfo->errmsg = pestrdup(errmsg, dbh->is_persistent);
42782 + sqlite_freemem(errmsg);
42784 + einfo->errmsg = pestrdup(sqlite_error_string(einfo->errcode), dbh->is_persistent);
42786 + } else { /* no error */
42787 + strcpy(*pdo_err, PDO_ERR_NONE);
42790 + switch (einfo->errcode) {
42791 + case SQLITE_NOTFOUND:
42792 + strcpy(*pdo_err, "42S02");
42795 + case SQLITE_INTERRUPT:
42796 + strcpy(*pdo_err, "01002");
42799 + case SQLITE_NOLFS:
42800 + strcpy(*pdo_err, "HYC00");
42803 + case SQLITE_TOOBIG:
42804 + strcpy(*pdo_err, "22001");
42807 + case SQLITE_CONSTRAINT:
42808 + strcpy(*pdo_err, "23000");
42811 + case SQLITE_ERROR:
42813 + strcpy(*pdo_err, "HY000");
42817 + if (!dbh->methods) {
42818 + zend_throw_exception_ex(php_pdo_get_exception(), 0 TSRMLS_CC, "SQLSTATE[%s] [%d] %s",
42819 + *pdo_err, einfo->errcode, einfo->errmsg);
42822 + return einfo->errcode;
42826 +static int pdo_sqlite2_fetch_error_func(pdo_dbh_t *dbh, pdo_stmt_t *stmt, zval *info TSRMLS_DC)
42828 + pdo_sqlite2_db_handle *H = (pdo_sqlite2_db_handle *)dbh->driver_data;
42829 + pdo_sqlite2_error_info *einfo = &H->einfo;
42830 + pdo_sqlite2_stmt *S;
42833 + S = stmt->driver_data;
42834 + einfo = &S->einfo;
42837 + if (einfo->errcode) {
42838 + add_next_index_long(info, einfo->errcode);
42839 + if (einfo->errmsg) {
42840 + add_next_index_string(info, einfo->errmsg, 1);
42847 +static int sqlite2_handle_closer(pdo_dbh_t *dbh TSRMLS_DC) /* {{{ */
42849 + pdo_sqlite2_db_handle *H = (pdo_sqlite2_db_handle *)dbh->driver_data;
42853 + sqlite_close(H->db);
42856 + if (H->einfo.errmsg) {
42857 + pefree(H->einfo.errmsg, dbh->is_persistent);
42858 + H->einfo.errmsg = NULL;
42860 + pefree(H, dbh->is_persistent);
42861 + dbh->driver_data = NULL;
42867 +static int sqlite2_handle_preparer(pdo_dbh_t *dbh, const char *sql, long sql_len, pdo_stmt_t *stmt, zval *driver_options TSRMLS_DC)
42869 + pdo_sqlite2_db_handle *H = (pdo_sqlite2_db_handle *)dbh->driver_data;
42870 + pdo_sqlite2_stmt *S = ecalloc(1, sizeof(pdo_sqlite2_stmt));
42873 + stmt->driver_data = S;
42874 + stmt->methods = &sqlite2_stmt_methods;
42875 + stmt->supports_placeholders = PDO_PLACEHOLDER_NONE;
42877 + if (PDO_CURSOR_FWDONLY != pdo_attr_lval(driver_options, PDO_ATTR_CURSOR, PDO_CURSOR_FWDONLY TSRMLS_CC)) {
42878 + H->einfo.errcode = SQLITE_ERROR;
42879 + pdo_sqlite2_error(NULL, dbh);
42886 +static long sqlite2_handle_doer(pdo_dbh_t *dbh, const char *sql, long sql_len TSRMLS_DC)
42888 + pdo_sqlite2_db_handle *H = (pdo_sqlite2_db_handle *)dbh->driver_data;
42889 + char *errmsg = NULL;
42891 + if ((H->einfo.errcode = sqlite_exec(H->db, sql, NULL, NULL, &errmsg)) != SQLITE_OK) {
42892 + pdo_sqlite2_error(errmsg, dbh);
42895 + return sqlite_changes(H->db);
42899 +static char *pdo_sqlite2_last_insert_id(pdo_dbh_t *dbh, const char *name, unsigned int *len TSRMLS_DC)
42901 + pdo_sqlite2_db_handle *H = (pdo_sqlite2_db_handle *)dbh->driver_data;
42904 + id = php_pdo_int64_to_str(sqlite_last_insert_rowid(H->db) TSRMLS_CC);
42905 + *len = strlen(id);
42909 +static int sqlite2_handle_quoter(pdo_dbh_t *dbh, const char *unquoted, int unquotedlen, char **quoted, int *quotedlen, enum pdo_param_type paramtype TSRMLS_DC)
42913 + if (unquotedlen && (unquoted[0] == '\x01' || memchr(unquoted, '\0', unquotedlen) != NULL)) {
42914 + /* binary string */
42916 + ret = safe_emalloc(1 + unquotedlen / 254, 257, 5);
42919 + len = php_sqlite_encode_binary(unquoted, unquotedlen, ret+2);
42920 + ret[len + 2] = '\'';
42921 + ret[len + 3] = '\0';
42923 + *quotedlen = len + 3;
42924 + /* fprintf(stderr, "Quoting:%d:%.*s:\n", *quotedlen, *quotedlen, *quoted); */
42926 + } else if (unquotedlen) {
42927 + ret = sqlite_mprintf("'%q'", unquoted);
42929 + *quoted = estrdup(ret);
42930 + *quotedlen = strlen(ret);
42931 + sqlite_freemem(ret);
42936 + *quoted = estrdup("''");
42942 +static int sqlite2_handle_begin(pdo_dbh_t *dbh TSRMLS_DC)
42944 + pdo_sqlite2_db_handle *H = (pdo_sqlite2_db_handle *)dbh->driver_data;
42945 + char *errmsg = NULL;
42947 + if (sqlite_exec(H->db, "BEGIN", NULL, NULL, &errmsg) != SQLITE_OK) {
42948 + pdo_sqlite2_error(errmsg, dbh);
42954 +static int sqlite2_handle_commit(pdo_dbh_t *dbh TSRMLS_DC)
42956 + pdo_sqlite2_db_handle *H = (pdo_sqlite2_db_handle *)dbh->driver_data;
42957 + char *errmsg = NULL;
42959 + if (sqlite_exec(H->db, "COMMIT", NULL, NULL, &errmsg) != SQLITE_OK) {
42960 + pdo_sqlite2_error(errmsg, dbh);
42966 +static int sqlite2_handle_rollback(pdo_dbh_t *dbh TSRMLS_DC)
42968 + pdo_sqlite2_db_handle *H = (pdo_sqlite2_db_handle *)dbh->driver_data;
42969 + char *errmsg = NULL;
42971 + if (sqlite_exec(H->db, "ROLLBACK", NULL, NULL, &errmsg) != SQLITE_OK) {
42972 + pdo_sqlite2_error(errmsg, dbh);
42978 +static int pdo_sqlite2_get_attribute(pdo_dbh_t *dbh, long attr, zval *return_value TSRMLS_DC)
42981 + case PDO_ATTR_CLIENT_VERSION:
42982 + case PDO_ATTR_SERVER_VERSION:
42983 + ZVAL_STRING(return_value, (char *)sqlite_libversion(), 1);
42993 +static int pdo_sqlite2_set_attr(pdo_dbh_t *dbh, long attr, zval *val TSRMLS_DC)
42995 + pdo_sqlite2_db_handle *H = (pdo_sqlite2_db_handle *)dbh->driver_data;
42998 + case PDO_ATTR_TIMEOUT:
42999 + convert_to_long(val);
43000 + sqlite_busy_timeout(H->db, Z_LVAL_P(val) * 1000);
43006 +static PHP_FUNCTION(sqlite2_create_function)
43008 + /* TODO: implement this stuff */
43011 +static const zend_function_entry dbh_methods[] = {
43012 + PHP_FE(sqlite2_create_function, NULL)
43013 + {NULL, NULL, NULL}
43016 +static const zend_function_entry *get_driver_methods(pdo_dbh_t *dbh, int kind TSRMLS_DC)
43019 + case PDO_DBH_DRIVER_METHOD_KIND_DBH:
43020 + return dbh_methods;
43027 +static struct pdo_dbh_methods sqlite2_methods = {
43028 + sqlite2_handle_closer,
43029 + sqlite2_handle_preparer,
43030 + sqlite2_handle_doer,
43031 + sqlite2_handle_quoter,
43032 + sqlite2_handle_begin,
43033 + sqlite2_handle_commit,
43034 + sqlite2_handle_rollback,
43035 + pdo_sqlite2_set_attr,
43036 + pdo_sqlite2_last_insert_id,
43037 + pdo_sqlite2_fetch_error_func,
43038 + pdo_sqlite2_get_attribute,
43039 + NULL, /* check_liveness: not needed */
43040 + get_driver_methods
43043 +static char *make_filename_safe(const char *filename TSRMLS_DC)
43045 + if (*filename && strncmp(filename, ":memory:", sizeof(":memory:")-1)) {
43046 + char *fullpath = expand_filepath(filename, NULL TSRMLS_CC);
43052 + if (PG(safe_mode) && (!php_checkuid(fullpath, NULL, CHECKUID_CHECK_FILE_AND_DIR))) {
43057 + if (php_check_open_basedir(fullpath TSRMLS_CC)) {
43063 + return estrdup(filename);
43066 +static int authorizer(void *autharg, int access_type, const char *arg3, const char *arg4,
43067 + const char *arg5, const char *arg6)
43070 + switch (access_type) {
43071 + case SQLITE_COPY: {
43073 + filename = make_filename_safe(arg4 TSRMLS_CC);
43075 + return SQLITE_DENY;
43078 + return SQLITE_OK;
43081 + case SQLITE_ATTACH: {
43083 + filename = make_filename_safe(arg3 TSRMLS_CC);
43085 + return SQLITE_DENY;
43088 + return SQLITE_OK;
43092 + /* access allowed */
43093 + return SQLITE_OK;
43097 +static int pdo_sqlite2_handle_factory(pdo_dbh_t *dbh, zval *driver_options TSRMLS_DC) /* {{{ */
43099 + pdo_sqlite2_db_handle *H;
43101 + long timeout = 60;
43103 + char *errmsg = NULL;
43105 + H = pecalloc(1, sizeof(pdo_sqlite2_db_handle), dbh->is_persistent);
43107 + H->einfo.errcode = 0;
43108 + H->einfo.errmsg = NULL;
43109 + dbh->driver_data = H;
43111 + filename = make_filename_safe(dbh->data_source TSRMLS_CC);
43114 + zend_throw_exception_ex(php_pdo_get_exception(), 0 TSRMLS_CC,
43115 + "safe_mode/open_basedir prohibits opening %s",
43116 + dbh->data_source);
43120 + H->db = sqlite_open(filename, 0666, &errmsg);
43124 + H->einfo.errcode = SQLITE_ERROR;
43125 + pdo_sqlite2_error(errmsg, dbh);
43129 + sqlite_set_authorizer(H->db, authorizer, NULL);
43131 + if (driver_options) {
43132 + timeout = pdo_attr_lval(driver_options, PDO_ATTR_TIMEOUT, timeout TSRMLS_CC);
43134 + sqlite_busy_timeout(H->db, timeout * 1000);
43136 + dbh->alloc_own_columns = 1;
43137 + dbh->max_escaped_char_length = 2;
43142 + dbh->methods = &sqlite2_methods;
43148 +pdo_driver_t pdo_sqlite2_driver = {
43149 + PDO_DRIVER_HEADER(sqlite2),
43150 + pdo_sqlite2_handle_factory
43159 + * Local variables:
43161 + * c-basic-offset: 4
43163 + * vim600: noet sw=4 ts=4 fdm=marker
43164 + * vim<600: noet sw=4 ts=4
43167 +++ b/ext/sqlite/php_sqlite.def
43173 +sqlite_last_insert_rowid
43175 +sqlite_error_string
43178 +sqlite_busy_handler
43179 +sqlite_busy_timeout
43182 +sqlite_exec_printf
43183 +sqlite_exec_vprintf
43184 +sqlite_get_table_printf
43185 +sqlite_get_table_vprintf
43190 +sqlite_libencoding
43191 +sqlite_create_function
43192 +sqlite_create_aggregate
43193 +sqlite_function_type
43194 +sqlite_set_result_string
43195 +sqlite_set_result_int
43196 +sqlite_set_result_double
43197 +sqlite_set_result_error
43199 +sqlite_aggregate_context
43200 +sqlite_aggregate_count
43201 +sqlite_set_authorizer
43206 +; some experimental stuff
43207 +sqlite_last_statement_changes
43210 +sqlite_progress_handler
43211 +sqlite_commit_hook
43213 +++ b/ext/sqlite/php_sqlite.h
43216 + +----------------------------------------------------------------------+
43217 + | PHP Version 5 |
43218 + +----------------------------------------------------------------------+
43219 + | Copyright (c) 1997-2012 The PHP Group |
43220 + +----------------------------------------------------------------------+
43221 + | This source file is subject to version 3.01 of the PHP license, |
43222 + | that is bundled with this package in the file LICENSE, and is |
43223 + | available through the world-wide-web at the following url: |
43224 + | http://www.php.net/license/3_01.txt |
43225 + | If you did not receive a copy of the PHP license and are unable to |
43226 + | obtain it through the world-wide-web, please send a note to |
43227 + | license@php.net so we can mail you a copy immediately. |
43228 + +----------------------------------------------------------------------+
43229 + | Authors: Wez Furlong <wez@thebrainroom.com> |
43230 + | Tal Peer <tal@php.net> |
43231 + | Marcus Boerger <helly@php.net> |
43232 + +----------------------------------------------------------------------+
43237 +#ifndef PHP_SQLITE_H
43238 +#define PHP_SQLITE_H
43240 +extern zend_module_entry sqlite_module_entry;
43241 +#define phpext_sqlite_ptr &sqlite_module_entry
43247 +PHP_MINIT_FUNCTION(sqlite);
43248 +PHP_MSHUTDOWN_FUNCTION(sqlite);
43249 +PHP_RSHUTDOWN_FUNCTION(sqlite);
43250 +PHP_MINFO_FUNCTION(sqlite);
43252 +PHP_FUNCTION(sqlite_open);
43253 +PHP_FUNCTION(sqlite_popen);
43254 +PHP_FUNCTION(sqlite_close);
43255 +PHP_FUNCTION(sqlite_query);
43256 +PHP_FUNCTION(sqlite_exec);
43257 +PHP_FUNCTION(sqlite_unbuffered_query);
43258 +PHP_FUNCTION(sqlite_array_query);
43259 +PHP_FUNCTION(sqlite_single_query);
43261 +PHP_FUNCTION(sqlite_fetch_array);
43262 +PHP_FUNCTION(sqlite_fetch_object);
43263 +PHP_FUNCTION(sqlite_fetch_single);
43264 +PHP_FUNCTION(sqlite_fetch_all);
43265 +PHP_FUNCTION(sqlite_current);
43266 +PHP_FUNCTION(sqlite_column);
43268 +PHP_FUNCTION(sqlite_num_rows);
43269 +PHP_FUNCTION(sqlite_num_fields);
43270 +PHP_FUNCTION(sqlite_field_name);
43271 +PHP_FUNCTION(sqlite_seek);
43272 +PHP_FUNCTION(sqlite_rewind);
43273 +PHP_FUNCTION(sqlite_next);
43274 +PHP_FUNCTION(sqlite_prev);
43275 +PHP_FUNCTION(sqlite_key);
43277 +PHP_FUNCTION(sqlite_valid);
43278 +PHP_FUNCTION(sqlite_has_prev);
43280 +PHP_FUNCTION(sqlite_libversion);
43281 +PHP_FUNCTION(sqlite_libencoding);
43283 +PHP_FUNCTION(sqlite_changes);
43284 +PHP_FUNCTION(sqlite_last_insert_rowid);
43286 +PHP_FUNCTION(sqlite_escape_string);
43288 +PHP_FUNCTION(sqlite_busy_timeout);
43290 +PHP_FUNCTION(sqlite_last_error);
43291 +PHP_FUNCTION(sqlite_error_string);
43293 +PHP_FUNCTION(sqlite_create_aggregate);
43294 +PHP_FUNCTION(sqlite_create_function);
43295 +PHP_FUNCTION(sqlite_udf_decode_binary);
43296 +PHP_FUNCTION(sqlite_udf_encode_binary);
43298 +PHP_FUNCTION(sqlite_factory);
43300 +PHP_FUNCTION(sqlite_fetch_column_types);
43302 +ZEND_BEGIN_MODULE_GLOBALS(sqlite)
43304 +ZEND_END_MODULE_GLOBALS(sqlite)
43307 +#define SQLITE_G(v) TSRMG(sqlite_globals_id, zend_sqlite_globals *, v)
43309 +#define SQLITE_G(v) (sqlite_globals.v)
43316 + * Local variables:
43318 + * c-basic-offset: 4
43319 + * indent-tabs-mode: t
43323 +++ b/ext/sqlite/README
43325 +This is an extension for the SQLite Embeddable SQL Database Engine.
43326 +http://www.sqlite.org/
43328 +SQLite is a C library that implements an embeddable SQL database engine.
43329 +Programs that link with the SQLite library can have SQL database access
43330 +without running a separate RDBMS process.
43332 +SQLite is not a client library used to connect to a big database server.
43333 +SQLite is the server. The SQLite library reads and writes directly to and from
43334 +the database files on disk
43340 +++ b/ext/sqlite/sess_sqlite.c
43343 + +----------------------------------------------------------------------+
43344 + | PHP Version 5 |
43345 + +----------------------------------------------------------------------+
43346 + | Copyright (c) 1997-2012 The PHP Group |
43347 + +----------------------------------------------------------------------+
43348 + | This source file is subject to version 3.01 of the PHP license, |
43349 + | that is bundled with this package in the file LICENSE, and is |
43350 + | available through the world-wide-web at the following url: |
43351 + | http://www.php.net/license/3_01.txt |
43352 + | If you did not receive a copy of the PHP license and are unable to |
43353 + | obtain it through the world-wide-web, please send a note to |
43354 + | license@php.net so we can mail you a copy immediately. |
43355 + +----------------------------------------------------------------------+
43356 + | Authors: John Coggeshall <john@php.net> |
43357 + | Wez Furlong <wez@thebrainroom.com> |
43358 + +----------------------------------------------------------------------+
43365 +#if HAVE_PHP_SESSION && !defined(COMPILE_DL_SESSION)
43367 +#include "ext/session/php_session.h"
43368 +#include "ext/standard/php_lcg.h"
43369 +#include <sqlite.h>
43370 +#define SQLITE_RETVAL(__r) ((__r) == SQLITE_OK ? SUCCESS : FAILURE)
43371 +#define PS_SQLITE_DATA sqlite *db = (sqlite*)PS_GET_MOD_DATA()
43372 +extern int sqlite_encode_binary(const unsigned char *in, int n, unsigned char *out);
43373 +extern int sqlite_decode_binary(const unsigned char *in, unsigned char *out);
43377 +ps_module ps_mod_sqlite = {
43381 +PS_OPEN_FUNC(sqlite)
43383 + char *errmsg = NULL;
43386 + /* TODO: do we need a safe_mode check here? */
43387 + db = sqlite_open(save_path, 0666, &errmsg);
43388 + if (db == NULL) {
43389 + php_error_docref(NULL TSRMLS_CC, E_WARNING,
43390 + "SQLite: failed to open/create session database `%s' - %s", save_path, errmsg);
43391 + sqlite_freemem(errmsg);
43395 + /* allow up to 1 minute when busy */
43396 + sqlite_busy_timeout(db, 60000);
43398 + sqlite_exec(db, "PRAGMA default_synchronous = OFF", NULL, NULL, NULL);
43399 + sqlite_exec(db, "PRAGMA count_changes = OFF", NULL, NULL, NULL);
43401 + /* This will fail if the table already exists, but that's not a big problem. I'm
43402 + unclear as to how to check for a table's existence in SQLite -- that would be better here. */
43404 + "CREATE TABLE session_data ("
43405 + " sess_id PRIMARY KEY,"
43407 + " updated INTEGER "
43408 + ")", NULL, NULL, NULL);
43410 + PS_SET_MOD_DATA(db);
43415 +PS_CLOSE_FUNC(sqlite)
43419 + sqlite_close(db);
43424 +PS_READ_FUNC(sqlite)
43428 + const char *tail;
43430 + int colcount, result;
43431 + const char **rowdata, **colnames;
43437 + query = sqlite_mprintf("SELECT value FROM session_data WHERE sess_id='%q' LIMIT 1", key);
43438 + if (query == NULL) {
43443 + if (sqlite_compile(db, query, &tail, &vm, &error) != SQLITE_OK) {
43444 + php_error_docref(NULL TSRMLS_CC, E_WARNING, "SQLite: Could not compile session read query: %s", error);
43445 + sqlite_freemem(error);
43446 + sqlite_freemem(query);
43450 + switch ((result = sqlite_step(vm, &colcount, &rowdata, &colnames))) {
43452 + if (rowdata[0] != NULL) {
43453 + *vallen = strlen(rowdata[0]);
43455 + *val = emalloc(*vallen);
43456 + *vallen = sqlite_decode_binary(rowdata[0], *val);
43457 + (*val)[*vallen] = '\0';
43459 + *val = STR_EMPTY_ALLOC();
43464 + sqlite_freemem(error);
43468 + if (SQLITE_OK != sqlite_finalize(vm, &error)) {
43469 + php_error_docref(NULL TSRMLS_CC, E_WARNING, "SQLite: session read: error %s", error);
43470 + sqlite_freemem(error);
43474 + sqlite_freemem(query);
43476 + return *val == NULL ? FAILURE : SUCCESS;
43479 +PS_WRITE_FUNC(sqlite)
43490 + binary = safe_emalloc(1 + vallen / 254, 257, 3);
43491 + binlen = sqlite_encode_binary((const unsigned char*)val, vallen, binary);
43493 + rv = sqlite_exec_printf(db, "REPLACE INTO session_data VALUES('%q', '%q', %d)", NULL, NULL, &error, key, binary, t);
43494 + if (rv != SQLITE_OK) {
43495 + php_error_docref(NULL TSRMLS_CC, E_WARNING, "SQLite: session write query failed: %s", error);
43496 + sqlite_freemem(error);
43500 + return SQLITE_RETVAL(rv);
43503 +PS_DESTROY_FUNC(sqlite)
43508 + rv = sqlite_exec_printf(db, "DELETE FROM session_data WHERE sess_id='%q'", NULL, NULL, NULL, key);
43510 + return SQLITE_RETVAL(rv);
43513 +PS_GC_FUNC(sqlite)
43517 + time_t t = time(NULL);
43519 + rv = sqlite_exec_printf(db,
43520 + "DELETE FROM session_data WHERE (%d - updated) > %d",
43521 + NULL, NULL, NULL, t, maxlifetime);
43523 + /* because SQLite does not actually clear the deleted data from the database
43524 + * we need to occassionaly do so manually to prevent the sessions database
43525 + * from growing endlessly.
43527 + if ((int) ((float) PS(gc_divisor) * PS(gc_divisor) * php_combined_lcg(TSRMLS_C)) < PS(gc_probability)) {
43528 + rv = sqlite_exec_printf(db, "VACUUM", NULL, NULL, NULL);
43530 + return SQLITE_RETVAL(rv);
43533 +#endif /* HAVE_PHP_SESSION && !defined(COMPILE_DL_SESSION) */
43536 + * Local variables:
43538 + * c-basic-offset: 4
43540 + * vim600: sw=4 ts=4 fdm=marker
43541 + * vim<600: sw=4 ts=4
43544 +++ b/ext/sqlite/sqlite.c
43547 + +----------------------------------------------------------------------+
43548 + | PHP Version 5 |
43549 + +----------------------------------------------------------------------+
43550 + | Copyright (c) 1997-2012 The PHP Group |
43551 + +----------------------------------------------------------------------+
43552 + | This source file is subject to version 3.01 of the PHP license, |
43553 + | that is bundled with this package in the file LICENSE, and is |
43554 + | available through the world-wide-web at the following url: |
43555 + | http://www.php.net/license/3_01.txt |
43556 + | If you did not receive a copy of the PHP license and are unable to |
43557 + | obtain it through the world-wide-web, please send a note to |
43558 + | license@php.net so we can mail you a copy immediately. |
43559 + +----------------------------------------------------------------------+
43560 + | Authors: Wez Furlong <wez@thebrainroom.com> |
43561 + | Tal Peer <tal@php.net> |
43562 + | Marcus Boerger <helly@php.net> |
43563 + +----------------------------------------------------------------------+
43568 +#ifdef HAVE_CONFIG_H
43569 +#include "config.h"
43572 +#define PHP_SQLITE_MODULE_VERSION "2.0-dev"
43575 +#include "php_ini.h"
43576 +#include "ext/standard/info.h"
43577 +#if HAVE_PHP_SESSION && !defined(COMPILE_DL_SESSION)
43578 +#include "ext/session/php_session.h"
43580 +#include "php_sqlite.h"
43583 +# include <time.h>
43586 +#include <unistd.h>
43589 +#include <sqlite.h>
43591 +#include "zend_exceptions.h"
43592 +#include "zend_interfaces.h"
43594 +#if defined(HAVE_SPL) && ((PHP_MAJOR_VERSION > 5) || (PHP_MAJOR_VERSION == 5 && PHP_MINOR_VERSION >= 1))
43595 +extern PHPAPI zend_class_entry *spl_ce_RuntimeException;
43596 +extern PHPAPI zend_class_entry *spl_ce_Countable;
43599 +#if PHP_SQLITE2_HAVE_PDO
43600 +# include "pdo/php_pdo.h"
43601 +# include "pdo/php_pdo_driver.h"
43602 +extern pdo_driver_t pdo_sqlite2_driver;
43605 +#ifndef safe_emalloc
43606 +# define safe_emalloc(a,b,c) emalloc((a)*(b)+(c))
43609 +ZEND_DECLARE_MODULE_GLOBALS(sqlite)
43610 +static PHP_GINIT_FUNCTION(sqlite);
43612 +#if HAVE_PHP_SESSION && !defined(COMPILE_DL_SESSION)
43613 +extern ps_module ps_mod_sqlite;
43614 +#define ps_sqlite_ptr &ps_mod_sqlite
43617 +extern int sqlite_encode_binary(const unsigned char *in, int n, unsigned char *out);
43618 +extern int sqlite_decode_binary(const unsigned char *in, unsigned char *out);
43620 +#define php_sqlite_encode_binary(in, n, out) sqlite_encode_binary((const unsigned char *)in, n, (unsigned char *)out)
43621 +#define php_sqlite_decode_binary(in, out) in && *in ? sqlite_decode_binary((const unsigned char *)in, (unsigned char *)out) : 0
43623 +static int sqlite_count_elements(zval *object, long *count TSRMLS_DC);
43625 +static int le_sqlite_db, le_sqlite_result, le_sqlite_pdb;
43627 +static inline void php_sqlite_strtoupper(char *s)
43629 + while (*s!='\0') {
43630 + *s = toupper(*s);
43635 +static inline void php_sqlite_strtolower(char *s)
43637 + while (*s!='\0') {
43638 + *s = tolower(*s);
43646 +STD_PHP_INI_ENTRY_EX("sqlite.assoc_case", "0", PHP_INI_ALL, OnUpdateLong, assoc_case, zend_sqlite_globals, sqlite_globals, display_link_numbers)
43650 +#define DB_FROM_ZVAL(db, zv) ZEND_FETCH_RESOURCE2(db, struct php_sqlite_db *, zv, -1, "sqlite database", le_sqlite_db, le_sqlite_pdb)
43652 +#define DB_FROM_OBJECT(db, object) \
43654 + sqlite_object *obj = (sqlite_object*) zend_object_store_get_object(object TSRMLS_CC); \
43655 + db = obj->u.db; \
43657 + php_error_docref(NULL TSRMLS_CC, E_WARNING, "The database wasn't opened"); \
43662 +#define RES_FROM_OBJECT_RESTORE_ERH(res, object, error_handling) \
43664 + sqlite_object *obj = (sqlite_object*) zend_object_store_get_object(object TSRMLS_CC); \
43665 + res = obj->u.res; \
43667 + php_error_docref(NULL TSRMLS_CC, E_WARNING, "No result set available"); \
43668 + if (error_handling) \
43669 + zend_restore_error_handling(error_handling TSRMLS_CC); \
43674 +#define RES_FROM_OBJECT(res, object) RES_FROM_OBJECT_RESTORE_ERH(res, object, NULL)
43676 +#define PHP_SQLITE_EMPTY_QUERY \
43677 + if (!sql_len || !*sql) { \
43678 + php_error_docref(NULL TSRMLS_CC, E_WARNING, "Cannot execute empty query."); \
43682 +struct php_sqlite_result {
43683 + struct php_sqlite_db *db;
43689 + char **col_names;
43695 +struct php_sqlite_db {
43697 + int last_err_code;
43698 + zend_bool is_persistent;
43701 + HashTable callbacks;
43704 +struct php_sqlite_agg_functions {
43705 + struct php_sqlite_db *db;
43711 +static void php_sqlite_fetch_array(struct php_sqlite_result *res, int mode, zend_bool decode_binary, int move_next, zval *return_value TSRMLS_DC);
43712 +static int php_sqlite_fetch(struct php_sqlite_result *rres TSRMLS_DC);
43714 +enum { PHPSQLITE_ASSOC = 1, PHPSQLITE_NUM = 2, PHPSQLITE_BOTH = PHPSQLITE_ASSOC|PHPSQLITE_NUM };
43717 +ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite_popen, 0, 0, 1)
43718 + ZEND_ARG_INFO(0, filename)
43719 + ZEND_ARG_INFO(0, mode)
43720 + ZEND_ARG_INFO(1, error_message)
43721 +ZEND_END_ARG_INFO()
43723 +ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite_open, 0, 0, 1)
43724 + ZEND_ARG_INFO(0, filename)
43725 + ZEND_ARG_INFO(0, mode)
43726 + ZEND_ARG_INFO(1, error_message)
43727 +ZEND_END_ARG_INFO()
43729 +ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite_factory, 0, 0, 1)
43730 + ZEND_ARG_INFO(0, filename)
43731 + ZEND_ARG_INFO(0, mode)
43732 + ZEND_ARG_INFO(1, error_message)
43733 +ZEND_END_ARG_INFO()
43735 +ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite_busy_timeout, 0, 0, 2)
43736 + ZEND_ARG_INFO(0, db)
43737 + ZEND_ARG_INFO(0, ms)
43738 +ZEND_END_ARG_INFO()
43740 +ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite_method_busy_timeout, 0, 0, 1)
43741 + ZEND_ARG_INFO(0, ms)
43742 +ZEND_END_ARG_INFO()
43744 +ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite_close, 0, 0, 1)
43745 + ZEND_ARG_INFO(0, db)
43746 +ZEND_END_ARG_INFO()
43748 +ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite_unbuffered_query, 0, 0, 2)
43749 + ZEND_ARG_INFO(0, query)
43750 + ZEND_ARG_INFO(0, db)
43751 + ZEND_ARG_INFO(0, result_type)
43752 + ZEND_ARG_INFO(1, error_message)
43753 +ZEND_END_ARG_INFO()
43755 +ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite_method_unbuffered_query, 0, 0, 1)
43756 + ZEND_ARG_INFO(0, query)
43757 + ZEND_ARG_INFO(0, result_type)
43758 + ZEND_ARG_INFO(1, error_message)
43759 +ZEND_END_ARG_INFO()
43761 +ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite_fetch_column_types, 0, 0, 2)
43762 + ZEND_ARG_INFO(0, table_name)
43763 + ZEND_ARG_INFO(0, db)
43764 + ZEND_ARG_INFO(0, result_type)
43765 +ZEND_END_ARG_INFO()
43767 +ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite_method_fetch_column_types, 0, 0, 1)
43768 + ZEND_ARG_INFO(0, table_name)
43769 + ZEND_ARG_INFO(0, result_type)
43770 +ZEND_END_ARG_INFO()
43772 +ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite_query, 0, 0, 2)
43773 + ZEND_ARG_INFO(0, query)
43774 + ZEND_ARG_INFO(0, db)
43775 + ZEND_ARG_INFO(0, result_type)
43776 + ZEND_ARG_INFO(1, error_message)
43777 +ZEND_END_ARG_INFO()
43779 +ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite_method_query, 0, 0, 1)
43780 + ZEND_ARG_INFO(0, query)
43781 + ZEND_ARG_INFO(0, result_type)
43782 + ZEND_ARG_INFO(1, error_message)
43783 +ZEND_END_ARG_INFO()
43785 +ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite_exec, 0, 0, 2)
43786 + ZEND_ARG_INFO(0, query)
43787 + ZEND_ARG_INFO(0, db)
43788 + ZEND_ARG_INFO(1, error_message)
43789 +ZEND_END_ARG_INFO()
43791 +ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite_method_exec, 0, 0, 1)
43792 + ZEND_ARG_INFO(0, query)
43793 + ZEND_ARG_INFO(1, error_message)
43794 +ZEND_END_ARG_INFO()
43796 +ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite_fetch_all, 0, 0, 1)
43797 + ZEND_ARG_INFO(0, result)
43798 + ZEND_ARG_INFO(0, result_type)
43799 + ZEND_ARG_INFO(0, decode_binary)
43800 +ZEND_END_ARG_INFO()
43802 +ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite_method_fetch_all, 0, 0, 0)
43803 + ZEND_ARG_INFO(0, result_type)
43804 + ZEND_ARG_INFO(0, decode_binary)
43805 +ZEND_END_ARG_INFO()
43807 +ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite_fetch_array, 0, 0, 1)
43808 + ZEND_ARG_INFO(0, result)
43809 + ZEND_ARG_INFO(0, result_type)
43810 + ZEND_ARG_INFO(0, decode_binary)
43811 +ZEND_END_ARG_INFO()
43813 +ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite_method_fetch_array, 0, 0, 0)
43814 + ZEND_ARG_INFO(0, result_type)
43815 + ZEND_ARG_INFO(0, decode_binary)
43816 +ZEND_END_ARG_INFO()
43818 +ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite_fetch_object, 0, 0, 1)
43819 + ZEND_ARG_INFO(0, result)
43820 + ZEND_ARG_INFO(0, class_name)
43821 + ZEND_ARG_INFO(0, ctor_params)
43822 + ZEND_ARG_INFO(0, decode_binary)
43823 +ZEND_END_ARG_INFO()
43825 +ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite_method_fetch_object, 0, 0, 0)
43826 + ZEND_ARG_INFO(0, class_name)
43827 + ZEND_ARG_INFO(0, ctor_params)
43828 + ZEND_ARG_INFO(0, decode_binary)
43829 +ZEND_END_ARG_INFO()
43831 +ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite_array_query, 0, 0, 2)
43832 + ZEND_ARG_INFO(0, db)
43833 + ZEND_ARG_INFO(0, query)
43834 + ZEND_ARG_INFO(0, result_type)
43835 + ZEND_ARG_INFO(0, decode_binary)
43836 +ZEND_END_ARG_INFO()
43838 +ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite_method_array_query, 0, 0, 1)
43839 + ZEND_ARG_INFO(0, query)
43840 + ZEND_ARG_INFO(0, result_type)
43841 + ZEND_ARG_INFO(0, decode_binary)
43842 +ZEND_END_ARG_INFO()
43844 +ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite_single_query, 0, 0, 2)
43845 + ZEND_ARG_INFO(0, db)
43846 + ZEND_ARG_INFO(0, query)
43847 + ZEND_ARG_INFO(0, first_row_only)
43848 + ZEND_ARG_INFO(0, decode_binary)
43849 +ZEND_END_ARG_INFO()
43851 +ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite_method_single_query, 0, 0, 1)
43852 + ZEND_ARG_INFO(0, query)
43853 + ZEND_ARG_INFO(0, first_row_only)
43854 + ZEND_ARG_INFO(0, decode_binary)
43855 +ZEND_END_ARG_INFO()
43857 +ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite_fetch_single, 0, 0, 1)
43858 + ZEND_ARG_INFO(0, result)
43859 + ZEND_ARG_INFO(0, decode_binary)
43860 +ZEND_END_ARG_INFO()
43862 +ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite_method_fetch_single, 0, 0, 0)
43863 + ZEND_ARG_INFO(0, decode_binary)
43864 +ZEND_END_ARG_INFO()
43866 +ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite_current, 0, 0, 1)
43867 + ZEND_ARG_INFO(0, result)
43868 + ZEND_ARG_INFO(0, result_type)
43869 + ZEND_ARG_INFO(0, decode_binary)
43870 +ZEND_END_ARG_INFO()
43872 +ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite_method_current, 0, 0, 0)
43873 + ZEND_ARG_INFO(0, result_type)
43874 + ZEND_ARG_INFO(0, decode_binary)
43875 +ZEND_END_ARG_INFO()
43877 +ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite_column, 0, 0, 2)
43878 + ZEND_ARG_INFO(0, result)
43879 + ZEND_ARG_INFO(0, index_or_name)
43880 + ZEND_ARG_INFO(0, decode_binary)
43881 +ZEND_END_ARG_INFO()
43883 +ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite_method_column, 0, 0, 1)
43884 + ZEND_ARG_INFO(0, index_or_name)
43885 + ZEND_ARG_INFO(0, decode_binary)
43886 +ZEND_END_ARG_INFO()
43888 +ZEND_BEGIN_ARG_INFO(arginfo_sqlite_libversion, 0)
43889 +ZEND_END_ARG_INFO()
43891 +ZEND_BEGIN_ARG_INFO(arginfo_sqlite_libencoding, 0)
43892 +ZEND_END_ARG_INFO()
43894 +ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite_changes, 0, 0, 1)
43895 + ZEND_ARG_INFO(0, db)
43896 +ZEND_END_ARG_INFO()
43898 +ZEND_BEGIN_ARG_INFO(arginfo_sqlite_method_changes, 0)
43899 +ZEND_END_ARG_INFO()
43901 +ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite_last_insert_rowid, 0, 0, 1)
43902 + ZEND_ARG_INFO(0, db)
43903 +ZEND_END_ARG_INFO()
43905 +ZEND_BEGIN_ARG_INFO(arginfo_sqlite_method_last_insert_rowid, 0)
43906 +ZEND_END_ARG_INFO()
43908 +ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite_num_rows, 0, 0, 1)
43909 + ZEND_ARG_INFO(0, result)
43910 +ZEND_END_ARG_INFO()
43912 +ZEND_BEGIN_ARG_INFO(arginfo_sqlite_method_num_rows, 0)
43913 +ZEND_END_ARG_INFO()
43915 +ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite_valid, 0, 0, 1)
43916 + ZEND_ARG_INFO(0, result)
43917 +ZEND_END_ARG_INFO()
43919 +ZEND_BEGIN_ARG_INFO(arginfo_sqlite_method_valid, 0)
43920 +ZEND_END_ARG_INFO()
43922 +ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite_has_prev, 0, 0, 1)
43923 + ZEND_ARG_INFO(0, result)
43924 +ZEND_END_ARG_INFO()
43926 +ZEND_BEGIN_ARG_INFO(arginfo_sqlite_method_has_prev, 0)
43927 +ZEND_END_ARG_INFO()
43929 +ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite_num_fields, 0, 0, 1)
43930 + ZEND_ARG_INFO(0, result)
43931 +ZEND_END_ARG_INFO()
43933 +ZEND_BEGIN_ARG_INFO(arginfo_sqlite_method_num_fields, 0)
43934 +ZEND_END_ARG_INFO()
43936 +ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite_field_name, 0, 0, 2)
43937 + ZEND_ARG_INFO(0, result)
43938 + ZEND_ARG_INFO(0, field_index)
43939 +ZEND_END_ARG_INFO()
43941 +ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite_method_field_name, 0, 0, 1)
43942 + ZEND_ARG_INFO(0, field_index)
43943 +ZEND_END_ARG_INFO()
43945 +ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite_seek, 0, 0, 2)
43946 + ZEND_ARG_INFO(0, result)
43947 + ZEND_ARG_INFO(0, row)
43948 +ZEND_END_ARG_INFO()
43950 +ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite_method_seek, 0, 0, 1)
43951 + ZEND_ARG_INFO(0, row)
43952 +ZEND_END_ARG_INFO()
43954 +ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite_rewind, 0, 0, 1)
43955 + ZEND_ARG_INFO(0, result)
43956 +ZEND_END_ARG_INFO()
43958 +ZEND_BEGIN_ARG_INFO(arginfo_sqlite_method_rewind, 0)
43959 +ZEND_END_ARG_INFO()
43961 +ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite_next, 0, 0, 1)
43962 + ZEND_ARG_INFO(0, result)
43963 +ZEND_END_ARG_INFO()
43965 +ZEND_BEGIN_ARG_INFO(arginfo_sqlite_method_next, 0)
43966 +ZEND_END_ARG_INFO()
43968 +ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite_key, 0, 0, 1)
43969 + ZEND_ARG_INFO(0, result)
43970 +ZEND_END_ARG_INFO()
43972 +ZEND_BEGIN_ARG_INFO(arginfo_sqlite_method_key, 0)
43973 +ZEND_END_ARG_INFO()
43975 +ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite_prev, 0, 0, 1)
43976 + ZEND_ARG_INFO(0, result)
43977 +ZEND_END_ARG_INFO()
43979 +ZEND_BEGIN_ARG_INFO(arginfo_sqlite_method_prev, 0)
43980 +ZEND_END_ARG_INFO()
43982 +ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite_escape_string, 0, 0, 1)
43983 + ZEND_ARG_INFO(0, item)
43984 +ZEND_END_ARG_INFO()
43986 +ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite_last_error, 0, 0, 1)
43987 + ZEND_ARG_INFO(0, db)
43988 +ZEND_END_ARG_INFO()
43990 +ZEND_BEGIN_ARG_INFO(arginfo_sqlite_method_last_error, 0)
43991 +ZEND_END_ARG_INFO()
43993 +ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite_error_string, 0, 0, 1)
43994 + ZEND_ARG_INFO(0, error_code)
43995 +ZEND_END_ARG_INFO()
43997 +ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite_create_aggregate, 0, 0, 4)
43998 + ZEND_ARG_INFO(0, db)
43999 + ZEND_ARG_INFO(0, funcname)
44000 + ZEND_ARG_INFO(0, step_func)
44001 + ZEND_ARG_INFO(0, finalize_func)
44002 + ZEND_ARG_INFO(0, num_args)
44003 +ZEND_END_ARG_INFO()
44005 +ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite_method_create_aggregate, 0, 0, 3)
44006 + ZEND_ARG_INFO(0, funcname)
44007 + ZEND_ARG_INFO(0, step_func)
44008 + ZEND_ARG_INFO(0, finalize_func)
44009 + ZEND_ARG_INFO(0, num_args)
44010 +ZEND_END_ARG_INFO()
44012 +ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite_create_function, 0, 0, 3)
44013 + ZEND_ARG_INFO(0, db)
44014 + ZEND_ARG_INFO(0, funcname)
44015 + ZEND_ARG_INFO(0, callback)
44016 + ZEND_ARG_INFO(0, num_args)
44017 +ZEND_END_ARG_INFO()
44019 +ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite_method_create_function, 0, 0, 2)
44020 + ZEND_ARG_INFO(0, funcname)
44021 + ZEND_ARG_INFO(0, callback)
44022 + ZEND_ARG_INFO(0, num_args)
44023 +ZEND_END_ARG_INFO()
44025 +ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite_udf_encode_binary, 0, 0, 1)
44026 + ZEND_ARG_INFO(0, data)
44027 +ZEND_END_ARG_INFO()
44029 +ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite_udf_decode_binary, 0, 0, 1)
44030 + ZEND_ARG_INFO(0, data)
44031 +ZEND_END_ARG_INFO()
44034 +const zend_function_entry sqlite_functions[] = {
44035 + PHP_FE(sqlite_open, arginfo_sqlite_open)
44036 + PHP_FE(sqlite_popen, arginfo_sqlite_popen)
44037 + PHP_FE(sqlite_close, arginfo_sqlite_close)
44038 + PHP_FE(sqlite_query, arginfo_sqlite_query)
44039 + PHP_FE(sqlite_exec, arginfo_sqlite_exec)
44040 + PHP_FE(sqlite_array_query, arginfo_sqlite_array_query)
44041 + PHP_FE(sqlite_single_query, arginfo_sqlite_single_query)
44042 + PHP_FE(sqlite_fetch_array, arginfo_sqlite_fetch_array)
44043 + PHP_FE(sqlite_fetch_object, arginfo_sqlite_fetch_object)
44044 + PHP_FE(sqlite_fetch_single, arginfo_sqlite_fetch_single)
44045 + PHP_FALIAS(sqlite_fetch_string, sqlite_fetch_single, arginfo_sqlite_fetch_single)
44046 + PHP_FE(sqlite_fetch_all, arginfo_sqlite_fetch_all)
44047 + PHP_FE(sqlite_current, arginfo_sqlite_current)
44048 + PHP_FE(sqlite_column, arginfo_sqlite_column)
44049 + PHP_FE(sqlite_libversion, arginfo_sqlite_libversion)
44050 + PHP_FE(sqlite_libencoding, arginfo_sqlite_libencoding)
44051 + PHP_FE(sqlite_changes, arginfo_sqlite_changes)
44052 + PHP_FE(sqlite_last_insert_rowid, arginfo_sqlite_last_insert_rowid)
44053 + PHP_FE(sqlite_num_rows, arginfo_sqlite_num_rows)
44054 + PHP_FE(sqlite_num_fields, arginfo_sqlite_num_fields)
44055 + PHP_FE(sqlite_field_name, arginfo_sqlite_field_name)
44056 + PHP_FE(sqlite_seek, arginfo_sqlite_seek)
44057 + PHP_FE(sqlite_rewind, arginfo_sqlite_rewind)
44058 + PHP_FE(sqlite_next, arginfo_sqlite_next)
44059 + PHP_FE(sqlite_prev, arginfo_sqlite_prev)
44060 + PHP_FE(sqlite_valid, arginfo_sqlite_valid)
44061 + PHP_FALIAS(sqlite_has_more, sqlite_valid, arginfo_sqlite_valid)
44062 + PHP_FE(sqlite_has_prev, arginfo_sqlite_has_prev)
44063 + PHP_FE(sqlite_escape_string, arginfo_sqlite_escape_string)
44064 + PHP_FE(sqlite_busy_timeout, arginfo_sqlite_busy_timeout)
44065 + PHP_FE(sqlite_last_error, arginfo_sqlite_last_error)
44066 + PHP_FE(sqlite_error_string, arginfo_sqlite_error_string)
44067 + PHP_FE(sqlite_unbuffered_query, arginfo_sqlite_unbuffered_query)
44068 + PHP_FE(sqlite_create_aggregate, arginfo_sqlite_create_aggregate)
44069 + PHP_FE(sqlite_create_function, arginfo_sqlite_create_function)
44070 + PHP_FE(sqlite_factory, arginfo_sqlite_factory)
44071 + PHP_FE(sqlite_udf_encode_binary, arginfo_sqlite_udf_encode_binary)
44072 + PHP_FE(sqlite_udf_decode_binary, arginfo_sqlite_udf_decode_binary)
44073 + PHP_FE(sqlite_fetch_column_types, arginfo_sqlite_fetch_column_types)
44074 + {NULL, NULL, NULL}
44077 +const zend_function_entry sqlite_funcs_db[] = {
44078 + PHP_ME_MAPPING(__construct, sqlite_open, arginfo_sqlite_open, 0)
44079 +/* PHP_ME_MAPPING(close, sqlite_close, NULL, 0)*/
44080 + PHP_ME_MAPPING(query, sqlite_query, arginfo_sqlite_method_query, 0)
44081 + PHP_ME_MAPPING(queryExec, sqlite_exec, arginfo_sqlite_method_exec, 0)
44082 + PHP_ME_MAPPING(arrayQuery, sqlite_array_query, arginfo_sqlite_method_array_query, 0)
44083 + PHP_ME_MAPPING(singleQuery, sqlite_single_query, arginfo_sqlite_method_single_query, 0)
44084 + PHP_ME_MAPPING(unbufferedQuery, sqlite_unbuffered_query, arginfo_sqlite_method_unbuffered_query, 0)
44085 + PHP_ME_MAPPING(lastInsertRowid, sqlite_last_insert_rowid, arginfo_sqlite_method_last_insert_rowid, 0)
44086 + PHP_ME_MAPPING(changes, sqlite_changes, arginfo_sqlite_method_changes, 0)
44087 + PHP_ME_MAPPING(createAggregate, sqlite_create_aggregate, arginfo_sqlite_method_create_aggregate, 0)
44088 + PHP_ME_MAPPING(createFunction, sqlite_create_function, arginfo_sqlite_method_create_function, 0)
44089 + PHP_ME_MAPPING(busyTimeout, sqlite_busy_timeout, arginfo_sqlite_method_busy_timeout, 0)
44090 + PHP_ME_MAPPING(lastError, sqlite_last_error, arginfo_sqlite_method_last_error, 0)
44091 + PHP_ME_MAPPING(fetchColumnTypes, sqlite_fetch_column_types, arginfo_sqlite_method_fetch_column_types, 0)
44092 +/* PHP_ME_MAPPING(error_string, sqlite_error_string, NULL, 0) static */
44093 +/* PHP_ME_MAPPING(escape_string, sqlite_escape_string, NULL, 0) static */
44094 + {NULL, NULL, NULL}
44097 +const zend_function_entry sqlite_funcs_query[] = {
44098 + PHP_ME_MAPPING(fetch, sqlite_fetch_array, arginfo_sqlite_method_fetch_array, 0)
44099 + PHP_ME_MAPPING(fetchObject, sqlite_fetch_object, arginfo_sqlite_method_fetch_object, 0)
44100 + PHP_ME_MAPPING(fetchSingle, sqlite_fetch_single, arginfo_sqlite_method_fetch_single, 0)
44101 + PHP_ME_MAPPING(fetchAll, sqlite_fetch_all, arginfo_sqlite_method_fetch_all, 0)
44102 + PHP_ME_MAPPING(column, sqlite_column, arginfo_sqlite_method_column, 0)
44103 + PHP_ME_MAPPING(numFields, sqlite_num_fields, arginfo_sqlite_method_num_fields, 0)
44104 + PHP_ME_MAPPING(fieldName, sqlite_field_name, arginfo_sqlite_method_field_name, 0)
44106 + PHP_ME_MAPPING(current, sqlite_current, arginfo_sqlite_method_current, 0)
44107 + PHP_ME_MAPPING(key, sqlite_key, arginfo_sqlite_method_key, 0)
44108 + PHP_ME_MAPPING(next, sqlite_next, arginfo_sqlite_method_next, 0)
44109 + PHP_ME_MAPPING(valid, sqlite_valid, arginfo_sqlite_method_valid, 0)
44110 + PHP_ME_MAPPING(rewind, sqlite_rewind, arginfo_sqlite_method_rewind, 0)
44112 + PHP_ME_MAPPING(count, sqlite_num_rows, arginfo_sqlite_method_num_rows, 0)
44114 + PHP_ME_MAPPING(prev, sqlite_prev, arginfo_sqlite_method_prev, 0)
44115 + PHP_ME_MAPPING(hasPrev, sqlite_has_prev, arginfo_sqlite_method_has_prev, 0)
44116 + PHP_ME_MAPPING(numRows, sqlite_num_rows, arginfo_sqlite_method_num_rows, 0)
44117 + PHP_ME_MAPPING(seek, sqlite_seek, arginfo_sqlite_method_seek, 0)
44118 + {NULL, NULL, NULL}
44121 +const zend_function_entry sqlite_funcs_ub_query[] = {
44122 + PHP_ME_MAPPING(fetch, sqlite_fetch_array, arginfo_sqlite_method_fetch_array, 0)
44123 + PHP_ME_MAPPING(fetchObject, sqlite_fetch_object, arginfo_sqlite_method_fetch_object, 0)
44124 + PHP_ME_MAPPING(fetchSingle, sqlite_fetch_single, arginfo_sqlite_method_fetch_single, 0)
44125 + PHP_ME_MAPPING(fetchAll, sqlite_fetch_all, arginfo_sqlite_method_fetch_all, 0)
44126 + PHP_ME_MAPPING(column, sqlite_column, arginfo_sqlite_method_column, 0)
44127 + PHP_ME_MAPPING(numFields, sqlite_num_fields, arginfo_sqlite_method_num_fields, 0)
44128 + PHP_ME_MAPPING(fieldName, sqlite_field_name, arginfo_sqlite_method_field_name, 0)
44130 + PHP_ME_MAPPING(current, sqlite_current, arginfo_sqlite_method_current, 0)
44131 + PHP_ME_MAPPING(next, sqlite_next, arginfo_sqlite_method_next, 0)
44132 + PHP_ME_MAPPING(valid, sqlite_valid, arginfo_sqlite_method_valid, 0)
44133 + {NULL, NULL, NULL}
44136 +const zend_function_entry sqlite_funcs_exception[] = {
44137 + {NULL, NULL, NULL}
44140 +/* Dependancies */
44141 +static const zend_module_dep sqlite_deps[] = {
44142 +#if defined(HAVE_SPL) && ((PHP_MAJOR_VERSION > 5) || (PHP_MAJOR_VERSION == 5 && PHP_MINOR_VERSION >= 1))
44143 + ZEND_MOD_REQUIRED("spl")
44145 +#if HAVE_PHP_SESSION && !defined(COMPILE_DL_SESSION)
44146 + ZEND_MOD_REQUIRED("session")
44148 +#ifdef PHP_SQLITE2_HAVE_PDO
44149 + ZEND_MOD_REQUIRED("pdo")
44151 + {NULL, NULL, NULL}
44154 +zend_module_entry sqlite_module_entry = {
44155 +#if ZEND_MODULE_API_NO >= 20050922
44156 + STANDARD_MODULE_HEADER_EX, NULL,
44158 +#elif ZEND_MODULE_API_NO >= 20010901
44159 + STANDARD_MODULE_HEADER,
44162 + sqlite_functions,
44163 + PHP_MINIT(sqlite),
44164 + PHP_MSHUTDOWN(sqlite),
44166 + PHP_RSHUTDOWN(sqlite),
44167 + PHP_MINFO(sqlite),
44168 +#if ZEND_MODULE_API_NO >= 20010901
44169 + PHP_SQLITE_MODULE_VERSION,
44171 +#if ZEND_MODULE_API_NO >= 20060613
44172 + PHP_MODULE_GLOBALS(sqlite),
44173 + PHP_GINIT(sqlite),
44176 + STANDARD_MODULE_PROPERTIES_EX
44178 + STANDARD_MODULE_PROPERTIES
44183 +#ifdef COMPILE_DL_SQLITE
44184 +ZEND_GET_MODULE(sqlite)
44187 +static int php_sqlite_callback_invalidator(struct php_sqlite_agg_functions *funcs TSRMLS_DC)
44189 + if (!funcs->is_valid) {
44193 + if (funcs->step) {
44194 + zval_ptr_dtor(&funcs->step);
44195 + funcs->step = NULL;
44198 + if (funcs->fini) {
44199 + zval_ptr_dtor(&funcs->fini);
44200 + funcs->fini = NULL;
44203 + funcs->is_valid = 0;
44209 +static void php_sqlite_callback_dtor(void *pDest)
44211 + struct php_sqlite_agg_functions *funcs = (struct php_sqlite_agg_functions*)pDest;
44213 + if (funcs->is_valid) {
44216 + php_sqlite_callback_invalidator(funcs TSRMLS_CC);
44220 +static ZEND_RSRC_DTOR_FUNC(php_sqlite_db_dtor)
44223 + struct php_sqlite_db *db = (struct php_sqlite_db*)rsrc->ptr;
44225 + sqlite_close(db->db);
44227 + zend_hash_destroy(&db->callbacks);
44229 + pefree(db, db->is_persistent);
44231 + rsrc->ptr = NULL;
44235 +static void real_result_dtor(struct php_sqlite_result *res TSRMLS_DC)
44240 + sqlite_finalize(res->vm, NULL);
44243 + if (res->table) {
44244 + if (!res->buffered && res->nrows) {
44245 + res->nrows = 1; /* only one row is stored */
44247 + for (i = 0; i < res->nrows; i++) {
44248 + base = i * res->ncolumns;
44249 + for (j = 0; j < res->ncolumns; j++) {
44250 + if (res->table[base + j] != NULL) {
44251 + efree(res->table[base + j]);
44255 + efree(res->table);
44257 + if (res->col_names) {
44258 + for (j = 0; j < res->ncolumns; j++) {
44259 + efree(res->col_names[j]);
44261 + efree(res->col_names);
44265 + zend_list_delete(res->db->rsrc_id);
44270 +static int _clean_unfinished_results(zend_rsrc_list_entry *le, void *db TSRMLS_DC)
44272 + if (Z_TYPE_P(le) == le_sqlite_result) {
44273 + struct php_sqlite_result *res = (struct php_sqlite_result *)le->ptr;
44274 + if (res->db->rsrc_id == ((struct php_sqlite_db*)db)->rsrc_id) {
44275 + return ZEND_HASH_APPLY_REMOVE;
44278 + return ZEND_HASH_APPLY_KEEP;
44281 +static ZEND_RSRC_DTOR_FUNC(php_sqlite_result_dtor)
44283 + struct php_sqlite_result *res = (struct php_sqlite_result *)rsrc->ptr;
44284 + real_result_dtor(res TSRMLS_CC);
44287 +static int php_sqlite_forget_persistent_id_numbers(zend_rsrc_list_entry *rsrc TSRMLS_DC)
44289 + struct php_sqlite_db *db = (struct php_sqlite_db*)rsrc->ptr;
44291 + if (Z_TYPE_P(rsrc) != le_sqlite_pdb) {
44295 + /* prevent bad mojo if someone tries to use a previously registered function in the next request */
44296 + zend_hash_apply(&db->callbacks, (apply_func_t)php_sqlite_callback_invalidator TSRMLS_CC);
44298 + db->rsrc_id = FAILURE;
44300 + /* don't leave pending commits hanging around */
44301 + sqlite_exec(db->db, "ROLLBACK", NULL, NULL, NULL);
44306 +PHP_RSHUTDOWN_FUNCTION(sqlite)
44308 + zend_hash_apply(&EG(persistent_list), (apply_func_t)php_sqlite_forget_persistent_id_numbers TSRMLS_CC);
44312 +/* {{{ PHP Function interface */
44313 +static void php_sqlite_generic_function_callback(sqlite_func *func, int argc, const char **argv)
44315 + zval *retval = NULL;
44316 + zval ***zargs = NULL;
44319 + char *callable = NULL, *errbuf=NULL;
44322 + /* sanity check the args */
44324 + sqlite_set_result_error(func, "not enough parameters", -1);
44328 + ZVAL_STRING(&funcname, (char*)argv[0], 1);
44330 + if (!zend_make_callable(&funcname, &callable TSRMLS_CC)) {
44331 + spprintf(&errbuf, 0, "function `%s' is not a function name", callable);
44332 + sqlite_set_result_error(func, errbuf, -1);
44335 + zval_dtor(&funcname);
44340 + zargs = (zval ***)safe_emalloc((argc - 1), sizeof(zval **), 0);
44342 + for (i = 0; i < argc-1; i++) {
44343 + zargs[i] = emalloc(sizeof(zval *));
44344 + MAKE_STD_ZVAL(*zargs[i]);
44345 + ZVAL_STRING(*zargs[i], (char*)argv[i+1], 1);
44349 + res = call_user_function_ex(EG(function_table),
44355 + 0, NULL TSRMLS_CC);
44357 + zval_dtor(&funcname);
44359 + if (res == SUCCESS) {
44360 + if (retval == NULL) {
44361 + sqlite_set_result_string(func, NULL, 0);
44363 + switch (Z_TYPE_P(retval)) {
44365 + sqlite_set_result_string(func, Z_STRVAL_P(retval), Z_STRLEN_P(retval));
44369 + sqlite_set_result_int(func, Z_LVAL_P(retval));
44372 + sqlite_set_result_double(func, Z_DVAL_P(retval));
44376 + sqlite_set_result_string(func, NULL, 0);
44381 + spprintf(&errbuf, 0, "call_user_function_ex failed for function %s()", callable);
44382 + sqlite_set_result_error(func, errbuf, -1);
44389 + zval_ptr_dtor(&retval);
44393 + for (i = 0; i < argc-1; i++) {
44394 + zval_ptr_dtor(zargs[i]);
44402 +/* {{{ callback for sqlite_create_function */
44403 +static void php_sqlite_function_callback(sqlite_func *func, int argc, const char **argv)
44405 + zval *retval = NULL;
44406 + zval ***zargs = NULL;
44408 + struct php_sqlite_agg_functions *funcs = sqlite_user_data(func);
44411 + if (!funcs->is_valid) {
44412 + sqlite_set_result_error(func, "this function has not been correctly defined for this request", -1);
44417 + zargs = (zval ***)safe_emalloc(argc, sizeof(zval **), 0);
44419 + for (i = 0; i < argc; i++) {
44420 + zargs[i] = emalloc(sizeof(zval *));
44421 + MAKE_STD_ZVAL(*zargs[i]);
44423 + if (argv[i] == NULL) {
44424 + ZVAL_NULL(*zargs[i]);
44426 + ZVAL_STRING(*zargs[i], (char*)argv[i], 1);
44431 + res = call_user_function_ex(EG(function_table),
44437 + 0, NULL TSRMLS_CC);
44439 + if (res == SUCCESS) {
44440 + if (retval == NULL) {
44441 + sqlite_set_result_string(func, NULL, 0);
44443 + switch (Z_TYPE_P(retval)) {
44445 + /* TODO: for binary results, need to encode the string */
44446 + sqlite_set_result_string(func, Z_STRVAL_P(retval), Z_STRLEN_P(retval));
44450 + sqlite_set_result_int(func, Z_LVAL_P(retval));
44453 + sqlite_set_result_double(func, Z_DVAL_P(retval));
44457 + sqlite_set_result_string(func, NULL, 0);
44461 + sqlite_set_result_error(func, "call_user_function_ex failed", -1);
44465 + zval_ptr_dtor(&retval);
44469 + for (i = 0; i < argc; i++) {
44470 + zval_ptr_dtor(zargs[i]);
44478 +/* {{{ callback for sqlite_create_aggregate: step function */
44479 +static void php_sqlite_agg_step_function_callback(sqlite_func *func, int argc, const char **argv)
44481 + zval *retval = NULL;
44483 + zval **context_p;
44484 + int i, res, zargc;
44485 + struct php_sqlite_agg_functions *funcs = sqlite_user_data(func);
44488 + if (!funcs->is_valid) {
44489 + sqlite_set_result_error(func, "this function has not been correctly defined for this request", -1);
44493 + /* sanity check the args */
44498 + zargc = argc + 1;
44499 + zargs = (zval ***)safe_emalloc(zargc, sizeof(zval **), 0);
44501 + /* first arg is always the context zval */
44502 + context_p = (zval **)sqlite_aggregate_context(func, sizeof(*context_p));
44504 + if (*context_p == NULL) {
44505 + MAKE_STD_ZVAL(*context_p);
44506 + Z_SET_ISREF_PP(context_p);
44507 + Z_TYPE_PP(context_p) = IS_NULL;
44510 + zargs[0] = context_p;
44512 + /* copy the other args */
44513 + for (i = 0; i < argc; i++) {
44514 + zargs[i+1] = emalloc(sizeof(zval *));
44515 + MAKE_STD_ZVAL(*zargs[i+1]);
44516 + if (argv[i] == NULL) {
44517 + ZVAL_NULL(*zargs[i+1]);
44519 + ZVAL_STRING(*zargs[i+1], (char*)argv[i], 1);
44523 + res = call_user_function_ex(EG(function_table),
44529 + 0, NULL TSRMLS_CC);
44531 + if (res != SUCCESS) {
44532 + php_error_docref(NULL TSRMLS_CC, E_WARNING, "call_user_function_ex failed");
44536 + zval_ptr_dtor(&retval);
44540 + for (i = 1; i < zargc; i++) {
44541 + zval_ptr_dtor(zargs[i]);
44549 +/* {{{ callback for sqlite_create_aggregate: finalize function */
44550 +static void php_sqlite_agg_fini_function_callback(sqlite_func *func)
44552 + zval *retval = NULL;
44554 + struct php_sqlite_agg_functions *funcs = sqlite_user_data(func);
44555 + zval **context_p;
44558 + if (!funcs->is_valid) {
44559 + sqlite_set_result_error(func, "this function has not been correctly defined for this request", -1);
44563 + context_p = (zval **)sqlite_aggregate_context(func, sizeof(*context_p));
44565 + res = call_user_function_ex(EG(function_table),
44571 + 0, NULL TSRMLS_CC);
44573 + if (res == SUCCESS) {
44574 + if (retval == NULL) {
44575 + sqlite_set_result_string(func, NULL, 0);
44577 + switch (Z_TYPE_P(retval)) {
44579 + /* TODO: for binary results, need to encode the string */
44580 + sqlite_set_result_string(func, Z_STRVAL_P(retval), Z_STRLEN_P(retval));
44584 + sqlite_set_result_int(func, Z_LVAL_P(retval));
44587 + sqlite_set_result_double(func, Z_DVAL_P(retval));
44591 + sqlite_set_result_string(func, NULL, 0);
44595 + sqlite_set_result_error(func, "call_user_function_ex failed", -1);
44599 + zval_ptr_dtor(&retval);
44602 + zval_ptr_dtor(context_p);
44606 +/* {{{ Authorization Callback */
44607 +static int php_sqlite_authorizer(void *autharg, int access_type, const char *arg3, const char *arg4,
44608 + const char *arg5, const char *arg6)
44610 + switch (access_type) {
44611 + case SQLITE_COPY:
44612 + if (strncmp(arg4, ":memory:", sizeof(":memory:") - 1)) {
44614 + if (PG(safe_mode) && (!php_checkuid(arg4, NULL, CHECKUID_CHECK_FILE_AND_DIR))) {
44615 + return SQLITE_DENY;
44618 + if (php_check_open_basedir(arg4 TSRMLS_CC)) {
44619 + return SQLITE_DENY;
44622 + return SQLITE_OK;
44623 +#ifdef SQLITE_ATTACH
44624 + case SQLITE_ATTACH:
44625 + if (strncmp(arg3, ":memory:", sizeof(":memory:") - 1)) {
44627 + if (PG(safe_mode) && (!php_checkuid(arg3, NULL, CHECKUID_CHECK_FILE_AND_DIR))) {
44628 + return SQLITE_DENY;
44631 + if (php_check_open_basedir(arg3 TSRMLS_CC)) {
44632 + return SQLITE_DENY;
44635 + return SQLITE_OK;
44639 + /* access allowed */
44640 + return SQLITE_OK;
44645 +/* {{{ OO init/structure stuff */
44646 +#define REGISTER_SQLITE_CLASS(name, c_name, parent) \
44648 + zend_class_entry ce; \
44649 + INIT_CLASS_ENTRY(ce, "SQLite" # name, sqlite_funcs_ ## c_name); \
44650 + ce.create_object = sqlite_object_new_ ## c_name; \
44651 + sqlite_ce_ ## c_name = zend_register_internal_class_ex(&ce, parent, NULL TSRMLS_CC); \
44652 + memcpy(&sqlite_object_handlers_ ## c_name, zend_get_std_object_handlers(), sizeof(zend_object_handlers)); \
44653 + sqlite_object_handlers_ ## c_name.clone_obj = NULL; \
44654 + sqlite_ce_ ## c_name->ce_flags |= ZEND_ACC_FINAL_CLASS; \
44657 +zend_class_entry *sqlite_ce_db, *sqlite_ce_exception;
44658 +zend_class_entry *sqlite_ce_query, *sqlite_ce_ub_query;
44660 +static zend_object_handlers sqlite_object_handlers_db;
44661 +static zend_object_handlers sqlite_object_handlers_query;
44662 +static zend_object_handlers sqlite_object_handlers_ub_query;
44663 +static zend_object_handlers sqlite_object_handlers_exception;
44668 +} sqlite_obj_type;
44670 +typedef struct _sqlite_object {
44672 + sqlite_obj_type type;
44674 + struct php_sqlite_db *db;
44675 + struct php_sqlite_result *res;
44680 +static int sqlite_free_persistent(zend_rsrc_list_entry *le, void *ptr TSRMLS_DC)
44682 + return le->ptr == ptr ? ZEND_HASH_APPLY_REMOVE : ZEND_HASH_APPLY_KEEP;
44685 +static void sqlite_object_free_storage(void *object TSRMLS_DC)
44687 + sqlite_object *intern = (sqlite_object *)object;
44689 + zend_object_std_dtor(&intern->std TSRMLS_CC);
44691 + if (intern->u.ptr) {
44692 + if (intern->type == is_db) {
44693 + if (intern->u.db->rsrc_id) {
44694 + zend_list_delete(intern->u.db->rsrc_id);
44695 + zend_hash_apply_with_argument(&EG(persistent_list), (apply_func_arg_t) sqlite_free_persistent, &intern->u.ptr TSRMLS_CC);
44698 + real_result_dtor(intern->u.res TSRMLS_CC);
44705 +static void sqlite_object_new(zend_class_entry *class_type, zend_object_handlers *handlers, zend_object_value *retval TSRMLS_DC)
44707 + sqlite_object *intern;
44710 + intern = emalloc(sizeof(sqlite_object));
44711 + memset(intern, 0, sizeof(sqlite_object));
44713 + zend_object_std_init(&intern->std, class_type TSRMLS_CC);
44714 + zend_hash_copy(intern->std.properties, &class_type->default_properties, (copy_ctor_func_t) zval_add_ref, (void *) &tmp, sizeof(zval *));
44716 + retval->handle = zend_objects_store_put(intern, (zend_objects_store_dtor_t)zend_objects_destroy_object, (zend_objects_free_object_storage_t) sqlite_object_free_storage, NULL TSRMLS_CC);
44717 + retval->handlers = handlers;
44720 +static zend_object_value sqlite_object_new_db(zend_class_entry *class_type TSRMLS_DC)
44722 + zend_object_value retval;
44724 + sqlite_object_new(class_type, &sqlite_object_handlers_db, &retval TSRMLS_CC);
44728 +static zend_object_value sqlite_object_new_query(zend_class_entry *class_type TSRMLS_DC)
44730 + zend_object_value retval;
44732 + sqlite_object_new(class_type, &sqlite_object_handlers_query, &retval TSRMLS_CC);
44736 +static zend_object_value sqlite_object_new_ub_query(zend_class_entry *class_type TSRMLS_DC)
44738 + zend_object_value retval;
44740 + sqlite_object_new(class_type, &sqlite_object_handlers_ub_query, &retval TSRMLS_CC);
44744 +static zend_object_value sqlite_object_new_exception(zend_class_entry *class_type TSRMLS_DC)
44746 + zend_object_value retval;
44748 + sqlite_object_new(class_type, &sqlite_object_handlers_exception, &retval TSRMLS_CC);
44752 +#define SQLITE_REGISTER_OBJECT(_type, _object, _ptr) \
44754 + sqlite_object *obj; \
44755 + obj = (sqlite_object*)zend_object_store_get_object(_object TSRMLS_CC); \
44756 + obj->type = is_ ## _type; \
44757 + obj->u._type = _ptr; \
44760 +static zend_class_entry *sqlite_get_ce_query(const zval *object TSRMLS_DC)
44762 + return sqlite_ce_query;
44765 +static zend_class_entry *sqlite_get_ce_ub_query(const zval *object TSRMLS_DC)
44767 + return sqlite_ce_ub_query;
44770 +static zval * sqlite_instanciate(zend_class_entry *pce, zval *object TSRMLS_DC)
44773 + ALLOC_ZVAL(object);
44775 + Z_TYPE_P(object) = IS_OBJECT;
44776 + object_init_ex(object, pce);
44777 + Z_SET_REFCOUNT_P(object, 1);
44778 + Z_SET_ISREF_P(object);
44782 +typedef struct _sqlite_object_iterator {
44783 + zend_object_iterator it;
44784 + struct php_sqlite_result *res;
44786 +} sqlite_object_iterator;
44788 +void sqlite_iterator_dtor(zend_object_iterator *iter TSRMLS_DC)
44790 + zval *object = (zval*)((sqlite_object_iterator*)iter)->it.data;
44792 + if (((sqlite_object_iterator*)iter)->value) {
44793 + zval_ptr_dtor(&((sqlite_object_iterator*)iter)->value);
44794 + ((sqlite_object_iterator*)iter)->value = NULL;
44796 + zval_ptr_dtor(&object);
44800 +void sqlite_iterator_rewind(zend_object_iterator *iter TSRMLS_DC)
44802 + struct php_sqlite_result *res = ((sqlite_object_iterator*)iter)->res;
44804 + if (((sqlite_object_iterator*)iter)->value) {
44805 + zval_ptr_dtor(&((sqlite_object_iterator*)iter)->value);
44806 + ((sqlite_object_iterator*)iter)->value = NULL;
44809 + res->curr_row = 0;
44813 +int sqlite_iterator_valid(zend_object_iterator *iter TSRMLS_DC)
44815 + struct php_sqlite_result *res = ((sqlite_object_iterator*)iter)->res;
44817 + if (res && res->curr_row < res->nrows && res->nrows) { /* curr_row may be -1 */
44824 +void sqlite_iterator_get_current_data(zend_object_iterator *iter, zval ***data TSRMLS_DC)
44826 + struct php_sqlite_result *res = ((sqlite_object_iterator*)iter)->res;
44828 + *data = &((sqlite_object_iterator*)iter)->value;
44829 + if (res && !**data) {
44830 + MAKE_STD_ZVAL(**data);
44831 + php_sqlite_fetch_array(res, res->mode, 1, 0, **data TSRMLS_CC);
44836 +int sqlite_iterator_get_current_key(zend_object_iterator *iter, char **str_key, uint *str_key_len, ulong *int_key TSRMLS_DC)
44838 + struct php_sqlite_result *res = ((sqlite_object_iterator*)iter)->res;
44841 + *str_key_len = 0;
44842 + *int_key = res ? res->curr_row : 0;
44843 + return HASH_KEY_IS_LONG;
44846 +void sqlite_iterator_move_forward(zend_object_iterator *iter TSRMLS_DC)
44848 + struct php_sqlite_result *res = ((sqlite_object_iterator*)iter)->res;
44850 + if (((sqlite_object_iterator*)iter)->value) {
44851 + zval_ptr_dtor(&((sqlite_object_iterator*)iter)->value);
44852 + ((sqlite_object_iterator*)iter)->value = NULL;
44855 + if (!res->buffered && res->vm) {
44856 + php_sqlite_fetch(res TSRMLS_CC);
44858 + if (res->curr_row >= res->nrows) {
44859 + /* php_error_docref(NULL TSRMLS_CC, E_WARNING, "no more rows available"); */
44867 +zend_object_iterator_funcs sqlite_ub_query_iterator_funcs = {
44868 + sqlite_iterator_dtor,
44869 + sqlite_iterator_valid,
44870 + sqlite_iterator_get_current_data,
44871 + sqlite_iterator_get_current_key,
44872 + sqlite_iterator_move_forward,
44876 +zend_object_iterator_funcs sqlite_query_iterator_funcs = {
44877 + sqlite_iterator_dtor,
44878 + sqlite_iterator_valid,
44879 + sqlite_iterator_get_current_data,
44880 + sqlite_iterator_get_current_key,
44881 + sqlite_iterator_move_forward,
44882 + sqlite_iterator_rewind
44885 +zend_object_iterator *sqlite_get_iterator(zend_class_entry *ce, zval *object, int by_ref TSRMLS_DC)
44887 + sqlite_object_iterator *iterator = emalloc(sizeof(sqlite_object_iterator));
44889 + sqlite_object *obj = (sqlite_object*) zend_object_store_get_object(object TSRMLS_CC);
44892 + zend_error(E_RECOVERABLE_ERROR, "An iterator cannot be used with foreach by reference");
44894 + Z_ADDREF_P(object);
44895 + iterator->it.data = (void*)object;
44896 + iterator->it.funcs = ce->iterator_funcs.funcs;
44897 + iterator->res = obj->u.res;
44898 + iterator->value = NULL;
44899 + return (zend_object_iterator*)iterator;
44903 +static PHP_GINIT_FUNCTION(sqlite)
44905 + sqlite_globals->assoc_case = 0;
44908 +PHP_MINIT_FUNCTION(sqlite)
44910 + REGISTER_SQLITE_CLASS(Database, db, NULL);
44911 + REGISTER_SQLITE_CLASS(Result, query, NULL);
44912 + REGISTER_SQLITE_CLASS(Unbuffered, ub_query, NULL);
44913 +#if defined(HAVE_SPL) && ((PHP_MAJOR_VERSION > 5) || (PHP_MAJOR_VERSION == 5 && PHP_MINOR_VERSION >= 1))
44914 + REGISTER_SQLITE_CLASS(Exception, exception, spl_ce_RuntimeException);
44916 + REGISTER_SQLITE_CLASS(Exception, exception, zend_exception_get_default(TSRMLS_C));
44919 + sqlite_ce_db->ce_flags &= ~ZEND_ACC_FINAL_CLASS;
44920 + sqlite_ce_db->constructor->common.fn_flags |= ZEND_ACC_FINAL;
44922 + sqlite_object_handlers_query.get_class_entry = sqlite_get_ce_query;
44923 + sqlite_object_handlers_ub_query.get_class_entry = sqlite_get_ce_ub_query;
44924 + sqlite_object_handlers_ub_query.count_elements = sqlite_count_elements;
44926 + sqlite_ce_ub_query->get_iterator = sqlite_get_iterator;
44927 + sqlite_ce_ub_query->iterator_funcs.funcs = &sqlite_ub_query_iterator_funcs;
44929 +#if defined(HAVE_SPL) && ((PHP_MAJOR_VERSION > 5) || (PHP_MAJOR_VERSION == 5 && PHP_MINOR_VERSION >= 1))
44930 + zend_class_implements(sqlite_ce_query TSRMLS_CC, 2, zend_ce_iterator, spl_ce_Countable);
44932 + zend_class_implements(sqlite_ce_query TSRMLS_CC, 1, zend_ce_iterator);
44934 + sqlite_ce_query->get_iterator = sqlite_get_iterator;
44935 + sqlite_ce_query->iterator_funcs.funcs = &sqlite_query_iterator_funcs;
44937 + REGISTER_INI_ENTRIES();
44939 +#if HAVE_PHP_SESSION && !defined(COMPILE_DL_SESSION)
44940 + php_session_register_module(ps_sqlite_ptr);
44943 + le_sqlite_db = zend_register_list_destructors_ex(php_sqlite_db_dtor, NULL, "sqlite database", module_number);
44944 + le_sqlite_pdb = zend_register_list_destructors_ex(NULL, php_sqlite_db_dtor, "sqlite database (persistent)", module_number);
44945 + le_sqlite_result = zend_register_list_destructors_ex(php_sqlite_result_dtor, NULL, "sqlite result", module_number);
44947 + REGISTER_LONG_CONSTANT("SQLITE_BOTH", PHPSQLITE_BOTH, CONST_CS|CONST_PERSISTENT);
44948 + REGISTER_LONG_CONSTANT("SQLITE_NUM", PHPSQLITE_NUM, CONST_CS|CONST_PERSISTENT);
44949 + REGISTER_LONG_CONSTANT("SQLITE_ASSOC", PHPSQLITE_ASSOC, CONST_CS|CONST_PERSISTENT);
44951 + REGISTER_LONG_CONSTANT("SQLITE_OK", SQLITE_OK, CONST_CS|CONST_PERSISTENT);
44952 + REGISTER_LONG_CONSTANT("SQLITE_ERROR", SQLITE_ERROR, CONST_CS|CONST_PERSISTENT);
44953 + REGISTER_LONG_CONSTANT("SQLITE_INTERNAL", SQLITE_INTERNAL, CONST_CS|CONST_PERSISTENT);
44954 + REGISTER_LONG_CONSTANT("SQLITE_PERM", SQLITE_PERM, CONST_CS|CONST_PERSISTENT);
44955 + REGISTER_LONG_CONSTANT("SQLITE_ABORT", SQLITE_ABORT, CONST_CS|CONST_PERSISTENT);
44956 + REGISTER_LONG_CONSTANT("SQLITE_BUSY", SQLITE_BUSY, CONST_CS|CONST_PERSISTENT);
44957 + REGISTER_LONG_CONSTANT("SQLITE_LOCKED", SQLITE_LOCKED, CONST_CS|CONST_PERSISTENT);
44958 + REGISTER_LONG_CONSTANT("SQLITE_NOMEM", SQLITE_NOMEM, CONST_CS|CONST_PERSISTENT);
44959 + REGISTER_LONG_CONSTANT("SQLITE_READONLY", SQLITE_READONLY, CONST_CS|CONST_PERSISTENT);
44960 + REGISTER_LONG_CONSTANT("SQLITE_INTERRUPT", SQLITE_INTERRUPT, CONST_CS|CONST_PERSISTENT);
44961 + REGISTER_LONG_CONSTANT("SQLITE_IOERR", SQLITE_IOERR, CONST_CS|CONST_PERSISTENT);
44962 + REGISTER_LONG_CONSTANT("SQLITE_CORRUPT", SQLITE_CORRUPT, CONST_CS|CONST_PERSISTENT);
44963 + REGISTER_LONG_CONSTANT("SQLITE_NOTFOUND", SQLITE_NOTFOUND, CONST_CS|CONST_PERSISTENT);
44964 + REGISTER_LONG_CONSTANT("SQLITE_FULL", SQLITE_FULL, CONST_CS|CONST_PERSISTENT);
44965 + REGISTER_LONG_CONSTANT("SQLITE_CANTOPEN", SQLITE_CANTOPEN, CONST_CS|CONST_PERSISTENT);
44966 + REGISTER_LONG_CONSTANT("SQLITE_PROTOCOL", SQLITE_PROTOCOL, CONST_CS|CONST_PERSISTENT);
44967 + REGISTER_LONG_CONSTANT("SQLITE_EMPTY", SQLITE_EMPTY, CONST_CS|CONST_PERSISTENT);
44968 + REGISTER_LONG_CONSTANT("SQLITE_SCHEMA", SQLITE_SCHEMA, CONST_CS|CONST_PERSISTENT);
44969 + REGISTER_LONG_CONSTANT("SQLITE_TOOBIG", SQLITE_TOOBIG, CONST_CS|CONST_PERSISTENT);
44970 + REGISTER_LONG_CONSTANT("SQLITE_CONSTRAINT", SQLITE_CONSTRAINT, CONST_CS|CONST_PERSISTENT);
44971 + REGISTER_LONG_CONSTANT("SQLITE_MISMATCH", SQLITE_MISMATCH, CONST_CS|CONST_PERSISTENT);
44972 + REGISTER_LONG_CONSTANT("SQLITE_MISUSE", SQLITE_MISUSE, CONST_CS|CONST_PERSISTENT);
44973 + REGISTER_LONG_CONSTANT("SQLITE_NOLFS", SQLITE_NOLFS, CONST_CS|CONST_PERSISTENT);
44974 + REGISTER_LONG_CONSTANT("SQLITE_AUTH", SQLITE_AUTH, CONST_CS|CONST_PERSISTENT);
44975 + REGISTER_LONG_CONSTANT("SQLITE_NOTADB", SQLITE_NOTADB, CONST_CS|CONST_PERSISTENT);
44976 +#ifdef SQLITE_FORMAT
44977 + REGISTER_LONG_CONSTANT("SQLITE_FORMAT", SQLITE_FORMAT, CONST_CS|CONST_PERSISTENT);
44979 + REGISTER_LONG_CONSTANT("SQLITE_ROW", SQLITE_ROW, CONST_CS|CONST_PERSISTENT);
44980 + REGISTER_LONG_CONSTANT("SQLITE_DONE", SQLITE_DONE, CONST_CS|CONST_PERSISTENT);
44982 +#ifdef PHP_SQLITE2_HAVE_PDO
44983 + if (FAILURE == php_pdo_register_driver(&pdo_sqlite2_driver)) {
44991 +PHP_MSHUTDOWN_FUNCTION(sqlite)
44993 + UNREGISTER_INI_ENTRIES();
44995 +#ifdef PHP_SQLITE2_HAVE_PDO
44996 + php_pdo_unregister_driver(&pdo_sqlite2_driver);
45002 +PHP_MINFO_FUNCTION(sqlite)
45004 + php_info_print_table_start();
45005 + php_info_print_table_header(2, "SQLite support", "enabled");
45006 + php_info_print_table_row(2, "PECL Module version", PHP_SQLITE_MODULE_VERSION " $Id$");
45007 + php_info_print_table_row(2, "SQLite Library", sqlite_libversion());
45008 + php_info_print_table_row(2, "SQLite Encoding", sqlite_libencoding());
45009 + php_info_print_table_end();
45011 + DISPLAY_INI_ENTRIES();
45014 +static struct php_sqlite_db *php_sqlite_open(char *filename, int mode, char *persistent_id, zval *return_value, zval *errmsg, zval *object TSRMLS_DC)
45016 + char *errtext = NULL;
45017 + sqlite *sdb = NULL;
45018 + struct php_sqlite_db *db = NULL;
45020 + sdb = sqlite_open(filename, mode, &errtext);
45022 + if (sdb == NULL) {
45024 + php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s", errtext);
45027 + ZVAL_STRING(errmsg, errtext, 1);
45030 + sqlite_freemem(errtext);
45032 + /* if object is not an object then we're called from the factory() function */
45033 + if (object && Z_TYPE_P(object) != IS_OBJECT) {
45041 + db = (struct php_sqlite_db *)pemalloc(sizeof(struct php_sqlite_db), persistent_id ? 1 : 0);
45042 + db->is_persistent = persistent_id ? 1 : 0;
45043 + db->last_err_code = SQLITE_OK;
45046 + zend_hash_init(&db->callbacks, 0, NULL, php_sqlite_callback_dtor, db->is_persistent);
45048 + /* register the PHP functions */
45049 + sqlite_create_function(sdb, "php", -1, php_sqlite_generic_function_callback, 0);
45051 + /* set default busy handler; keep retrying up until 1 minute has passed,
45052 + * then fail with a busy status code */
45053 + sqlite_busy_timeout(sdb, 60000);
45055 + /* authorizer hook so we can enforce safe mode
45056 + * Note: the declaration of php_sqlite_authorizer is correct for 2.8.2 of libsqlite,
45057 + * and IS backwards binary compatible with earlier versions */
45058 + if (PG(safe_mode) || (PG(open_basedir) && *PG(open_basedir))) {
45059 + sqlite_set_authorizer(sdb, php_sqlite_authorizer, NULL);
45062 + db->rsrc_id = ZEND_REGISTER_RESOURCE(object ? NULL : return_value, db, persistent_id ? le_sqlite_pdb : le_sqlite_db);
45064 + /* if object is not an object then we're called from the factory() function */
45065 + if (Z_TYPE_P(object) != IS_OBJECT) {
45066 + sqlite_instanciate(sqlite_ce_db, object TSRMLS_CC);
45068 + /* and now register the object */
45069 + SQLITE_REGISTER_OBJECT(db, object, db)
45072 + if (persistent_id) {
45073 + zend_rsrc_list_entry le;
45075 + Z_TYPE(le) = le_sqlite_pdb;
45078 + if (FAILURE == zend_hash_update(&EG(persistent_list), persistent_id,
45079 + strlen(persistent_id)+1,
45080 + (void *)&le, sizeof(le), NULL)) {
45081 + php_error_docref(NULL TSRMLS_CC, E_WARNING, "Failed to register persistent resource");
45088 +/* {{{ proto resource sqlite_popen(string filename [, int mode [, string &error_message]])
45089 + Opens a persistent handle to a SQLite database. Will create the database if it does not exist. */
45090 +PHP_FUNCTION(sqlite_popen)
45092 + long mode = 0666;
45093 + char *filename, *fullpath, *hashkey;
45094 + int filename_len, hashkeylen;
45095 + zval *errmsg = NULL;
45096 + struct php_sqlite_db *db = NULL;
45097 + zend_rsrc_list_entry *le;
45099 + if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|lz/",
45100 + &filename, &filename_len, &mode, &errmsg)) {
45104 + zval_dtor(errmsg);
45105 + ZVAL_NULL(errmsg);
45108 + if (strlen(filename) != filename_len) {
45111 + if (strncmp(filename, ":memory:", sizeof(":memory:") - 1)) {
45112 + /* resolve the fully-qualified path name to use as the hash key */
45113 + if (!(fullpath = expand_filepath(filename, NULL TSRMLS_CC))) {
45117 + if ((PG(safe_mode) && (!php_checkuid(fullpath, NULL, CHECKUID_CHECK_FILE_AND_DIR))) ||
45118 + php_check_open_basedir(fullpath TSRMLS_CC)) {
45123 + fullpath = estrndup(filename, filename_len);
45126 + hashkeylen = spprintf(&hashkey, 0, "sqlite_pdb_%s:%ld", fullpath, mode);
45128 + /* do we have an existing persistent connection ? */
45129 + if (SUCCESS == zend_hash_find(&EG(persistent_list), hashkey, hashkeylen+1, (void*)&le)) {
45130 + if (Z_TYPE_P(le) == le_sqlite_pdb) {
45131 + db = (struct php_sqlite_db*)le->ptr;
45133 + if (db->rsrc_id == FAILURE) {
45134 + /* give it a valid resource id for this request */
45135 + db->rsrc_id = ZEND_REGISTER_RESOURCE(return_value, db, le_sqlite_pdb);
45138 + /* sanity check to ensure that the resource is still a valid regular resource
45140 + if (zend_list_find(db->rsrc_id, &type) == db) {
45141 + /* already accessed this request; map it */
45142 + zend_list_addref(db->rsrc_id);
45143 + ZVAL_RESOURCE(return_value, db->rsrc_id);
45145 + db->rsrc_id = ZEND_REGISTER_RESOURCE(return_value, db, le_sqlite_pdb);
45153 + php_error_docref(NULL TSRMLS_CC, E_WARNING, "Some other type of persistent resource is using this hash key!?");
45158 + /* now we need to open the database */
45159 + php_sqlite_open(fullpath, (int)mode, hashkey, return_value, errmsg, NULL TSRMLS_CC);
45166 +/* {{{ proto resource sqlite_open(string filename [, int mode [, string &error_message]])
45167 + Opens a SQLite database. Will create the database if it does not exist. */
45168 +PHP_FUNCTION(sqlite_open)
45170 + long mode = 0666;
45171 + char *filename, *fullpath = NULL;
45172 + int filename_len;
45173 + zval *errmsg = NULL;
45174 + zval *object = getThis();
45175 + zend_error_handling error_handling;
45177 + zend_replace_error_handling(object ? EH_THROW : EH_NORMAL, sqlite_ce_exception, &error_handling TSRMLS_CC);
45178 + if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|lz/",
45179 + &filename, &filename_len, &mode, &errmsg)) {
45180 + zend_restore_error_handling(&error_handling TSRMLS_CC);
45184 + zval_dtor(errmsg);
45185 + ZVAL_NULL(errmsg);
45188 + if (strlen(filename) != filename_len) {
45189 + zend_restore_error_handling(&error_handling TSRMLS_CC);
45193 + if (strncmp(filename, ":memory:", sizeof(":memory:") - 1)) {
45194 + /* resolve the fully-qualified path name to use as the hash key */
45195 + if (!(fullpath = expand_filepath(filename, NULL TSRMLS_CC))) {
45196 + zend_restore_error_handling(&error_handling TSRMLS_CC);
45204 + if ((PG(safe_mode) && (!php_checkuid(fullpath, NULL, CHECKUID_CHECK_FILE_AND_DIR))) ||
45205 + php_check_open_basedir(fullpath TSRMLS_CC)) {
45207 + zend_restore_error_handling(&error_handling TSRMLS_CC);
45216 + php_sqlite_open(fullpath ? fullpath : filename, (int)mode, NULL, return_value, errmsg, object TSRMLS_CC);
45221 + zend_restore_error_handling(&error_handling TSRMLS_CC);
45225 +/* {{{ proto object sqlite_factory(string filename [, int mode [, string &error_message]])
45226 + Opens a SQLite database and creates an object for it. Will create the database if it does not exist. */
45227 +PHP_FUNCTION(sqlite_factory)
45229 + long mode = 0666;
45230 + char *filename, *fullpath = NULL;
45231 + int filename_len;
45232 + zval *errmsg = NULL;
45233 + zend_error_handling error_handling;
45235 + zend_replace_error_handling(EH_THROW, sqlite_ce_exception, &error_handling TSRMLS_CC);
45236 + if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|lz/",
45237 + &filename, &filename_len, &mode, &errmsg)) {
45238 + zend_restore_error_handling(&error_handling TSRMLS_CC);
45242 + zval_dtor(errmsg);
45243 + ZVAL_NULL(errmsg);
45246 + if (strlen(filename) != filename_len) {
45247 + zend_restore_error_handling(&error_handling TSRMLS_CC);
45251 + if (strncmp(filename, ":memory:", sizeof(":memory:") - 1)) {
45252 + /* resolve the fully-qualified path name to use as the hash key */
45253 + if (!(fullpath = expand_filepath(filename, NULL TSRMLS_CC))) {
45254 + zend_restore_error_handling(&error_handling TSRMLS_CC);
45258 + if ((PG(safe_mode) && (!php_checkuid(fullpath, NULL, CHECKUID_CHECK_FILE_AND_DIR))) ||
45259 + php_check_open_basedir(fullpath TSRMLS_CC)) {
45261 + zend_restore_error_handling(&error_handling TSRMLS_CC);
45266 + php_sqlite_open(fullpath ? fullpath : filename, (int)mode, NULL, return_value, errmsg, return_value TSRMLS_CC);
45270 + zend_restore_error_handling(&error_handling TSRMLS_CC);
45274 +/* {{{ proto void sqlite_busy_timeout(resource db, int ms)
45275 + Set busy timeout duration. If ms <= 0, all busy handlers are disabled. */
45276 +PHP_FUNCTION(sqlite_busy_timeout)
45279 + struct php_sqlite_db *db;
45281 + zval *object = getThis();
45284 + if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &ms)) {
45287 + DB_FROM_OBJECT(db, object);
45289 + if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rl", &zdb, &ms)) {
45292 + DB_FROM_ZVAL(db, &zdb);
45295 + sqlite_busy_timeout(db->db, ms);
45299 +/* {{{ proto void sqlite_close(resource db)
45300 + Closes an open sqlite database. */
45301 +PHP_FUNCTION(sqlite_close)
45304 + struct php_sqlite_db *db;
45305 + zval *object = getThis();
45308 + php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Ignored, you must destruct the object instead");
45310 + if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &zdb)) {
45313 + DB_FROM_ZVAL(db, &zdb);
45316 + zend_hash_apply_with_argument(&EG(regular_list),
45317 + (apply_func_arg_t) _clean_unfinished_results,
45320 + zend_list_delete(Z_RESVAL_P(zdb));
45324 +/* {{{ php_sqlite_fetch */
45325 +static int php_sqlite_fetch(struct php_sqlite_result *rres TSRMLS_DC)
45327 + const char **rowdata, **colnames;
45328 + int ret, i, base;
45329 + char *errtext = NULL;
45332 + ret = sqlite_step(rres->vm, &rres->ncolumns, &rowdata, &colnames);
45333 + if (!rres->nrows) {
45334 + /* first row - lets copy the column names */
45335 + rres->col_names = safe_emalloc(rres->ncolumns, sizeof(char *), 0);
45336 + for (i = 0; i < rres->ncolumns; i++) {
45337 + rres->col_names[i] = estrdup((char*)colnames[i]);
45339 + if (SQLITE_G(assoc_case) == 1) {
45340 + php_sqlite_strtoupper(rres->col_names[i]);
45341 + } else if (SQLITE_G(assoc_case) == 2) {
45342 + php_sqlite_strtolower(rres->col_names[i]);
45345 + if (!rres->buffered) {
45346 + /* non buffered mode - also fetch memory for on single row */
45347 + rres->table = safe_emalloc(rres->ncolumns, sizeof(char *), 0);
45353 + if (rres->buffered) {
45354 + /* add the row to our collection */
45355 + if (rres->nrows + 1 >= rres->alloc_rows) {
45356 + rres->alloc_rows = rres->alloc_rows ? rres->alloc_rows * 2 : 16;
45357 + rres->table = safe_erealloc(rres->table, rres->alloc_rows, rres->ncolumns*sizeof(char *), 0);
45359 + base = rres->nrows * rres->ncolumns;
45360 + for (i = 0; i < rres->ncolumns; i++) {
45361 + if (rowdata[i]) {
45362 + rres->table[base + i] = estrdup(rowdata[i]);
45364 + rres->table[base + i] = NULL;
45370 + /* non buffered: only fetch one row but first free data if not first row */
45371 + if (rres->nrows++) {
45372 + for (i = 0; i < rres->ncolumns; i++) {
45373 + if (rres->table[i]) {
45374 + efree(rres->table[i]);
45378 + for (i = 0; i < rres->ncolumns; i++) {
45379 + if (rowdata[i]) {
45380 + rres->table[i] = estrdup(rowdata[i]);
45382 + rres->table[i] = NULL;
45389 + case SQLITE_BUSY:
45390 + case SQLITE_ERROR:
45391 + case SQLITE_MISUSE:
45392 + case SQLITE_DONE:
45395 + ret = sqlite_finalize(rres->vm, &errtext);
45398 + if (ret != SQLITE_OK) {
45399 + php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s", errtext);
45400 + sqlite_freemem(errtext);
45404 + rres->db->last_err_code = ret;
45410 +/* {{{ sqlite_query */
45411 +void sqlite_query(zval *object, struct php_sqlite_db *db, char *sql, long sql_len, int mode, int buffered, zval *return_value, struct php_sqlite_result **prres, zval *errmsg TSRMLS_DC)
45413 + struct php_sqlite_result res, *rres;
45415 + char *errtext = NULL;
45416 + const char *tail;
45418 + memset(&res, 0, sizeof(res));
45419 + res.buffered = buffered;
45422 + ret = sqlite_compile(db->db, sql, &tail, &res.vm, &errtext);
45423 + db->last_err_code = ret;
45425 + if (ret != SQLITE_OK) {
45426 + php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s", errtext);
45428 + ZVAL_STRING(errmsg, errtext, 1);
45430 + sqlite_freemem(errtext);
45432 + } else if (!res.vm) { /* empty query */
45434 + if (return_value) {
45446 + *prres = (struct php_sqlite_result*)emalloc(sizeof(**prres));
45448 + memcpy(*prres, &res, sizeof(**prres));
45449 + (*prres)->db = db;
45450 + zend_list_addref(db->rsrc_id);
45453 + /* now the result set is ready for stepping: get first row */
45454 + if (php_sqlite_fetch((*prres) TSRMLS_CC) != SQLITE_OK) {
45455 + real_result_dtor((*prres) TSRMLS_CC);
45457 + if (return_value) {
45464 + (*prres)->curr_row = 0;
45467 + sqlite_object *obj;
45469 + sqlite_instanciate(sqlite_ce_query, return_value TSRMLS_CC);
45471 + sqlite_instanciate(sqlite_ce_ub_query, return_value TSRMLS_CC);
45473 + obj = (sqlite_object *) zend_object_store_get_object(return_value TSRMLS_CC);
45474 + obj->type = is_result;
45475 + obj->u.res = (*prres);
45476 + } else if (return_value) {
45477 + ZEND_REGISTER_RESOURCE(object ? NULL : return_value, (*prres), le_sqlite_result);
45482 +/* {{{ proto resource sqlite_unbuffered_query(string query, resource db [ , int result_type [, string &error_message]])
45483 + Executes a query that does not prefetch and buffer all data. */
45484 +PHP_FUNCTION(sqlite_unbuffered_query)
45487 + struct php_sqlite_db *db;
45490 + long mode = PHPSQLITE_BOTH;
45491 + char *errtext = NULL;
45492 + zval *errmsg = NULL;
45493 + zval *object = getThis();
45496 + if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|lz/", &sql, &sql_len, &mode, &errmsg)) {
45499 + DB_FROM_OBJECT(db, object);
45501 + if (FAILURE == zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET,
45502 + ZEND_NUM_ARGS() TSRMLS_CC, "sr|lz/", &sql, &sql_len, &zdb, &mode, &errmsg) &&
45503 + FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rs|lz/", &zdb, &sql, &sql_len, &mode, &errmsg)) {
45506 + DB_FROM_ZVAL(db, &zdb);
45510 + zval_dtor(errmsg);
45511 + ZVAL_NULL(errmsg);
45514 + PHP_SQLITE_EMPTY_QUERY;
45516 + /* avoid doing work if we can */
45517 + if (!return_value_used) {
45518 + db->last_err_code = sqlite_exec(db->db, sql, NULL, NULL, &errtext);
45520 + if (db->last_err_code != SQLITE_OK) {
45521 + php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s", errtext);
45523 + ZVAL_STRING(errmsg, errtext, 1);
45525 + sqlite_freemem(errtext);
45530 + sqlite_query(object, db, sql, sql_len, (int)mode, 0, return_value, NULL, errmsg TSRMLS_CC);
45534 +/* {{{ proto resource sqlite_fetch_column_types(string table_name, resource db [, int result_type])
45535 + Return an array of column types from a particular table. */
45536 +PHP_FUNCTION(sqlite_fetch_column_types)
45539 + struct php_sqlite_db *db;
45542 + char *errtext = NULL;
45543 + zval *object = getThis();
45544 + struct php_sqlite_result res;
45545 + const char **rowdata, **colnames, *tail;
45547 + long result_type = PHPSQLITE_ASSOC;
45550 + if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|l", &tbl, &tbl_len, &result_type)) {
45553 + DB_FROM_OBJECT(db, object);
45555 + if (FAILURE == zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET,
45556 + ZEND_NUM_ARGS() TSRMLS_CC, "sr|l", &tbl, &tbl_len, &zdb, &result_type) &&
45557 + FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rs|l", &zdb, &tbl, &tbl_len, &result_type)) {
45560 + DB_FROM_ZVAL(db, &zdb);
45563 + if (!(sql = sqlite_mprintf("SELECT * FROM '%q' LIMIT 1", tbl))) {
45567 + sqlite_exec(db->db, "PRAGMA show_datatypes = ON", NULL, NULL, NULL);
45569 + db->last_err_code = sqlite_compile(db->db, sql, &tail, &res.vm, &errtext);
45571 + sqlite_freemem(sql);
45573 + if (db->last_err_code != SQLITE_OK) {
45574 + php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s", errtext);
45575 + sqlite_freemem(errtext);
45580 + sqlite_step(res.vm, &ncols, &rowdata, &colnames);
45582 + array_init(return_value);
45584 + for (i = 0; i < ncols; i++) {
45585 + if (result_type == PHPSQLITE_ASSOC) {
45586 + char *colname = estrdup((char *)colnames[i]);
45588 + if (SQLITE_G(assoc_case) == 1) {
45589 + php_sqlite_strtoupper(colname);
45590 + } else if (SQLITE_G(assoc_case) == 2) {
45591 + php_sqlite_strtolower(colname);
45594 + add_assoc_string(return_value, colname, colnames[ncols + i] ? (char *)colnames[ncols + i] : "", 1);
45597 + if (result_type == PHPSQLITE_NUM) {
45598 + add_index_string(return_value, i, colnames[ncols + i] ? (char *)colnames[ncols + i] : "", 1);
45602 + sqlite_finalize(res.vm, NULL);
45605 + sqlite_exec(db->db, "PRAGMA show_datatypes = OFF", NULL, NULL, NULL);
45609 +/* {{{ proto resource sqlite_query(string query, resource db [, int result_type [, string &error_message]])
45610 + Executes a query against a given database and returns a result handle. */
45611 +PHP_FUNCTION(sqlite_query)
45614 + struct php_sqlite_db *db;
45617 + long mode = PHPSQLITE_BOTH;
45618 + char *errtext = NULL;
45619 + zval *errmsg = NULL;
45620 + zval *object = getThis();
45623 + if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|lz/", &sql, &sql_len, &mode, &errmsg)) {
45626 + DB_FROM_OBJECT(db, object);
45628 + if (FAILURE == zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET,
45629 + ZEND_NUM_ARGS() TSRMLS_CC, "sr|lz/", &sql, &sql_len, &zdb, &mode, &errmsg) &&
45630 + FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rs|lz/", &zdb, &sql, &sql_len, &mode, &errmsg)) {
45633 + DB_FROM_ZVAL(db, &zdb);
45637 + zval_dtor(errmsg);
45638 + ZVAL_NULL(errmsg);
45641 + PHP_SQLITE_EMPTY_QUERY;
45643 + /* avoid doing work if we can */
45644 + if (!return_value_used) {
45645 + db->last_err_code = sqlite_exec(db->db, sql, NULL, NULL, &errtext);
45647 + if (db->last_err_code != SQLITE_OK) {
45648 + php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s", errtext);
45650 + ZVAL_STRING(errmsg, errtext, 1);
45652 + sqlite_freemem(errtext);
45657 + sqlite_query(object, db, sql, sql_len, (int)mode, 1, return_value, NULL, errmsg TSRMLS_CC);
45661 +/* {{{ proto boolean sqlite_exec(string query, resource db[, string &error_message])
45662 + Executes a result-less query against a given database */
45663 +PHP_FUNCTION(sqlite_exec)
45666 + struct php_sqlite_db *db;
45669 + char *errtext = NULL;
45670 + zval *errmsg = NULL;
45671 + zval *object = getThis();
45674 + if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|z/", &sql, &sql_len, &errmsg)) {
45677 + DB_FROM_OBJECT(db, object);
45679 + if(FAILURE == zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET,
45680 + ZEND_NUM_ARGS() TSRMLS_CC, "sr", &sql, &sql_len, &zdb) &&
45681 + FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rs|z/", &zdb, &sql, &sql_len, &errmsg)) {
45684 + DB_FROM_ZVAL(db, &zdb);
45688 + zval_dtor(errmsg);
45689 + ZVAL_NULL(errmsg);
45692 + PHP_SQLITE_EMPTY_QUERY;
45694 + db->last_err_code = sqlite_exec(db->db, sql, NULL, NULL, &errtext);
45696 + if (db->last_err_code != SQLITE_OK) {
45697 + php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s", errtext);
45699 + ZVAL_STRING(errmsg, errtext, 1);
45701 + sqlite_freemem(errtext);
45709 +/* {{{ php_sqlite_fetch_array */
45710 +static void php_sqlite_fetch_array(struct php_sqlite_result *res, int mode, zend_bool decode_binary, int move_next, zval *return_value TSRMLS_DC)
45712 + int j, n = res->ncolumns, buffered = res->buffered;
45713 + const char **rowdata, **colnames;
45715 + /* check range of the row */
45716 + if (res->curr_row >= res->nrows) {
45720 + colnames = (const char**)res->col_names;
45721 + if (res->buffered) {
45722 + rowdata = (const char**)&res->table[res->curr_row * res->ncolumns];
45724 + rowdata = (const char**)res->table;
45727 + /* now populate the result */
45728 + array_init(return_value);
45730 + for (j = 0; j < n; j++) {
45732 + MAKE_STD_ZVAL(decoded);
45734 + if (rowdata[j] == NULL) {
45735 + ZVAL_NULL(decoded);
45736 + } else if (decode_binary && rowdata[j][0] == '\x01') {
45737 + Z_STRVAL_P(decoded) = emalloc(strlen(rowdata[j]));
45738 + Z_STRLEN_P(decoded) = php_sqlite_decode_binary(rowdata[j]+1, Z_STRVAL_P(decoded));
45739 + Z_STRVAL_P(decoded)[Z_STRLEN_P(decoded)] = '\0';
45740 + Z_TYPE_P(decoded) = IS_STRING;
45742 + efree((char*)rowdata[j]);
45743 + rowdata[j] = NULL;
45746 + ZVAL_STRING(decoded, (char*)rowdata[j], buffered);
45748 + rowdata[j] = NULL;
45752 + if (mode & PHPSQLITE_NUM) {
45753 + if (mode & PHPSQLITE_ASSOC) {
45754 + add_index_zval(return_value, j, decoded);
45755 + Z_ADDREF_P(decoded);
45756 + add_assoc_zval(return_value, (char*)colnames[j], decoded);
45758 + add_next_index_zval(return_value, decoded);
45761 + add_assoc_zval(return_value, (char*)colnames[j], decoded);
45766 + if (!res->buffered) {
45767 + /* non buffered: fetch next row */
45768 + php_sqlite_fetch(res TSRMLS_CC);
45770 + /* advance the row pointer */
45776 +/* {{{ php_sqlite_fetch_column */
45777 +static void php_sqlite_fetch_column(struct php_sqlite_result *res, zval *which, zend_bool decode_binary, zval *return_value TSRMLS_DC)
45780 + const char **rowdata, **colnames;
45782 + /* check range of the row */
45783 + if (res->curr_row >= res->nrows) {
45787 + colnames = (const char**)res->col_names;
45789 + if (Z_TYPE_P(which) == IS_LONG) {
45790 + j = Z_LVAL_P(which);
45792 + convert_to_string_ex(&which);
45793 + for (j = 0; j < res->ncolumns; j++) {
45794 + if (!strcasecmp((char*)colnames[j], Z_STRVAL_P(which))) {
45799 + if (j < 0 || j >= res->ncolumns) {
45800 + php_error_docref(NULL TSRMLS_CC, E_WARNING, "No such column %d", j);
45804 + if (res->buffered) {
45805 + rowdata = (const char**)&res->table[res->curr_row * res->ncolumns];
45807 + rowdata = (const char**)res->table;
45810 + if (rowdata[j] == NULL) {
45812 + } else if (decode_binary && rowdata[j] != NULL && rowdata[j][0] == '\x01') {
45813 + int l = strlen(rowdata[j]);
45814 + char *decoded = emalloc(l);
45815 + l = php_sqlite_decode_binary(rowdata[j]+1, decoded);
45816 + decoded[l] = '\0';
45817 + RETVAL_STRINGL(decoded, l, 0);
45818 + if (!res->buffered) {
45819 + efree((char*)rowdata[j]);
45820 + rowdata[j] = NULL;
45823 + RETVAL_STRING((char*)rowdata[j], res->buffered);
45824 + if (!res->buffered) {
45825 + rowdata[j] = NULL;
45831 +/* {{{ proto array sqlite_fetch_all(resource result [, int result_type [, bool decode_binary]])
45832 + Fetches all rows from a result set as an array of arrays. */
45833 +PHP_FUNCTION(sqlite_fetch_all)
45835 + zval *zres, *ent;
45836 + long mode = PHPSQLITE_BOTH;
45837 + zend_bool decode_binary = 1;
45838 + struct php_sqlite_result *res;
45839 + zval *object = getThis();
45842 + if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|lb", &mode, &decode_binary)) {
45845 + RES_FROM_OBJECT(res, object);
45846 + if (!ZEND_NUM_ARGS()) {
45847 + mode = res->mode;
45850 + if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r|lb", &zres, &mode, &decode_binary)) {
45853 + ZEND_FETCH_RESOURCE(res, struct php_sqlite_result *, &zres, -1, "sqlite result", le_sqlite_result);
45854 + if (ZEND_NUM_ARGS() < 2) {
45855 + mode = res->mode;
45859 + if (res->curr_row >= res->nrows && res->nrows) {
45860 + if (!res->buffered) {
45861 + php_error_docref(NULL TSRMLS_CC, E_WARNING, "One or more rowsets were already returned; returning NULL this time");
45863 + res->curr_row = 0;
45867 + array_init(return_value);
45869 + while (res->curr_row < res->nrows) {
45870 + MAKE_STD_ZVAL(ent);
45871 + php_sqlite_fetch_array(res, mode, decode_binary, 1, ent TSRMLS_CC);
45872 + add_next_index_zval(return_value, ent);
45877 +/* {{{ proto array sqlite_fetch_array(resource result [, int result_type [, bool decode_binary]])
45878 + Fetches the next row from a result set as an array. */
45879 +PHP_FUNCTION(sqlite_fetch_array)
45882 + long mode = PHPSQLITE_BOTH;
45883 + zend_bool decode_binary = 1;
45884 + struct php_sqlite_result *res;
45885 + zval *object = getThis();
45888 + if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|lb", &mode, &decode_binary)) {
45891 + RES_FROM_OBJECT(res, object);
45892 + if (!ZEND_NUM_ARGS()) {
45893 + mode = res->mode;
45896 + if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r|lb", &zres, &mode, &decode_binary)) {
45899 + ZEND_FETCH_RESOURCE(res, struct php_sqlite_result *, &zres, -1, "sqlite result", le_sqlite_result);
45900 + if (ZEND_NUM_ARGS() < 2) {
45901 + mode = res->mode;
45905 + php_sqlite_fetch_array(res, mode, decode_binary, 1, return_value TSRMLS_CC);
45909 +/* {{{ proto object sqlite_fetch_object(resource result [, string class_name [, NULL|array ctor_params [, bool decode_binary]]])
45910 + Fetches the next row from a result set as an object. */
45911 + /* note that you can do array(&$val) for param ctor_params */
45912 +PHP_FUNCTION(sqlite_fetch_object)
45915 + zend_bool decode_binary = 1;
45916 + struct php_sqlite_result *res;
45917 + zval *object = getThis();
45918 + char *class_name = NULL;
45919 + int class_name_len;
45920 + zend_class_entry *ce;
45922 + zend_fcall_info fci;
45923 + zend_fcall_info_cache fcc;
45924 + zval *retval_ptr;
45925 + zval *ctor_params = NULL;
45926 + zend_error_handling error_handling;
45928 + zend_replace_error_handling(object ? EH_THROW : EH_NORMAL, sqlite_ce_exception, &error_handling TSRMLS_CC);
45930 + if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|szb", &class_name, &class_name_len, &ctor_params, &decode_binary)) {
45931 + zend_restore_error_handling(&error_handling TSRMLS_CC);
45934 + RES_FROM_OBJECT_RESTORE_ERH(res, object, &error_handling);
45935 + if (!class_name) {
45936 + ce = zend_standard_class_def;
45938 + ce = zend_fetch_class(class_name, class_name_len, ZEND_FETCH_CLASS_AUTO TSRMLS_CC);
45941 + if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r|szb", &zres, &class_name, &class_name_len, &ctor_params, &decode_binary)) {
45942 + zend_restore_error_handling(&error_handling TSRMLS_CC);
45945 + ZEND_FETCH_RESOURCE(res, struct php_sqlite_result *, &zres, -1, "sqlite result", le_sqlite_result);
45946 + if (!class_name) {
45947 + ce = zend_standard_class_def;
45949 + ce = zend_fetch_class(class_name, class_name_len, ZEND_FETCH_CLASS_AUTO TSRMLS_CC);
45954 + zend_throw_exception_ex(sqlite_ce_exception, 0 TSRMLS_CC, "Could not find class '%s'", class_name);
45955 + zend_restore_error_handling(&error_handling TSRMLS_CC);
45959 + if (res->curr_row < res->nrows) {
45960 + php_sqlite_fetch_array(res, PHPSQLITE_ASSOC, decode_binary, 1, &dataset TSRMLS_CC);
45962 + zend_restore_error_handling(&error_handling TSRMLS_CC);
45966 + object_and_properties_init(return_value, ce, NULL);
45967 + zend_merge_properties(return_value, Z_ARRVAL(dataset), 1 TSRMLS_CC);
45969 + zend_restore_error_handling(&error_handling TSRMLS_CC);
45971 + if (ce->constructor) {
45972 + fci.size = sizeof(fci);
45973 + fci.function_table = &ce->function_table;
45974 + fci.function_name = NULL;
45975 + fci.symbol_table = NULL;
45976 + fci.object_ptr = return_value;
45977 + fci.retval_ptr_ptr = &retval_ptr;
45978 + if (ctor_params && Z_TYPE_P(ctor_params) != IS_NULL) {
45979 + if (Z_TYPE_P(ctor_params) == IS_ARRAY) {
45980 + HashTable *ht = Z_ARRVAL_P(ctor_params);
45983 + fci.param_count = 0;
45984 + fci.params = safe_emalloc(sizeof(zval*), ht->nNumOfElements, 0);
45985 + p = ht->pListHead;
45986 + while (p != NULL) {
45987 + fci.params[fci.param_count++] = (zval**)p->pData;
45988 + p = p->pListNext;
45991 + /* Two problems why we throw exceptions here: PHP is typeless
45992 + * and hence passing one argument that's not an array could be
45993 + * by mistake and the other way round is possible, too. The
45994 + * single value is an array. Also we'd have to make that one
45995 + * argument passed by reference.
45997 + zend_throw_exception(sqlite_ce_exception, "Parameter ctor_params must be an array", 0 TSRMLS_CC);
46001 + fci.param_count = 0;
46002 + fci.params = NULL;
46004 + fci.no_separation = 1;
46006 + fcc.initialized = 1;
46007 + fcc.function_handler = ce->constructor;
46008 + fcc.calling_scope = EG(scope);
46009 + fcc.called_scope = Z_OBJCE_P(return_value);
46010 + fcc.object_ptr = return_value;
46012 + if (zend_call_function(&fci, &fcc TSRMLS_CC) == FAILURE) {
46013 + zend_throw_exception_ex(sqlite_ce_exception, 0 TSRMLS_CC, "Could not execute %s::%s()", class_name, ce->constructor->common.function_name);
46015 + if (retval_ptr) {
46016 + zval_ptr_dtor(&retval_ptr);
46019 + if (fci.params) {
46020 + efree(fci.params);
46022 + } else if (ctor_params && Z_TYPE_P(ctor_params) != IS_NULL) {
46023 + zend_throw_exception_ex(sqlite_ce_exception, 0 TSRMLS_CC, "Class %s does not have a constructor, use NULL for parameter ctor_params or omit it", class_name);
46028 +/* {{{ proto array sqlite_array_query(resource db, string query [ , int result_type [, bool decode_binary]])
46029 + Executes a query against a given database and returns an array of arrays. */
46030 +PHP_FUNCTION(sqlite_array_query)
46033 + struct php_sqlite_db *db;
46034 + struct php_sqlite_result *rres;
46037 + long mode = PHPSQLITE_BOTH;
46038 + char *errtext = NULL;
46039 + zend_bool decode_binary = 1;
46040 + zval *object = getThis();
46043 + if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|lb", &sql, &sql_len, &mode, &decode_binary)) {
46046 + DB_FROM_OBJECT(db, object);
46048 + if (FAILURE == zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET,
46049 + ZEND_NUM_ARGS() TSRMLS_CC, "sr|lb", &sql, &sql_len, &zdb, &mode, &decode_binary) &&
46050 + FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rs|lb", &zdb, &sql, &sql_len, &mode, &decode_binary)) {
46053 + DB_FROM_ZVAL(db, &zdb);
46056 + PHP_SQLITE_EMPTY_QUERY;
46058 + /* avoid doing work if we can */
46059 + if (!return_value_used) {
46060 + db->last_err_code = sqlite_exec(db->db, sql, NULL, NULL, &errtext);
46062 + if (db->last_err_code != SQLITE_OK) {
46063 + php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s", errtext);
46064 + sqlite_freemem(errtext);
46069 + rres = (struct php_sqlite_result *)ecalloc(1, sizeof(*rres));
46070 + sqlite_query(NULL, db, sql, sql_len, (int)mode, 0, NULL, &rres, NULL TSRMLS_CC);
46071 + if (db->last_err_code != SQLITE_OK) {
46078 + array_init(return_value);
46080 + while (rres->curr_row < rres->nrows) {
46081 + MAKE_STD_ZVAL(ent);
46082 + php_sqlite_fetch_array(rres, mode, decode_binary, 1, ent TSRMLS_CC);
46083 + add_next_index_zval(return_value, ent);
46085 + real_result_dtor(rres TSRMLS_CC);
46089 +/* {{{ php_sqlite_fetch_single */
46090 +static void php_sqlite_fetch_single(struct php_sqlite_result *res, zend_bool decode_binary, zval *return_value TSRMLS_DC)
46092 + const char **rowdata;
46096 + /* check range of the row */
46097 + if (res->curr_row >= res->nrows) {
46102 + if (res->buffered) {
46103 + rowdata = (const char**)&res->table[res->curr_row * res->ncolumns];
46105 + rowdata = (const char**)res->table;
46108 + if (decode_binary && rowdata[0] != NULL && rowdata[0][0] == '\x01') {
46109 + decoded = emalloc(strlen(rowdata[0]));
46110 + decoded_len = php_sqlite_decode_binary(rowdata[0]+1, decoded);
46111 + if (!res->buffered) {
46112 + efree((char*)rowdata[0]);
46113 + rowdata[0] = NULL;
46115 + } else if (rowdata[0]) {
46116 + decoded_len = strlen((char*)rowdata[0]);
46117 + if (res->buffered) {
46118 + decoded = estrndup((char*)rowdata[0], decoded_len);
46120 + decoded = (char*)rowdata[0];
46121 + rowdata[0] = NULL;
46128 + if (!res->buffered) {
46129 + /* non buffered: fetch next row */
46130 + php_sqlite_fetch(res TSRMLS_CC);
46132 + /* advance the row pointer */
46135 + if (decoded == NULL) {
46138 + RETURN_STRINGL(decoded, decoded_len, 0);
46144 +/* {{{ proto array sqlite_single_query(resource db, string query [, bool first_row_only [, bool decode_binary]])
46145 + Executes a query and returns either an array for one single column or the value of the first row. */
46146 +PHP_FUNCTION(sqlite_single_query)
46149 + struct php_sqlite_db *db;
46150 + struct php_sqlite_result *rres;
46153 + char *errtext = NULL;
46154 + zend_bool decode_binary = 1;
46155 + zend_bool srow = 1;
46156 + zval *object = getThis();
46159 + if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|bb", &sql, &sql_len, &srow, &decode_binary)) {
46162 + RES_FROM_OBJECT(db, object);
46164 + if (FAILURE == zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET,
46165 + ZEND_NUM_ARGS() TSRMLS_CC, "sr|bb", &sql, &sql_len, &zdb, &srow, &decode_binary) &&
46166 + FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rs|bb", &zdb, &sql, &sql_len, &srow, &decode_binary)) {
46169 + DB_FROM_ZVAL(db, &zdb);
46172 + PHP_SQLITE_EMPTY_QUERY;
46174 + /* avoid doing work if we can */
46175 + if (!return_value_used) {
46176 + db->last_err_code = sqlite_exec(db->db, sql, NULL, NULL, &errtext);
46178 + if (db->last_err_code != SQLITE_OK) {
46179 + php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s", errtext);
46180 + sqlite_freemem(errtext);
46185 + rres = (struct php_sqlite_result *)ecalloc(1, sizeof(*rres));
46186 + sqlite_query(NULL, db, sql, sql_len, PHPSQLITE_NUM, 0, NULL, &rres, NULL TSRMLS_CC);
46187 + if (db->last_err_code != SQLITE_OK) {
46195 + array_init(return_value);
46198 + while (rres->curr_row < rres->nrows) {
46199 + MAKE_STD_ZVAL(ent);
46200 + php_sqlite_fetch_single(rres, decode_binary, ent TSRMLS_CC);
46202 + /* if set and we only have 1 row in the result set, return the result as a string. */
46204 + if (rres->curr_row == 1 && rres->curr_row >= rres->nrows) {
46205 + *return_value = *ent;
46206 + zval_copy_ctor(return_value);
46212 + array_init(return_value);
46215 + add_next_index_zval(return_value, ent);
46218 + real_result_dtor(rres TSRMLS_CC);
46223 +/* {{{ proto string sqlite_fetch_single(resource result [, bool decode_binary])
46224 + Fetches the first column of a result set as a string. */
46225 +PHP_FUNCTION(sqlite_fetch_single)
46228 + zend_bool decode_binary = 1;
46229 + struct php_sqlite_result *res;
46230 + zval *object = getThis();
46233 + if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|b", &decode_binary)) {
46236 + RES_FROM_OBJECT(res, object);
46238 + if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r|b", &zres, &decode_binary)) {
46241 + ZEND_FETCH_RESOURCE(res, struct php_sqlite_result *, &zres, -1, "sqlite result", le_sqlite_result);
46244 + php_sqlite_fetch_single(res, decode_binary, return_value TSRMLS_CC);
46248 +/* {{{ proto array sqlite_current(resource result [, int result_type [, bool decode_binary]])
46249 + Fetches the current row from a result set as an array. */
46250 +PHP_FUNCTION(sqlite_current)
46253 + long mode = PHPSQLITE_BOTH;
46254 + zend_bool decode_binary = 1;
46255 + struct php_sqlite_result *res;
46256 + zval *object = getThis();
46259 + if (ZEND_NUM_ARGS() && FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|lb", &mode, &decode_binary)) {
46262 + RES_FROM_OBJECT(res, object);
46263 + if (!ZEND_NUM_ARGS()) {
46264 + mode = res->mode;
46267 + if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r|lb", &zres, &mode, &decode_binary)) {
46270 + ZEND_FETCH_RESOURCE(res, struct php_sqlite_result *, &zres, -1, "sqlite result", le_sqlite_result);
46271 + if (ZEND_NUM_ARGS() < 2) {
46272 + mode = res->mode;
46276 + php_sqlite_fetch_array(res, mode, decode_binary, 0, return_value TSRMLS_CC);
46280 +/* {{{ proto mixed sqlite_column(resource result, mixed index_or_name [, bool decode_binary])
46281 + Fetches a column from the current row of a result set. */
46282 +PHP_FUNCTION(sqlite_column)
46286 + zend_bool decode_binary = 1;
46287 + struct php_sqlite_result *res;
46288 + zval *object = getThis();
46291 + if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z|b", &which, &decode_binary)) {
46294 + RES_FROM_OBJECT(res, object);
46296 + if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rz|b", &zres, &which, &decode_binary)) {
46299 + ZEND_FETCH_RESOURCE(res, struct php_sqlite_result *, &zres, -1, "sqlite result", le_sqlite_result);
46302 + php_sqlite_fetch_column(res, which, decode_binary, return_value TSRMLS_CC);
46306 +/* {{{ proto string sqlite_libversion()
46307 + Returns the version of the linked SQLite library. */
46308 +PHP_FUNCTION(sqlite_libversion)
46310 + if (zend_parse_parameters_none() == FAILURE) {
46313 + RETURN_STRING((char*)sqlite_libversion(), 1);
46317 +/* {{{ proto string sqlite_libencoding()
46318 + Returns the encoding (iso8859 or UTF-8) of the linked SQLite library. */
46319 +PHP_FUNCTION(sqlite_libencoding)
46321 + if (zend_parse_parameters_none() == FAILURE) {
46324 + RETURN_STRING((char*)sqlite_libencoding(), 1);
46328 +/* {{{ proto int sqlite_changes(resource db)
46329 + Returns the number of rows that were changed by the most recent SQL statement. */
46330 +PHP_FUNCTION(sqlite_changes)
46333 + struct php_sqlite_db *db;
46334 + zval *object = getThis();
46337 + if (zend_parse_parameters_none() == FAILURE) {
46340 + DB_FROM_OBJECT(db, object);
46342 + if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &zdb)) {
46345 + DB_FROM_ZVAL(db, &zdb);
46348 + RETURN_LONG(sqlite_changes(db->db));
46352 +/* {{{ proto int sqlite_last_insert_rowid(resource db)
46353 + Returns the rowid of the most recently inserted row. */
46354 +PHP_FUNCTION(sqlite_last_insert_rowid)
46357 + struct php_sqlite_db *db;
46358 + zval *object = getThis();
46361 + if (zend_parse_parameters_none() == FAILURE) {
46364 + DB_FROM_OBJECT(db, object);
46366 + if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &zdb)) {
46369 + DB_FROM_ZVAL(db, &zdb);
46372 + RETURN_LONG(sqlite_last_insert_rowid(db->db));
46376 +static int sqlite_count_elements(zval *object, long *count TSRMLS_DC) /* {{{ */
46378 + sqlite_object *obj = (sqlite_object*) zend_object_store_get_object(object TSRMLS_CC);
46380 + if (obj->u.res == NULL) {
46381 + zend_throw_exception(sqlite_ce_exception, "Row count is not available for this query", 0 TSRMLS_CC);
46385 + if (obj->u.res->buffered) {
46386 + * count = obj->u.res->nrows;
46389 + zend_throw_exception(sqlite_ce_exception, "Row count is not available for unbuffered queries", 0 TSRMLS_CC);
46394 +/* {{{ proto int sqlite_num_rows(resource result)
46395 + Returns the number of rows in a buffered result set. */
46396 +PHP_FUNCTION(sqlite_num_rows)
46399 + struct php_sqlite_result *res;
46400 + zval *object = getThis();
46403 + if (zend_parse_parameters_none() == FAILURE) {
46406 + RES_FROM_OBJECT(res, object);
46408 + if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &zres)) {
46411 + ZEND_FETCH_RESOURCE(res, struct php_sqlite_result *, &zres, -1, "sqlite result", le_sqlite_result);
46414 + if (res->buffered) {
46415 + RETURN_LONG(res->nrows);
46417 + php_error_docref(NULL TSRMLS_CC, E_WARNING, "Row count is not available for unbuffered queries");
46423 +/* {{{ proto bool sqlite_valid(resource result)
46424 + Returns whether more rows are available. */
46425 +PHP_FUNCTION(sqlite_valid)
46428 + struct php_sqlite_result *res;
46429 + zval *object = getThis();
46432 + if (zend_parse_parameters_none() == FAILURE) {
46435 + RES_FROM_OBJECT(res, object);
46437 + if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &zres)) {
46440 + ZEND_FETCH_RESOURCE(res, struct php_sqlite_result *, &zres, -1, "sqlite result", le_sqlite_result);
46443 + RETURN_BOOL(res->curr_row < res->nrows && res->nrows); /* curr_row may be -1 */
46447 +/* {{{ proto bool sqlite_has_prev(resource result)
46448 + * Returns whether a previous row is available. */
46449 +PHP_FUNCTION(sqlite_has_prev)
46452 + struct php_sqlite_result *res;
46453 + zval *object = getThis();
46456 + if (zend_parse_parameters_none() == FAILURE) {
46459 + RES_FROM_OBJECT(res, object);
46461 + if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &zres)) {
46464 + ZEND_FETCH_RESOURCE(res, struct php_sqlite_result *, &zres, -1, "sqlite result", le_sqlite_result);
46467 + if(!res->buffered) {
46468 + php_error_docref(NULL TSRMLS_CC, E_WARNING, "you cannot use sqlite_has_prev on unbuffered querys");
46472 + RETURN_BOOL(res->curr_row);
46476 +/* {{{ proto int sqlite_num_fields(resource result)
46477 + Returns the number of fields in a result set. */
46478 +PHP_FUNCTION(sqlite_num_fields)
46481 + struct php_sqlite_result *res;
46482 + zval *object = getThis();
46485 + if (zend_parse_parameters_none() == FAILURE) {
46488 + RES_FROM_OBJECT(res, object);
46490 + if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &zres)) {
46493 + ZEND_FETCH_RESOURCE(res, struct php_sqlite_result *, &zres, -1, "sqlite result", le_sqlite_result);
46496 + RETURN_LONG(res->ncolumns);
46500 +/* {{{ proto string sqlite_field_name(resource result, int field_index)
46501 + Returns the name of a particular field of a result set. */
46502 +PHP_FUNCTION(sqlite_field_name)
46505 + struct php_sqlite_result *res;
46507 + zval *object = getThis();
46510 + if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &field)) {
46513 + RES_FROM_OBJECT(res, object);
46515 + if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rl", &zres, &field)) {
46518 + ZEND_FETCH_RESOURCE(res, struct php_sqlite_result *, &zres, -1, "sqlite result", le_sqlite_result);
46521 + if (field < 0 || field >= res->ncolumns) {
46522 + php_error_docref(NULL TSRMLS_CC, E_WARNING, "field %ld out of range", field);
46526 + RETURN_STRING(res->col_names[field], 1);
46530 +/* {{{ proto bool sqlite_seek(resource result, int row)
46531 + Seek to a particular row number of a buffered result set. */
46532 +PHP_FUNCTION(sqlite_seek)
46535 + struct php_sqlite_result *res;
46537 + zval *object = getThis();
46540 + if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &row)) {
46543 + RES_FROM_OBJECT(res, object);
46545 + if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rl", &zres, &row)) {
46548 + ZEND_FETCH_RESOURCE(res, struct php_sqlite_result *, &zres, -1, "sqlite result", le_sqlite_result);
46551 + if (!res->buffered) {
46552 + php_error_docref(NULL TSRMLS_CC, E_WARNING, "Cannot seek an unbuffered result set");
46556 + if (row < 0 || row >= res->nrows) {
46557 + php_error_docref(NULL TSRMLS_CC, E_WARNING, "row %ld out of range", row);
46561 + res->curr_row = row;
46566 +/* {{{ proto bool sqlite_rewind(resource result)
46567 + Seek to the first row number of a buffered result set. */
46568 +PHP_FUNCTION(sqlite_rewind)
46571 + struct php_sqlite_result *res;
46572 + zval *object = getThis();
46575 + if (zend_parse_parameters_none() == FAILURE) {
46578 + RES_FROM_OBJECT(res, object);
46580 + if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &zres)) {
46583 + ZEND_FETCH_RESOURCE(res, struct php_sqlite_result *, &zres, -1, "sqlite result", le_sqlite_result);
46586 + if (!res->buffered) {
46587 + php_error_docref(NULL TSRMLS_CC, E_WARNING, "Cannot rewind an unbuffered result set");
46591 + if (!res->nrows) {
46592 + php_error_docref(NULL TSRMLS_CC, E_NOTICE, "no rows received");
46596 + res->curr_row = 0;
46601 +/* {{{ proto bool sqlite_next(resource result)
46602 + Seek to the next row number of a result set. */
46603 +PHP_FUNCTION(sqlite_next)
46606 + struct php_sqlite_result *res;
46607 + zval *object = getThis();
46610 + if (zend_parse_parameters_none() == FAILURE) {
46613 + RES_FROM_OBJECT(res, object);
46615 + if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &zres)) {
46618 + ZEND_FETCH_RESOURCE(res, struct php_sqlite_result *, &zres, -1, "sqlite result", le_sqlite_result);
46621 + if (!res->buffered && res->vm) {
46622 + php_sqlite_fetch(res TSRMLS_CC);
46625 + if (res->curr_row >= res->nrows) {
46626 + php_error_docref(NULL TSRMLS_CC, E_WARNING, "no more rows available");
46636 +/* {{{ proto int sqlite_key(resource result)
46637 + Return the current row index of a buffered result. */
46638 +PHP_FUNCTION(sqlite_key)
46641 + struct php_sqlite_result *res;
46642 + zval *object = getThis();
46645 + if (zend_parse_parameters_none() == FAILURE) {
46648 + RES_FROM_OBJECT(res, object);
46650 + if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &zres)) {
46653 + ZEND_FETCH_RESOURCE(res, struct php_sqlite_result *, &zres, -1, "sqlite result", le_sqlite_result);
46656 + RETURN_LONG(res->curr_row);
46660 +/* {{{ proto bool sqlite_prev(resource result)
46661 + * Seek to the previous row number of a result set. */
46662 +PHP_FUNCTION(sqlite_prev)
46665 + struct php_sqlite_result *res;
46666 + zval *object = getThis();
46669 + if (zend_parse_parameters_none() == FAILURE) {
46672 + RES_FROM_OBJECT(res, object);
46674 + if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &zres)) {
46677 + ZEND_FETCH_RESOURCE(res, struct php_sqlite_result *, &zres, -1, "sqlite result", le_sqlite_result);
46680 + if (!res->buffered) {
46681 + php_error_docref(NULL TSRMLS_CC, E_WARNING, "you cannot use sqlite_prev on unbuffered querys");
46685 + if (res->curr_row <= 0) {
46686 + php_error_docref(NULL TSRMLS_CC, E_WARNING, "no previous row available");
46696 +/* {{{ proto string sqlite_escape_string(string item)
46697 + Escapes a string for use as a query parameter. */
46698 +PHP_FUNCTION(sqlite_escape_string)
46700 + char *string = NULL;
46704 + if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &string, &stringlen)) {
46708 + if (stringlen && (string[0] == '\x01' || memchr(string, '\0', stringlen) != NULL)) {
46709 + /* binary string */
46712 + ret = safe_emalloc(1 + stringlen / 254, 257, 3);
46714 + enclen = php_sqlite_encode_binary(string, stringlen, ret+1);
46715 + RETVAL_STRINGL(ret, enclen+1, 0);
46717 + } else if (stringlen) {
46718 + ret = sqlite_mprintf("%q", string);
46720 + RETVAL_STRING(ret, 1);
46721 + sqlite_freemem(ret);
46724 + RETURN_EMPTY_STRING();
46729 +/* {{{ proto int sqlite_last_error(resource db)
46730 + Returns the error code of the last error for a database. */
46731 +PHP_FUNCTION(sqlite_last_error)
46734 + struct php_sqlite_db *db;
46735 + zval *object = getThis();
46738 + if (zend_parse_parameters_none() == FAILURE) {
46741 + DB_FROM_OBJECT(db, object);
46743 + if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &zdb)) {
46746 + DB_FROM_ZVAL(db, &zdb);
46749 + RETURN_LONG(db->last_err_code);
46753 +/* {{{ proto string sqlite_error_string(int error_code)
46754 + Returns the textual description of an error code. */
46755 +PHP_FUNCTION(sqlite_error_string)
46760 + if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &code)) {
46764 + msg = sqlite_error_string(code);
46767 + RETURN_STRING((char*)msg, 1);
46774 +/* manages duplicate registrations of a particular function, and
46775 + * also handles the case where the db is using a persistent connection */
46776 +enum callback_prep_t { DO_REG, SKIP_REG, ERR };
46778 +static enum callback_prep_t prep_callback_struct(struct php_sqlite_db *db, int is_agg,
46780 + zval *step, zval *fini, struct php_sqlite_agg_functions **funcs)
46782 + struct php_sqlite_agg_functions *alloc_funcs, func_tmp;
46785 + enum callback_prep_t ret;
46787 + hashkeylen = spprintf(&hashkey, 0, "%s-%s", is_agg ? "agg" : "reg", funcname);
46789 + /* is it already registered ? */
46790 + if (SUCCESS == zend_hash_find(&db->callbacks, hashkey, hashkeylen+1, (void*)&alloc_funcs)) {
46791 + /* override the previous definition */
46793 + if (alloc_funcs->is_valid) {
46794 + /* release these */
46796 + if (alloc_funcs->step) {
46797 + zval_ptr_dtor(&alloc_funcs->step);
46798 + alloc_funcs->step = NULL;
46801 + if (alloc_funcs->fini) {
46802 + zval_ptr_dtor(&alloc_funcs->fini);
46803 + alloc_funcs->fini = NULL;
46809 + /* add a new one */
46810 + func_tmp.db = db;
46812 + ret = SUCCESS == zend_hash_update(&db->callbacks, hashkey, hashkeylen+1,
46813 + (void*)&func_tmp, sizeof(func_tmp), (void**)&alloc_funcs) ? DO_REG : ERR;
46818 + MAKE_STD_ZVAL(alloc_funcs->step);
46819 + *(alloc_funcs->step) = *step;
46820 + zval_copy_ctor(alloc_funcs->step);
46821 + INIT_PZVAL(alloc_funcs->step);
46824 + MAKE_STD_ZVAL(alloc_funcs->fini);
46825 + *(alloc_funcs->fini) = *fini;
46826 + zval_copy_ctor(alloc_funcs->fini);
46827 + INIT_PZVAL(alloc_funcs->fini);
46829 + alloc_funcs->fini = NULL;
46831 + alloc_funcs->is_valid = 1;
46832 + *funcs = alloc_funcs;
46838 +/* {{{ proto bool sqlite_create_aggregate(resource db, string funcname, mixed step_func, mixed finalize_func[, long num_args])
46839 + Registers an aggregate function for queries. */
46840 +PHP_FUNCTION(sqlite_create_aggregate)
46842 + char *funcname = NULL;
46843 + int funcname_len;
46844 + zval *zstep, *zfinal, *zdb;
46845 + struct php_sqlite_db *db;
46846 + struct php_sqlite_agg_functions *funcs;
46847 + char *callable = NULL;
46848 + long num_args = -1;
46849 + zval *object = getThis();
46852 + if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "szz|l", &funcname, &funcname_len, &zstep, &zfinal, &num_args)) {
46855 + DB_FROM_OBJECT(db, object);
46857 + if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rszz|l", &zdb, &funcname, &funcname_len, &zstep, &zfinal, &num_args)) {
46860 + DB_FROM_ZVAL(db, &zdb);
46863 + if (!zend_is_callable(zstep, 0, &callable TSRMLS_CC)) {
46864 + php_error_docref(NULL TSRMLS_CC, E_WARNING, "step function `%s' is not callable", callable);
46870 + if (!zend_is_callable(zfinal, 0, &callable TSRMLS_CC)) {
46871 + php_error_docref(NULL TSRMLS_CC, E_WARNING, "finalize function `%s' is not callable", callable);
46878 + if (prep_callback_struct(db, 1, funcname, zstep, zfinal, &funcs) == DO_REG) {
46879 + sqlite_create_aggregate(db->db, funcname, num_args,
46880 + php_sqlite_agg_step_function_callback,
46881 + php_sqlite_agg_fini_function_callback, funcs);
46888 +/* {{{ proto bool sqlite_create_function(resource db, string funcname, mixed callback[, long num_args])
46889 + Registers a "regular" function for queries. */
46890 +PHP_FUNCTION(sqlite_create_function)
46892 + char *funcname = NULL;
46893 + int funcname_len;
46894 + zval *zcall, *zdb;
46895 + struct php_sqlite_db *db;
46896 + struct php_sqlite_agg_functions *funcs;
46897 + char *callable = NULL;
46898 + long num_args = -1;
46900 + zval *object = getThis();
46903 + if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sz|l", &funcname, &funcname_len, &zcall, &num_args)) {
46906 + DB_FROM_OBJECT(db, object);
46908 + if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rsz|l", &zdb, &funcname, &funcname_len, &zcall, &num_args)) {
46911 + DB_FROM_ZVAL(db, &zdb);
46914 + if (!zend_is_callable(zcall, 0, &callable TSRMLS_CC)) {
46915 + php_error_docref(NULL TSRMLS_CC, E_WARNING, "function `%s' is not callable", callable);
46921 + if (prep_callback_struct(db, 0, funcname, zcall, NULL, &funcs) == DO_REG) {
46922 + sqlite_create_function(db->db, funcname, num_args, php_sqlite_function_callback, funcs);
46927 +/* {{{ proto string sqlite_udf_encode_binary(string data)
46928 + Apply binary encoding (if required) to a string to return from an UDF. */
46929 +PHP_FUNCTION(sqlite_udf_encode_binary)
46931 + char *data = NULL;
46934 + if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s!", &data, &datalen)) {
46938 + if (data == NULL) {
46941 + if (datalen && (data[0] == '\x01' || memchr(data, '\0', datalen) != NULL)) {
46942 + /* binary string */
46946 + ret = safe_emalloc(1 + datalen / 254, 257, 3);
46948 + enclen = php_sqlite_encode_binary(data, datalen, ret+1);
46949 + RETVAL_STRINGL(ret, enclen+1, 0);
46951 + RETVAL_STRINGL(data, datalen, 1);
46956 +/* {{{ proto string sqlite_udf_decode_binary(string data)
46957 + Decode binary encoding on a string parameter passed to an UDF. */
46958 +PHP_FUNCTION(sqlite_udf_decode_binary)
46960 + char *data = NULL;
46963 + if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s!", &data, &datalen)) {
46967 + if (data == NULL) {
46970 + if (datalen && data[0] == '\x01') {
46971 + /* encoded string */
46975 + ret = emalloc(datalen);
46976 + enclen = php_sqlite_decode_binary(data+1, ret);
46977 + ret[enclen] = '\0';
46978 + RETVAL_STRINGL(ret, enclen, 0);
46980 + RETVAL_STRINGL(data, datalen, 1);
46987 + * Local variables:
46989 + * c-basic-offset: 4
46991 + * vim600: sw=4 ts=4 fdm=marker
46992 + * vim<600: sw=4 ts=4
46995 +++ b/ext/sqlite/sqlite.dsp
46997 +# Microsoft Developer Studio Project File - Name="sqlite" - Package Owner=<4>
\r
46998 +# Microsoft Developer Studio Generated Build File, Format Version 6.00
\r
46999 +# ** DO NOT EDIT **
\r
47001 +# TARGTYPE "Win32 (x86) Dynamic-Link Library" 0x0102
\r
47003 +CFG=sqlite - Win32 Debug_TS
\r
47004 +!MESSAGE This is not a valid makefile. To build this project using NMAKE,
\r
47005 +!MESSAGE use the Export Makefile command and run
\r
47007 +!MESSAGE NMAKE /f "sqlite.mak".
\r
47009 +!MESSAGE You can specify a configuration when running NMAKE
\r
47010 +!MESSAGE by defining the macro CFG on the command line. For example:
\r
47012 +!MESSAGE NMAKE /f "sqlite.mak" CFG="sqlite - Win32 Debug_TS"
\r
47014 +!MESSAGE Possible choices for configuration are:
\r
47016 +!MESSAGE "sqlite - Win32 Release_TS" (based on "Win32 (x86) Dynamic-Link Library")
\r
47017 +!MESSAGE "sqlite - Win32 Debug_TS" (based on "Win32 (x86) Dynamic-Link Library")
\r
47021 +# PROP AllowPerConfigDependencies 0
\r
47022 +# PROP Scc_ProjName ""
\r
47023 +# PROP Scc_LocalPath ""
\r
47028 +!IF "$(CFG)" == "sqlite - Win32 Release_TS"
\r
47030 +# PROP BASE Use_MFC 0
\r
47031 +# PROP BASE Use_Debug_Libraries 0
\r
47032 +# PROP BASE Output_Dir "Release_TS"
\r
47033 +# PROP BASE Intermediate_Dir "Release_TS"
\r
47034 +# PROP BASE Ignore_Export_Lib 0
\r
47035 +# PROP BASE Target_Dir ""
\r
47036 +# PROP Use_MFC 0
\r
47037 +# PROP Use_Debug_Libraries 0
\r
47038 +# PROP Output_Dir "Release_TS"
\r
47039 +# PROP Intermediate_Dir "Release_TS"
\r
47040 +# PROP Ignore_Export_Lib 0
\r
47041 +# PROP Target_Dir ""
\r
47042 +# ADD BASE CPP /nologo /MD /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "SQLITE_EXPORTS" /YX /FD /c
\r
47043 +# ADD CPP /nologo /MD /W3 /GX /O2 /I "..\.." /I "..\..\main" /I "..\..\Zend" /I "..\..\TSRM" /I "..\..\win32" /I "..\..\..\php_build" /D ZEND_DEBUG=0 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "COMPILE_DL_SQLITE" /D ZTS=1 /D "ZEND_WIN32" /D "PHP_WIN32" /D HAVE_SQLITE=1 /D "PHP_SQLITE_EXPORTS" /FR /YX /FD /c
\r
47044 +# ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /win32
\r
47045 +# ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32
\r
47046 +# ADD BASE RSC /l 0x407 /d "NDEBUG"
\r
47047 +# ADD RSC /l 0x407 /d "NDEBUG"
\r
47048 +BSC32=bscmake.exe
\r
47049 +# ADD BASE BSC32 /nologo
\r
47050 +# ADD BSC32 /nologo
\r
47052 +# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /dll /machine:I386
\r
47053 +# ADD LINK32 php5ts.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /dll /machine:I386 /out:"..\..\Release_TS\php_sqlite.dll" /libpath:"..\..\Release_TS" /libpath:"..\..\Release_TS_Inline" /libpath:"..\..\..\php_build\release"
\r
47055 +!ELSEIF "$(CFG)" == "sqlite - Win32 Debug_TS"
\r
47057 +# PROP BASE Use_MFC 0
\r
47058 +# PROP BASE Use_Debug_Libraries 1
\r
47059 +# PROP BASE Output_Dir "Debug_TS"
\r
47060 +# PROP BASE Intermediate_Dir "Debug_TS"
\r
47061 +# PROP BASE Target_Dir ""
\r
47062 +# PROP Use_MFC 0
\r
47063 +# PROP Use_Debug_Libraries 1
\r
47064 +# PROP Output_Dir "Debug_TS"
\r
47065 +# PROP Intermediate_Dir "Debug_TS"
\r
47066 +# PROP Ignore_Export_Lib 0
\r
47067 +# PROP Target_Dir ""
\r
47068 +# ADD BASE CPP /nologo /MDd /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "SQLITE_EXPORTS" /YX /FD /GZ /c
\r
47069 +# ADD CPP /nologo /MDd /W3 /Gm /GX /ZI /Od /I "..\.." /I "..\..\main" /I "..\..\Zend" /I "..\..\TSRM" /I "..\..\win32" /I "..\..\..\php_build" /D ZEND_DEBUG=1 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "COMPILE_DL_SQLITE" /D ZTS=1 /D "ZEND_WIN32" /D "PHP_WIN32" /D HAVE_SQLITE=1 /D "PHP_SQLITE_EXPORTS" /YX /FD /GZ /c
\r
47070 +# ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /win32
\r
47071 +# ADD MTL /nologo /D "_DEBUG" /mktyplib203 /win32
\r
47072 +# ADD BASE RSC /l 0x407 /d "_DEBUG"
\r
47073 +# ADD RSC /l 0x407 /d "_DEBUG"
\r
47074 +BSC32=bscmake.exe
\r
47075 +# ADD BASE BSC32 /nologo
\r
47076 +# ADD BSC32 /nologo
\r
47078 +# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /dll /debug /machine:I386 /pdbtype:sept
\r
47079 +# ADD LINK32 php5ts_debug.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /dll /debug /machine:I386 /out:"..\..\Debug_TS\php_sqlite.dll" /pdbtype:sept /libpath:"..\..\Debug_TS" /libpath:"..\..\..\php_build\release"
\r
47085 +# Name "sqlite - Win32 Release_TS"
\r
47086 +# Name "sqlite - Win32 Debug_TS"
\r
47087 +# Begin Group "Source Files"
\r
47089 +# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat"
\r
47090 +# Begin Group "libsqlite"
\r
47092 +# PROP Default_Filter ""
\r
47093 +# Begin Source File
\r
47095 +SOURCE=.\libsqlite\src\attach.c
\r
47096 +# End Source File
\r
47097 +# Begin Source File
\r
47099 +SOURCE=.\libsqlite\src\auth.c
\r
47100 +# End Source File
\r
47101 +# Begin Source File
\r
47103 +SOURCE=.\libsqlite\src\btree.c
\r
47104 +# End Source File
\r
47105 +# Begin Source File
\r
47107 +SOURCE=.\libsqlite\src\btree.h
\r
47108 +# End Source File
\r
47109 +# Begin Source File
\r
47111 +SOURCE=.\libsqlite\src\btree_rb.c
\r
47112 +# End Source File
\r
47113 +# Begin Source File
\r
47115 +SOURCE=.\libsqlite\src\build.c
\r
47116 +# End Source File
\r
47117 +# Begin Source File
\r
47119 +SOURCE=.\libsqlite\src\config.h
\r
47120 +# End Source File
\r
47121 +# Begin Source File
\r
47123 +SOURCE=.\libsqlite\src\copy.c
\r
47124 +# End Source File
\r
47125 +# Begin Source File
\r
47127 +SOURCE=.\libsqlite\src\date.c
\r
47128 +# End Source File
\r
47129 +# Begin Source File
\r
47131 +SOURCE=.\libsqlite\src\delete.c
\r
47132 +# End Source File
\r
47133 +# Begin Source File
\r
47135 +SOURCE=.\libsqlite\src\encode.c
\r
47136 +# End Source File
\r
47137 +# Begin Source File
\r
47139 +SOURCE=.\libsqlite\src\expr.c
\r
47140 +# End Source File
\r
47141 +# Begin Source File
\r
47143 +SOURCE=.\libsqlite\src\func.c
\r
47144 +# End Source File
\r
47145 +# Begin Source File
\r
47147 +SOURCE=.\libsqlite\src\hash.c
\r
47148 +# End Source File
\r
47149 +# Begin Source File
\r
47151 +SOURCE=.\libsqlite\src\hash.h
\r
47152 +# End Source File
\r
47153 +# Begin Source File
\r
47155 +SOURCE=.\libsqlite\src\insert.c
\r
47156 +# End Source File
\r
47157 +# Begin Source File
\r
47159 +SOURCE=.\libsqlite\src\main.c
\r
47160 +# End Source File
\r
47161 +# Begin Source File
\r
47163 +SOURCE=.\libsqlite\src\opcodes.c
\r
47164 +# End Source File
\r
47165 +# Begin Source File
\r
47167 +SOURCE=.\libsqlite\src\opcodes.h
\r
47168 +# End Source File
\r
47169 +# Begin Source File
\r
47171 +SOURCE=.\libsqlite\src\os.c
\r
47172 +# End Source File
\r
47173 +# Begin Source File
\r
47175 +SOURCE=.\libsqlite\src\os.h
\r
47176 +# End Source File
\r
47177 +# Begin Source File
\r
47179 +SOURCE=.\libsqlite\src\pager.c
\r
47180 +# End Source File
\r
47181 +# Begin Source File
\r
47183 +SOURCE=.\libsqlite\src\pager.h
\r
47184 +# End Source File
\r
47185 +# Begin Source File
\r
47187 +SOURCE=.\libsqlite\src\parse.c
\r
47188 +# End Source File
\r
47189 +# Begin Source File
\r
47191 +SOURCE=.\libsqlite\src\parse.h
\r
47192 +# End Source File
\r
47193 +# Begin Source File
\r
47195 +SOURCE=.\libsqlite\src\pragma.c
\r
47196 +# End Source File
\r
47197 +# Begin Source File
\r
47199 +SOURCE=.\libsqlite\src\printf.c
\r
47200 +# End Source File
\r
47201 +# Begin Source File
\r
47203 +SOURCE=.\libsqlite\src\random.c
\r
47204 +# End Source File
\r
47205 +# Begin Source File
\r
47207 +SOURCE=.\libsqlite\src\select.c
\r
47208 +# End Source File
\r
47209 +# Begin Source File
\r
47211 +SOURCE=.\libsqlite\src\sqlite.h
\r
47212 +# End Source File
\r
47213 +# Begin Source File
\r
47215 +SOURCE=.\libsqlite\src\sqlite.w32.h
\r
47217 +!IF "$(CFG)" == "sqlite - Win32 Release_TS"
\r
47219 +# Begin Custom Build
\r
47220 +InputDir=.\libsqlite\src
\r
47221 +InputPath=.\libsqlite\src\sqlite.w32.h
\r
47223 +"$(InputDir)\sqlite.h" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
\r
47224 + copy $(InputPath) $(InputDir)\sqlite.h
\r
47226 +# End Custom Build
\r
47228 +!ELSEIF "$(CFG)" == "sqlite - Win32 Debug_TS"
\r
47230 +# Begin Custom Build
\r
47231 +InputDir=.\libsqlite\src
\r
47232 +InputPath=.\libsqlite\src\sqlite.w32.h
\r
47234 +"$(InputDir)\sqlite.h" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
\r
47235 + copy $(InputPath) $(InputDir)\sqlite.h
\r
47237 +# End Custom Build
\r
47241 +# End Source File
\r
47242 +# Begin Source File
\r
47244 +SOURCE=.\libsqlite\src\sqlite_config.w32.h
\r
47246 +!IF "$(CFG)" == "sqlite - Win32 Release_TS"
\r
47248 +# Begin Custom Build
\r
47249 +InputDir=.\libsqlite\src
\r
47250 +InputPath=.\libsqlite\src\sqlite_config.w32.h
\r
47252 +"$(InputDir)\config.h" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
\r
47253 + copy $(InputPath) $(InputDir)\config.h
\r
47255 +# End Custom Build
\r
47257 +!ELSEIF "$(CFG)" == "sqlite - Win32 Debug_TS"
\r
47259 +# Begin Custom Build
\r
47260 +InputDir=.\libsqlite\src
\r
47261 +InputPath=.\libsqlite\src\sqlite_config.w32.h
\r
47263 +"$(InputDir)\config.h" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
\r
47264 + copy $(InputPath) $(InputDir)\config.h
\r
47266 +# End Custom Build
\r
47270 +# End Source File
\r
47271 +# Begin Source File
\r
47273 +SOURCE=.\libsqlite\src\sqliteInt.h
\r
47274 +# End Source File
\r
47275 +# Begin Source File
\r
47277 +SOURCE=.\libsqlite\src\table.c
\r
47278 +# End Source File
\r
47279 +# Begin Source File
\r
47281 +SOURCE=.\libsqlite\src\tokenize.c
\r
47282 +# End Source File
\r
47283 +# Begin Source File
\r
47285 +SOURCE=.\libsqlite\src\trigger.c
\r
47286 +# End Source File
\r
47287 +# Begin Source File
\r
47289 +SOURCE=.\libsqlite\src\update.c
\r
47290 +# End Source File
\r
47291 +# Begin Source File
\r
47293 +SOURCE=.\libsqlite\src\util.c
\r
47294 +# End Source File
\r
47295 +# Begin Source File
\r
47297 +SOURCE=.\libsqlite\src\vacuum.c
\r
47298 +# End Source File
\r
47299 +# Begin Source File
\r
47301 +SOURCE=.\libsqlite\src\vdbe.c
\r
47302 +# End Source File
\r
47303 +# Begin Source File
\r
47305 +SOURCE=.\libsqlite\src\vdbe.h
\r
47306 +# End Source File
\r
47307 +# Begin Source File
\r
47309 +SOURCE=.\libsqlite\src\vdbeaux.c
\r
47310 +# End Source File
\r
47311 +# Begin Source File
\r
47313 +SOURCE=.\libsqlite\src\where.c
\r
47314 +# End Source File
\r
47316 +# Begin Source File
\r
47318 +SOURCE=.\php_sqlite.def
\r
47319 +# End Source File
\r
47320 +# Begin Source File
\r
47322 +SOURCE=.\sqlite.c
\r
47323 +# ADD CPP /I "libsqlite\src"
\r
47324 +# End Source File
\r
47326 +# Begin Group "Header Files"
\r
47328 +# PROP Default_Filter "h;hpp;hxx;hm;inl"
\r
47329 +# Begin Source File
\r
47331 +SOURCE=.\php_sqlite.h
\r
47332 +# End Source File
\r
47337 +++ b/ext/sqlite/sqlite.php
47340 +if (!extension_loaded("sqlite")) {
47342 + if (!extension_loaded("sqlite")) {
47343 + exit("Please enable SQLite support\n");
47347 +debug_zval_dump(sqlite_libversion());
47348 +debug_zval_dump(sqlite_libencoding());
47350 +$s = sqlite_open("weztest.sqlite", 0666, $err);
47352 +debug_zval_dump($err);
47353 +debug_zval_dump($s);
47355 +$r = sqlite_query("create table foo (a INTEGER PRIMARY KEY, b INTEGER )", $s);
47356 +debug_zval_dump(sqlite_last_error($s));
47357 +debug_zval_dump(sqlite_error_string(sqlite_last_error($s)));
47359 +$r = sqlite_query("select *, php('md5', sql) as o from sqlite_master", $s);
47360 +debug_zval_dump($r);
47361 +debug_zval_dump(sqlite_num_rows($r));
47362 +debug_zval_dump(sqlite_num_fields($r));
47364 +for ($j = 0; $j < sqlite_num_fields($r); $j++) {
47365 + echo "Field $j is " . sqlite_field_name($r, $j) . "\n";
47368 +while ($row = sqlite_fetch_array($r, SQLITE_ASSOC)) {
47376 +++ b/ext/sqlite/tests/blankdb.inc
47379 +$db = sqlite_open(":memory:");
47382 +++ b/ext/sqlite/tests/blankdb_oo.inc
47385 +$db = new SQLiteDatabase(":memory:");
47388 +++ b/ext/sqlite/tests/bug26911.phpt
47391 +Bug #26911 (crash when fetching data from empty queries)
47393 +<?php if (!extension_loaded("sqlite")) print "skip"; ?>
47396 + $db = sqlite_open(":memory:");
47397 + $a = sqlite_query($db, " ");
47398 + echo "I am ok\n";
47403 +++ b/ext/sqlite/tests/bug28112.phpt
47406 +Bug #28112 (sqlite_query() crashing apache on malformed query)
47408 +<?php if (!extension_loaded("sqlite")) print "skip"; ?>
47412 +if (!($db = sqlite_open(":memory:", 666, $error))) die ("Couldn't open the database");
47413 +sqlite_query($db, "create table frob (foo INTEGER PRIMARY KEY, bar text);");
47414 +$res = @sqlite_array_query($db, "");
47422 +++ b/ext/sqlite/tests/bug35248.phpt
47425 +Bug #35248 (sqlite_query does not return parse error message)
47427 +<?php if (!extension_loaded("sqlite")) print "skip"; ?>
47430 + $db = sqlite_open(":memory:");
47431 + $res = @sqlite_query($db, "asdfesdfa", SQLITE_NUM, $err);
47433 + $res = @sqlite_unbuffered_query($db, "asdfesdfa", SQLITE_NUM, $err);
47437 +string(30) "near "asdfesdfa": syntax error"
47438 +string(30) "near "asdfesdfa": syntax error"
47440 +++ b/ext/sqlite/tests/bug38759.phpt
47443 +Bug #38759 (sqlite2 empty query causes segfault)
47446 +if (!extension_loaded("pdo")) print "skip";
47447 +if (!extension_loaded("sqlite")) print "skip";
47452 +$dbh = new PDO('sqlite2::memory:');
47453 +var_dump($dbh->query(" "));
47461 +++ b/ext/sqlite/tests/bug48679.phpt
47464 +Bug #48679 (sqlite2 count on unbuffered query causes segfault)
47467 +if (!extension_loaded("sqlite")) print "skip";
47473 + $x = new sqliteunbuffered;
47475 +} catch (SQLiteException $e) {
47476 + var_dump($e->getMessage());
47481 +string(41) "Row count is not available for this query"
47484 +++ b/ext/sqlite/tests/pdo/common.phpt
47489 +<?php # vim:ft=php
47490 +if (!extension_loaded('pdo') || !extension_loaded('sqlite')) print 'skip'; ?>
47494 + 'PDOTEST_DSN' => 'sqlite2::memory:'
47496 + 'TESTS' => 'ext/pdo/tests'
47499 +++ b/ext/sqlite/tests/sqlite_001.phpt
47502 +sqlite: sqlite_open/close
47504 +sqlite.assoc_case=0
47506 +<?php if (!extension_loaded("sqlite")) print "skip"; ?>
47509 +require_once('blankdb.inc');
47511 +sqlite_close($db);
47518 +++ b/ext/sqlite/tests/sqlite_002.phpt
47521 +sqlite: Simple insert/select
47523 +sqlite.assoc_case=0
47525 +<?php # vim:ft=php
47526 +if (!extension_loaded("sqlite")) print "skip"; ?>
47529 +include "blankdb.inc";
47531 +sqlite_query("CREATE TABLE foo(c1 date, c2 time, c3 varchar(64))", $db);
47532 +sqlite_query("INSERT INTO foo VALUES ('2002-01-02', '12:49:00', NULL)", $db);
47533 +$r = sqlite_query("SELECT * from foo", $db);
47534 +var_dump(sqlite_fetch_array($r));
47535 +sqlite_close($db);
47540 + string(10) "2002-01-02"
47542 + string(10) "2002-01-02"
47544 + string(8) "12:49:00"
47546 + string(8) "12:49:00"
47553 +++ b/ext/sqlite/tests/sqlite_003.phpt
47556 +sqlite: Simple insert/select, different result represenatation
47558 +sqlite.assoc_case=0
47561 +if (!extension_loaded("sqlite")) print "skip"; ?>
47564 +include "blankdb.inc";
47566 +sqlite_query("CREATE TABLE foo(c1 date, c2 time, c3 varchar(64))", $db);
47567 +sqlite_query("INSERT INTO foo VALUES ('2002-01-02', '12:49:00', NULL)", $db);
47568 +$r = sqlite_query("SELECT * from foo", $db);
47569 +var_dump(sqlite_fetch_array($r, SQLITE_BOTH));
47570 +$r = sqlite_query("SELECT * from foo", $db);
47571 +var_dump(sqlite_fetch_array($r, SQLITE_NUM));
47572 +$r = sqlite_query("SELECT * from foo", $db);
47573 +var_dump(sqlite_fetch_array($r, SQLITE_ASSOC));
47574 +sqlite_close($db);
47579 + string(10) "2002-01-02"
47581 + string(10) "2002-01-02"
47583 + string(8) "12:49:00"
47585 + string(8) "12:49:00"
47593 + string(10) "2002-01-02"
47595 + string(8) "12:49:00"
47601 + string(10) "2002-01-02"
47603 + string(8) "12:49:00"
47608 +++ b/ext/sqlite/tests/sqlite_004.phpt
47611 +sqlite: binary encoding
47613 +sqlite.assoc_case=0
47615 +<?php # vim:ft=php
47616 +if (!extension_loaded("sqlite")) print "skip"; ?>
47619 +include "blankdb.inc";
47624 + "\x01hello there",
47625 + "hello\x00there",
47629 +sqlite_query("CREATE TABLE strings(a)", $db);
47631 +foreach ($strings as $str) {
47632 + sqlite_query("INSERT INTO strings VALUES('" . sqlite_escape_string($str) . "')", $db);
47636 +$r = sqlite_query("SELECT * from strings", $db);
47637 +while ($row = sqlite_fetch_array($r, SQLITE_NUM)) {
47638 + if ($row[0] !== $strings[$i]) {
47640 + var_dump($row[0]);
47641 + var_dump($strings[$i]);
47648 +sqlite_close($db);
47660 +++ b/ext/sqlite/tests/sqlite_005.phpt
47663 +sqlite: aggregate functions
47665 +sqlite.assoc_case=0
47667 +<?php # vim:ft=php
47668 +if (!extension_loaded("sqlite")) print "skip"; ?>
47671 +include "blankdb.inc";
47679 +sqlite_query("CREATE TABLE strings(a)", $db);
47681 +foreach ($data as $str) {
47682 + sqlite_query("INSERT INTO strings VALUES('" . sqlite_escape_string($str) . "')", $db);
47685 +function cat_step(&$context, $string)
47687 + $context .= $string;
47690 +function cat_fin(&$context)
47695 +sqlite_create_aggregate($db, "cat", "cat_step", "cat_fin");
47697 +$r = sqlite_query("SELECT cat(a) from strings", $db);
47698 +while ($row = sqlite_fetch_array($r, SQLITE_NUM)) {
47702 +sqlite_close($db);
47709 + string(11) "onetwothree"
47713 +++ b/ext/sqlite/tests/sqlite_006.phpt
47716 +sqlite: regular functions
47718 +sqlite.assoc_case=0
47720 +<?php # vim:ft=php
47721 +if (!extension_loaded("sqlite")) print "skip"; ?>
47724 +include "blankdb.inc";
47727 + array("one", "uno"),
47728 + array("two", "dos"),
47729 + array("three", "tres"),
47732 +sqlite_query("CREATE TABLE strings(a,b)", $db);
47734 +function implode_args()
47736 + $args = func_get_args();
47737 + $sep = array_shift($args);
47738 + return implode($sep, $args);
47741 +foreach ($data as $row) {
47742 + sqlite_query("INSERT INTO strings VALUES('" . sqlite_escape_string($row[0]) . "','" . sqlite_escape_string($row[1]) . "')", $db);
47745 +sqlite_create_function($db, "implode", "implode_args");
47747 +$r = sqlite_query("SELECT implode('-', a, b) from strings", $db);
47748 +while ($row = sqlite_fetch_array($r, SQLITE_NUM)) {
47752 +sqlite_close($db);
47759 + string(7) "one-uno"
47763 + string(7) "two-dos"
47767 + string(10) "three-tres"
47771 +++ b/ext/sqlite/tests/sqlite_007.phpt
47774 +sqlite: Simple insert/select (unbuffered)
47776 +sqlite.assoc_case=0
47779 +if (!extension_loaded("sqlite")) print "skip"; ?>
47782 +include "blankdb.inc";
47784 +sqlite_query("CREATE TABLE foo(c1 date, c2 time, c3 varchar(64))", $db);
47785 +sqlite_query("INSERT INTO foo VALUES ('2002-01-02', '12:49:00', NULL)", $db);
47786 +$r = sqlite_unbuffered_query("SELECT * from foo", $db);
47787 +var_dump(sqlite_fetch_array($r, SQLITE_BOTH));
47788 +$r = sqlite_unbuffered_query("SELECT * from foo", $db);
47789 +var_dump(sqlite_fetch_array($r, SQLITE_NUM));
47790 +$r = sqlite_unbuffered_query("SELECT * from foo", $db);
47791 +var_dump(sqlite_fetch_array($r, SQLITE_ASSOC));
47792 +sqlite_close($db);
47797 + string(10) "2002-01-02"
47799 + string(10) "2002-01-02"
47801 + string(8) "12:49:00"
47803 + string(8) "12:49:00"
47811 + string(10) "2002-01-02"
47813 + string(8) "12:49:00"
47819 + string(10) "2002-01-02"
47821 + string(8) "12:49:00"
47826 +++ b/ext/sqlite/tests/sqlite_008.phpt
47829 +sqlite: fetch all (buffered)
47831 +sqlite.assoc_case=0
47833 +<?php # vim:ft=php
47834 +if (!extension_loaded("sqlite")) print "skip"; ?>
47837 +include "blankdb.inc";
47845 +sqlite_query("CREATE TABLE strings(a VARCHAR)", $db);
47847 +foreach ($data as $str) {
47848 + sqlite_query("INSERT INTO strings VALUES('$str')", $db);
47851 +$r = sqlite_query("SELECT a from strings", $db);
47852 +while ($row = sqlite_fetch_array($r, SQLITE_NUM)) {
47856 +sqlite_close($db);
47871 + string(5) "three"
47875 +++ b/ext/sqlite/tests/sqlite_009.phpt
47878 +sqlite: fetch all (unbuffered)
47880 +sqlite.assoc_case=0
47882 +<?php # vim:ft=php
47883 +if (!extension_loaded("sqlite")) print "skip"; ?>
47886 +include "blankdb.inc";
47894 +sqlite_query("CREATE TABLE strings(a VARCHAR)", $db);
47896 +foreach ($data as $str) {
47897 + sqlite_query("INSERT INTO strings VALUES('$str')", $db);
47900 +$r = sqlite_unbuffered_query("SELECT a from strings", $db);
47901 +while ($row = sqlite_fetch_array($r, SQLITE_NUM)) {
47905 +sqlite_close($db);
47920 + string(5) "three"
47924 +++ b/ext/sqlite/tests/sqlite_010.phpt
47927 +sqlite: fetch all (iterator)
47929 +sqlite.assoc_case=0
47931 +<?php # vim:ft=php
47932 +if (!extension_loaded("sqlite")) print "skip"; ?>
47935 +include "blankdb.inc";
47943 +sqlite_query("CREATE TABLE strings(a VARCHAR)", $db);
47945 +foreach ($data as $str) {
47946 + sqlite_query("INSERT INTO strings VALUES('$str')", $db);
47949 +$r = sqlite_unbuffered_query("SELECT a from strings", $db);
47950 +while (sqlite_valid($r)) {
47951 + var_dump(sqlite_current($r, SQLITE_NUM));
47954 +$r = sqlite_query("SELECT a from strings", $db);
47955 +while (sqlite_valid($r)) {
47956 + var_dump(sqlite_current($r, SQLITE_NUM));
47959 +sqlite_rewind($r);
47960 +while (sqlite_valid($r)) {
47961 + var_dump(sqlite_current($r, SQLITE_NUM));
47965 +sqlite_close($db);
47980 + string(5) "three"
47992 + string(5) "three"
48004 + string(5) "three"
48008 +++ b/ext/sqlite/tests/sqlite_011.phpt
48011 +sqlite: returned associative column names
48013 +sqlite.assoc_case=0
48016 +if (!extension_loaded("sqlite")) print "skip"; ?>
48019 +include "blankdb.inc";
48021 +sqlite_query("CREATE TABLE foo (c1 char, c2 char, c3 char)", $db);
48022 +sqlite_query("CREATE TABLE bar (c1 char, c2 char, c3 char)", $db);
48023 +sqlite_query("INSERT INTO foo VALUES ('1', '2', '3')", $db);
48024 +sqlite_query("INSERT INTO bar VALUES ('4', '5', '6')", $db);
48025 +$r = sqlite_query("SELECT * from foo, bar", $db, SQLITE_ASSOC);
48026 +var_dump(sqlite_fetch_array($r));
48027 +sqlite_close($db);
48045 +++ b/ext/sqlite/tests/sqlite_012.phpt
48048 +sqlite: read field names
48050 +sqlite.assoc_case=0
48052 +<?php # vim:ft=php
48053 +if (!extension_loaded("sqlite")) print "skip"; ?>
48056 +include "blankdb.inc";
48058 +sqlite_query("CREATE TABLE strings(foo VARCHAR, bar VARCHAR, baz VARCHAR)", $db);
48060 +echo "Buffered\n";
48061 +$r = sqlite_query("SELECT * from strings", $db);
48062 +for($i=0; $i<sqlite_num_fields($r); $i++) {
48063 + var_dump(sqlite_field_name($r, $i));
48065 +echo "Unbuffered\n";
48066 +$r = sqlite_unbuffered_query("SELECT * from strings", $db);
48067 +for($i=0; $i<sqlite_num_fields($r); $i++) {
48068 + var_dump(sqlite_field_name($r, $i));
48071 +sqlite_close($db);
48086 +++ b/ext/sqlite/tests/sqlite_013.phpt
48089 +sqlite: fetch column
48091 +sqlite.assoc_case=0
48093 +<?php # vim:ft=php
48094 +if (!extension_loaded("sqlite")) print "skip"; ?>
48097 +include "blankdb.inc";
48100 + array (0 => 'one', 1 => 'two'),
48101 + array (0 => 'three', 1 => 'four')
48104 +sqlite_query("CREATE TABLE strings(a VARCHAR, b VARCHAR)", $db);
48106 +foreach ($data as $str) {
48107 + sqlite_query("INSERT INTO strings VALUES('${str[0]}','${str[1]}')", $db);
48110 +echo "====BUFFERED====\n";
48111 +$r = sqlite_query("SELECT a, b from strings", $db);
48112 +while (sqlite_valid($r)) {
48113 + var_dump(sqlite_current($r, SQLITE_NUM));
48114 + var_dump(sqlite_column($r, 0));
48115 + var_dump(sqlite_column($r, 1));
48116 + var_dump(sqlite_column($r, 'a'));
48117 + var_dump(sqlite_column($r, 'b'));
48120 +echo "====UNBUFFERED====\n";
48121 +$r = sqlite_unbuffered_query("SELECT a, b from strings", $db);
48122 +while (sqlite_valid($r)) {
48123 + var_dump(sqlite_column($r, 0));
48124 + var_dump(sqlite_column($r, 'b'));
48125 + var_dump(sqlite_column($r, 1));
48126 + var_dump(sqlite_column($r, 'a'));
48130 +sqlite_close($db);
48148 + string(5) "three"
48156 +====UNBUFFERED====
48167 +++ b/ext/sqlite/tests/sqlite_014.phpt
48170 +sqlite: fetch all (fetch_all)
48172 +sqlite.assoc_case=0
48174 +<?php # vim:ft=php
48175 +if (!extension_loaded("sqlite")) print "skip"; ?>
48178 +include "blankdb.inc";
48186 +sqlite_query("CREATE TABLE strings(a VARCHAR)", $db);
48188 +foreach ($data as $str) {
48189 + sqlite_query("INSERT INTO strings VALUES('$str')", $db);
48192 +echo "unbuffered twice\n";
48193 +$r = sqlite_unbuffered_query("SELECT a from strings", $db, SQLITE_NUM);
48194 +var_dump(sqlite_fetch_all($r));
48195 +var_dump(sqlite_fetch_all($r));
48197 +echo "unbuffered with fetch_array\n";
48198 +$r = sqlite_unbuffered_query("SELECT a from strings", $db, SQLITE_NUM);
48199 +var_dump(sqlite_fetch_array($r));
48200 +var_dump(sqlite_fetch_all($r));
48202 +echo "buffered\n";
48203 +$r = sqlite_query("SELECT a from strings", $db, SQLITE_NUM);
48204 +var_dump(sqlite_fetch_all($r));
48205 +var_dump(sqlite_fetch_array($r));
48206 +var_dump(sqlite_fetch_all($r));
48208 +sqlite_close($db);
48228 + string(5) "three"
48232 +Warning: sqlite_fetch_all(): One or more rowsets were already returned; returning NULL this time in %ssqlite_014.php on line %d
48235 +unbuffered with fetch_array
48249 + string(5) "three"
48267 + string(5) "three"
48285 + string(5) "three"
48290 +++ b/ext/sqlite/tests/sqlite_015.phpt
48293 +sqlite: fetch all (array_query)
48295 +sqlite.assoc_case=0
48297 +<?php # vim:ft=php
48298 +if (!extension_loaded("sqlite")) print "skip"; ?>
48301 +include "blankdb.inc";
48309 +sqlite_query("CREATE TABLE strings(a VARCHAR)", $db);
48311 +foreach ($data as $str) {
48312 + sqlite_query("INSERT INTO strings VALUES('$str')", $db);
48315 +$res = sqlite_array_query("SELECT a from strings", $db, SQLITE_NUM);
48337 + string(5) "three"
48342 +++ b/ext/sqlite/tests/sqlite_016.phpt
48345 +sqlite: fetch single
48347 +sqlite.assoc_case=0
48349 +<?php # vim:ft=php
48350 +if (!extension_loaded("sqlite")) print "skip"; ?>
48353 +include "blankdb.inc";
48356 + array (0 => 'one', 1 => 'two'),
48357 + array (0 => 'three', 1 => 'four')
48360 +sqlite_query("CREATE TABLE strings(a VARCHAR, b VARCHAR)", $db);
48362 +foreach ($data as $str) {
48363 + sqlite_query("INSERT INTO strings VALUES('${str[0]}','${str[1]}')", $db);
48366 +echo "====BUFFERED====\n";
48367 +$r = sqlite_query("SELECT a, b from strings", $db);
48368 +while (sqlite_valid($r)) {
48369 + var_dump(sqlite_fetch_single($r));
48371 +echo "====UNBUFFERED====\n";
48372 +$r = sqlite_unbuffered_query("SELECT a, b from strings", $db);
48373 +while (sqlite_valid($r)) {
48374 + var_dump(sqlite_fetch_single($r));
48377 +sqlite_close($db);
48385 +====UNBUFFERED====
48390 +++ b/ext/sqlite/tests/sqlite_017.phpt
48393 +sqlite: UDF binary handling functions
48395 +<?php # vim:ft=php
48396 +if (!extension_loaded("sqlite")) print "skip"; ?>
48402 + "this has a \x00 char in the middle",
48403 + "\x01 this has an 0x01 at the start",
48404 + "this has \x01 in the middle"
48407 +foreach ($data as $item) {
48408 + $coded = sqlite_udf_encode_binary($item);
48409 + echo bin2hex($coded) . "\n";
48410 + $decoded = sqlite_udf_decode_binary($coded);
48411 + if ($item != $decoded) {
48412 + echo "FAIL! $item decoded is $decoded\n";
48420 +68656c6c6f207468657265
48421 +0101736768721f6760721f601fff1f626760711f686d1f7367641f6c6863636b64
48422 +0102ff1e726667711e665f711e5f6c1e2e762e2f1e5f721e7266631e71725f7072
48423 +7468697320686173200120696e20746865206d6964646c65
48426 +++ b/ext/sqlite/tests/sqlite_018.phpt
48429 +sqlite: crash on bad queries inside sqlite_array_query()
48431 +<?php # vim:ft=php
48432 +if (!extension_loaded("sqlite")) print "skip"; ?>
48435 +include "blankdb.inc";
48437 +sqlite_array_query($db, "SELECT foo FROM foobar");
48438 +sqlite_close($db);
48441 +Warning: sqlite_array_query(): no such table: foobar in %s on line %d
48443 +++ b/ext/sqlite/tests/sqlite_019.phpt
48446 +sqlite: single query
48448 +<?php # vim:ft=php
48449 +if (!extension_loaded("sqlite")) print "skip"; ?>
48452 +include "blankdb.inc";
48454 +sqlite_query($db, "CREATE TABLE test_db ( id INTEGER PRIMARY KEY, data VARCHAR(100) )");
48455 +for ($i = 0; $i < 10; $i++) {
48456 + sqlite_query($db, "INSERT INTO test_db (data) VALUES('{$i}data')");
48458 +sqlite_query($db, "INSERT INTO test_db (data) VALUES(NULL)");
48460 +var_dump(sqlite_single_query($db, "SELECT id FROM test_db WHERE id=5"));
48461 +var_dump(sqlite_single_query($db, "SELECT * FROM test_db WHERE id=4"));
48462 +var_dump(sqlite_single_query($db, "SELECT data FROM test_db WHERE id=6"));
48463 +var_dump(sqlite_single_query($db, "SELECT * FROM test_db WHERE id < 5"));
48464 +var_dump(sqlite_single_query($db, "SELECT * FROM test db WHERE id < 4"));
48465 +var_dump(sqlite_single_query($db, "SELECT * FROM test_db WHERE id=999999"));
48466 +var_dump(sqlite_single_query($db, "SELECT id FROM test_db WHERE id=5", FALSE));
48468 +sqlite_close($db);
48485 +Warning: sqlite_single_query(): no such table: test in %s on line %d
48493 +++ b/ext/sqlite/tests/sqlite_022.phpt
48496 +sqlite: sqlite_seek
48498 +sqlite.assoc_case=0
48500 +<?php # vim:ft=php
48501 +if (!extension_loaded("sqlite")) print "skip"; ?>
48504 +include "blankdb.inc";
48512 +sqlite_query("CREATE TABLE strings(a)", $db);
48514 +foreach ($data as $str) {
48515 + sqlite_query("INSERT INTO strings VALUES('$str')", $db);
48518 +$res = sqlite_query("SELECT a FROM strings", $db, SQLITE_NUM);
48519 +for ($idx = -1; $idx < 4; $idx++) {
48520 + echo "====SEEK:$idx====\n";
48521 + sqlite_seek($res, $idx);
48522 + var_dump(sqlite_current($res));
48524 +echo "====AGAIN====\n";
48525 +for ($idx = -1; $idx < 4; $idx++) {
48526 + echo "====SEEK:$idx====\n";
48527 + sqlite_seek($res, $idx);
48528 + var_dump(sqlite_current($res));
48531 +sqlite_close($db);
48533 +echo "====DONE!====\n";
48538 +Warning: sqlite_seek(): row -1 out of range in %ssqlite_022.php on line %d
48556 + string(5) "three"
48560 +Warning: sqlite_seek(): row 3 out of range in %ssqlite_022.php on line %d
48563 + string(5) "three"
48568 +Warning: sqlite_seek(): row -1 out of range in %ssqlite_022.php on line %d
48571 + string(5) "three"
48586 + string(5) "three"
48590 +Warning: sqlite_seek(): row 3 out of range in %ssqlite_022.php on line %d
48593 + string(5) "three"
48597 +++ b/ext/sqlite/tests/sqlite_023.phpt
48600 +sqlite: sqlite_[has_]prev
48602 +sqlite.assoc_case=0
48604 +<?php # vim:ft=php
48605 +if (!extension_loaded("sqlite")) print "skip"; ?>
48608 +include "blankdb.inc";
48616 +sqlite_query("CREATE TABLE strings(a)", $db);
48618 +foreach ($data as $str) {
48619 + sqlite_query("INSERT INTO strings VALUES('$str')", $db);
48622 +$r = sqlite_query("SELECT a FROM strings", $db, SQLITE_NUM);
48624 +echo "====TRAVERSE====\n";
48625 +for(sqlite_rewind($r); sqlite_valid($r); sqlite_next($r)) {
48626 + var_dump(sqlite_current($r));
48629 +echo "====REVERSE====\n";
48632 + var_dump(sqlite_current($r));
48633 +} while(sqlite_has_prev($r));
48635 +echo "====UNBUFFERED====\n";
48637 +$r = sqlite_unbuffered_query("SELECT a FROM strings", $db, SQLITE_NUM);
48639 +echo "====TRAVERSE====\n";
48640 +for(sqlite_rewind($r); sqlite_valid($r); sqlite_next($r)) {
48641 + var_dump(sqlite_current($r));
48644 +echo "====REVERSE====\n";
48647 + var_dump(sqlite_current($r));
48648 +} while(sqlite_has_prev($r));
48650 +sqlite_close($db);
48652 +echo "====DONE!====\n";
48666 + string(5) "three"
48671 + string(5) "three"
48681 +====UNBUFFERED====
48684 +Warning: sqlite_rewind(): Cannot rewind an unbuffered result set in %ssqlite_023.php on line %d
48695 + string(5) "three"
48699 +Warning: sqlite_prev(): you cannot use sqlite_prev on unbuffered querys in %ssqlite_023.php on line %d
48702 +Warning: sqlite_has_prev(): you cannot use sqlite_has_prev on unbuffered querys in %ssqlite_023.php on line %d
48705 +++ b/ext/sqlite/tests/sqlite_024.phpt
48708 +sqlite: sqlite_fetch_object
48710 +sqlite.assoc_case=0
48712 +<?php # vim:ft=php
48713 +if (!extension_loaded("sqlite")) print "skip"; ?>
48716 +include "blankdb.inc";
48719 + function __construct() {
48720 + echo __METHOD__ . "\n";
48730 +sqlite_query($db, "CREATE TABLE strings(a)");
48732 +foreach ($data as $str) {
48733 + sqlite_query($db, "INSERT INTO strings VALUES('$str')");
48736 +echo "====class24====\n";
48737 +$res = sqlite_query($db, "SELECT a FROM strings", SQLITE_ASSOC);
48738 +while (sqlite_valid($res)) {
48739 + var_dump(sqlite_fetch_object($res, 'class24'));
48742 +echo "====stdclass====\n";
48743 +$res = sqlite_query($db, "SELECT a FROM strings", SQLITE_ASSOC);
48744 +while (sqlite_valid($res)) {
48745 + var_dump(sqlite_fetch_object($res));
48748 +sqlite_close($db);
48750 +echo "====DONE!====\n";
48754 +class24::__construct
48755 +object(class24)#%d (1) {
48759 +class24::__construct
48760 +object(class24)#%d (1) {
48764 +class24::__construct
48765 +object(class24)#%d (1) {
48767 + string(5) "three"
48770 +object(stdClass)#%d (1) {
48774 +object(stdClass)#%d (1) {
48778 +object(stdClass)#%d (1) {
48780 + string(5) "three"
48784 +++ b/ext/sqlite/tests/sqlite_025.phpt
48787 +sqlite: sqlite_fetch_object in a loop
48789 +sqlite.assoc_case=0
48791 +<?php # vim:ft=php
48792 +if (!extension_loaded("sqlite")) print "skip"; ?>
48795 +include "blankdb.inc";
48797 +sqlite_query($db, "CREATE TABLE strings(a)");
48799 +foreach (array("one", "two", "three") as $str) {
48800 + sqlite_query($db, "INSERT INTO strings VALUES('$str')");
48803 +$res = sqlite_query("SELECT * FROM strings", $db);
48805 +while (($obj = sqlite_fetch_object($res))) {
48809 +sqlite_close($db);
48812 +object(stdClass)#1 (1) {
48816 +object(stdClass)#2 (1) {
48820 +object(stdClass)#1 (1) {
48822 + string(5) "three"
48824 \ No newline at end of file
48826 +++ b/ext/sqlite/tests/sqlite_026.phpt
48829 +sqlite: sqlite_fetch_column_types
48831 +<?php # vim:ft=php
48832 +if (!extension_loaded("sqlite")) print "skip"; ?>
48835 +include "blankdb.inc";
48837 +sqlite_query($db, "CREATE TABLE strings(a, b INTEGER, c VARCHAR(10), d)");
48838 +sqlite_query($db, "INSERT INTO strings VALUES('1', '2', '3', 'abc')");
48840 +var_dump(sqlite_fetch_column_types($db, "strings"));
48842 +sqlite_close($db);
48849 + string(7) "INTEGER"
48851 + string(11) "VARCHAR(10)"
48856 +++ b/ext/sqlite/tests/sqlite_027.phpt
48859 +sqlite: crash inside sqlite_escape_string() & sqlite_udf_encode_binary
48861 +<?php # vim:ft=php
48862 +if (!extension_loaded("sqlite")) print "skip"; ?>
48867 + var_dump(strlen(sqlite_escape_string(str_repeat("\0", 20000000))));
48868 + var_dump(strlen(sqlite_udf_encode_binary(str_repeat("\0", 20000000))));
48874 +++ b/ext/sqlite/tests/sqlite_closures_001.phpt
48877 +sqlite: aggregate functions with closures
48879 +sqlite.assoc_case=0
48881 +<?php # vim:ft=php
48882 +if (!extension_loaded("sqlite")) print "skip"; ?>
48885 +include "blankdb.inc";
48893 +sqlite_query("CREATE TABLE strings(a)", $db);
48895 +foreach ($data as $str) {
48896 + sqlite_query("INSERT INTO strings VALUES('" . sqlite_escape_string($str) . "')", $db);
48899 +function cat_step(&$context, $string)
48901 + $context .= $string;
48904 +function cat_fin(&$context)
48909 +sqlite_create_aggregate($db, "cat", function (&$context, $string) {
48910 + $context .= $string;
48911 +}, function (&$context) {
48915 +$r = sqlite_query("SELECT cat(a) from strings", $db);
48916 +while ($row = sqlite_fetch_array($r, SQLITE_NUM)) {
48920 +sqlite_close($db);
48927 + string(11) "onetwothree"
48931 +++ b/ext/sqlite/tests/sqlite_closures_002.phpt
48934 +sqlite: regular functions with closures
48936 +sqlite.assoc_case=0
48938 +<?php # vim:ft=php
48939 +if (!extension_loaded("sqlite")) print "skip"; ?>
48942 +include "blankdb.inc";
48945 + array("one", "uno"),
48946 + array("two", "dos"),
48947 + array("three", "tres"),
48950 +sqlite_query("CREATE TABLE strings(a,b)", $db);
48952 +foreach ($data as $row) {
48953 + sqlite_query("INSERT INTO strings VALUES('" . sqlite_escape_string($row[0]) . "','" . sqlite_escape_string($row[1]) . "')", $db);
48956 +sqlite_create_function($db, "implode", function () {
48957 + $args = func_get_args();
48958 + $sep = array_shift($args);
48959 + return implode($sep, $args);
48962 +$r = sqlite_query("SELECT implode('-', a, b) from strings", $db);
48963 +while ($row = sqlite_fetch_array($r, SQLITE_NUM)) {
48967 +sqlite_close($db);
48974 + string(7) "one-uno"
48978 + string(7) "two-dos"
48982 + string(10) "three-tres"
48986 +++ b/ext/sqlite/tests/sqlitedatabase_arrayquery.phpt
48989 +Testing SQLiteDatabase::ArrayQuery with NULL-byte string
48992 +if (!extension_loaded("sqlite")) print "skip";
48997 +$method = new ReflectionMethod('sqlitedatabase::arrayquery');
48999 +$class = $method->getDeclaringClass()->newInstanceArgs(array(':memory:'));
49003 +$method->invokeArgs($class, array_fill(0, 2, $p));
49004 +$method->invokeArgs($class, array_fill(0, 1, $p));
49008 +Warning: SQLiteDatabase::arrayQuery() expects parameter 2 to be long, string given in %s on line %d
49010 +Warning: SQLiteDatabase::arrayQuery(): Cannot execute empty query. in %s on line %d
49012 +++ b/ext/sqlite/tests/sqlite_exec_basic.phpt
49015 +Test sqlite_exec() function : basic functionality
49017 +<?php if (!extension_loaded("sqlite")) print "skip sqlite extension not loaded"; ?>
49020 +/* Prototype : boolean sqlite_exec(string query, resource db[, string &error_message])
49021 + * Description: Executes a result-less query against a given database
49022 + * Source code: ext/sqlite/sqlite.c
49023 + * Alias to functions:
49026 +echo "*** Testing sqlite_exec() : basic functionality ***\n";
49028 +// set up variables
49029 +$query = 'CREATE TABLE foobar (id INTEGER PRIMARY KEY, name CHAR(255));';
49030 +$error_message = null;
49033 +$db = sqlite_open(':memory:');
49034 +var_dump( sqlite_exec($db, $query) );
49035 +sqlite_close($db);
49038 +$db = new SQLiteDatabase(':memory:');
49039 +var_dump( $db->queryExec($query, $error_message) );
49044 +*** Testing sqlite_exec() : basic functionality ***
49049 +++ b/ext/sqlite/tests/sqlite_exec_error.phpt
49052 +Test sqlite_exec() function : error behaviour and functionality
49054 +<?php if (!extension_loaded("sqlite")) print "skip sqlite extension not loaded"; ?>
49057 +/* Prototype : boolean sqlite_exec(string query, resource db[, string &error_message])
49058 + * Description: Executes a result-less query against a given database
49059 + * Source code: ext/sqlite/sqlite.c
49060 + * Alias to functions:
49063 +echo "*** Testing sqlite_exec() : error functionality ***\n";
49065 +// set up variables
49066 +$fail = 'CRE ATE TABLE';
49067 +$error_message = null;
49070 +$db = sqlite_open(':memory:');
49071 +var_dump( sqlite_exec($db, $fail, $error_message) );
49072 +var_dump( $error_message );
49073 +var_dump( sqlite_exec($db) );
49074 +sqlite_close($db);
49077 +$db = new SQLiteDatabase(':memory:');
49078 +var_dump( $db->queryExec($fail, $error_message, 'fooparam') );
49083 +*** Testing sqlite_exec() : error functionality ***
49085 +Warning: sqlite_exec(): near "CRE": syntax error in %s on line %d
49087 +%string|unicode%(24) "near "CRE": syntax error"
49089 +Warning: sqlite_exec() expects at least 2 parameters, 1 given in %s on line %d
49092 +Warning: SQLiteDatabase::queryExec() expects at most 2 parameters, 3 given in %s on line %d
49096 +++ b/ext/sqlite/tests/sqlite_last_error_basic.phpt
49099 +Test sqlite_last_error() function : basic functionality
49101 +<?php if (!extension_loaded("sqlite")) print "skip sqlite extension not loaded"; ?>
49104 +/* Prototype : int sqlite_last_error(resource db)
49105 + * Description: Returns the error code of the last error for a database.
49106 + * Source code: ext/sqlite/sqlite.c
49107 + * Alias to functions:
49110 +echo "*** Testing sqlite_last_error() : basic functionality ***\n";
49112 +// set up variables
49113 +$query = 'CREATE TAB LE foobar (id INTEGER PRIMARY KEY, name CHAR(255));';
49114 +$query_ok = 'CREATE TABLE foobar (id INTEGER, name CHAR(255));';
49117 +$db = sqlite_open(':memory:');
49118 +var_dump( sqlite_last_error($db) === SQLITE_OK );
49119 +sqlite_exec($db, $query);
49120 +var_dump( sqlite_last_error($db) === SQLITE_ERROR );
49121 +sqlite_exec($db, $query_ok);
49122 +var_dump( sqlite_last_error($db) === SQLITE_OK );
49123 +sqlite_close($db);
49126 +$db = new SQLiteDatabase(':memory:');
49127 +$db->queryExec($query);
49128 +var_dump( $db->lastError() === SQLITE_ERROR );
49129 +$db->queryExec($query_ok);
49130 +var_dump( $db->lastError() === SQLITE_OK );
49135 +*** Testing sqlite_last_error() : basic functionality ***
49138 +Warning: sqlite_exec(): near "TAB": syntax error in %s on line %d
49142 +Warning: SQLiteDatabase::queryExec(): near "TAB": syntax error in %s on line %d
49147 +++ b/ext/sqlite/tests/sqlite_last_error_error.phpt
49150 +Test sqlite_last_error() function : error conditions
49152 +<?php if (!extension_loaded("sqlite")) print "skip sqlite extension not loaded"; ?>
49155 +/* Prototype : int sqlite_last_error(resource db)
49156 + * Description: Returns the error code of the last error for a database.
49157 + * Source code: ext/sqlite/sqlite.c
49158 + * Alias to functions:
49161 +echo "*** Testing sqlite_last_error() : error conditions ***\n";
49164 +echo "\n-- Testing sqlite_last_error() function with Zero arguments --\n";
49165 +var_dump( sqlite_last_error() );
49167 +//Test sqlite_last_error with one more than the expected number of arguments
49168 +echo "\n-- Testing sqlite_last_error() function with more than expected no. of arguments --\n";
49170 +$db = sqlite_open(':memory:');
49172 +var_dump( sqlite_last_error($db, $extra_arg) );
49173 +sqlite_close($db);
49175 +$db = new SQLiteDatabase(':memory:');
49176 +var_dump( $db->lastError($extra_arg) );
49181 +*** Testing sqlite_last_error() : error conditions ***
49183 +-- Testing sqlite_last_error() function with Zero arguments --
49185 +Warning: sqlite_last_error() expects exactly 1 parameter, 0 given in %s on line %d
49188 +-- Testing sqlite_last_error() function with more than expected no. of arguments --
49190 +Warning: sqlite_last_error() expects exactly 1 parameter, 2 given in %s on line %d
49193 +Warning: SQLiteDatabase::lastError() expects exactly 0 parameters, 1 given in %s on line %d
49197 +++ b/ext/sqlite/tests/sqlite_oo_001.phpt
49200 +sqlite-oo: sqlite_open/close
49202 +sqlite.assoc_case=0
49204 +<?php if (!extension_loaded("sqlite")) print "skip"; ?>
49207 +require_once('blankdb_oo.inc');
49213 +object(SQLiteDatabase)#%d (0) {
49217 +++ b/ext/sqlite/tests/sqlite_oo_002.phpt
49220 +sqlite-oo: Simple insert/select
49222 +sqlite.assoc_case=0
49224 +<?php # vim:ft=php
49225 +if (!extension_loaded("sqlite")) print "skip"; ?>
49228 +require_once('blankdb_oo.inc');
49231 +var_dump($db->query("CREATE TABLE foo(c1 date, c2 time, c3 varchar(64))"));
49232 +var_dump($db->query("INSERT INTO foo VALUES ('2002-01-02', '12:49:00', NULL)"));
49233 +$r = $db->query("SELECT * from foo");
49235 +var_dump($r->fetch());
49238 +object(SQLiteDatabase)#%d (0) {
49240 +object(SQLiteResult)#%d (0) {
49242 +object(SQLiteResult)#%d (0) {
49244 +object(SQLiteResult)#%d (0) {
49248 + string(10) "2002-01-02"
49250 + string(10) "2002-01-02"
49252 + string(8) "12:49:00"
49254 + string(8) "12:49:00"
49261 +++ b/ext/sqlite/tests/sqlite_oo_003.phpt
49264 +sqlite-oo: Simple insert/select, different result representation
49266 +sqlite.assoc_case=0
49268 +<?php # vim:ft=php
49269 +if (!extension_loaded("sqlite")) print "skip"; ?>
49272 +include "blankdb_oo.inc";
49274 +$db->query("CREATE TABLE foo(c1 date, c2 time, c3 varchar(64))");
49275 +$db->query("INSERT INTO foo VALUES ('2002-01-02', '12:49:00', NULL)");
49276 +$r = $db->query("SELECT * from foo");
49277 +var_dump($r->fetch(SQLITE_BOTH));
49278 +$r = $db->query("SELECT * from foo");
49279 +var_dump($r->fetch(SQLITE_NUM));
49280 +$r = $db->query("SELECT * from foo");
49281 +var_dump($r->fetch(SQLITE_ASSOC));
49286 + string(10) "2002-01-02"
49288 + string(10) "2002-01-02"
49290 + string(8) "12:49:00"
49292 + string(8) "12:49:00"
49300 + string(10) "2002-01-02"
49302 + string(8) "12:49:00"
49308 + string(10) "2002-01-02"
49310 + string(8) "12:49:00"
49315 +++ b/ext/sqlite/tests/sqlite_oo_008.phpt
49318 +sqlite-oo: fetch all (buffered)
49320 +sqlite.assoc_case=0
49322 +<?php # vim:ft=php
49323 +if (!extension_loaded("sqlite")) print "skip"; ?>
49326 +include "blankdb_oo.inc";
49334 +$db->query("CREATE TABLE strings(a VARCHAR)");
49336 +foreach ($data as $str) {
49337 + $db->query("INSERT INTO strings VALUES('$str')");
49340 +$r = $db->query("SELECT a from strings");
49341 +while ($row = $r->fetch(SQLITE_NUM)) {
49357 + string(5) "three"
49361 +++ b/ext/sqlite/tests/sqlite_oo_009.phpt
49364 +sqlite-oo: fetch all (unbuffered)
49366 +sqlite.assoc_case=0
49368 +<?php # vim:ft=php
49369 +if (!extension_loaded("sqlite")) print "skip"; ?>
49372 +include "blankdb_oo.inc";
49380 +$db->query("CREATE TABLE strings(a VARCHAR)");
49382 +foreach ($data as $str) {
49383 + $db->query("INSERT INTO strings VALUES('$str')");
49386 +$r = $db->unbufferedQuery("SELECT a from strings");
49387 +while ($row = $r->fetch(SQLITE_NUM)) {
49403 + string(5) "three"
49407 +++ b/ext/sqlite/tests/sqlite_oo_010.phpt
49410 +sqlite-oo: fetch all (iterator)
49412 +sqlite.assoc_case=0
49414 +<?php # vim:ft=php
49415 +if (!extension_loaded("sqlite")) print "skip"; ?>
49418 +include "blankdb_oo.inc";
49426 +$db->query("CREATE TABLE strings(a VARCHAR)");
49428 +foreach ($data as $str) {
49429 + $db->query("INSERT INTO strings VALUES('$str')");
49432 +$r = $db->unbufferedQuery("SELECT a from strings", SQLITE_NUM);
49433 +while ($row = $r->valid()) {
49434 + var_dump($r->current());
49450 + string(5) "three"
49454 +++ b/ext/sqlite/tests/sqlite_oo_011.phpt
49457 +sqlite-oo: returned associative column names
49459 +sqlite.assoc_case=0
49461 +<?php # vim:ft=php
49462 +if (!extension_loaded("sqlite")) print "skip"; ?>
49465 +include "blankdb_oo.inc";
49467 +$db->query("CREATE TABLE foo (c1 char, c2 char, c3 char)");
49468 +$db->query("CREATE TABLE bar (c1 char, c2 char, c3 char)");
49469 +$db->query("INSERT INTO foo VALUES ('1', '2', '3')");
49470 +$db->query("INSERT INTO bar VALUES ('4', '5', '6')");
49471 +$r = $db->query("SELECT * from foo, bar", SQLITE_ASSOC);
49472 +var_dump($r->fetch());
49490 +++ b/ext/sqlite/tests/sqlite_oo_012.phpt
49493 +sqlite-oo: read field names
49495 +sqlite.assoc_case=0
49497 +<?php # vim:ft=php
49498 +if (!extension_loaded("sqlite")) print "skip"; ?>
49501 +include "blankdb_oo.inc";
49503 +$db->query("CREATE TABLE strings(foo VARCHAR, bar VARCHAR, baz VARCHAR)");
49505 +echo "Buffered\n";
49506 +$r = $db->query("SELECT * from strings");
49507 +for($i=0; $i<$r->numFields(); $i++) {
49508 + var_dump($r->fieldName($i));
49510 +echo "Unbuffered\n";
49511 +$r = $db->unbufferedQuery("SELECT * from strings");
49512 +for($i=0; $i<$r->numFields(); $i++) {
49513 + var_dump($r->fieldName($i));
49528 +++ b/ext/sqlite/tests/sqlite_oo_013.phpt
49531 +sqlite-oo: fetch column
49533 +sqlite.assoc_case=0
49535 +<?php # vim:ft=php
49536 +if (!extension_loaded("sqlite")) print "skip"; ?>
49539 +include "blankdb_oo.inc";
49542 + array (0 => 'one', 1 => 'two'),
49543 + array (0 => 'three', 1 => 'four')
49546 +$db->query("CREATE TABLE strings(a VARCHAR, b VARCHAR)");
49548 +foreach ($data as $str) {
49549 + $db->query("INSERT INTO strings VALUES('${str[0]}','${str[1]}')");
49552 +echo "====BUFFERED====\n";
49553 +$r = $db->query("SELECT a, b from strings");
49554 +while ($r->valid()) {
49555 + var_dump($r->current(SQLITE_NUM));
49556 + var_dump($r->column(0));
49557 + var_dump($r->column(1));
49558 + var_dump($r->column('a'));
49559 + var_dump($r->column('b'));
49562 +echo "====UNBUFFERED====\n";
49563 +$r = $db->unbufferedQuery("SELECT a, b from strings");
49564 +while ($r->valid()) {
49565 + var_dump($r->column(0));
49566 + var_dump($r->column('b'));
49567 + var_dump($r->column(1));
49568 + var_dump($r->column('a'));
49587 + string(5) "three"
49595 +====UNBUFFERED====
49606 +++ b/ext/sqlite/tests/sqlite_oo_014.phpt
49609 +sqlite-oo: fetch all
49611 +sqlite.assoc_case=0
49613 +<?php # vim:ft=php
49614 +if (!extension_loaded("sqlite")) print "skip"; ?>
49617 +include "blankdb_oo.inc";
49625 +$db->query("CREATE TABLE strings(a VARCHAR)");
49627 +foreach ($data as $str) {
49628 + $db->query("INSERT INTO strings VALUES('$str')");
49631 +echo "unbuffered twice\n";
49632 +$r = $db->unbufferedQuery("SELECT a from strings", SQLITE_NUM);
49633 +var_dump($r->fetchAll());
49634 +var_dump($r->fetchAll());
49636 +echo "unbuffered with fetch_array\n";
49637 +$r = $db->unbufferedQuery("SELECT a from strings", SQLITE_NUM);
49638 +var_dump($r->fetch());
49639 +var_dump($r->fetchAll());
49641 +echo "buffered\n";
49642 +$r = $db->query("SELECT a from strings", SQLITE_NUM);
49643 +var_dump($r->fetchAll());
49644 +var_dump($r->fetch());
49645 +var_dump($r->fetchAll());
49665 + string(5) "three"
49669 +Warning: SQLiteUnbuffered::fetchAll(): One or more rowsets were already returned; returning NULL this time in %ssqlite_oo_014.php on line %d
49672 +unbuffered with fetch_array
49686 + string(5) "three"
49704 + string(5) "three"
49722 + string(5) "three"
49727 +++ b/ext/sqlite/tests/sqlite_oo_015.phpt
49730 +sqlite-oo: array_query
49732 +sqlite.assoc_case=0
49734 +<?php # vim:ft=php
49735 +if (!extension_loaded("sqlite")) print "skip"; ?>
49738 +include "blankdb_oo.inc";
49746 +$db->query("CREATE TABLE strings(a VARCHAR)");
49748 +foreach ($data as $str) {
49749 + $db->query("INSERT INTO strings VALUES('$str')");
49752 +$res = $db->arrayQuery("SELECT a from strings", SQLITE_NUM);
49772 + string(5) "three"
49777 +++ b/ext/sqlite/tests/sqlite_oo_016.phpt
49780 +sqlite-oo: fetch single
49782 +sqlite.assoc_case=0
49784 +<?php # vim:ft=php
49785 +if (!extension_loaded("sqlite")) print "skip"; ?>
49788 +include "blankdb_oo.inc";
49791 + array (0 => 'one', 1 => 'two'),
49792 + array (0 => 'three', 1 => 'four')
49795 +$db->query("CREATE TABLE strings(a VARCHAR, b VARCHAR)");
49797 +foreach ($data as $str) {
49798 + $db->query("INSERT INTO strings VALUES('${str[0]}','${str[1]}')");
49801 +echo "====BUFFERED====\n";
49802 +$r = $db->query("SELECT a, b from strings");
49803 +while ($r->valid()) {
49804 + var_dump($r->fetchSingle());
49806 +echo "====UNBUFFERED====\n";
49807 +$r = $db->unbufferedQuery("SELECT a, b from strings");
49808 +while ($r->valid()) {
49809 + var_dump($r->fetchSingle());
49817 +====UNBUFFERED====
49822 +++ b/ext/sqlite/tests/sqlite_oo_020.phpt
49825 +sqlite-oo: factory and exception
49827 +sqlite.assoc_case=0
49829 +<?php # vim:ft=php
49830 +if (!extension_loaded("sqlite")) print "skip"; ?>
49833 +$dbname = tempnam(dirname(__FILE__), "phpsql");
49834 +function cleanup() {
49835 + global $db, $dbname;
49840 +register_shutdown_function("cleanup");
49843 + $db = sqlite_factory();
49844 +} catch(SQLiteException $err) {
49845 + echo "Message: ".$err->getMessage()."\n";
49846 + echo "File: ".$err->getFile()."\n";
49847 + //echo "Line: ".$err->getLine()."\n";
49848 + //print_r($err->getTrace());
49849 + //echo "BackTrace: ".$err->getTraceAsString()."\n";
49852 +$db = sqlite_factory($dbname);
49855 + array (0 => 'one', 1 => 'two'),
49856 + array (0 => 'three', 1 => 'four')
49859 +$db->query("CREATE TABLE strings(a VARCHAR, b VARCHAR)");
49861 +foreach ($data as $str) {
49862 + $db->query("INSERT INTO strings VALUES('${str[0]}','${str[1]}')");
49865 +$r = $db->unbufferedQuery("SELECT a, b from strings");
49866 +while ($r->valid()) {
49867 + var_dump($r->current(SQLITE_NUM));
49875 +Message: sqlite_factory() expects at least 1 parameter, 0 given
49876 +File: %ssqlite_oo_020.php
49885 + string(5) "three"
49891 +++ b/ext/sqlite/tests/sqlite_oo_021.phpt
49894 +sqlite-oo: single query
49896 +<?php # vim:ft=php
49897 +if (!extension_loaded("sqlite")) print "skip"; ?>
49900 +include "blankdb_oo.inc";
49902 +$db->query("CREATE TABLE test_db ( id INTEGER PRIMARY KEY, data VARCHAR(100) )");
49903 +for ($i = 0; $i < 10; $i++) {
49904 + $db->query("INSERT INTO test_db (data) VALUES('{$i}data')");
49906 +$db->query("INSERT INTO test_db (data) VALUES(NULL)");
49908 +var_dump($db->singleQuery("SELECT id FROM test_db WHERE id=5"));
49909 +var_dump($db->singleQuery("SELECT * FROM test_db WHERE id=4"));
49910 +var_dump($db->singleQuery("SELECT data FROM test_db WHERE id=6"));
49911 +var_dump($db->singleQuery("SELECT * FROM test_db WHERE id < 5"));
49912 +var_dump($db->singleQuery("SELECT * FROM test db WHERE id < 4"));
49913 +var_dump($db->singleQuery("SELECT * FROM test_db WHERE id=999999"));
49914 +var_dump($db->singleQuery("SELECT id FROM test_db WHERE id=5", FALSE));
49933 +Warning: SQLiteDatabase::singleQuery(): no such table: test in %s on line %d
49942 +++ b/ext/sqlite/tests/sqlite_oo_022.phpt
49945 +sqlite-oo: sqlite::seek
49947 +sqlite.assoc_case=0
49949 +<?php # vim:ft=php
49950 +if (!extension_loaded("sqlite")) print "skip"; ?>
49953 +include "blankdb_oo.inc";
49961 +$db->query("CREATE TABLE strings(a)");
49963 +foreach ($data as $str) {
49964 + $db->query("INSERT INTO strings VALUES('$str')");
49967 +$res = $db->query("SELECT a FROM strings", SQLITE_NUM);
49968 +for ($idx = -1; $idx < 4; $idx++) {
49969 + echo "====SEEK:$idx====\n";
49970 + $res->seek($idx);
49971 + var_dump($res->current());
49973 +echo "====AGAIN====\n";
49974 +for ($idx = -1; $idx < 4; $idx++) {
49975 + echo "====SEEK:$idx====\n";
49976 + $res->seek($idx);
49977 + var_dump($res->current());
49979 +echo "====DONE!====\n";
49984 +Warning: SQLiteResult::seek(): row -1 out of range in %ssqlite_oo_022.php on line %d
50002 + string(5) "three"
50006 +Warning: SQLiteResult::seek(): row 3 out of range in %ssqlite_oo_022.php on line %d
50009 + string(5) "three"
50014 +Warning: SQLiteResult::seek(): row -1 out of range in %ssqlite_oo_022.php on line %d
50017 + string(5) "three"
50032 + string(5) "three"
50036 +Warning: SQLiteResult::seek(): row 3 out of range in %ssqlite_oo_022.php on line %d
50039 + string(5) "three"
50043 +++ b/ext/sqlite/tests/sqlite_oo_024.phpt
50046 +sqlite-oo: sqlite::fetch_object
50048 +sqlite.assoc_case=0
50050 +<?php # vim:ft=php
50051 +if (!extension_loaded("sqlite")) print "skip"; ?>
50054 +include "blankdb_oo.inc";
50057 + function __construct() {
50058 + echo __METHOD__ . "\n";
50068 +$db->query("CREATE TABLE strings(a)");
50070 +foreach ($data as $str) {
50071 + $db->query("INSERT INTO strings VALUES('$str')");
50074 +echo "====class24====\n";
50075 +$res = $db->query("SELECT a FROM strings", SQLITE_ASSOC);
50076 +while ($res->valid()) {
50077 + var_dump($res->fetchObject('class24'));
50080 +echo "====stdclass====\n";
50081 +$res = $db->query("SELECT a FROM strings", SQLITE_ASSOC);
50082 +while ($res->valid()) {
50083 + var_dump($res->fetchObject());
50086 +echo "====DONE!====\n";
50090 +class24::__construct
50091 +object(class24)#%d (1) {
50095 +class24::__construct
50096 +object(class24)#%d (1) {
50100 +class24::__construct
50101 +object(class24)#%d (1) {
50103 + string(5) "three"
50106 +object(stdClass)#%d (1) {
50110 +object(stdClass)#%d (1) {
50114 +object(stdClass)#%d (1) {
50116 + string(5) "three"
50120 +++ b/ext/sqlite/tests/sqlite_oo_025.phpt
50123 +sqlite-oo: sqlite / foreach
50125 +sqlite.assoc_case=0
50127 +<?php # vim:ft=php
50128 +if (!extension_loaded("sqlite")) print "skip";
50132 +include "blankdb_oo.inc";
50140 +$db->query("CREATE TABLE strings(a VARCHAR)");
50142 +foreach ($data as $str) {
50143 + $db->query("INSERT INTO strings VALUES('$str')");
50146 +echo "====UNBUFFERED====\n";
50147 +$r = $db->unbufferedQuery("SELECT a from strings", SQLITE_NUM);
50148 +//var_dump(class_implements($r));
50149 +foreach($r as $row) {
50152 +echo "====NO-MORE====\n";
50153 +foreach($r as $row) {
50156 +echo "====DIRECT====\n";
50157 +foreach($db->unbufferedQuery("SELECT a from strings", SQLITE_NUM) as $row) {
50160 +echo "====BUFFERED====\n";
50161 +$r = $db->query("SELECT a from strings", SQLITE_NUM);
50162 +//var_dump(class_implements($r));
50163 +foreach($r as $row) {
50166 +foreach($r as $row) {
50172 +====UNBUFFERED====
50183 + string(5) "three"
50197 + string(5) "three"
50210 + string(5) "three"
50222 + string(5) "three"
50226 +++ b/ext/sqlite/tests/sqlite_oo_026.phpt
50229 +sqlite-oo: unbuffered
50231 +sqlite.assoc_case=0
50233 +<?php # vim:ft=php
50234 +if (!extension_loaded("sqlite")) print "skip";
50238 +include "blankdb_oo.inc";
50246 +$db->query("CREATE TABLE strings(a VARCHAR)");
50248 +foreach ($data as $str) {
50249 + $db->query("INSERT INTO strings VALUES('$str')");
50252 +echo "====FOREACH====\n";
50253 +$r = $db->unbufferedQuery("SELECT a from strings", SQLITE_NUM);
50254 +foreach($r as $idx => $row) {
50255 + var_dump($row[0]);
50256 + var_dump($row[0]);
50258 +echo "====FOR====\n";
50259 +$r = $db->unbufferedQuery("SELECT a from strings", SQLITE_NUM);
50260 +for(;$r->valid(); $r->next()) {
50261 + $v = $r->column(0);
50263 + $c = $r->column(0);
50264 + var_dump(is_null($c) || $c==$v);
50266 +echo "===DONE===\n";
50285 +++ b/ext/sqlite/tests/sqlite_oo_027.phpt
50288 +sqlite-oo: changes
50290 +sqlite.assoc_case=0
50292 +<?php # vim:ft=php
50293 +if (!extension_loaded("sqlite")) print "skip";
50297 +include "blankdb_oo.inc";
50299 +$data = array("one", "two", "three");
50301 +$db->query("CREATE TABLE strings(a VARCHAR)");
50303 +foreach ($data as $str) {
50304 + $db->query("INSERT INTO strings VALUES('$str')");
50305 + echo $db->changes() . "\n";
50308 +$db->query("UPDATE strings SET a='foo' WHERE a!='two'");
50309 +echo $db->changes() . "\n";
50311 +$db->query("DELETE FROM strings WHERE 1");
50312 +echo $db->changes() . "\n";
50315 +foreach ($data as $s) {
50316 + $str .= "INSERT INTO strings VALUES('".$s."');";
50319 +echo $db->changes() . "\n";
50330 +++ b/ext/sqlite/tests/sqlite_oo_028.phpt
50333 +sqlite-oo: sqlite_fetch_column_types
50335 +<?php # vim:ft=php
50336 +if (!extension_loaded("sqlite")) print "skip"; ?>
50339 +include "blankdb_oo.inc";
50341 +$db->query("CREATE TABLE strings(a, b INTEGER, c VARCHAR(10), d)");
50342 +$db->query("INSERT INTO strings VALUES('1', '2', '3', 'abc')");
50344 +var_dump($db->fetchColumnTypes("strings"));
50351 + string(7) "INTEGER"
50353 + string(11) "VARCHAR(10)"
50358 +++ b/ext/sqlite/tests/sqlite_oo_029.phpt
50361 +sqlite-oo: call method with $this
50363 +<?php # vim:ft=php
50364 +if (!extension_loaded("sqlite")) print "skip";
50368 +include "blankdb_oo.inc";
50370 +$db->query("CREATE TABLE strings(key VARCHAR(10), var VARCHAR(10))");
50371 +$db->query("INSERT INTO strings VALUES('foo', 'foo')");
50375 + function __construct($db){
50377 + $this->db->createFunction('link_keywords', array(&$this, 'linkers'), 1);
50380 + function getSingle($key)
50382 + return $this->db->singleQuery('SELECT link_keywords(var) FROM strings WHERE key=\''.$key.'\'', 1);
50385 + function linkers($str)
50387 + $str = str_replace('foo', 'bar', $str);
50393 + unset($this->db);
50396 + function __destruct()
50398 + echo "DESTRUCTED\n";
50402 +$obj = new sqlite_help($db);
50403 +echo $obj->getSingle('foo')."\n";
50414 +++ b/ext/sqlite/tests/sqlite_oo_030.phpt
50417 +sqlite-oo: calling static methods
50419 +sqlite.assoc_case=0
50421 +<?php # vim:ft=php
50422 +if (!extension_loaded("sqlite")) print "skip";
50427 +require_once('blankdb_oo.inc');
50430 + static function bar($param = NULL) {
50435 +function baz($param = NULL) {
50439 +var_dump($db->singleQuery("select php('baz')", 1));
50440 +var_dump($db->singleQuery("select php('baz', 1)", 1));
50441 +var_dump($db->singleQuery("select php('baz', \"PHP\")", 1));
50442 +var_dump($db->singleQuery("select php('foo::bar')", 1));
50443 +var_dump($db->singleQuery("select php('foo::bar', 1)", 1));
50444 +var_dump($db->singleQuery("select php('foo::bar', \"PHP\")", 1));
50445 +var_dump($db->singleQuery("select php('foo::bar(\"PHP\")')", 1));
50457 +Warning: SQLiteDatabase::singleQuery(): function `foo::bar("PHP")' is not a function name in %ssqlite_oo_030.php on line %d
50461 +++ b/ext/sqlite/tests/sqlite_popen_basic.phpt
50464 +SQLite: sqlite_popen() basic tests
50466 +<?php if (!extension_loaded("sqlite")) print "skip"; ?>
50469 +/* Prototype : resource sqlite_popen(string filename [, int mode [, string &error_message]])
50470 + * Description: Opens a persistent handle to a SQLite database. Will create the database if it does not exist.
50471 + * Source code: ext/sqlite/sqlite.c
50472 + * Alias to functions:
50475 + $db1 = sqlite_popen(":memory:");
50476 + $db2 = sqlite_popen(":memory:");
50481 + list($resourceId1) = sscanf((string) $db1, "resource(%d) of type (sqlite database (persistent))");
50482 + list($resourceId2) = sscanf((string) $db2, "resource(%d) of type (sqlite database (persistent))");
50484 + var_dump($resourceId1 === $resourceId2);
50487 +resource(%d) of type (sqlite database (persistent))
50488 +resource(%d) of type (sqlite database (persistent))
50491 +++ b/ext/sqlite/tests/sqlite_popen_error.phpt
50494 +Test sqlite_popen() function : error conditions
50496 +<?php if (!extension_loaded("sqlite")) print "skip sqlite extension not loaded"; ?>
50499 +/* Prototype : resource sqlite_popen(string filename [, int mode [, string &error_message]])
50500 + * Description: Opens a persistent handle to a SQLite database. Will create the database if it does not exist.
50501 + * Source code: ext/sqlite/sqlite.c
50502 + * Alias to functions:
50507 +echo "*** Testing sqlite_popen() : error conditions ***\n";
50509 +var_dump( sqlite_popen() );
50510 +var_dump( sqlite_popen(":memory:", 0666, $message, 'foobar') );
50511 +var_dump( sqlite_popen("", 0666, $message) );
50512 +var_dump( $message );
50517 +*** Testing sqlite_popen() : error conditions ***
50519 +Warning: sqlite_popen() expects at least 1 parameter, 0 given in %s on line %d
50522 +Warning: sqlite_popen() expects at most 3 parameters, 4 given in %s on line %d
50528 +++ b/ext/sqlite/tests/sqlite_session_001.phpt
50531 +sqlite, session storage test
50533 +Mats Lindh <mats at lindh.no>
50536 +session.save_handler = sqlite
50538 +if (!extension_loaded("session"))
50540 + die("skip Session module not loaded");
50542 +if (!extension_loaded("sqlite"))
50544 + die("skip Session module not loaded");
50548 +/* Description: Tests that sqlite can be used as a session save handler
50549 +* Source code: ext/sqlite/sess_sqlite.c
50553 +session_save_path(__DIR__ . "/sessiondb.sdb");
50555 +// create the session and set a session value
50557 +$_SESSION["test"] = "foo_bar";
50559 +// close the session and unset the value
50560 +session_write_close();
50561 +unset($_SESSION["test"]);
50562 +var_dump(isset($_SESSION["test"]));
50564 +// start the session again and check that we have the proper value
50566 +var_dump($_SESSION["test"]);
50571 +%unicode|string%(7) "foo_bar"
50574 + unlink(__DIR__ . "/sessiondb.sdb")
50577 +++ b/ext/sqlite/tests/sqlite_session_002.phpt
50580 +sqlite, session destroy test
50582 +Mats Lindh <mats at lindh.no>
50585 +session.save_handler = sqlite
50587 +if (!extension_loaded("session"))
50589 + die("skip Session module not loaded");
50591 +if (!extension_loaded("sqlite"))
50593 + die("skip sqlite module not loaded");
50597 +/* Description: Tests that sqlite will destroy a session when used as a session handler
50598 +* Source code: ext/sqlite/sess_sqlite.c
50601 +session_save_path(__DIR__ . "/sessiondb.sdb");
50603 +// start a session and save a value to it before commiting the session to the database
50605 +$_SESSION["test"] = "foo_bar";
50606 +session_write_close();
50608 +// remove the session value
50609 +unset($_SESSION["test"]);
50610 +var_dump(isset($_SESSION["test"]));
50612 +// start the session again and destroy it
50614 +var_dump($_SESSION["test"]);
50615 +session_destroy();
50616 +session_write_close();
50618 +unset($_SESSION["test"]);
50620 +// check that the session has been destroyed
50622 +var_dump(isset($_SESSION["test"]));
50627 +%unicode|string%(7) "foo_bar"
50631 + unlink(__DIR__ . "/sessiondb.sdb")
50634 +++ b/ext/sqlite/tests/sqlite_spl_001.phpt
50637 +sqlite-spl: Iteration
50639 +<?php # vim:ft=php
50640 +if (!extension_loaded("sqlite")) print "skip";
50641 +if (!extension_loaded("spl")) print "skip SPL is not present";
50645 +include "blankdb_oo.inc";
50647 +$db->query("CREATE TABLE menu(id_l int PRIMARY KEY, id_r int UNIQUE, key VARCHAR(10))");
50648 +$db->query("INSERT INTO menu VALUES( 1, 12, 'A')");
50649 +$db->query("INSERT INTO menu VALUES( 2, 9, 'B')");
50650 +$db->query("INSERT INTO menu VALUES(10, 11, 'F')");
50651 +$db->query("INSERT INTO menu VALUES( 3, 6, 'C')");
50652 +$db->query("INSERT INTO menu VALUES( 7, 8, 'E')");
50653 +$db->query("INSERT INTO menu VALUES( 4, 5, 'D')");
50655 +class SqliteNestedsetElement
50661 + function __construct($db)
50666 + function getLeft()
50668 + return $this->id_l;
50671 + function getRight()
50673 + return $this->id_r;
50676 + function __toString()
50678 + return $this->key;
50683 + return $this->key;
50687 +class SqliteNestedset implements RecursiveIterator
50692 + protected $entry;
50694 + function __construct($db, $id_l = 1)
50697 + $this->id_l = $id_l;
50698 + $this->id_r = $this->db->singleQuery('SELECT id_r FROM menu WHERE id_l='.$id_l, 1);
50699 + $this->id = $id_l;
50702 + function rewind()
50704 + $this->id = $this->id_l;
50710 + return is_object($this->entry);
50713 + function current()
50715 + return $this->entry->__toString();
50720 + return $this->entry->key();;
50725 + $this->id = $this->entry->getRight() + 1;
50729 + protected function fetch()
50731 + $res = $this->db->unbufferedQuery('SELECT * FROM menu WHERE id_l='.$this->id);
50732 + $this->entry = $res->fetchObject('SqliteNestedsetElement', array(&$this->db));
50736 + function hasChildren()
50738 + return $this->entry->getLeft() + 1 < $this->entry->getRight();
50741 + function getChildren()
50743 + return new SqliteNestedset($this->db, $this->entry->getLeft() + 1, $this->entry->getRight() - 1);
50747 +$menu_iterator = new RecursiveIteratorIterator(new SqliteNestedset($db), RecursiveIteratorIterator::SELF_FIRST);
50748 +foreach($menu_iterator as $entry) {
50749 + echo $menu_iterator->getDepth() . $entry . "\n";
50762 +++ b/ext/sqlite/tests/sqlite_spl_002.phpt
50765 +sqlite-spl: Countable
50767 +<?php # vim:ft=php
50768 +if (!extension_loaded("sqlite")) print "skip";
50769 +if (!extension_loaded("spl")) print "skip SPL is not present";
50773 +include "blankdb_oo.inc";
50775 +$db->query("CREATE TABLE menu(id_l int PRIMARY KEY, id_r int UNIQUE, key VARCHAR(10))");
50776 +$db->query("INSERT INTO menu VALUES( 1, 12, 'A')");
50777 +$db->query("INSERT INTO menu VALUES( 2, 9, 'B')");
50778 +$db->query("INSERT INTO menu VALUES(10, 11, 'F')");
50779 +$db->query("INSERT INTO menu VALUES( 3, 6, 'C')");
50780 +$db->query("INSERT INTO menu VALUES( 7, 8, 'E')");
50781 +$db->query("INSERT INTO menu VALUES( 4, 5, 'D')");
50783 +$res = $db->query("SELECT * from menu");
50785 +var_dump($res->count());
50786 +var_dump(count($res));
50794 +++ b/ext/sqlite/tests/sqlite_spl_003.phpt
50797 +sqlite-spl: Exception
50799 +<?php # vim:ft=php
50800 +if (!extension_loaded("sqlite")) print "skip";
50801 +if (!extension_loaded("spl")) print "skip SPL is not present";
50808 + $db = sqlite_factory();
50810 +catch(SQLiteException $e)
50812 + $parents = class_parents($e);
50813 + if (array_key_exists('RuntimeException', $parents))
50825 +++ b/ext/sqlite/TODO
50827 +- Implement a PDO driver, called sqlite2
50829 +- Transparent binary encoding of return values from PHP callback functions.
50831 +- Add user-space callback for the authorizer function (this is potentially
50832 + very slow, so it needs to be implemented carefully).
50834 +- Add user-space callback to handle busy databases.
50836 + o Test how robust we are when a user-space function is registered as
50837 + a callback for a persistent connection in script A, then script B is
50838 + called that doesn't register the callback but does make use of the
50839 + function in an SQL query.
50840 + --> Our test suite doesn't allow us to test persistent connections
50843 +- Use later version of built-in library