diff --git a/Makefile.in b/Makefile.in index 77a7af9dce..14c059c1f3 100644 --- a/Makefile.in +++ b/Makefile.in @@ -945,6 +945,12 @@ sqlite3_analyzer.c: sqlite3.c $(TOP)/src/test_stat.c $(TOP)/src/tclsqlite.c $(TO sqlite3_analyzer$(TEXE): sqlite3_analyzer.c $(LTLINK) sqlite3_analyzer.c -o $@ $(LIBTCL) $(TLIBS) +showdb$(TEXE): $(TOP)/tool/showdb.c sqlite3.c + $(LTLINK) -o $@ $(TOP)/tool/showdb.c sqlite3.c $(TLIBS) + +wordcount$(TEXE): $(TOP)/test/wordcount.c sqlite3.c + $(LTLINK) -o $@ $(TOP)/test/wordcount.c sqlite3.c $(TLIBS) + # Standard install and cleanup targets # lib_install: libsqlite3.la diff --git a/Makefile.msc b/Makefile.msc index 4a43cd4108..41ceb8fcfa 100644 --- a/Makefile.msc +++ b/Makefile.msc @@ -1355,6 +1355,14 @@ sqlite3_analyzer.exe: sqlite3_analyzer.c $(LIBRESOBJS) $(LTLINK) -DBUILD_sqlite -DTCLSH=2 -I$(TCLINCDIR) sqlite3_analyzer.c \ /link $(LTLINKOPTS) $(LTLIBPATHS) $(LIBRESOBJS) $(LTLIBS) $(TLIBS) +showdb.exe: $(TOP)/tool/showdb.c sqlite3.c + $(LTLINK) -DSQLITE_THREADSAFE=0 -DSQLITE_OMIT_LOAD_EXTENSION -o $@ \ + $(TOP)/tool/showdb.c sqlite3.c + +wordcount.exe: $(TOP)/test/wordcount.c sqlite3.c + $(LTLINK) -DSQLITE_THREADSAFE=0 -DSQLITE_OMIT_LOAD_EXTENSION -o $@ \ + $(TOP)/test/wordcount.c sqlite3.c + clean: del /Q *.lo *.ilk *.lib *.obj *.pdb sqlite3.exe libsqlite3.lib del /Q *.cod *.da *.bb *.bbg gmon.out diff --git a/VERSION b/VERSION index f280719674..a08ffae0ca 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -3.8.1 +3.8.2 diff --git a/configure b/configure index 57546c1a58..d4bbd2d9be 100755 --- a/configure +++ b/configure @@ -1,6 +1,6 @@ #! /bin/sh # Guess values for system-dependent variables and create Makefiles. -# Generated by GNU Autoconf 2.62 for sqlite 3.8.1. +# Generated by GNU Autoconf 2.62 for sqlite 3.8.2. # # Copyright (C) 1992, 1993, 1994, 1995, 1996, 1998, 1999, 2000, 2001, # 2002, 2003, 2004, 2005, 2006, 2007, 2008 Free Software Foundation, Inc. @@ -743,8 +743,8 @@ SHELL=${CONFIG_SHELL-/bin/sh} # Identity of this package. PACKAGE_NAME='sqlite' PACKAGE_TARNAME='sqlite' -PACKAGE_VERSION='3.8.1' -PACKAGE_STRING='sqlite 3.8.1' +PACKAGE_VERSION='3.8.2' +PACKAGE_STRING='sqlite 3.8.2' PACKAGE_BUGREPORT='' # Factoring default headers for most tests. @@ -1483,7 +1483,7 @@ if test "$ac_init_help" = "long"; then # Omit some internal or obsolete options to make the list less imposing. # This message is too long to be a string in the A/UX 3.1 sh. cat <<_ACEOF -\`configure' configures sqlite 3.8.1 to adapt to many kinds of systems. +\`configure' configures sqlite 3.8.2 to adapt to many kinds of systems. Usage: $0 [OPTION]... [VAR=VALUE]... @@ -1548,7 +1548,7 @@ fi if test -n "$ac_init_help"; then case $ac_init_help in - short | recursive ) echo "Configuration of sqlite 3.8.1:";; + short | recursive ) echo "Configuration of sqlite 3.8.2:";; esac cat <<\_ACEOF @@ -1664,7 +1664,7 @@ fi test -n "$ac_init_help" && exit $ac_status if $ac_init_version; then cat <<\_ACEOF -sqlite configure 3.8.1 +sqlite configure 3.8.2 generated by GNU Autoconf 2.62 Copyright (C) 1992, 1993, 1994, 1995, 1996, 1998, 1999, 2000, 2001, @@ -1678,7 +1678,7 @@ cat >config.log <<_ACEOF This file contains any messages produced by compilers while running configure, to aid debugging if configure makes a mistake. -It was created by sqlite $as_me 3.8.1, which was +It was created by sqlite $as_me 3.8.2, which was generated by GNU Autoconf 2.62. Invocation command line was $ $0 $@ @@ -14021,7 +14021,7 @@ exec 6>&1 # report actual input values of CONFIG_FILES etc. instead of their # values after options handling. ac_log=" -This file was extended by sqlite $as_me 3.8.1, which was +This file was extended by sqlite $as_me 3.8.2, which was generated by GNU Autoconf 2.62. Invocation command line was CONFIG_FILES = $CONFIG_FILES @@ -14074,7 +14074,7 @@ Report bugs to ." _ACEOF cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 ac_cs_version="\\ -sqlite config.status 3.8.1 +sqlite config.status 3.8.2 configured by $0, generated by GNU Autoconf 2.62, with options \\"`$as_echo "$ac_configure_args" | sed 's/^ //; s/[\\""\`\$]/\\\\&/g'`\\" diff --git a/ext/fts3/fts3_expr.c b/ext/fts3/fts3_expr.c index 29fb2887da..9c71f26ba1 100644 --- a/ext/fts3/fts3_expr.c +++ b/ext/fts3/fts3_expr.c @@ -155,6 +155,11 @@ int sqlite3Fts3OpenTokenizer( return rc; } +/* +** Function getNextNode(), which is called by fts3ExprParse(), may itself +** call fts3ExprParse(). So this forward declaration is required. +*/ +static int fts3ExprParse(ParseContext *, const char *, int, Fts3Expr **, int *); /* ** Extract the next token from buffer z (length n) using the tokenizer @@ -189,7 +194,31 @@ static int getNextToken( int nByte; /* total space to allocate */ rc = pModule->xNext(pCursor, &zToken, &nToken, &iStart, &iEnd, &iPosition); - if( rc==SQLITE_OK ){ + + if( (rc==SQLITE_OK || rc==SQLITE_DONE) && sqlite3_fts3_enable_parentheses ){ + int i; + if( rc==SQLITE_DONE ) iStart = n; + for(i=0; inNest++; + rc = fts3ExprParse(pParse, &z[i+1], n-i-1, &pRet, &nConsumed); + if( rc==SQLITE_OK && !pRet ){ + rc = SQLITE_DONE; + } + nConsumed = (int)(i + 1 + nConsumed); + break; + } + + if( z[i]==')' ){ + rc = SQLITE_DONE; + pParse->nNest--; + nConsumed = i+1; + break; + } + } + } + + if( nConsumed==0 && rc==SQLITE_OK ){ nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase) + nToken; pRet = (Fts3Expr *)fts3MallocZero(nByte); if( !pRet ){ @@ -369,12 +398,6 @@ no_mem: return SQLITE_NOMEM; } -/* -** Function getNextNode(), which is called by fts3ExprParse(), may itself -** call fts3ExprParse(). So this forward declaration is required. -*/ -static int fts3ExprParse(ParseContext *, const char *, int, Fts3Expr **, int *); - /* ** The output variable *ppExpr is populated with an allocated Fts3Expr ** structure, or set to 0 if the end of the input buffer is reached. @@ -471,27 +494,6 @@ static int getNextNode( } } - /* Check for an open bracket. */ - if( sqlite3_fts3_enable_parentheses ){ - if( *zInput=='(' ){ - int nConsumed; - pParse->nNest++; - rc = fts3ExprParse(pParse, &zInput[1], nInput-1, ppExpr, &nConsumed); - if( rc==SQLITE_OK && !*ppExpr ){ - rc = SQLITE_DONE; - } - *pnConsumed = (int)((zInput - z) + 1 + nConsumed); - return rc; - } - - /* Check for a close bracket. */ - if( *zInput==')' ){ - pParse->nNest--; - *pnConsumed = (int)((zInput - z) + 1); - return SQLITE_DONE; - } - } - /* See if we are dealing with a quoted phrase. If this is the case, then ** search for the closing quote and pass the whole string to getNextString() ** for processing. This is easy to do, as fts3 has no syntax for escaping diff --git a/ext/rtree/rtree.c b/ext/rtree/rtree.c index 815a8993e4..577e19d4c6 100644 --- a/ext/rtree/rtree.c +++ b/ext/rtree/rtree.c @@ -137,6 +137,16 @@ typedef union RtreeCoord RtreeCoord; */ #define HASHSIZE 128 +/* The xBestIndex method of this virtual table requires an estimate of +** the number of rows in the virtual table to calculate the costs of +** various strategies. If possible, this estimate is loaded from the +** sqlite_stat1 table (with RTREE_MIN_ROWEST as a hard-coded minimum). +** Otherwise, if no sqlite_stat1 entry is available, use +** RTREE_DEFAULT_ROWEST. +*/ +#define RTREE_DEFAULT_ROWEST 1048576 +#define RTREE_MIN_ROWEST 100 + /* ** An rtree virtual-table object. */ @@ -151,6 +161,7 @@ struct Rtree { char *zName; /* Name of r-tree table */ RtreeNode *aHash[HASHSIZE]; /* Hash table of in-memory nodes. */ int nBusy; /* Current number of users of this structure */ + i64 nRowEst; /* Estimated number of rows in this table */ /* List of nodes removed during a CondenseTree operation. List is ** linked together via the pointer normally used for hash chains - @@ -1343,6 +1354,19 @@ static int rtreeFilter( return rc; } +/* +** Set the pIdxInfo->estimatedRows variable to nRow. Unless this +** extension is currently being used by a version of SQLite too old to +** support estimatedRows. In that case this function is a no-op. +*/ +static void setEstimatedRows(sqlite3_index_info *pIdxInfo, i64 nRow){ +#if SQLITE_VERSION_NUMBER>=3008002 + if( sqlite3_libversion_number()>=3008002 ){ + pIdxInfo->estimatedRows = nRow; + } +#endif +} + /* ** Rtree virtual table module xBestIndex method. There are three ** table scan strategies to choose from (in order from most to @@ -1378,13 +1402,14 @@ static int rtreeFilter( ** is 'a', the second from the left 'b' etc. */ static int rtreeBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){ + Rtree *pRtree = (Rtree*)tab; int rc = SQLITE_OK; int ii; + i64 nRow; /* Estimated rows returned by this scan */ int iIdx = 0; char zIdxStr[RTREE_MAX_DIMENSIONS*8+1]; memset(zIdxStr, 0, sizeof(zIdxStr)); - UNUSED_PARAMETER(tab); assert( pIdxInfo->idxStr==0 ); for(ii=0; iinConstraint && iIdx<(int)(sizeof(zIdxStr)-1); ii++){ @@ -1404,9 +1429,11 @@ static int rtreeBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){ /* This strategy involves a two rowid lookups on an B-Tree structures ** and then a linear search of an R-Tree node. This should be ** considered almost as quick as a direct rowid lookup (for which - ** sqlite uses an internal cost of 0.0). + ** sqlite uses an internal cost of 0.0). It is expected to return + ** a single row. */ - pIdxInfo->estimatedCost = 10.0; + pIdxInfo->estimatedCost = 30.0; + setEstimatedRows(pIdxInfo, 1); return SQLITE_OK; } @@ -1435,8 +1462,11 @@ static int rtreeBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){ if( iIdx>0 && 0==(pIdxInfo->idxStr = sqlite3_mprintf("%s", zIdxStr)) ){ return SQLITE_NOMEM; } - assert( iIdx>=0 ); - pIdxInfo->estimatedCost = (2000000.0 / (double)(iIdx + 1)); + + nRow = pRtree->nRowEst / (iIdx + 1); + pIdxInfo->estimatedCost = (double)6.0 * (double)nRow; + setEstimatedRows(pIdxInfo, nRow); + return rc; } @@ -2911,6 +2941,37 @@ static int rtreeRename(sqlite3_vtab *pVtab, const char *zNewName){ return rc; } +/* +** This function populates the pRtree->nRowEst variable with an estimate +** of the number of rows in the virtual table. If possible, this is based +** on sqlite_stat1 data. Otherwise, use RTREE_DEFAULT_ROWEST. +*/ +static int rtreeQueryStat1(sqlite3 *db, Rtree *pRtree){ + const char *zSql = "SELECT stat FROM sqlite_stat1 WHERE tbl= ? || '_rowid'"; + sqlite3_stmt *p; + int rc; + i64 nRow = 0; + + rc = sqlite3_prepare_v2(db, zSql, -1, &p, 0); + if( rc==SQLITE_OK ){ + sqlite3_bind_text(p, 1, pRtree->zName, -1, SQLITE_STATIC); + if( sqlite3_step(p)==SQLITE_ROW ) nRow = sqlite3_column_int64(p, 0); + rc = sqlite3_finalize(p); + }else if( rc!=SQLITE_NOMEM ){ + rc = SQLITE_OK; + } + + if( rc==SQLITE_OK ){ + if( nRow==0 ){ + pRtree->nRowEst = RTREE_DEFAULT_ROWEST; + }else{ + pRtree->nRowEst = MAX(nRow, RTREE_MIN_ROWEST); + } + } + + return rc; +} + static sqlite3_module rtreeModule = { 0, /* iVersion */ rtreeCreate, /* xCreate - create a table */ @@ -2996,6 +3057,7 @@ static int rtreeSqlInit( appStmt[7] = &pRtree->pWriteParent; appStmt[8] = &pRtree->pDeleteParent; + rc = rtreeQueryStat1(db, pRtree); for(i=0; i10 } { 0 0 0 {SCAN TABLE t1 VIRTUAL TABLE INDEX 2:CaEb} - 0 1 1 {SCAN TABLE t2} + 0 1 1 {SEARCH TABLE t2 USING AUTOMATIC COVERING INDEX (v=?)} } do_eqp_test rtree6.2.5 { diff --git a/ext/rtree/rtreeC.test b/ext/rtree/rtreeC.test new file mode 100644 index 0000000000..47e8581483 --- /dev/null +++ b/ext/rtree/rtreeC.test @@ -0,0 +1,112 @@ +# 2011 March 2 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# Make sure the rtreenode() testing function can handle entries with +# 64-bit rowids. +# + +if {![info exists testdir]} { + set testdir [file join [file dirname [info script]] .. .. test] +} +source $testdir/tester.tcl +ifcapable !rtree { finish_test ; return } +set testprefix rtreeC + +do_execsql_test 1.0 { + CREATE VIRTUAL TABLE r_tree USING rtree(id, min_x, max_x, min_y, max_y); + CREATE TABLE t(x, y); +} + +do_eqp_test 1.1 { + SELECT * FROM r_tree, t + WHERE t.x>=min_x AND t.x<=max_x AND t.y>=min_y AND t.x<=max_y +} { + 0 0 1 {SCAN TABLE t} + 0 1 0 {SCAN TABLE r_tree VIRTUAL TABLE INDEX 2:DdBcDbBa} +} + +do_eqp_test 1.2 { + SELECT * FROM t, r_tree + WHERE t.x>=min_x AND t.x<=max_x AND t.y>=min_y AND t.x<=max_y +} { + 0 0 0 {SCAN TABLE t} + 0 1 1 {SCAN TABLE r_tree VIRTUAL TABLE INDEX 2:DdBcDbBa} +} + +do_eqp_test 1.3 { + SELECT * FROM t, r_tree + WHERE t.x>=min_x AND t.x<=max_x AND t.y>=min_y AND ?<=max_y +} { + 0 0 0 {SCAN TABLE t} + 0 1 1 {SCAN TABLE r_tree VIRTUAL TABLE INDEX 2:DdBcDbBa} +} + +do_eqp_test 1.5 { + SELECT * FROM t, r_tree +} { + 0 0 1 {SCAN TABLE r_tree VIRTUAL TABLE INDEX 2:} + 0 1 0 {SCAN TABLE t} +} + +do_execsql_test 2.0 { + INSERT INTO t VALUES(0, 0); + INSERT INTO t VALUES(0, 1); + INSERT INTO t VALUES(0, 2); + INSERT INTO t VALUES(0, 3); + INSERT INTO t VALUES(0, 4); + INSERT INTO t VALUES(0, 5); + INSERT INTO t VALUES(0, 6); + INSERT INTO t VALUES(0, 7); + INSERT INTO t VALUES(0, 8); + INSERT INTO t VALUES(0, 9); + + INSERT INTO t SELECT x+1, y FROM t; + INSERT INTO t SELECT x+2, y FROM t; + INSERT INTO t SELECT x+4, y FROM t; + INSERT INTO r_tree SELECT NULL, x-1, x+1, y-1, y+1 FROM t; + ANALYZE; +} + +db close +sqlite3 db test.db + +do_eqp_test 2.1 { + SELECT * FROM r_tree, t + WHERE t.x>=min_x AND t.x<=max_x AND t.y>=min_y AND t.x<=max_y +} { + 0 0 1 {SCAN TABLE t} + 0 1 0 {SCAN TABLE r_tree VIRTUAL TABLE INDEX 2:DdBcDbBa} +} + +do_eqp_test 2.2 { + SELECT * FROM t, r_tree + WHERE t.x>=min_x AND t.x<=max_x AND t.y>=min_y AND t.x<=max_y +} { + 0 0 0 {SCAN TABLE t} + 0 1 1 {SCAN TABLE r_tree VIRTUAL TABLE INDEX 2:DdBcDbBa} +} + +do_eqp_test 2.3 { + SELECT * FROM t, r_tree + WHERE t.x>=min_x AND t.x<=max_x AND t.y>=min_y AND ?<=max_y +} { + 0 0 0 {SCAN TABLE t} + 0 1 1 {SCAN TABLE r_tree VIRTUAL TABLE INDEX 2:DdBcDbBa} +} + +do_eqp_test 2.5 { + SELECT * FROM t, r_tree +} { + 0 0 1 {SCAN TABLE r_tree VIRTUAL TABLE INDEX 2:} + 0 1 0 {SCAN TABLE t} +} + +finish_test + diff --git a/magic.txt b/magic.txt index c6340d9b18..add96a7363 100644 --- a/magic.txt +++ b/magic.txt @@ -27,4 +27,5 @@ >60 belong =0x5f4d544e Monotone source repository - >68 belong =0x47504b47 OGC GeoPackage file - >68 belong =0x47503130 OGC GeoPackage version 1.0 file - +>68 belong =0x45737269 Esri Spatially-Enabled Database - >0 string =SQLite SQLite3 database diff --git a/main.mk b/main.mk index 1605cff788..f13dce48a2 100644 --- a/main.mk +++ b/main.mk @@ -631,10 +631,14 @@ $(TEST_EXTENSION): $(TOP)/src/test_loadext.c extensiontest: testfixture$(EXE) $(TEST_EXTENSION) ./testfixture$(EXE) $(TOP)/test/loadext.test -showdb: $(TOP)/tool/showdb.c sqlite3.c - $(TCC) -DSQLITE_THREADSAFE=0 -DSQLITE_OMIT_LOAD_EXTENSION -o showdb \ +showdb$(EXE): $(TOP)/tool/showdb.c sqlite3.c + $(TCC) -DSQLITE_THREADSAFE=0 -DSQLITE_OMIT_LOAD_EXTENSION -o showdb$(EXE) \ $(TOP)/tool/showdb.c sqlite3.c +wordcount$(EXE): $(TOP)/test/wordcount.c sqlite3.c + $(TCC) -DSQLITE_THREADSAFE=0 -DSQLITE_OMIT_LOAD_EXTENSION -o wordcount$(EXE) \ + $(TOP)/test/wordcount.c sqlite3.c + # This target will fail if the SQLite amalgamation contains any exported # symbols that do not begin with "sqlite3_". It is run as part of the # releasetest.tcl script. diff --git a/manifest b/manifest index 4112e0a47f..fcac3f7230 100644 --- a/manifest +++ b/manifest @@ -1,12 +1,12 @@ -C Merge\sall\strunk\schanges\ssince\s3.8.1\sinto\sthe\ssessions\sbranch. -D 2013-10-28T22:47:24.844 +C Merge\sin\sthe\sWITHOUT\sROWID\schanges.\s\sA\sfew\stests\sare\sfailing\snow.\s\sThey\swill\nbe\sfixed\sin\sa\sfollow-on\scheck-in. +D 2013-11-11T22:55:26.153 F Makefile.arm-wince-mingw32ce-gcc d6df77f1f48d690bd73162294bbba7f59507c72f -F Makefile.in 15f75d6d804c5552a05390d1982c1114b8ce6d2d +F Makefile.in bb787d5227c6aa95915ff04e9634a0a469297ea4 F Makefile.linux-gcc 91d710bdc4998cb015f39edf3cb314ec4f4d7e23 -F Makefile.msc 72a3e9091272201b337908e136de753ba38c8206 +F Makefile.msc ec33274b488575929601e26d7e815e340ded812c F Makefile.vxworks db21ed42a01d5740e656b16f92cb5d8d5e5dd315 F README cd04a36fbc7ea56932a4052d7d0b7f09f27c33d6 -F VERSION a8d1f6839521130dc73c5408cdd24bcfd791df34 +F VERSION 52f7e22bfcec71a462e34194b4ae1671380fde59 F aclocal.m4 a5c22d164aff7ed549d53a90fa56d56955281f50 F addopcodes.awk 17dc593f791f874d2c23a0f9360850ded0286531 F art/sqlite370.eps aa97a671332b432a54e1d74ff5e8775be34200c2 @@ -38,7 +38,7 @@ F autoconf/tea/win/rules.vc c511f222b80064096b705dbeb97060ee1d6b6d63 F config.guess 226d9a188c6196f3033ffc651cbc9dcee1a42977 F config.h.in 0921066a13130082764ab4ab6456f7b5bebe56de F config.sub 9ebe4c3b3dab6431ece34f16828b594fb420da55 -F configure d9bb8485d40dd905e09c895692a0699628abace8 x +F configure f97b17cd80fa428e5df4e70a36ed5b4ed21100c2 x F configure.ac 4cf9f60785143fa141b10962ccc885d973792e9a F contrib/sqlitecon.tcl 210a913ad63f9f991070821e599d600bd913e0ad F doc/lemon.html 334dbf6621b8fb8790297ec1abf3cfa4621709d1 @@ -82,7 +82,7 @@ F ext/fts3/fts3.c f25ae5729d40cc4e661c0a552685038f27e72bc9 F ext/fts3/fts3.h 3a10a0af180d502cecc50df77b1b22df142817fe F ext/fts3/fts3Int.h 8689f7cf85020e7f88d1e761eeac480c3b0ea7ad F ext/fts3/fts3_aux.c 5c211e17a64885faeb16b9ba7772f9d5445c2365 -F ext/fts3/fts3_expr.c f8eb1046063ba342c7114eba175cabb31c4a64e7 +F ext/fts3/fts3_expr.c 5165c365cb5a035f5be8bb296f7aa3211d43e4ac F ext/fts3/fts3_hash.c 8dd2d06b66c72c628c2732555a32bc0943114914 F ext/fts3/fts3_hash.h 39cf6874dc239d6b4e30479b1975fe5b22a3caaf F ext/fts3/fts3_icu.c e319e108661147bcca8dd511cd562f33a1ba81b5 @@ -120,19 +120,20 @@ F ext/misc/vfslog.c fe40fab5c077a40477f7e5eba994309ecac6cc95 F ext/misc/vtshim.c babb0dc2bf116029e3e7c9a618b8a1377045303e F ext/misc/wholenumber.c 784b12543d60702ebdd47da936e278aa03076212 F ext/rtree/README 6315c0d73ebf0ec40dedb5aa0e942bc8b54e3761 -F ext/rtree/rtree.c db516d7e59a14c92df10b552789509f2b632df3a +F ext/rtree/rtree.c a4e18b2c150adad20aecbeb3408cd235a0a57441 F ext/rtree/rtree.h 834dbcb82dc85b2481cde6a07cdadfddc99e9b9e F ext/rtree/rtree1.test cf679265ecafff494a768ac9c2f43a70915a6290 F ext/rtree/rtree2.test acbb3a4ce0f4fbc2c304d2b4b784cfa161856bba F ext/rtree/rtree3.test a494da55c30ee0bc9b01a91c80c81b387b22d2dc F ext/rtree/rtree4.test c8fe384f60ebd49540a5fecc990041bf452eb6e0 F ext/rtree/rtree5.test 6a510494f12454bf57ef28f45bc7764ea279431e -F ext/rtree/rtree6.test fb94b98c1145b7f44c72635d11492f35349ab27e +F ext/rtree/rtree6.test fe0bd377a21c68ce2826129d14354c884cb1f354 F ext/rtree/rtree7.test 1fa710b9e6bf997a0c1a537b81be7bb6fded1971 F ext/rtree/rtree8.test db79c812f9e4a11f9b1f3f9934007884610a713a F ext/rtree/rtree9.test d86ebf08ff6328895613ed577dd8a2a37c472c34 F ext/rtree/rtreeA.test ace05e729a36e342d40cf94e9efc7b4723d9dcdf F ext/rtree/rtreeB.test 983e567b49b5dca165940f66b87e161aa30e82b2 +F ext/rtree/rtreeC.test 0c3dcd379e012c76df5e59d53bc99a8b48f1603b F ext/rtree/rtree_perf.tcl 6c18c1f23cd48e0f948930c98dfdd37dfccb5195 F ext/rtree/rtree_util.tcl 06aab2ed5b826545bf215fff90ecb9255a8647ea F ext/rtree/sqlite3rtree.h c34c1e41d1ab80bb8ad09aae402c9c956871a765 @@ -154,13 +155,13 @@ F ext/session/sqlite3session.h 6c35057241567ed6319f750ee504a81c459225e1 F ext/session/test_session.c d38968307c05229cc8cd603722cf305d6f768832 F install-sh 9d4de14ab9fb0facae2f48780b874848cbf2f895 x F ltmain.sh 3ff0879076df340d2e23ae905484d8c15d5fdea8 -F magic.txt 814d3de5ec227817ff2ad26cbc73159c968a2a58 -F main.mk f572e71022e342deb3a4786a728eb20765e0cfae +F magic.txt f439556c5ce01ced70987e5ee86549a45165d9ff +F main.mk 384a11414a17c25a5df667174050ec50181f46a9 F mkdll.sh 7d09b23c05d56532e9d44a50868eb4b12ff4f74a F mkextu.sh 416f9b7089d80e5590a29692c9d9280a10dbad9f F mkextw.sh d2a981497b404d6498f5ff3e3b1f3816bdfcb338 -F mkopcodec.awk f6fccee29e68493bfd90a2e0466ede5fa94dd2fc -F mkopcodeh.awk e7334b45c023b5ee2efc6e8f479560c2026fa34a +F mkopcodec.awk c2ff431854d702cdd2d779c9c0d1f58fa16fa4ea +F mkopcodeh.awk 987ee588ff3bb4043bed2185c1ee2bdc39b1e526 F mkso.sh fd21c06b063bb16a5d25deea1752c2da6ac3ed83 F mptest/config01.test 3c6adcbc50b991866855f1977ff172eb6d901271 F mptest/config02.test 4415dfe36c48785f751e16e32c20b077c28ae504 @@ -173,35 +174,35 @@ F sqlite.pc.in 42b7bf0d02e08b9e77734a47798d1a55a9e0716b F sqlite3.1 6be1ad09113570e1fc8dcaff84c9b0b337db5ffc F sqlite3.pc.in 48fed132e7cb71ab676105d2a4dc77127d8c1f3a F src/alter.c 2af0330bb1b601af7a7789bf7229675fd772a083 -F src/analyze.c f1c5ed1fe128c3f106dcd95e97ee9ef94db7a3fa +F src/analyze.c 27f0c132aa0679189837e0addf8762e7fd6831b6 F src/attach.c 0a17c9364895316ca4f52d06a97a72c0af1ae8b3 F src/auth.c 523da7fb4979469955d822ff9298352d6b31de34 F src/backup.c 2f1987981139bd2f6d8c728d64bf09fb387443c3 F src/bitvec.c 19a4ba637bd85f8f63fc8c9bae5ade9fb05ec1cb F src/btmutex.c 976f45a12e37293e32cae0281b15a21d48a8aaa7 -F src/btree.c 509722ce305471b626d3401c0631a808fd33237b +F src/btree.c 260dedc13119e6fb7930380bd3d294b98362bf5a F src/btree.h bfe0e8c5759b4ec77b0d18390064a6ef3cdffaaf F src/btreeInt.h f038e818bfadf75afbd09819ed93c26a333d39e0 -F src/build.c 6d9a545d726956fdc0c63d7076291fc9e7207484 +F src/build.c 4d740243144d9e5058a46df7d05d1243f449b4d7 F src/callback.c f99a8957ba2adf369645fac0db09ad8adcf1caa2 F src/complete.c dc1d136c0feee03c2f7550bafc0d29075e36deac F src/ctime.c ea4b7f3623a0fcb1146e7f245d7410033e86859c F src/date.c 593c744b2623971e45affd0bde347631bdfa4625 -F src/delete.c 92d409e4c3ab3c5f1173451971a40226ce4cfe1c -F src/expr.c e7338ccffdc391c53ba2d51c5eb6a2f5299e040e +F src/delete.c 714f86ed9d563f12313d92d600ae1c9e68c6fa14 +F src/expr.c e7bbe3c6916e141f27a28655d3cf325b817695e4 F src/fault.c 160a0c015b6c2629d3899ed2daf63d75754a32bb -F src/fkey.c 5dc10cbaa355753903cd2a64da040f948997ebf8 -F src/func.c 2c47b65e6e00e3e9374942f28254faf8adafe398 +F src/fkey.c 78364daed38e26269c53ddb94c515bceac1063c6 +F src/func.c 96caa9dfd1febf9a4b720de4c43ccfb392a52b73 F src/global.c 5caf4deab621abb45b4c607aad1bd21c20aac759 F src/hash.c ac3470bbf1ca4ae4e306a8ecb0fdf1731810ffe4 F src/hash.h 8890a25af81fb85a9ad7790d32eedab4b994da22 F src/hwtime.h d32741c8f4df852c7d959236615444e2b1063b08 -F src/insert.c feaa30b45af7f6a6bf363cc0ac05c1c25d162eff +F src/insert.c 0f4d5b41d1cd8291e98af33587f2a4bbb3d59abb F src/journal.c b4124532212b6952f42eb2c12fa3c25701d8ba8d F src/legacy.c 0df0b1550b9cc1f58229644735e317ac89131f12 F src/lempar.c cdf0a000315332fc9b50b62f3b5e22e080a0952b F src/loadext.c 867c7b330b740c6c917af9956b13b81d0a048303 -F src/main.c 0cc0574e656567999115fe93666a3f97ad917e86 +F src/main.c d802034d4a145e440b651dc67c590355f41c64b5 F src/malloc.c 543a8eb5508eaf4cadf55a9b503379eba2088128 F src/mem0.c 6a55ebe57c46ca1a7d98da93aaa07f99f1059645 F src/mem1.c 437c7c4af964895d4650f29881df63535caaa1fa @@ -218,26 +219,26 @@ F src/notify.c 976dd0f6171d4588e89e874fcc765e92914b6d30 F src/os.c b4ad71336fd96f97776f75587cd9e8218288f5be F src/os.h 4a46270a64e9193af4a0aaa3bc2c66dc07c29b3f F src/os_common.h 92815ed65f805560b66166e3583470ff94478f04 -F src/os_unix.c 243fb37f47dc072fc59839ea241ff0a17c8d76e6 -F src/os_win.c b159b5249d9f70607d961bbdd1dbba789c75812c +F src/os_unix.c 143624d9eabb3b997c59cf594e0d06c56edd43e9 +F src/os_win.c ef091b347d682cb24fc575ac9a6290341af62e2b F src/pager.c 2aa4444ffe86e9282d03bc349a4a5e49bd77c0e8 F src/pager.h f094af9f6ececfaa8a1e93876905a4f34233fb0c -F src/parse.y a97566d6da75075589a7c716d1bda14b586cf8da +F src/parse.y 073a8294e1826f1b1656e84806b77e4199f4bb57 F src/pcache.c f8043b433a57aba85384a531e3937a804432a346 F src/pcache.h a5e4f5d9f5d592051d91212c5949517971ae6222 F src/pcache1.c a467393909a4ed7ca9de066d85ba5c5b04a5be63 -F src/pragma.c 6fb3125fff078cd81db0039ac778948df4e8cb6f +F src/pragma.c 3b7b766382ac679d3c1a7ba368aa008f9a756d59 F src/prepare.c fa6988589f39af8504a61731614cd4f6ae71554f F src/printf.c da9119eb31a187a4b99f60aa4a225141c0ebb74b F src/random.c 0b2dbc37fdfbfa6bd455b091dfcef5bdb32dba68 -F src/resolve.c 572585a96bf282bb9c3d9e08785ec3cae21dc488 +F src/resolve.c fc4673cc49b116e51e7f12de074c0acf8f2388f9 F src/rowset.c 64655f1a627c9c212d9ab497899e7424a34222e0 -F src/select.c 15127b54cc11defb2cddef6914e1f384501a61c4 -F src/shell.c d5eebdc6034014103de2b9d58e1d3f6f7de0fb50 -F src/sqlite.h.in f287bd97f9cdf6ec8f57f37cf2e590ed6b9f6302 +F src/select.c a040df82c4ac90b27114e1c21a05d77cc6dc6f80 +F src/shell.c 03d8d9b4052430343ff30d646334621f980f1202 +F src/sqlite.h.in 359a06b4832eba83e832712b9708c731c2a13a7a F src/sqlite3.rc 11094cc6a157a028b301a9f06b3d03089ea37c3e F src/sqlite3ext.h 886f5a34de171002ad46fae8c36a7d8051c190fc -F src/sqliteInt.h cc58deabef26a4a82e7b40c47316968e359c6fae +F src/sqliteInt.h 4d218f4480af7672cff22bb4ef589410f5415f68 F src/sqliteLimit.h 164b0e6749d31e0daa1a4589a169d31c0dec7b3d F src/status.c 7ac05a5c7017d0b9f0b4bcd701228b784f987158 F src/table.c 2cd62736f845d82200acfa1287e33feb3c15d62e @@ -247,7 +248,7 @@ F src/test2.c 7355101c085304b90024f2261e056cdff13c6c35 F src/test3.c 1c0e5d6f080b8e33c1ce8b3078e7013fdbcd560c F src/test4.c 9b32d22f5f150abe23c1830e2057c4037c45b3df F src/test5.c a6d1ac55ac054d0b2b8f37b5e655b6c92645a013 -F src/test6.c 00af0fe1947305222b8ed488a69c76c5a2b632e2 +F src/test6.c 4f958b71334695e65746d357dac77709732b28db F src/test7.c 72b732baa5642f795655ba1126ea032af46ecfd2 F src/test8.c c7aab1d9fbbf54fc33d43b73aa24aa55f9eaf534 F src/test9.c bea1e8cf52aa93695487badedd6e1886c321ea60 @@ -255,7 +256,7 @@ F src/test_async.c 21e11293a2f72080eda70e1124e9102044531cd8 F src/test_autoext.c dea8a01a7153b9adc97bd26161e4226329546e12 F src/test_backup.c 3875e899222b651e18b662f86e0e50daa946344e F src/test_btree.c 5b89601dcb42a33ba8b820a6b763cc9cb48bac16 -F src/test_config.c 9ec20c94a3290f64d60c6db12c3e88ed3de9e501 +F src/test_config.c 740b371afbfa12d47fd44d515a685b00c4015850 F src/test_demovfs.c 69b2085076654ebc18014cbc6386f04409c959a9 F src/test_devsym.c e7498904e72ba7491d142d5c83b476c4e76993bc F src/test_fs.c ced436e3d4b8e4681328409b8081051ce614e28f @@ -267,7 +268,7 @@ F src/test_intarray.h 2ece66438cfd177b78d1bfda7a4180cd3a10844d F src/test_journal.c f5c0a05b7b3d5930db769b5ee6c3766dc2221a64 F src/test_loadext.c df586c27176e3c2cb2e099c78da67bf14379a56e F src/test_malloc.c eba4e1c5847cc98e7edc98f62265cd2abafba7a6 -F src/test_multiplex.c 5d691eeb6cb6aa7888da28eba5e62a9a857d3c0f +F src/test_multiplex.c 9f304bf04170c91c0318238d512df2da039eb1c8 F src/test_multiplex.h 110a8c4d356e0aa464ca8730375608a9a0b61ae1 F src/test_mutex.c 293042d623ebba969160f471a82aa1551626454f F src/test_onefile.c 0396f220561f3b4eedc450cef26d40c593c69a25 @@ -279,7 +280,7 @@ F src/test_rtree.c f3d1d12538dccb75fd916e3fa58f250edbdd3b47 F src/test_schema.c cd12a2223c3a394f4d07bb93bdf6d344c5c121b6 F src/test_server.c a2615049954cbb9cfb4a62e18e2f0616e4dc38fe F src/test_sqllog.c c1c1bbedbcaf82b93d83e4f9dd990e62476a680e -F src/test_stat.c d1569c7a4839f13e80187e2c26b2ab4da2d03935 +F src/test_stat.c 9898687a6c2beca733b0dd6fe19163d987826d31 F src/test_superlock.c 2b97936ca127d13962c3605dbc9a4ef269c424cd F src/test_syscall.c 16dbe79fb320fadb5acd7a0a59f49e52ab2d2091 F src/test_tclvar.c f4dc67d5f780707210d6bb0eb6016a431c04c7fa @@ -287,32 +288,32 @@ F src/test_thread.c 1e133a40b50e9c035b00174035b846e7eef481cb F src/test_vfs.c e72f555ef7a59080f898fcf1a233deb9eb704ea9 F src/test_vfstrace.c 34b544e80ba7fb77be15395a609c669df2e660a2 F src/test_wsd.c 41cadfd9d97fe8e3e4e44f61a4a8ccd6f7ca8fe9 -F src/tokenize.c 70061085a51f2f4fc15ece94f32c03bcb78e63b2 -F src/trigger.c ba0a883cd536b7dfdd4df3733001f5372a4299da -F src/update.c be9831a714638ed5b66e215451d4775d136ea745 +F src/tokenize.c ec4c1a62b890bf1dbcdb966399e140b904c700a4 +F src/trigger.c 53d6b5d50b3b23d4fcd0a36504feb5cff9aed716 +F src/update.c faee30d7aa32a1196b9eb751b8e50d9ff0ad6ea7 F src/utf.c 6fc6c88d50448c469c5c196acf21617a24f90269 F src/util.c 2fa6c821d28bbdbeec1b2a7b091a281c9ef8f918 -F src/vacuum.c f313bc97123a4dd4bfd3f50a00c4d44c08a5b1b7 -F src/vdbe.c 7663e009b870623f664fc4d4d0634767d4a927a3 -F src/vdbe.h 7aa3ab6210a68471c8490dedfc9aa4ef5684b9a0 -F src/vdbeInt.h 2eaf8a38ec76738bbb18429e6c4f317e3766742e +F src/vacuum.c 3728d74919d4fb1356f9e9a13e27773db60b7179 +F src/vdbe.c 8b6b4fcea067e9ea3736538378765098018284f8 +F src/vdbe.h c7aa561dea0070486c49a3aab6d550bb84728bda +F src/vdbeInt.h fe226d7290e8c1eb2d334dadfeb3f3285b3f2d14 F src/vdbeapi.c 8ade912f7023a3b35ee64497a94718ddbd7269c3 -F src/vdbeaux.c 371a22e7485e57048be1e625eb0b82e3429b0f58 -F src/vdbeblob.c 1268e0bcb8e21fa32520b0fc376e1bcdfaa0c642 -F src/vdbemem.c 649933bad3e922465b726eaf85c72a75acba2ab7 -F src/vdbesort.c 3937e06b2a0e354500e17dc206ef4c35770a5017 +F src/vdbeaux.c f2905bb192c946ee0e223b5eca9411592eaa7976 +F src/vdbeblob.c 0ab871fa7466efaef05877f06d650f0f7401cbe0 +F src/vdbemem.c cc529bbf4f13e4e181bdb446bf6e6962ab030b4b +F src/vdbesort.c 9d83601f9d6243fe70dd0169a2820c5ddfd48147 F src/vdbetrace.c e7ec40e1999ff3c6414424365d5941178966dcbc F src/vtab.c 5a423b042eb1402ef77697d03d6a67378d97bc8d F src/wal.c 7dc3966ef98b74422267e7e6e46e07ff6c6eb1b4 F src/wal.h df01efe09c5cb8c8e391ff1715cca294f89668a4 F src/walker.c e9e593d5bb798c3e67fc3893dfe7055c9e7d8d74 -F src/where.c f18400f121fd27385f41cdff7aa8a811feca842e +F src/where.c 85766647d693ed7cfba42dfce07e2cb9c3384bd9 F test/8_3_names.test ebbb5cd36741350040fd28b432ceadf495be25b2 F test/aggerror.test a867e273ef9e3d7919f03ef4f0e8c0d2767944f2 F test/aggnested.test 45c0201e28045ad38a530b5a144b73cd4aa2cfd6 F test/alias.test 4529fbc152f190268a15f9384a5651bbbabc9d87 F test/all.test 6ff7b43c2b4b905c74dc4a813d201d0fa64c5783 -F test/alter.test 775a1dded3f8247983c9a3e767b011d9a5114442 +F test/alter.test e88dfa77e020c2b48e52a8020c70171ab828e079 F test/alter2.test 7ea05c7d92ac99349a802ef7ada17294dd647060 F test/alter3.test 49c9d9fba2b8fcdce2dedeca97bbf1f369cc548d F test/alter4.test 8e93bf7a7e6919b14b0c9a6c1e4908bcf21b0165 @@ -344,10 +345,10 @@ F test/auth2.test c3b415b76c033bedb81292118fb7c01f5f10cbcd F test/auth3.test a4755e6a2a2fea547ffe63c874eb569e60a28eb5 F test/autoinc.test bd30d372d00045252f6c2e41b5f41455e1975acf F test/autoindex1.test d4dfe14001dfcb74cfbd7107f45a79fc1ab6183e -F test/autovacuum.test 9f22a7733f39c56ef6a5665d10145ac25d8cb574 +F test/autovacuum.test 941892505d2c0f410a0cb5970dfa1c7c4e5f6e74 F test/autovacuum_ioerr2.test 8a367b224183ad801e0e24dcb7d1501f45f244b4 F test/avtrans.test 0252654f4295ddda3b2cce0e894812259e655a85 -F test/backcompat.test ecd841f3a3bfb81518721879cc56a760670e3198 +F test/backcompat.test 5f8ad58b3eaebc78cd2c66c65476a42e6f32b2ad F test/backup.test c9cdd23a495864b9edf75a9fa66f5cb7e10fcf62 F test/backup2.test 34986ef926ea522911a51dfdb2f8e99b7b75ebcf F test/backup4.test 2a2e4a64388090b152de753fd9e123f28f6a3bd4 @@ -375,21 +376,21 @@ F test/boundary4.test 89e02fa66397b8a325d5eb102b5806f961f8ec4b F test/btreefault.test c2bcb542685eea44621275cfedbd8a13f65201e3 F test/busy.test 76b4887f8b9160ba903c1ac22e8ff406ad6ae2f0 F test/cache.test 13bc046b26210471ca6f2889aceb1ea52dc717de -F test/capi2.test e8b18cc61090b6e5e388f54d6b125d711d1b265a +F test/capi2.test 011c16da245fdc0106a2785035de6b242c05e738 F test/capi3.test 56ab450125ead38846cbae7e5b6a216686c3cffa F test/capi3b.test efb2b9cfd127efa84433cd7a2d72ce0454ae0dc4 F test/capi3c.test 93d24621c9ff84da9da060f30431e0453db1cdb0 F test/capi3d.test 6d0fc0a86d73f42dd19a7d8b7761ab9bc02277d0 F test/capi3e.test ad90088b18b0367125ff2d4b5400153fd2f99aab F test/cast.test 4c275cbdc8202d6f9c54a3596701719868ac7dc3 -F test/check.test 1e9be446eb0bbd47a5f65955802e9632425096ab +F test/check.test 5831ddb6f2c687782eaf2e1a07b6e17f24c4f763 F test/close.test 340bd24cc58b16c6bc01967402755027c37eb815 F test/closure01.test dbb28f1ea9eeaf0a53ec5bc0fed352e479def8c7 F test/coalesce.test cee0dccb9fbd2d494b77234bccf9dc6c6786eb91 F test/collate1.test b709989e6e6ff6e1d2bd64231c2c1d8146846c9e F test/collate2.test 9aaa410a00734e48bcb27f3872617d6f69b2a621 F test/collate3.test 79558a286362cb9ed603c6fa543f1cda7f563f0f -F test/collate4.test 031f7265c13308b724ba3c49f41cc04612bd92b1 +F test/collate4.test f04d5168685f2eef637ecfa2d4ddf8ec0d600177 F test/collate5.test 65d928034d30d2d263a80f6359f7549ee1598ec6 F test/collate6.test 8be65a182abaac8011a622131486dafb8076e907 F test/collate7.test 8ec29d98f3ee4ccebce6e16ce3863fb6b8c7b868 @@ -398,7 +399,9 @@ F test/collate9.test 3adcc799229545940df2f25308dd1ad65869145a F test/collateA.test b8218ab90d1fa5c59dcf156efabb1b2599c580d6 F test/colmeta.test 087c42997754b8c648819832241daf724f813322 F test/colname.test 08948a4809d22817e0e5de89c7c0a8bd90cb551b -F test/conflict.test 0b3922d2304a14a47e3ccd61bbd6824327af659b +F test/conflict.test 841bcf7cabbfca39c577eb8411ea8601843b46a8 +F test/conflict2.test 3ed0b6ec3c2cb8acebbc89677ea0e58c01aaa1ff +F test/conflict3.test dec0634c0f31dec9a4b01c63063e939f0cd21b6b F test/contrib01.test 2a1cbc0f2f48955d7d073f725765da6fbceda6b4 F test/corrupt.test 4aabd06cff3fe759e3e658bcc17b71789710665e F test/corrupt2.test 9c0ab4becd50e9050bc1ebb8675456a4e5587bf0 @@ -425,13 +428,13 @@ F test/crash4.test fe2821baf37168dc59dd733dcf7dba2a401487bc F test/crash5.test 05dd3aa9dbb751a22d5cdaf22a9c49b6667aa219 F test/crash6.test 4c56f1e40d0291e1110790a99807aa875b1647ba F test/crash7.test 1a194c4900a255258cf94b7fcbfd29536db572df -F test/crash8.test 38767cb504bbe491de6be4a7006b154973a2309f +F test/crash8.test 61442a9964ab6b124fc5254e4258b45747842e6f F test/crashtest1.c 09c1c7d728ccf4feb9e481671e29dda5669bbcc2 F test/createtab.test b5de160630b209c4b8925bdcbbaf48cc90b67fe8 F test/cse.test 277350a26264495e86b1785f34d2d0c8600e021c F test/ctime.test 7bd009071e242aac4f18521581536b652b789a47 F test/date.test 42973251b9429f2c41b77eb98a7b0b0ba2d3b2c0 -F test/dbstatus.test aee30c3f337e6c217ff06df59fb8fe6e6448dce2 +F test/dbstatus.test 8de104bb5606f19537d23cd553b41349b5ab1204 F test/dbstatus2.test 10418e62b3db5dca070f0c3eef3ea13946f339c2 F test/default.test 6faf23ccb300114924353007795aa9a8ec0aa9dc F test/delete.test a065b05d2ebf60fd16639c579a4adfb7c381c701 @@ -443,19 +446,19 @@ F test/descidx3.test 09ddbe3f5295f482d2f8b687cf6db8bad7acd9a2 F test/diskfull.test 106391384780753ea6896b7b4f005d10e9866b6e F test/distinct.test 44028aaf161a5e80a2f229622b3a174d3b352810 F test/distinctagg.test 1a6ef9c87a58669438fc771450d7a72577417376 -F test/e_createtable.test ee9b70a38369ae44360febb411976aa3c8cf2689 +F test/e_createtable.test 3b453432cd14a12732ee9467597d2274ca37ce36 F test/e_delete.test d5186e2f5478b659f16a2c8b66c09892823e542a F test/e_droptrigger.test 3cd080807622c13e5bbb61fc9a57bd7754da2412 F test/e_dropview.test 0c9f7f60989164a70a67a9d9c26d1083bc808306 F test/e_expr.test d5cdda0e4ffb17760858ed4c7c4ece07efc40f71 -F test/e_fkey.test 17cfb40002d165299681f39aac0cb5890c359935 +F test/e_fkey.test d83a04478bb9c02d2c513518548a69f818869f41 F test/e_fts3.test 5c02288842e4f941896fd44afdef564dd5fc1459 -F test/e_insert.test 291e056e1a442a5e5166a989a8a03a46e38225ca -F test/e_reindex.test e175794fc41f8e8aef34772e87a7d7b7a9251dd3 +F test/e_insert.test 1e44f84d2abe44d66e4fbf198be4b20e3cc724a0 +F test/e_reindex.test 396b7b4f0a66863b4e95116a67d93b227193e589 F test/e_resolve.test dcce9308fb13b934ce29591105d031d3e14fbba6 F test/e_select.test d3226cb94fae4af3f198e68e71f655e106d0be47 F test/e_select2.test 22c660a7becf0712c95e1ca1b2d9e716a1261460 -F test/e_update.test bea00499e43ee1da77b03cdb0b20c7c864c1ec5a +F test/e_update.test 312cb8f5ccfe41515a6bb092f8ea562a9bd54d52 F test/e_uri.test a2c92d80093a7efdcfbb11093651cbea87097b6b F test/e_vacuum.test 5bfbdc21b65c0abf24398d0ba31dc88d93ca77a9 F test/enc.test e54531cd6bf941ee6760be041dff19a104c7acea @@ -463,7 +466,7 @@ F test/enc2.test 83437a79ba1545a55fb549309175c683fb334473 F test/enc3.test 90683ad0e6ea587b9d5542ca93568af9a9858c40 F test/enc4.test c8f1ce3618508fd0909945beb8b8831feef2c020 F test/eqp.test 57c6c604c2807fb5531731c5323133453c24afac -F test/errmsg.test 050717f1c6a5685de9c79f5f9f6b83d7c592f73a +F test/errmsg.test f31592a594b44ee121371d25ddd5d63497bb3401 F test/eval.test bc269c365ba877554948441e91ad5373f9f91be3 F test/exclusive.test c7ebbc756eacf544c108b15eed64d7d4e5f86b75 F test/exclusive2.test 881193eccec225cfed9d7f744b65e57f26adee25 @@ -474,11 +477,11 @@ F test/fallocate.test 3e979af17dfa7e5e9dda5eba1a696c04fa9d47f7 F test/filectrl.test 14fa712e42c4cb791e09dfd58a6a03efb47ef13a F test/filefmt.test cb34663f126cbc2d358af552dcaf5c72769b0146 F test/fkey1.test e1d1fa84cde579185ea01358436839703e415a5b -F test/fkey2.test 06e0b4cc9e1b3271ae2ae6feeb19755468432111 -F test/fkey3.test 5ec899d12b13bcf1e9ef40eff7fb692fdb91392e +F test/fkey2.test 32ca728bcb854feed72d1406ea375fe423eebff2 +F test/fkey3.test 76d475c80b84ee7a5d062e56ccb6ea68882e2b49 F test/fkey4.test 86446017011273aad8f9a99c1a65019e7bd9ca9d F test/fkey5.test 8a1fde4e7721ae00b05b3178888833726ca2df8d -F test/fkey6.test cd81be336e0664c7e4d3523efb67171d720192ef +F test/fkey6.test 6697550baa38505c9952eff130ab26a2d156c0cc F test/fkey7.test e31d0e71a41c1d29349a16448d6c420e2c53a8fc F test/fkey_malloc.test bb74c9cb8f8fceed03b58f8a7ef2df98520bbd51 F test/format4.test 1f0cac8ff3895e9359ed87e41aaabee982a812eb @@ -551,7 +554,7 @@ F test/fts3defer2.test a3b6cbeabaf28c9398652a4d101ea224d9358479 F test/fts3defer3.test dd53fc13223c6d8264a98244e9b19abd35ed71cd F test/fts3drop.test 1b906e293d6773812587b3dc458cb9e8f3f0c297 F test/fts3e.test 1f6c6ac9cc8b772ca256e6b22aaeed50c9350851 -F test/fts3expr.test 5e745b2b6348499d9ef8d59015de3182072c564c +F test/fts3expr.test 06f1a96facc8f3e4b1ad5cc001dc5c8e83e68b9f F test/fts3expr2.test 18da930352e5693eaa163a3eacf96233b7290d1a F test/fts3expr3.test 9e91b8edbcb197bf2e92161aa7696446d96dce5f F test/fts3fault.test cb72dccb0a3b9f730f16c5240f3fcb9303eb1660 @@ -585,7 +588,7 @@ F test/full.test 6b3c8fb43c6beab6b95438c1675374b95fab245d F test/func.test c7e80a44eebac8604397eb2ad83d0d5d9d541237 F test/func2.test 772d66227e4e6684b86053302e2d74a2500e1e0f F test/func3.test dbccee9133cfef1473c59ec07b5f0262b9d72f9a -F test/func4.test cb3f888a1cafad195a1f8d396875bdb11dc4faf9 +F test/func4.test 6beacdfcb0e18c358e6c2dcacf1b65d1fa80955f F test/fuzz-oss1.test 4912e528ec9cf2f42134456933659d371c9e0d74 F test/fuzz.test 77fd50afc12847af50fcf1941679d90adebadde6 F test/fuzz2.test 207d0f9d06db3eaf47a6b7bfc835b8e2fc397167 @@ -597,13 +600,13 @@ F test/fuzzerfault.test 8792cd77fd5bce765b05d0c8e01b9edcf8af8536 F test/genesis.tcl 1e2e2e8e5cc4058549a154ff1892fe5c9de19f98 F test/hook.test 777b2541f6dd4f4ca5e8d6b66c1df1b3717aeab6 F test/icu.test 70df4faca133254c042d02ae342c0a141f2663f4 -F test/in.test 5941096407d8c133b9eff15bd3e666624b6cbde3 +F test/in.test 047c4671328e9032ab95666a67021adbbd36e98e F test/in2.test 5d4c61d17493c832f7d2d32bef785119e87bde75 F test/in3.test 3cbf58c87f4052cee3a58b37b6389777505aa0c0 F test/in4.test 64f3cc1acde1b9161ccdd8e5bde3daefdb5b2617 F test/in5.test 99f9a40af01711b06d2d614ecfe96129f334fba3 F test/incrblob.test e81846d214f3637622620fbde7cd526781cfe328 -F test/incrblob2.test edc3a96e557bd61fb39acc8d2edd43371fbbaa19 +F test/incrblob2.test bf4d549aa4a466d7fbe3e3a3693d3861263d5600 F test/incrblob3.test d8d036fde015d4a159cd3cbae9d29003b37227a4 F test/incrblob4.test f26502a5697893e5acea268c910f16478c2f0fab F test/incrblob_err.test d2562d2771ebffd4b3af89ef64c140dd44371597 @@ -612,24 +615,25 @@ F test/incrvacuum.test d2a6ddf5e429720b5fe502766af747915ccf6c32 F test/incrvacuum2.test 379eeb8740b0ef60c372c439ad4cbea20b34bb9b F test/incrvacuum3.test 75256fb1377e7c39ef2de62bfc42bbff67be295a F test/incrvacuum_ioerr.test 6ae2f783424e47a0033304808fe27789cf93e635 -F test/index.test f2abacfb83d384ae36b8a919fbd94b1319333e55 +F test/index.test 4d990005a67a36984e4f1a5f1bdccea8d08da4ee F test/index2.test ee83c6b5e3173a3d7137140d945d9a5d4fdfb9d6 -F test/index3.test 423a25c789fc8cc51aaf2a4370bbdde2d9e9eed7 -F test/index4.test 2983216eb8c86ee62d9ed7cb206b5cc3331c0026 +F test/index3.test 55a90cff99834305e8141df7afaef39674b57062 +F test/index4.test ab92e736d5946840236cd61ac3191f91a7856bf6 F test/index5.test fc07c14193c0430814e7a08b5da46888ee795c33 -F test/index6.test 9996f064672c03e768e256e4bf7cff4b63e8b109 +F test/index6.test 936979c3a1e87b81feaed2d00505665bf142d764 +F test/index7.test a3baf9a625bda7fd49471e99aeae04095fbfeecf F test/indexedby.test b2f22f3e693a53813aa3f50b812eb609ba6df1ec F test/indexfault.test 31d4ab9a7d2f6e9616933eb079722362a883eb1d F test/init.test 15c823093fdabbf7b531fe22cf037134d09587a7 F test/insert.test 489aa12a027c83d291f5034a83c8c32e6be1dca2 F test/insert2.test 4f3a04d168c728ed5ec2c88842e772606c7ce435 F test/insert3.test 1b7db95a03ad9c5013fdf7d6722b6cd66ee55e30 -F test/insert4.test 87f6798f31d60c4e177622fcc3663367e6ecbd90 +F test/insert4.test b00ddf82d6d4f0a6f3999f42bb6a3c813ea70707 F test/insert5.test 394f96728d1258f406fe5f5aeb0aaf29487c39a6 F test/instr.test 737bbf80685232033f3abedc6ae92f75860b5dd2 F test/intarray.test 066b7d7ac38d25bf96f87f1b017bfc687551cdd4 F test/interrupt.test dfe9a67a94b0b2d8f70545ba1a6cca10780d71cc -F test/intpkey.test a9674fc6195e0952e4e6105a9981ce1e48e7f215 +F test/intpkey.test 7506090fc08e028712a8bf47e5f54111947e3844 F test/io.test 3a7abcef18727cc0f2399e04b0e8903eccae50f8 F test/ioerr.test 40bb2cfcab63fb6aa7424cd97812a84bc16b5fb8 F test/ioerr2.test 9d71166f8466eda510f1af6137bdabaa82b5408d @@ -691,7 +695,7 @@ F test/mallocK.test d79968641d1b70d88f6c01bdb9a7eb4a55582cc9 F test/malloc_common.tcl 58e54229c4132ef882a11fab6419ec4cd3073589 F test/manydb.test 28385ae2087967aa05c38624cec7d96ec74feb3e F test/mem5.test c6460fba403c5703141348cd90de1c294188c68f -F test/memdb.test db5260330676de007be8530d6ecc7c9ab2b06ad3 +F test/memdb.test fcb5297b321b562084fc79d64d5a12a1cd2b639b F test/memleak.test 10b9c6c57e19fc68c32941495e9ba1c50123f6e2 F test/memsubsys1.test f97cfd0b30e85c2f1ed16d642e7ac58006be84b2 F test/memsubsys2.test 3a1c1a9de48e5726faa85108b02459fae8cb9ee9 @@ -699,9 +703,9 @@ F test/minmax.test 42fbad0e81afaa6e0de41c960329f2b2c3526efd F test/minmax2.test b44bae787fc7b227597b01b0ca5575c7cb54d3bc F test/minmax3.test cc1e8b010136db0d01a6f2a29ba5a9f321034354 F test/minmax4.test 536a3360470633a177e42fbc19660d146b51daef -F test/misc1.test 889b40722442380a2f6575f30831b32b2372d70e +F test/misc1.test 9bed1bd334065a57dc841cff969d4fc1eeb6d49b F test/misc2.test 00d7de54eda90e237fc9a38b9e5ccc769ebf6d4d -F test/misc3.test fe55130a43e444ee75e2156ff75dc96e964b5738 +F test/misc3.test cf3dda47d5dda3e53fc5804a100d3c82be736c9d F test/misc4.test 9c078510fbfff05a9869a0b6d8b86a623ad2c4f6 F test/misc5.test 528468b26d03303b1f047146e5eefc941b9069f5 F test/misc6.test 953cc693924d88e6117aeba16f46f0bf5abede91 @@ -720,7 +724,7 @@ F test/nan.test e9648b9d007c7045242af35e11a984d4b169443a F test/notify1.test 669b2b743618efdc18ca4b02f45423d5d2304abf F test/notify2.test ce23eb522c9e1fff6443f96376fe67872202061c F test/notify3.test 10ff25cde502e72a92053a2f215d64bece4ef934 -F test/notnull.test 2afad748d18fd66d01f66463de73b3e2501fb226 +F test/notnull.test f8fcf58669ddba79274daa2770d61dfad8274f62 F test/null.test a8b09b8ed87852742343b33441a9240022108993 F test/numcast.test 5d126f7f581432e86a90d1e35cac625164aec4a1 F test/openv2.test 0d3040974bf402e19b7df4b783e447289d7ab394 @@ -728,9 +732,9 @@ F test/orderby1.test 9b524aff9147288da43a6d7ddfdcff47fa2303c6 F test/orderby2.test bc11009f7cd99d96b1b11e57b199b00633eb5b04 F test/orderby3.test 8619d06a3debdcd80a27c0fdea5c40b468854b99 F test/orderby4.test 4d39bfbaaa3ae64d026ca2ff166353d2edca4ba4 -F test/orderby5.test 02eca502a0f97c77ce383b0dfa17e99c6a107b8d +F test/orderby5.test 0eb82d5890c3f3d0563966560cfdc984ea69e30c F test/oserror.test 50417780d0e0d7cd23cf12a8277bb44024765df3 -F test/pager1.test 16b649c8f0b38d446acbcff8a7bf055a9be43276 +F test/pager1.test 1acbdb14c5952a72dd43129cabdbf69aaa3ed1fa F test/pager2.test 67b8f40ae98112bcdba1f2b2d03ea83266418c71 F test/pager3.test 3856d9c80839be0668efee1b74811b1b7f7fc95f F test/pagerfault.test 7285379906ab2f1108b8e82bbdf2d386cc8ff3ff @@ -742,7 +746,7 @@ F test/pcache.test b09104b03160aca0d968d99e8cd2c5b1921a993d F test/pcache2.test a83efe2dec0d392f814bfc998def1d1833942025 F test/percentile.test b98fc868d71eb5619d42a1702e9ab91718cbed54 F test/permutations.test 08dbc6b0f4afbdffd701346ffae2998bb612c335 -F test/pragma.test 5e7de6c32a5d764f09437d2025f07e4917b9e178 +F test/pragma.test e882183ecd21d064cec5c7aaea174fbd36293429 F test/pragma2.test aea7b3d82c76034a2df2b38a13745172ddc0bc13 F test/printf.test ec9870c4dce8686a37818e0bf1aba6e6a1863552 F test/progress.test a282973d1d17f08071bc58a77d6b80f2a81c354d @@ -761,11 +765,11 @@ F test/reindex.test 44edd3966b474468b823d481eafef0c305022254 F test/releasetest.mk 2eced2f9ae701fd0a29e714a241760503ccba25a F test/releasetest.tcl 06d289d8255794073a58d2850742f627924545ce F test/resolver01.test 33abf37ff8335e6bf98f2b45a0af3e06996ccd9a -F test/rollback.test a1b4784b864331eae8b2a98c189efa2a8b11ff07 +F test/rollback.test e9504a009a202c3ed711da2e6879ff60c5a4669c F test/rowhash.test 0bc1d31415e4575d10cacf31e1a66b5cc0f8be81 F test/rowid.test f777404492adb0e00868fd706a3721328fd3af48 F test/rtree.test 0c8d9dd458d6824e59683c19ab2ffa9ef946f798 -F test/savepoint.test f5acd87d0c7a5f4ad6c547b47fd18c0e1aeaf048 +F test/savepoint.test 6c53f76dffe5df0dd87646efe3e7aa159c36e07b F test/savepoint2.test 9b8543940572a2f01a18298c3135ad0c9f4f67d7 F test/savepoint3.test e328085853b14898d78ceea00dfe7db18bb6a9ec F test/savepoint4.test c8f8159ade6d2acd9128be61e1230f1c1edc6cc0 @@ -776,7 +780,7 @@ F test/schema.test 8f7999be894260f151adf15c2c7540f1c6d6a481 F test/schema2.test 906408621ea881fdb496d878b1822572a34e32c5 F test/schema3.test 1bc1008e1f8cb5654b248c55f27249366eb7ed38 F test/schema4.test e6a66e20cc69f0e306667c08be7fda3d11707dc5 -F test/schema5.test 0103e4c0313b3725b5ae5600bdca53006ab53db3 +F test/schema5.test 29699b4421f183c8f0e88bd28ce7d75d13ea653e F test/securedel.test 87a2561151af1f1e349071a89fdd77059f50113c F test/securedel2.test 2d54c28e46eb1fd6902089958b20b1b056c6f1c5 F test/select1.test fc2a61f226a649393664ad54bc5376631801517c @@ -827,7 +831,7 @@ F test/speed4p.explain 6b5f104ebeb34a038b2f714150f51d01143e59aa F test/speed4p.test 0e51908951677de5a969b723e03a27a1c45db38b F test/spellfix.test 8c40b169b104086d8795781f670ba3c786d6d8be F test/sqllimits1.test b1aae27cc98eceb845e7f7adf918561256e31298 -F test/stat.test be8d477306006ec696bc86757cfb34bec79447ce +F test/stat.test c8eccfe8fcd3f3cfc864ce22d5b9e803a3c69940 F test/stmt.test 25d64e3dbf9a3ce89558667d7f39d966fe2a71b9 F test/subquery.test 666fdecceac258f5fd84bed09a64e49d9f37edd9 F test/subquery2.test 91e1e364072aeff431d1f9689b15147e421d88c7 @@ -837,13 +841,14 @@ F test/superlock.test 1cde669f68d2dd37d6c9bd35eee1d95491ae3fc2 F test/sync.test a34cd43e98b7fb84eabbf38f7ed8f7349b3f3d85 F test/syscall.test a653783d985108c4912cc64d341ffbbb55ad2806 F test/sysfault.test fa776e60bf46bdd3ae69f0b73e46ee3977a58ae6 -F test/table.test 30423211108121884588d24d6776c7f38702ad7b +F test/table.test 580d23530187026d4502fae74a490f0408cf2cc7 F test/tableapi.test 2674633fa95d80da917571ebdd759a14d9819126 +F test/tableopts.test dba698ba97251017b7c80d738c198d39ab747930 F test/tclsqlite.test a7308276aad2e6c0bfb5b0414424dd0d9cc0cad7 F test/tempdb.test 19d0f66e2e3eeffd68661a11c83ba5e6ace9128c F test/temptable.test d2c9b87a54147161bcd1822e30c1d1cd891e5b30 F test/temptrigger.test 0a48d94222d50e6e50d72ac103606c4f8e7cbb81 -F test/tester.tcl 282c1a6b541bd2518a28030884073d1b6dfe98ba +F test/tester.tcl c52441bc75166cf9eab488fef33a5367518b5a89 F test/thread001.test 9f22fd3525a307ff42a326b6bc7b0465be1745a5 F test/thread002.test e630504f8a06c00bf8bbe68528774dd96aeb2e58 F test/thread003.test ee4c9efc3b86a6a2767516a37bd64251272560a7 @@ -867,7 +872,7 @@ F test/tkt-38cb5df375.test f3cc8671f1eb604d4ae9cf886ed4366bec656678 F test/tkt-3998683a16.test 6d1d04d551ed1704eb3396ca87bb9ccc8c5c1eb7 F test/tkt-3a77c9714e.test b08bca26de1140bdf004a37716582a43d7bd8be8 F test/tkt-3fe897352e.test 27e26eb0f1811aeba4d65aba43a4c52e99da5e70 -F test/tkt-4a03edc4c8.test 2865e4edbc075b954daa82f8da7cc973033ec76e +F test/tkt-4a03edc4c8.test 91c0e135888cdc3d4eea82406a44b05c8c1648d0 F test/tkt-4dd95f6943.test 3d0ce415d2ee15d3d564121960016b9c7be79407 F test/tkt-54844eea3f.test a12b851128f46a695e4e378cca67409b9b8f5894 F test/tkt-5d863f876e.test c9f36ca503fa154a3655f92a69d2c30da1747bfa @@ -875,7 +880,7 @@ F test/tkt-5e10420e8d.test 904d1687b3c06d43e5b3555bbcf6802e7c0ffd84 F test/tkt-5ee23731f.test 9db6e1d7209dc0794948b260d6f82b2b1de83a9f F test/tkt-6bfb98dfc0.test 24780633627b5cfc0635a5500c2389ebfb563336 F test/tkt-752e1646fc.test ea78d88d14fe9866bdd991c634483334639e13bf -F test/tkt-78e04e52ea.test b0190d3375cf88b97d32188149cc99ccf22f556b +F test/tkt-78e04e52ea.test 813779f8888f3ca226df656c4eef078f9635f3c9 F test/tkt-7a31705a7e6.test e75a2bba4eec801b92c8040eb22096ac6d35e844 F test/tkt-7bbfb7d442.test 7b2cd79c7a17ae6750e75ec1a7846712a69c9d18 F test/tkt-80ba201079.test 105a721e6aad0ae3c5946d7615d1e4d03f6145b8 @@ -887,7 +892,7 @@ F test/tkt-94c04eaadb.test fa9c71192f7e2ea2d51bf078bc34e8da6088bf71 F test/tkt-9d68c883.test 458f7d82a523d7644b54b497c986378a7d8c8b67 F test/tkt-9f2eb3abac.test 85bc63e749f050e6a61c8f9207f1eee65c9d3395 F test/tkt-a7b7803e.test 159ef554234fa1f9fb318c751b284bd1cf858da4 -F test/tkt-b1d3a2e531.test 610ef582413171b379652663111b1f996d9f8f78 +F test/tkt-b1d3a2e531.test 8f7576e41ca179289ee1a8fee28386fd8e4b0550 F test/tkt-b351d95f9.test d14a503c414c5c58fdde3e80f9a3cfef986498c0 F test/tkt-b72787b1.test a95e8cdad0b98af1853ac7f0afd4ab27b77bf5f3 F test/tkt-bd484a090c.test 60460bf946f79a79712b71f202eda501ca99b898 @@ -914,7 +919,7 @@ F test/tkt1512.test a1df1f66caf0b9122d6220c15dcee230298c2c2f F test/tkt1514.test ddef38e34fea72eb1ab935ded9f17a3fb71dd9df F test/tkt1536.test 83ff7a7b6e248016f8d682d4f7a4ae114070d466 F test/tkt1537.test e3a14332de9770be8ff14bd15c19a49cbec10808 -F test/tkt1567.test 18023cc3626a365f0118e17b66decedec93b1a6f +F test/tkt1567.test 52f329386ac77e59260d4af1c58490d61377db20 F test/tkt1644.test 80b6a2bb17885f3cf1cb886d97cdad13232bb869 F test/tkt1667.test 4700d931ed19ea3983e8e703becb28079250b460 F test/tkt1873.test 0e1b8c023050a430c2525179ed4022ddc7c31264 @@ -962,7 +967,7 @@ F test/tkt3527.test 1a6a48441b560bdc53aec581a868eb576234874d F test/tkt3541.test 5dc257bde9bc833ab9cc6844bf170b998dbb950a F test/tkt3554.test f599967f279077bace39220cbe76085c7b423725 F test/tkt3581.test 1966b7193f1e3f14951cce8c66907ae69454e9a3 -F test/tkt35xx.test 69d038ce5898f1b64f2084b780bbab1cf9be0a25 +F test/tkt35xx.test f38c1b03713179d414969187c941466e44945b35 F test/tkt3630.test 929f64852103054125200bc825c316d5f75d42f7 F test/tkt3718.test 3b59dcb5c4e7754dacd91e7fd353a61492cc402a F test/tkt3731.test 0c5f4cbffe102d43c3b2188af91a9e36348f974b @@ -996,7 +1001,7 @@ F test/trans2.test d5337e61de45e66b1fcbf9db833fa8c82e624b22 F test/trans3.test 373ac5183cc56be69f48ae44090e7f672939f732 F test/transitive1.test 03f532954f46cdf5608f7766bff0b0c52bf2a7cd F test/trigger1.test dc47573ac79ffe0ee3eecaa517d70d8dacbccd03 -F test/trigger2.test 834187beafd1db383af0c659cfa49b0576832816 +F test/trigger2.test 5cd7d69a7ba1143ee045e4ae2963ff32ae4c87a6 F test/trigger3.test aa640bb2bbb03edd5ff69c055117ea088f121945 F test/trigger4.test 74700b76ebf3947b2f7a92405141eb2cf2a5d359 F test/trigger5.test 619391a3e9fc194081d22cefd830d811e7badf83 @@ -1006,17 +1011,17 @@ F test/trigger8.test 30cb0530bd7c4728055420e3f739aa00412eafa4 F test/trigger9.test 5b0789f1c5c4600961f8e68511b825b87be53e31 F test/triggerA.test fe5597f47ee21bacb4936dc827994ed94161e332 F test/triggerB.test 56780c031b454abac2340dbb3b71ac5c56c3d7fe -F test/triggerC.test a7b4367392c755bc5fd5fff88011753e6b6afe90 +F test/triggerC.test a68980c5955d62ee24be6f97129d824f199f9a4c F test/triggerD.test 8e7f3921a92a5797d472732108109e44575fa650 F test/triggerE.test 355e9c5cbaed5cd039a60baad1fb2197caeb8e52 F test/tt3_checkpoint.c 415eccce672d681b297485fc20f44cdf0eac93af F test/types.test bf816ce73c7dfcfe26b700c19f97ef4050d194ff F test/types2.test 3555aacf8ed8dc883356e59efc314707e6247a84 F test/types3.test 99e009491a54f4dc02c06bdbc0c5eea56ae3e25a -F test/unique.test cadb172bbd5a2e83cd644d186ccd602085e54edc +F test/unique.test 93f8b2ef5ea51b9495f8d6493429b1fd0f465264 F test/unixexcl.test a9870e46cc6f8390a494513d4f2bf55b5a8b3e46 F test/unordered.test ef85ac8f2f3c93ed2b9e811b684de73175fc464c -F test/update.test 8bc86fd7ef1a00014f76dc6a6a7c974df4aef172 +F test/update.test 1b6c488a8f993d090b7ee9ad0e234faa161b3aeb F test/uri.test 63e03df051620a18f794b4f4adcdefb3c23b6751 F test/utf16align.test 54cd35a27c005a9b6e7815d887718780b6a462ae F test/vacuum.test ce91c39f7f91a4273bf620efad21086b5aa6ef1d @@ -1026,7 +1031,7 @@ F test/vacuum4.test d3f8ecff345f166911568f397d2432c16d2867d9 F test/varint.test ab7b110089a08b9926ed7390e7e97bdefeb74102 F test/veryquick.test 57ab846bacf7b90cf4e9a672721ea5c5b669b661 F test/view.test 4057630287bfa5955628fe90a13d4c225d1c7352 -F test/vtab1.test 1550abf90bc2b996f8c34e0be3fdb251af54fa41 +F test/vtab1.test 45ddde57764659c0ec90874bcb6c4831f1004c06 F test/vtab2.test 7bcffc050da5c68f4f312e49e443063e2d391c0d F test/vtab3.test baad99fd27217f5d6db10660522e0b7192446de1 F test/vtab4.test 942f8b8280b3ea8a41dae20e7822d065ca1cb275 @@ -1044,7 +1049,7 @@ F test/vtabF.test fd5ad376f5a34fe0891df1f3cddb4fe7c3eb077e F test/vtab_alter.test 9e374885248f69e251bdaacf480b04a197f125e5 F test/vtab_err.test 0d4d8eb4def1d053ac7c5050df3024fd47a3fbd8 F test/vtab_shared.test 82f463886e18d7f8395a4b6167c91815efe54839 -F test/wal.test 3a6ebdf0287b38b5537c07c517b30dda9aaac317 +F test/wal.test a59d00eaa0901e42b8a2ef21f2a4c972ee1f1bd4 F test/wal2.test d4b470f13c87f6d8268b004380afa04c3c67cb90 F test/wal3.test b22eb662bcbc148c5f6d956eaf94b047f7afe9c0 F test/wal4.test 4744e155cd6299c6bd99d3eab1c82f77db9cdb3c @@ -1076,7 +1081,7 @@ F test/where4.test e9b9e2f2f98f00379e6031db6a6fca29bae782a2 F test/where5.test fdf66f96d29a064b63eb543e28da4dfdccd81ad2 F test/where6.test 5da5a98cec820d488e82708301b96cb8c18a258b F test/where7.test 5a4b0abc207d71da4deecd734ad8579e8dd40aa8 -F test/where8.test 6f95896633cf2d307b5263145b942b7d33e837c6 +F test/where8.test d2b4fd6d7b7c5d44f590182a05033d78a14c00a1 F test/where8m.test da346596e19d54f0aba35ebade032a7c47d79739 F test/where9.test 4f3eab951353a3ae164befc521c777dfa903e46c F test/whereA.test 4d253178d135ec46d1671e440cd8f2b916aa6e6b @@ -1090,9 +1095,14 @@ F test/wherelimit.test 5e9fd41e79bb2b2d588ed999d641d9c965619b31 F test/wild001.test bca33f499866f04c24510d74baf1e578d4e44b1c F test/win32lock.test 7a6bd73a5dcdee39b5bb93e92395e1773a194361 F test/win32longpath.test e2aafc07e6990fe86c69be22a3d1a0e210cd329b +F test/without_rowid1.test aaa26da19d543cd8d3d2d0e686dfa255556c15c8 +F test/without_rowid2.test af260339f79d13cb220288b67cd287fbcf81ad99 +F test/without_rowid3.test eac3d5c8a1924725b58503a368f2cbd24fd6c8a0 +F test/without_rowid4.test 4e08bcbaee0399f35d58b5581881e7a6243d458a +F test/wordcount.c 2c2cc1119de42e6730ca8bd149666f0e0095108a F test/zeroblob.test caaecfb4f908f7bc086ed238668049f96774d688 F test/zerodamage.test 209d7ed441f44cc5299e4ebffbef06fd5aabfefd -F tool/build-all-msvc.bat 38623a30fd58288fda5cc7f7df2682aaab75c9d5 x +F tool/build-all-msvc.bat 1bac6adc3fdb4d9204f21d17b14be25778370e48 x F tool/build-shell.sh 950f47c6174f1eea171319438b93ba67ff5bf367 F tool/checkSpacing.c 810e51703529a204fc4e1eb060e9ab663e3c06d2 F tool/diffdb.c 7524b1b5df217c20cd0431f6789851a4e0cb191b @@ -1106,7 +1116,7 @@ F tool/lemon.c 796930d5fc2036c7636f3f1ee12f9ae03719a2eb F tool/lempar.c 01ca97f87610d1dac6d8cd96ab109ab1130e76dc F tool/logest.c 7ad625cac3d54012b27d468b7af6612f78b9ba75 F tool/mkautoconfamal.sh f8d8dbf7d62f409ebed5134998bf5b51d7266383 -F tool/mkkeywordhash.c bb52064aa614e1426445e4b2b9b00eeecd23cc79 +F tool/mkkeywordhash.c 189d76644e373c7d0864c628deb8ce7b4f403591 F tool/mkopts.tcl 66ac10d240cc6e86abd37dc908d50382f84ff46e F tool/mkpragmatab.tcl 17d40faae6c4b865633bfc5763821402a1cbefc3 F tool/mkspeedsql.tcl a1a334d288f7adfe6e996f2e712becf076745c97 @@ -1126,7 +1136,7 @@ F tool/showjournal.c b62cecaab86a4053d944c276bb5232e4d17ece02 F tool/showwal.c 3f7f7da5ec0cba51b1449a75f700493377da57b5 F tool/soak1.tcl 8d407956e1a45b485a8e072470a3e629a27037fe F tool/space_used.tcl f714c41a59e326b8b9042f415b628b561bafa06b -F tool/spaceanal.tcl d8c11da184b1a13d0456d786e70b3867e141b74a +F tool/spaceanal.tcl 8e50b217c56a6a086a1b47eac9d09c5cd65b996f F tool/speedtest.tcl 06c76698485ccf597b9e7dbb1ac70706eb873355 F tool/speedtest16.c c8a9c793df96db7e4933f0852abb7a03d48f2e81 F tool/speedtest2.tcl ee2149167303ba8e95af97873c575c3e0fab58ff @@ -1141,7 +1151,7 @@ F tool/vdbe-compress.tcl f12c884766bd14277f4fcedcae07078011717381 F tool/warnings-clang.sh f6aa929dc20ef1f856af04a730772f59283631d4 F tool/warnings.sh d1a6de74685f360ab718efda6265994b99bbea01 F tool/win/sqlite.vsix 030f3eeaf2cb811a3692ab9c14d021a75ce41fff -P 5806546822b717d712dc7cd9de88a86f5bf2f715 3a9e3ed94bf617f00c48009b1a6d348a8f23a3cf -R 6a218c52fd606677f29de12012a31eb7 +P aa72ea8a004de7fe744fc13baef19d05aea607d5 f58d57017199421167dae8ebc67db2f19be45082 +R 3b17341d4c625bc46e3586e654b8390b U drh -Z 6c335f57007a8ea5e658e5dc44efd950 +Z 1cdf9fac9d6e4efb5a645c5741312eca diff --git a/manifest.uuid b/manifest.uuid index eb5e2715c7..e437b594ea 100644 --- a/manifest.uuid +++ b/manifest.uuid @@ -1 +1 @@ -aa72ea8a004de7fe744fc13baef19d05aea607d5 \ No newline at end of file +5addd1234ded59ce60fb633b76ac87d483377edd \ No newline at end of file diff --git a/mkopcodec.awk b/mkopcodec.awk index 2ef77d4cca..de19068c20 100644 --- a/mkopcodec.awk +++ b/mkopcodec.awk @@ -12,22 +12,36 @@ BEGIN { print "/* Automatically generated. Do not edit */" print "/* See the mkopcodec.awk script for details. */" printf "#if !defined(SQLITE_OMIT_EXPLAIN)" - printf " || !defined(NDEBUG)" printf " || defined(VDBE_PROFILE)" print " || defined(SQLITE_DEBUG)" + print "#if defined(SQLITE_ENABLE_EXPLAIN_COMMENTS) || defined(SQLITE_DEBUG)" + print "# define OpHelp(X) \"\\0\" X" + print "#else" + print "# define OpHelp(X)" + print "#endif" print "const char *sqlite3OpcodeName(int i){" print " static const char *const azName[] = { \"?\"," mx = 0 } -/define OP_/ { +/^.define OP_/ { sub("OP_","",$2) i = $3+0 label[i] = $2 if( mxnRowid ){ + sqlite3DbFree(db, p->u.aRowid); + p->nRowid = 0; + } +} +#endif + +/* Initialize the BLOB value of a ROWID +*/ +#ifdef SQLITE_ENABLE_STAT3_OR_STAT4 +static void sampleSetRowid(sqlite3 *db, Stat4Sample *p, int n, const u8 *pData){ + assert( db!=0 ); + if( p->nRowid ) sqlite3DbFree(db, p->u.aRowid); + p->u.aRowid = sqlite3DbMallocRaw(db, n); + if( p->u.aRowid ){ + p->nRowid = n; + memcpy(p->u.aRowid, pData, n); + }else{ + p->nRowid = 0; + } +} +#endif + +/* Initialize the INTEGER value of a ROWID. +*/ +#ifdef SQLITE_ENABLE_STAT3_OR_STAT4 +static void sampleSetRowidInt64(sqlite3 *db, Stat4Sample *p, i64 iRowid){ + assert( db!=0 ); + if( p->nRowid ) sqlite3DbFree(db, p->u.aRowid); + p->nRowid = 0; + p->u.iRowid = iRowid; +} +#endif + + +/* +** Copy the contents of object (*pFrom) into (*pTo). +*/ +#ifdef SQLITE_ENABLE_STAT3_OR_STAT4 +static void sampleCopy(Stat4Accum *p, Stat4Sample *pTo, Stat4Sample *pFrom){ + pTo->isPSample = pFrom->isPSample; + pTo->iCol = pFrom->iCol; + pTo->iHash = pFrom->iHash; + memcpy(pTo->anEq, pFrom->anEq, sizeof(tRowcnt)*p->nCol); + memcpy(pTo->anLt, pFrom->anLt, sizeof(tRowcnt)*p->nCol); + memcpy(pTo->anDLt, pFrom->anDLt, sizeof(tRowcnt)*p->nCol); + if( pFrom->nRowid ){ + sampleSetRowid(p->db, pTo, pFrom->nRowid, pFrom->u.aRowid); + }else{ + sampleSetRowidInt64(p->db, pTo, pFrom->u.iRowid); + } +} +#endif + +/* +** Reclaim all memory of a Stat4Accum structure. +*/ +static void stat4Destructor(void *pOld){ + Stat4Accum *p = (Stat4Accum*)pOld; +#ifdef SQLITE_ENABLE_STAT3_OR_STAT4 + int i; + for(i=0; inCol; i++) sampleClear(p->db, p->aBest+i); + for(i=0; imxSample; i++) sampleClear(p->db, p->a+i); + sampleClear(p->db, &p->current); +#endif + sqlite3DbFree(p->db, p); +} + /* ** Implementation of the stat_init(N,C) SQL function. The two parameters ** are the number of rows in the table or index (C) and the number of columns @@ -307,6 +384,7 @@ static void statInit( int nCol; /* Number of columns in index being sampled */ int nColUp; /* nCol rounded up for alignment */ int n; /* Bytes of space to allocate */ + sqlite3 *db; /* Database connection */ #ifdef SQLITE_ENABLE_STAT3_OR_STAT4 int mxSample = SQLITE_STAT4_SAMPLES; #endif @@ -323,16 +401,18 @@ static void statInit( + sizeof(tRowcnt)*nColUp /* Stat4Accum.anDLt */ #ifdef SQLITE_ENABLE_STAT3_OR_STAT4 + sizeof(tRowcnt)*nColUp /* Stat4Accum.anLt */ - + sizeof(Stat4Sample)*(nCol+mxSample) /* Stat4Accum.aBest[], a[] */ + + sizeof(Stat4Sample)*(nCol+mxSample) /* Stat4Accum.aBest[], a[] */ + sizeof(tRowcnt)*3*nColUp*(nCol+mxSample) #endif ; - p = sqlite3MallocZero(n); + db = sqlite3_context_db_handle(context); + p = sqlite3DbMallocZero(db, n); if( p==0 ){ sqlite3_result_error_nomem(context); return; } + p->db = db; p->nRow = 0; p->nCol = nCol; p->current.anDLt = (tRowcnt*)&p[1]; @@ -367,7 +447,7 @@ static void statInit( #endif /* Return a pointer to the allocated object to the caller */ - sqlite3_result_blob(context, p, sizeof(p), sqlite3_free); + sqlite3_result_blob(context, p, sizeof(p), stat4Destructor); } static const FuncDef statInitFuncdef = { 1+IsStat34, /* nArg */ @@ -441,25 +521,12 @@ static int sampleIsBetter( #endif } -/* -** Copy the contents of object (*pFrom) into (*pTo). -*/ -static void sampleCopy(Stat4Accum *p, Stat4Sample *pTo, Stat4Sample *pFrom){ - pTo->iRowid = pFrom->iRowid; - pTo->isPSample = pFrom->isPSample; - pTo->iCol = pFrom->iCol; - pTo->iHash = pFrom->iHash; - memcpy(pTo->anEq, pFrom->anEq, sizeof(tRowcnt)*p->nCol); - memcpy(pTo->anLt, pFrom->anLt, sizeof(tRowcnt)*p->nCol); - memcpy(pTo->anDLt, pFrom->anDLt, sizeof(tRowcnt)*p->nCol); -} - /* ** Copy the contents of sample *pNew into the p->a[] array. If necessary, ** remove the least desirable sample from p->a[] to make room. */ static void sampleInsert(Stat4Accum *p, Stat4Sample *pNew, int nEqZero){ - Stat4Sample *pSample; + Stat4Sample *pSample = 0; int i; assert( IsStat4 || nEqZero==0 ); @@ -499,8 +566,10 @@ static void sampleInsert(Stat4Accum *p, Stat4Sample *pNew, int nEqZero){ tRowcnt *anEq = pMin->anEq; tRowcnt *anLt = pMin->anLt; tRowcnt *anDLt = pMin->anDLt; + sampleClear(p->db, pMin); memmove(pMin, &pMin[1], sizeof(p->a[0])*(p->nSample-p->iMin-1)); pSample = &p->a[p->nSample-1]; + pSample->nRowid = 0; pSample->anEq = anEq; pSample->anDLt = anDLt; pSample->anLt = anLt; @@ -597,16 +666,17 @@ static void samplePushPrevious(Stat4Accum *p, int iChng){ } /* -** Implementation of the stat_push SQL function: stat_push(P,R,C) +** Implementation of the stat_push SQL function: stat_push(P,C,R) ** Arguments: ** ** P Pointer to the Stat4Accum object created by stat_init() ** C Index of left-most column to differ from previous row -** R Rowid for the current row +** R Rowid for the current row. Might be a key record for +** WITHOUT ROWID tables. ** ** The SQL function always returns NULL. ** -** The R parameter is only used for STAT3 and STAT4. +** The R parameter is only used for STAT3 and STAT4 */ static void statPush( sqlite3_context *context, @@ -646,7 +716,12 @@ static void statPush( } p->nRow++; #ifdef SQLITE_ENABLE_STAT3_OR_STAT4 - p->current.iRowid = sqlite3_value_int64(argv[2]); + if( sqlite3_value_type(argv[2])==SQLITE_INTEGER ){ + sampleSetRowidInt64(p->db, &p->current, sqlite3_value_int64(argv[2])); + }else{ + sampleSetRowid(p->db, &p->current, sqlite3_value_bytes(argv[2]), + sqlite3_value_blob(argv[2])); + } p->current.iHash = p->iPrn = p->iPrn*1103515245 + 12345; #endif @@ -770,7 +845,13 @@ static void statGet( p->iGet = 0; } if( p->iGetnSample ){ - sqlite3_result_int64(context, p->a[p->iGet].iRowid); + Stat4Sample *pS = p->a + p->iGet; + if( pS->nRowid==0 ){ + sqlite3_result_int64(context, pS->u.iRowid); + }else{ + sqlite3_result_blob(context, pS->u.aRowid, pS->nRowid, + SQLITE_TRANSIENT); + } } }else{ tRowcnt *aCnt = 0; @@ -907,22 +988,26 @@ static void analyzeOneTable( for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ int nCol; /* Number of columns indexed by pIdx */ - KeyInfo *pKey; /* KeyInfo structure for pIdx */ int *aGotoChng; /* Array of jump instruction addresses */ int addrRewind; /* Address of "OP_Rewind iIdxCur" */ int addrGotoChng0; /* Address of "Goto addr_chng_0" */ int addrNextRow; /* Address of "next_row:" */ + const char *zIdxName; /* Name of the index */ if( pOnlyIdx && pOnlyIdx!=pIdx ) continue; if( pIdx->pPartIdxWhere==0 ) needTableCnt = 0; VdbeNoopComment((v, "Begin analysis of %s", pIdx->zName)); - nCol = pIdx->nColumn; + nCol = pIdx->nKeyCol; aGotoChng = sqlite3DbMallocRaw(db, sizeof(int)*(nCol+1)); if( aGotoChng==0 ) continue; - pKey = sqlite3IndexKeyinfo(pParse, pIdx); /* Populate the register containing the index name. */ - sqlite3VdbeAddOp4(v, OP_String8, 0, regIdxname, 0, pIdx->zName, 0); + if( pIdx->autoIndex==2 && !HasRowid(pTab) ){ + zIdxName = pTab->zName; + }else{ + zIdxName = pIdx->zName; + } + sqlite3VdbeAddOp4(v, OP_String8, 0, regIdxname, 0, zIdxName, 0); /* ** Pseudo-code for loop that calls stat_push(): @@ -965,7 +1050,7 @@ static void analyzeOneTable( /* Open a read-only cursor on the index being analyzed. */ assert( iDb==sqlite3SchemaToIndex(db, pIdx->pSchema) ); sqlite3VdbeAddOp3(v, OP_OpenRead, iIdxCur, pIdx->tnum, iDb); - sqlite3VdbeChangeP4(v, -1, (char*)pKey, P4_KEYINFO_HANDOFF); + sqlite3VdbeSetP4KeyInfo(pParse, pIdx); VdbeComment((v, "%s", pIdx->zName)); /* Invoke the stat_init() function. The arguments are: @@ -1039,8 +1124,21 @@ static void analyzeOneTable( */ sqlite3VdbeJumpHere(v, aGotoChng[nCol]); #ifdef SQLITE_ENABLE_STAT3_OR_STAT4 - sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, regRowid); assert( regRowid==(regStat4+2) ); + if( HasRowid(pTab) ){ + sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, regRowid); + }else{ + Index *pPk = sqlite3PrimaryKeyIndex(pIdx->pTable); + int j, k, regKey; + regKey = sqlite3GetTempRange(pParse, pPk->nKeyCol); + for(j=0; jnKeyCol; j++){ + k = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[j]); + sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, k, regKey+j); + VdbeComment((v, "%s", pTab->aCol[pPk->aiColumn[j]].zName)); + } + sqlite3VdbeAddOp3(v, OP_MakeRecord, regKey, pPk->nKeyCol, regRowid); + sqlite3ReleaseTempRange(pParse, regKey, pPk->nKeyCol); + } #endif assert( regChng==(regStat4+1) ); sqlite3VdbeAddOp3(v, OP_Function, 1, regStat4, regTemp); @@ -1066,6 +1164,7 @@ static void analyzeOneTable( int regSampleRowid = regCol + nCol; int addrNext; int addrIsNull; + u8 seekOp = HasRowid(pTab) ? OP_NotExists : OP_NotFound; pParse->nMem = MAX(pParse->nMem, regCol+nCol+1); @@ -1075,13 +1174,13 @@ static void analyzeOneTable( callStatGet(v, regStat4, STAT_GET_NEQ, regEq); callStatGet(v, regStat4, STAT_GET_NLT, regLt); callStatGet(v, regStat4, STAT_GET_NDLT, regDLt); - sqlite3VdbeAddOp3(v, OP_NotExists, iTabCur, addrNext, regSampleRowid); + sqlite3VdbeAddOp4Int(v, seekOp, iTabCur, addrNext, regSampleRowid, 0); #ifdef SQLITE_ENABLE_STAT3 sqlite3ExprCodeGetColumnOfTable(v, pTab, iTabCur, pIdx->aiColumn[0], regSample); #else for(i=0; iaiColumn[i]; + i16 iCol = pIdx->aiColumn[i]; sqlite3ExprCodeGetColumnOfTable(v, pTab, iTabCur, iCol, regCol+i); } sqlite3VdbeAddOp3(v, OP_MakeRecord, regCol, nCol+1, regSample); @@ -1337,7 +1436,7 @@ static int analysisLoader(void *pData, int argc, char **argv, char **NotUsed){ z = argv[2]; if( pIndex ){ - decodeIntArray((char*)z, pIndex->nColumn+1, pIndex->aiRowEst, pIndex); + decodeIntArray((char*)z, pIndex->nKeyCol+1, pIndex->aiRowEst, pIndex); if( pIndex->pPartIdxWhere==0 ) pTable->nRowEst = pIndex->aiRowEst[0]; }else{ Index fakeIdx; @@ -1383,7 +1482,7 @@ static void initAvgEq(Index *pIdx){ IndexSample *aSample = pIdx->aSample; IndexSample *pFinal = &aSample[pIdx->nSample-1]; int iCol; - for(iCol=0; iColnColumn; iCol++){ + for(iCol=0; iColnKeyCol; iCol++){ int i; /* Used to iterate through samples */ tRowcnt sumEq = 0; /* Sum of the nEq values */ tRowcnt nSum = 0; /* Number of terms contributing to sumEq */ @@ -1411,6 +1510,23 @@ static void initAvgEq(Index *pIdx){ } } +/* +** Look up an index by name. Or, if the name of a WITHOUT ROWID table +** is supplied instead, find the PRIMARY KEY index for that table. +*/ +static Index *findIndexOrPrimaryKey( + sqlite3 *db, + const char *zName, + const char *zDb +){ + Index *pIdx = sqlite3FindIndex(db, zName, zDb); + if( pIdx==0 ){ + Table *pTab = sqlite3FindTable(db, zName, zDb); + if( pTab && !HasRowid(pTab) ) pIdx = sqlite3PrimaryKeyIndex(pTab); + } + return pIdx; +} + /* ** Load the content from either the sqlite_stat4 or sqlite_stat3 table ** into the relevant Index.aSample[] arrays. @@ -1460,14 +1576,14 @@ static int loadStatTbl( zIndex = (char *)sqlite3_column_text(pStmt, 0); if( zIndex==0 ) continue; nSample = sqlite3_column_int(pStmt, 1); - pIdx = sqlite3FindIndex(db, zIndex, zDb); + pIdx = findIndexOrPrimaryKey(db, zIndex, zDb); assert( pIdx==0 || bStat3 || pIdx->nSample==0 ); /* Index.nSample is non-zero at this point if data has already been ** loaded from the stat4 table. In this case ignore stat3 data. */ if( pIdx==0 || pIdx->nSample ) continue; if( bStat3==0 ){ - nIdxCol = pIdx->nColumn+1; - nAvgCol = pIdx->nColumn; + nIdxCol = pIdx->nKeyCol+1; + nAvgCol = pIdx->nKeyCol; } pIdx->nSampleCol = nIdxCol; nByte = sizeof(IndexSample) * nSample; @@ -1506,7 +1622,7 @@ static int loadStatTbl( zIndex = (char *)sqlite3_column_text(pStmt, 0); if( zIndex==0 ) continue; - pIdx = sqlite3FindIndex(db, zIndex, zDb); + pIdx = findIndexOrPrimaryKey(db, zIndex, zDb); if( pIdx==0 ) continue; /* This next condition is true if data has already been loaded from ** the sqlite_stat4 table. In this case ignore stat3 data. */ diff --git a/src/btree.c b/src/btree.c index d56dfbddbb..cebf95e8da 100644 --- a/src/btree.c +++ b/src/btree.c @@ -684,7 +684,7 @@ static int btreeMoveto( ){ int rc; /* Status code */ UnpackedRecord *pIdxKey; /* Unpacked index key */ - char aSpace[150]; /* Temp space for pIdxKey - to avoid a malloc */ + char aSpace[200]; /* Temp space for pIdxKey - to avoid a malloc */ char *pFree = 0; if( pKey ){ diff --git a/src/build.c b/src/build.c index 38bdad859f..c3999f2b9a 100644 --- a/src/build.c +++ b/src/build.c @@ -382,8 +382,10 @@ static void freeIndex(sqlite3 *db, Index *p){ #ifndef SQLITE_OMIT_ANALYZE sqlite3DeleteIndexSamples(db, p); #endif + if( db==0 || db->pnBytesFreed==0 ) sqlite3KeyInfoUnref(p->pKeyInfo); sqlite3ExprDelete(db, p->pPartIdxWhere); sqlite3DbFree(db, p->zColAff); + if( p->isResized ) sqlite3DbFree(db, p->azColl); sqlite3DbFree(db, p); } @@ -641,8 +643,7 @@ char *sqlite3NameFromToken(sqlite3 *db, Token *pName){ void sqlite3OpenMasterTable(Parse *p, int iDb){ Vdbe *v = sqlite3GetVdbe(p); sqlite3TableLock(p, iDb, MASTER_ROOT, 1, SCHEMA_TABLE(iDb)); - sqlite3VdbeAddOp3(v, OP_OpenWrite, 0, MASTER_ROOT, iDb); - sqlite3VdbeChangeP4(v, -1, (char *)5, P4_INT32); /* 5 column table */ + sqlite3VdbeAddOp4Int(v, OP_OpenWrite, 0, MASTER_ROOT, iDb, 5); if( p->nTab==0 ){ p->nTab = 1; } @@ -747,6 +748,27 @@ int sqlite3CheckObjectName(Parse *pParse, const char *zName){ return SQLITE_OK; } +/* +** Return the PRIMARY KEY index of a table +*/ +Index *sqlite3PrimaryKeyIndex(Table *pTab){ + Index *p; + for(p=pTab->pIndex; p && p->autoIndex!=2; p=p->pNext){} + return p; +} + +/* +** Return the column of index pIdx that corresponds to table +** column iCol. Return -1 if not found. +*/ +i16 sqlite3ColumnOfIndex(Index *pIdx, i16 iCol){ + int i; + for(i=0; inColumn; i++){ + if( iCol==pIdx->aiColumn[i] ) return i; + } + return -1; +} + /* ** Begin constructing a new table representation in memory. This is ** the first of several action routines that get called in response @@ -946,7 +968,7 @@ void sqlite3StartTable( }else #endif { - sqlite3VdbeAddOp2(v, OP_CreateTable, iDb, reg2); + pParse->addrCrTab = sqlite3VdbeAddOp2(v, OP_CreateTable, iDb, reg2); } sqlite3OpenMasterTable(pParse, iDb); sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1); @@ -1214,6 +1236,7 @@ void sqlite3AddPrimaryKey( Table *pTab = pParse->pNewTable; char *zType = 0; int iCol = -1, i; + int nTerm; if( pTab==0 || IN_DECLARE_VTAB ) goto primary_key_exit; if( pTab->tabFlags & TF_HasPrimaryKey ){ sqlite3ErrorMsg(pParse, @@ -1224,39 +1247,43 @@ void sqlite3AddPrimaryKey( if( pList==0 ){ iCol = pTab->nCol - 1; pTab->aCol[iCol].colFlags |= COLFLAG_PRIMKEY; + zType = pTab->aCol[iCol].zType; + nTerm = 1; }else{ - for(i=0; inExpr; i++){ + nTerm = pList->nExpr; + for(i=0; inCol; iCol++){ if( sqlite3StrICmp(pList->a[i].zName, pTab->aCol[iCol].zName)==0 ){ + pTab->aCol[iCol].colFlags |= COLFLAG_PRIMKEY; + zType = pTab->aCol[iCol].zType; break; } } - if( iColnCol ){ - pTab->aCol[iCol].colFlags |= COLFLAG_PRIMKEY; - } } - if( pList->nExpr>1 ) iCol = -1; } - if( iCol>=0 && iColnCol ){ - zType = pTab->aCol[iCol].zType; - } - if( zType && sqlite3StrICmp(zType, "INTEGER")==0 - && sortOrder==SQLITE_SO_ASC ){ + if( nTerm==1 + && zType && sqlite3StrICmp(zType, "INTEGER")==0 + && sortOrder==SQLITE_SO_ASC + ){ pTab->iPKey = iCol; pTab->keyConf = (u8)onError; assert( autoInc==0 || autoInc==1 ); pTab->tabFlags |= autoInc*TF_Autoincrement; + if( pList ) pParse->iPkSortOrder = pList->a[0].sortOrder; }else if( autoInc ){ #ifndef SQLITE_OMIT_AUTOINCREMENT sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an " "INTEGER PRIMARY KEY"); #endif }else{ + Vdbe *v = pParse->pVdbe; Index *p; + if( v ) pParse->addrSkipPK = sqlite3VdbeAddOp0(v, OP_Noop); p = sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0, 0, sortOrder, 0); if( p ){ p->autoIndex = 2; + if( v ) sqlite3VdbeJumpHere(v, pParse->addrSkipPK); } pList = 0; } @@ -1313,7 +1340,7 @@ void sqlite3AddCollateType(Parse *pParse, Token *pToken){ ** collation type was added. Correct this if it is the case. */ for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){ - assert( pIdx->nColumn==1 ); + assert( pIdx->nKeyCol==1 ); if( pIdx->aiColumn[0]==i ){ pIdx->azColl[0] = p->aCol[i].zColl; } @@ -1505,6 +1532,31 @@ static char *createTableStmt(sqlite3 *db, Table *p){ return zStmt; } +/* +** Resize an Index object to hold N columns total. Return SQLITE_OK +** on success and SQLITE_NOMEM on an OOM error. +*/ +static int resizeIndexObject(sqlite3 *db, Index *pIdx, int N){ + char *zExtra; + int nByte; + if( pIdx->nColumn>=N ) return SQLITE_OK; + assert( pIdx->isResized==0 ); + nByte = (sizeof(char*) + sizeof(i16) + 1)*N; + zExtra = sqlite3DbMallocZero(db, nByte); + if( zExtra==0 ) return SQLITE_NOMEM; + memcpy(zExtra, pIdx->azColl, sizeof(char*)*pIdx->nColumn); + pIdx->azColl = (char**)zExtra; + zExtra += sizeof(char*)*N; + memcpy(zExtra, pIdx->aiColumn, sizeof(i16)*pIdx->nColumn); + pIdx->aiColumn = (i16*)zExtra; + zExtra += sizeof(i16)*N; + memcpy(zExtra, pIdx->aSortOrder, pIdx->nColumn); + pIdx->aSortOrder = (u8*)zExtra; + pIdx->nColumn = N; + pIdx->isResized = 1; + return SQLITE_OK; +} + /* ** Estimate the total row width for a table. */ @@ -1523,16 +1575,148 @@ static void estimateTableWidth(Table *pTab){ ** Estimate the average size of a row for an index. */ static void estimateIndexWidth(Index *pIdx){ - unsigned wIndex = 1; + unsigned wIndex = 0; int i; const Column *aCol = pIdx->pTable->aCol; for(i=0; inColumn; i++){ - assert( pIdx->aiColumn[i]>=0 && pIdx->aiColumn[i]pTable->nCol ); - wIndex += aCol[pIdx->aiColumn[i]].szEst; + i16 x = pIdx->aiColumn[i]; + assert( xpTable->nCol ); + wIndex += x<0 ? 1 : aCol[pIdx->aiColumn[i]].szEst; } pIdx->szIdxRow = sqlite3LogEst(wIndex*4); } +/* Return true if value x is found any of the first nCol entries of aiCol[] +*/ +static int hasColumn(const i16 *aiCol, int nCol, int x){ + while( nCol-- > 0 ) if( x==*(aiCol++) ) return 1; + return 0; +} + +/* +** This routine runs at the end of parsing a CREATE TABLE statement that +** has a WITHOUT ROWID clause. The job of this routine is to convert both +** internal schema data structures and the generated VDBE code so that they +** are appropriate for a WITHOUT ROWID table instead of a rowid table. +** Changes include: +** +** (1) Convert the OP_CreateTable into an OP_CreateIndex. There is +** no rowid btree for a WITHOUT ROWID. Instead, the canonical +** data storage is a covering index btree. +** (2) Bypass the creation of the sqlite_master table entry +** for the PRIMARY KEY as the the primary key index is now +** identified by the sqlite_master table entry of the table itself. +** (3) Set the Index.tnum of the PRIMARY KEY Index object in the +** schema to the rootpage from the main table. +** (4) Set all columns of the PRIMARY KEY schema object to be NOT NULL. +** (5) Add all table columns to the PRIMARY KEY Index object +** so that the PRIMARY KEY is a covering index. The surplus +** columns are part of KeyInfo.nXField and are not used for +** sorting or lookup or uniqueness checks. +** (6) Replace the rowid tail on all automatically generated UNIQUE +** indices with the PRIMARY KEY columns. +*/ +static void convertToWithoutRowidTable(Parse *pParse, Table *pTab){ + Index *pIdx; + Index *pPk; + int nPk; + int i, j; + sqlite3 *db = pParse->db; + Vdbe *v = pParse->pVdbe; + + /* Convert the OP_CreateTable opcode that would normally create the + ** root-page for the table into a OP_CreateIndex opcode. The index + ** created will become the PRIMARY KEY index. + */ + if( pParse->addrCrTab ){ + assert( v ); + sqlite3VdbeGetOp(v, pParse->addrCrTab)->opcode = OP_CreateIndex; + } + + /* Bypass the creation of the PRIMARY KEY btree and the sqlite_master + ** table entry. + */ + if( pParse->addrSkipPK ){ + assert( v ); + sqlite3VdbeGetOp(v, pParse->addrSkipPK)->opcode = OP_Goto; + } + + /* Locate the PRIMARY KEY index. Or, if this table was originally + ** an INTEGER PRIMARY KEY table, create a new PRIMARY KEY index. + */ + if( pTab->iPKey>=0 ){ + ExprList *pList; + pList = sqlite3ExprListAppend(pParse, 0, 0); + if( pList==0 ) return; + pList->a[0].zName = sqlite3DbStrDup(pParse->db, + pTab->aCol[pTab->iPKey].zName); + pList->a[0].sortOrder = pParse->iPkSortOrder; + assert( pParse->pNewTable==pTab ); + pPk = sqlite3CreateIndex(pParse, 0, 0, 0, pList, pTab->keyConf, 0, 0, 0, 0); + if( pPk==0 ) return; + pPk->autoIndex = 2; + pTab->iPKey = -1; + }else{ + pPk = sqlite3PrimaryKeyIndex(pTab); + } + pPk->isCovering = 1; + assert( pPk!=0 ); + nPk = pPk->nKeyCol; + + /* Make sure every column of the PRIMARY KEY is NOT NULL */ + for(i=0; iaCol[pPk->aiColumn[i]].notNull = 1; + } + pPk->uniqNotNull = 1; + + /* The root page of the PRIMARY KEY is the table root page */ + pPk->tnum = pTab->tnum; + + /* Update the in-memory representation of all UNIQUE indices by converting + ** the final rowid column into one or more columns of the PRIMARY KEY. + */ + for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ + int n; + if( pIdx->autoIndex==2 ) continue; + for(i=n=0; iaiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) ) n++; + } + if( n==0 ){ + /* This index is a superset of the primary key */ + pIdx->nColumn = pIdx->nKeyCol; + continue; + } + if( resizeIndexObject(db, pIdx, pIdx->nKeyCol+n) ) return; + for(i=0, j=pIdx->nKeyCol; iaiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) ){ + pIdx->aiColumn[j] = pPk->aiColumn[i]; + pIdx->azColl[j] = pPk->azColl[i]; + j++; + } + } + assert( pIdx->nColumn>=pIdx->nKeyCol+n ); + assert( pIdx->nColumn>=j ); + } + + /* Add all table columns to the PRIMARY KEY index + */ + if( nPknCol ){ + if( resizeIndexObject(db, pPk, pTab->nCol) ) return; + for(i=0, j=nPk; inCol; i++){ + if( !hasColumn(pPk->aiColumn, j, i) ){ + assert( jnColumn ); + pPk->aiColumn[j] = i; + pPk->azColl[j] = "BINARY"; + j++; + } + } + assert( pPk->nColumn==j ); + assert( pTab->nCol==j ); + }else{ + pPk->nColumn = pTab->nCol; + } +} + /* ** This routine is called to report the final ")" that terminates ** a CREATE TABLE statement. @@ -1556,7 +1740,8 @@ static void estimateIndexWidth(Index *pIdx){ void sqlite3EndTable( Parse *pParse, /* Parse context */ Token *pCons, /* The ',' token after the last column defn. */ - Token *pEnd, /* The final ')' token in the CREATE TABLE */ + Token *pEnd, /* The ')' before options in the CREATE TABLE */ + u8 tabOpts, /* Extra table options. Usually 0. */ Select *pSelect /* Select from a "CREATE ... AS SELECT" */ ){ Table *p; /* The new table */ @@ -1572,6 +1757,31 @@ void sqlite3EndTable( assert( !db->init.busy || !pSelect ); + /* If the db->init.busy is 1 it means we are reading the SQL off the + ** "sqlite_master" or "sqlite_temp_master" table on the disk. + ** So do not write to the disk again. Extract the root page number + ** for the table from the db->init.newTnum field. (The page number + ** should have been put there by the sqliteOpenCb routine.) + */ + if( db->init.busy ){ + p->tnum = db->init.newTnum; + } + + /* Special processing for WITHOUT ROWID Tables */ + if( tabOpts & TF_WithoutRowid ){ + if( (p->tabFlags & TF_Autoincrement) ){ + sqlite3ErrorMsg(pParse, + "AUTOINCREMENT not allowed on WITHOUT ROWID tables"); + return; + } + if( (p->tabFlags & TF_HasPrimaryKey)==0 ){ + sqlite3ErrorMsg(pParse, "PRIMARY KEY missing on table %s", p->zName); + }else{ + p->tabFlags |= TF_WithoutRowid; + convertToWithoutRowidTable(pParse, p); + } + } + iDb = sqlite3SchemaToIndex(db, p->pSchema); #ifndef SQLITE_OMIT_CHECK @@ -1588,16 +1798,6 @@ void sqlite3EndTable( estimateIndexWidth(pIdx); } - /* If the db->init.busy is 1 it means we are reading the SQL off the - ** "sqlite_master" or "sqlite_temp_master" table on the disk. - ** So do not write to the disk again. Extract the root page number - ** for the table from the db->init.newTnum field. (The page number - ** should have been put there by the sqliteOpenCb routine.) - */ - if( db->init.busy ){ - p->tnum = db->init.newTnum; - } - /* If not initializing, then create a record for the new table ** in the SQLITE_MASTER table of the database. ** @@ -1671,7 +1871,9 @@ void sqlite3EndTable( if( pSelect ){ zStmt = createTableStmt(db, p); }else{ - n = (int)(pEnd->z - pParse->sNameToken.z) + 1; + Token *pEnd2 = tabOpts ? &pParse->sLastToken : pEnd; + n = (int)(pEnd2->z - pParse->sNameToken.z); + if( pEnd2->z[0]!=';' ) n += pEnd2->n; zStmt = sqlite3MPrintf(db, "CREATE %s %.*s", zType2, n, pParse->sNameToken.z ); @@ -1819,7 +2021,7 @@ void sqlite3CreateView( sEnd.n = 1; /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */ - sqlite3EndTable(pParse, 0, &sEnd, 0); + sqlite3EndTable(pParse, 0, &sEnd, 0, 0); return; } #endif /* SQLITE_OMIT_VIEW */ @@ -2274,8 +2476,8 @@ exit_drop_table: ** currently under construction. pFromCol determines which columns ** in the current table point to the foreign key. If pFromCol==0 then ** connect the key to the last column inserted. pTo is the name of -** the table referred to. pToCol is a list of tables in the other -** pTo table that the foreign key points to. flags contains all +** the table referred to (a.k.a the "parent" table). pToCol is a list +** of tables in the parent pTo table. flags contains all ** information about the conflict resolution algorithms specified ** in the ON DELETE, ON UPDATE and ON INSERT clauses. ** @@ -2458,16 +2660,13 @@ static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){ tnum = memRootPage; }else{ tnum = pIndex->tnum; - sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb); } - pKey = sqlite3IndexKeyinfo(pParse, pIndex); - sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb, - (char *)pKey, P4_KEYINFO_HANDOFF); - sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR|((memRootPage>=0)?OPFLAG_P2ISREG:0)); + pKey = sqlite3KeyInfoOfIndex(pParse, pIndex); /* Open the sorter cursor if we are to use one. */ iSorter = pParse->nTab++; - sqlite3VdbeAddOp4(v, OP_SorterOpen, iSorter, 0, 0, (char*)pKey, P4_KEYINFO); + sqlite3VdbeAddOp4(v, OP_SorterOpen, iSorter, 0, 0, (char*) + sqlite3KeyInfoRef(pKey), P4_KEYINFO); /* Open the table. Loop through all rows of the table, inserting index ** records into the sorter. */ @@ -2475,20 +2674,25 @@ static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){ addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0); regRecord = sqlite3GetTempReg(pParse); - sqlite3GenerateIndexKey(pParse, pIndex, iTab, regRecord, 1, &iPartIdxLabel); + sqlite3GenerateIndexKey(pParse, pIndex, iTab, regRecord, 0, &iPartIdxLabel); sqlite3VdbeAddOp2(v, OP_SorterInsert, iSorter, regRecord); sqlite3VdbeResolveLabel(v, iPartIdxLabel); sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1); sqlite3VdbeJumpHere(v, addr1); + if( memRootPage<0 ) sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb); + sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb, + (char *)pKey, P4_KEYINFO); + sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR|((memRootPage>=0)?OPFLAG_P2ISREG:0)); + addr1 = sqlite3VdbeAddOp2(v, OP_SorterSort, iSorter, 0); - if( pIndex->onError!=OE_None ){ + assert( pKey!=0 || db->mallocFailed || pParse->nErr ); + if( pIndex->onError!=OE_None && pKey!=0 ){ int j2 = sqlite3VdbeCurrentAddr(v) + 3; sqlite3VdbeAddOp2(v, OP_Goto, 0, j2); addr2 = sqlite3VdbeCurrentAddr(v); - sqlite3VdbeAddOp3(v, OP_SorterCompare, iSorter, j2, regRecord); - sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_UNIQUE, - OE_Abort, "indexed columns are not unique", P4_STATIC - ); + sqlite3VdbeAddOp4Int(v, OP_SorterCompare, iSorter, j2, regRecord, + pKey->nField - pIndex->nKeyCol); + sqlite3UniqueConstraint(pParse, OE_Abort, pIndex); }else{ addr2 = sqlite3VdbeCurrentAddr(v); } @@ -2504,6 +2708,41 @@ static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){ sqlite3VdbeAddOp1(v, OP_Close, iSorter); } +/* +** Allocate heap space to hold an Index object with nCol columns. +** +** Increase the allocation size to provide an extra nExtra bytes +** of 8-byte aligned space after the Index object and return a +** pointer to this extra space in *ppExtra. +*/ +Index *sqlite3AllocateIndexObject( + sqlite3 *db, /* Database connection */ + i16 nCol, /* Total number of columns in the index */ + int nExtra, /* Number of bytes of extra space to alloc */ + char **ppExtra /* Pointer to the "extra" space */ +){ + Index *p; /* Allocated index object */ + int nByte; /* Bytes of space for Index object + arrays */ + + nByte = ROUND8(sizeof(Index)) + /* Index structure */ + ROUND8(sizeof(char*)*nCol) + /* Index.azColl */ + ROUND8(sizeof(tRowcnt)*(nCol+1) + /* Index.aiRowEst */ + sizeof(i16)*nCol + /* Index.aiColumn */ + sizeof(u8)*nCol); /* Index.aSortOrder */ + p = sqlite3DbMallocZero(db, nByte + nExtra); + if( p ){ + char *pExtra = ((char*)p)+ROUND8(sizeof(Index)); + p->azColl = (char**)pExtra; pExtra += ROUND8(sizeof(char*)*nCol); + p->aiRowEst = (tRowcnt*)pExtra; pExtra += sizeof(tRowcnt)*(nCol+1); + p->aiColumn = (i16*)pExtra; pExtra += sizeof(i16)*nCol; + p->aSortOrder = (u8*)pExtra; + p->nColumn = nCol; + p->nKeyCol = nCol - 1; + *ppExtra = ((char*)p) + nByte; + } + return p; +} + /* ** Create a new index for an SQL table. pName1.pName2 is the name of the index ** and pTblList is the name of the table that is to be indexed. Both will @@ -2538,7 +2777,6 @@ Index *sqlite3CreateIndex( char *zName = 0; /* Name of the index */ int nName; /* Number of characters in zName */ int i, j; - Token nullId; /* Fake token for an empty ID list */ DbFixer sFix; /* For assigning database names to pTable */ int sortOrderMask; /* 1 to honor DESC in index. 0 to ignore. */ sqlite3 *db = pParse->db; @@ -2547,9 +2785,10 @@ Index *sqlite3CreateIndex( Token *pName = 0; /* Unqualified name of the index to create */ struct ExprList_item *pListItem; /* For looping over pList */ const Column *pTabCol; /* A column in the table */ - int nCol; /* Number of columns */ int nExtra = 0; /* Space allocated for zExtra[] */ + int nExtraCol; /* Number of extra columns needed */ char *zExtra; /* Extra space after the Index object */ + Index *pPk = 0; /* PRIMARY KEY index for WITHOUT ROWID tables */ assert( pParse->nErr==0 ); /* Never called with prior errors */ if( db->mallocFailed || IN_DECLARE_VTAB ){ @@ -2601,6 +2840,7 @@ Index *sqlite3CreateIndex( pTab->zName); goto exit_create_index; } + if( !HasRowid(pTab) ) pPk = sqlite3PrimaryKeyIndex(pTab); }else{ assert( pName==0 ); assert( pStart==0 ); @@ -2696,11 +2936,10 @@ Index *sqlite3CreateIndex( ** So create a fake list to simulate this. */ if( pList==0 ){ - nullId.z = pTab->aCol[pTab->nCol-1].zName; - nullId.n = sqlite3Strlen30((char*)nullId.z); pList = sqlite3ExprListAppend(pParse, 0, 0); if( pList==0 ) goto exit_create_index; - sqlite3ExprListSetName(pParse, pList, &nullId, 0); + pList->a[0].zName = sqlite3DbStrDup(pParse->db, + pTab->aCol[pTab->nCol-1].zName); pList->a[0].sortOrder = (u8)sortOrder; } @@ -2719,36 +2958,23 @@ Index *sqlite3CreateIndex( ** Allocate the index structure. */ nName = sqlite3Strlen30(zName); - nCol = pList->nExpr; - pIndex = sqlite3DbMallocZero(db, - ROUND8(sizeof(Index)) + /* Index structure */ - ROUND8(sizeof(tRowcnt)*(nCol+1)) + /* Index.aiRowEst */ - sizeof(char *)*nCol + /* Index.azColl */ - sizeof(int)*nCol + /* Index.aiColumn */ - sizeof(u8)*nCol + /* Index.aSortOrder */ - nName + 1 + /* Index.zName */ - nExtra /* Collation sequence names */ - ); + nExtraCol = pPk ? pPk->nKeyCol : 1; + pIndex = sqlite3AllocateIndexObject(db, pList->nExpr + nExtraCol, + nName + nExtra + 1, &zExtra); if( db->mallocFailed ){ goto exit_create_index; } - zExtra = (char*)pIndex; - pIndex->aiRowEst = (tRowcnt*)&zExtra[ROUND8(sizeof(Index))]; - pIndex->azColl = (char**) - ((char*)pIndex->aiRowEst + ROUND8(sizeof(tRowcnt)*nCol+1)); assert( EIGHT_BYTE_ALIGNMENT(pIndex->aiRowEst) ); assert( EIGHT_BYTE_ALIGNMENT(pIndex->azColl) ); - pIndex->aiColumn = (int *)(&pIndex->azColl[nCol]); - pIndex->aSortOrder = (u8 *)(&pIndex->aiColumn[nCol]); - pIndex->zName = (char *)(&pIndex->aSortOrder[nCol]); - zExtra = (char *)(&pIndex->zName[nName+1]); + pIndex->zName = zExtra; + zExtra += nName + 1; memcpy(pIndex->zName, zName, nName+1); pIndex->pTable = pTab; - pIndex->nColumn = pList->nExpr; pIndex->onError = (u8)onError; - pIndex->uniqNotNull = onError==OE_Abort; + pIndex->uniqNotNull = onError!=OE_None; pIndex->autoIndex = (u8)(pName==0); pIndex->pSchema = db->aDb[iDb].pSchema; + pIndex->nKeyCol = pList->nExpr; if( pPIWhere ){ sqlite3ResolveSelfReference(pParse, pTab, NC_PartIdx, pPIWhere, 0); pIndex->pPartIdxWhere = pPIWhere; @@ -2788,7 +3014,8 @@ Index *sqlite3CreateIndex( pParse->checkSchema = 1; goto exit_create_index; } - pIndex->aiColumn[i] = j; + assert( pTab->nCol<=0x7fff && j<=0x7fff ); + pIndex->aiColumn[i] = (i16)j; if( pListItem->pExpr ){ int nColl; assert( pListItem->pExpr->op==TK_COLLATE ); @@ -2811,6 +3038,23 @@ Index *sqlite3CreateIndex( pIndex->aSortOrder[i] = (u8)requestedSortOrder; if( pTab->aCol[j].notNull==0 ) pIndex->uniqNotNull = 0; } + if( pPk ){ + for(j=0; jnKeyCol; j++){ + int x = pPk->aiColumn[j]; + if( hasColumn(pIndex->aiColumn, pIndex->nKeyCol, x) ){ + pIndex->nColumn--; + }else{ + pIndex->aiColumn[i] = x; + pIndex->azColl[i] = pPk->azColl[j]; + pIndex->aSortOrder[i] = pPk->aSortOrder[j]; + i++; + } + } + assert( i==pIndex->nColumn ); + }else{ + pIndex->aiColumn[i] = -1; + pIndex->azColl[i] = "BINARY"; + } sqlite3DefaultRowEst(pIndex); if( pParse->pNewTable==0 ) estimateIndexWidth(pIndex); @@ -2843,8 +3087,8 @@ Index *sqlite3CreateIndex( assert( pIdx->autoIndex ); assert( pIndex->onError!=OE_None ); - if( pIdx->nColumn!=pIndex->nColumn ) continue; - for(k=0; knColumn; k++){ + if( pIdx->nKeyCol!=pIndex->nKeyCol ) continue; + for(k=0; knKeyCol; k++){ const char *z1; const char *z2; if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break; @@ -2852,7 +3096,7 @@ Index *sqlite3CreateIndex( z2 = pIndex->azColl[k]; if( z1!=z2 && sqlite3StrICmp(z1, z2) ) break; } - if( k==pIdx->nColumn ){ + if( k==pIdx->nKeyCol ){ if( pIdx->onError!=pIndex->onError ){ /* This constraint creates the same index as a previous ** constraint specified somewhere in the CREATE TABLE statement. @@ -2894,22 +3138,20 @@ Index *sqlite3CreateIndex( } } - /* If the db->init.busy is 0 then create the index on disk. This - ** involves writing the index into the master table and filling in the - ** index with the current table contents. + /* If this is the initial CREATE INDEX statement (or CREATE TABLE if the + ** index is an implied index for a UNIQUE or PRIMARY KEY constraint) then + ** emit code to allocate the index rootpage on disk and make an entry for + ** the index in the sqlite_master table and populate the index with + ** content. But, do not do this if we are simply reading the sqlite_master + ** table to parse the schema, or if this index is the PRIMARY KEY index + ** of a WITHOUT ROWID table. ** - ** The db->init.busy is 0 when the user first enters a CREATE INDEX - ** command. db->init.busy is 1 when a database is opened and - ** CREATE INDEX statements are read out of the master table. In - ** the latter case the index already exists on disk, which is why - ** we don't want to recreate it. - ** - ** If pTblName==0 it means this index is generated as a primary key - ** or UNIQUE constraint of a CREATE TABLE statement. Since the table + ** If pTblName==0 it means this index is generated as an implied PRIMARY KEY + ** or UNIQUE index in a CREATE TABLE statement. Since the table ** has just been created, it contains no data and the index initialization ** step can be skipped. */ - else if( pParse->nErr==0 ){ + else if( pParse->nErr==0 && (HasRowid(pTab) || pTblName!=0) ){ Vdbe *v; char *zStmt; int iMem = ++pParse->nMem; @@ -3021,12 +3263,12 @@ void sqlite3DefaultRowEst(Index *pIdx){ a[0] = pIdx->pTable->nRowEst; if( a[0]<10 ) a[0] = 10; n = 10; - for(i=1; i<=pIdx->nColumn; i++){ + for(i=1; i<=pIdx->nKeyCol; i++){ a[i] = n; if( n>5 ) n--; } if( pIdx->onError!=OE_None ){ - a[pIdx->nColumn] = 1; + a[pIdx->nKeyCol] = 1; } } @@ -3714,7 +3956,8 @@ void sqlite3HaltConstraint( int errCode, /* extended error code */ int onError, /* Constraint type */ char *p4, /* Error message */ - int p4type /* P4_STATIC or P4_TRANSIENT */ + i8 p4type, /* P4_STATIC or P4_TRANSIENT */ + u8 p5Errmsg /* P5_ErrMsg type */ ){ Vdbe *v = sqlite3GetVdbe(pParse); assert( (errCode&0xff)==SQLITE_CONSTRAINT ); @@ -3722,6 +3965,58 @@ void sqlite3HaltConstraint( sqlite3MayAbort(pParse); } sqlite3VdbeAddOp4(v, OP_Halt, errCode, onError, 0, p4, p4type); + if( p5Errmsg ) sqlite3VdbeChangeP5(v, p5Errmsg); +} + +/* +** Code an OP_Halt due to UNIQUE or PRIMARY KEY constraint violation. +*/ +void sqlite3UniqueConstraint( + Parse *pParse, /* Parsing context */ + int onError, /* Constraint type */ + Index *pIdx /* The index that triggers the constraint */ +){ + char *zErr; + int j; + StrAccum errMsg; + Table *pTab = pIdx->pTable; + + sqlite3StrAccumInit(&errMsg, 0, 0, 200); + errMsg.db = pParse->db; + for(j=0; jnKeyCol; j++){ + char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName; + if( j ) sqlite3StrAccumAppend(&errMsg, ", ", 2); + sqlite3StrAccumAppend(&errMsg, pTab->zName, -1); + sqlite3StrAccumAppend(&errMsg, ".", 1); + sqlite3StrAccumAppend(&errMsg, zCol, -1); + } + zErr = sqlite3StrAccumFinish(&errMsg); + sqlite3HaltConstraint(pParse, + (pIdx->autoIndex==2)?SQLITE_CONSTRAINT_PRIMARYKEY:SQLITE_CONSTRAINT_UNIQUE, + onError, zErr, P4_DYNAMIC, P5_ConstraintUnique); +} + + +/* +** Code an OP_Halt due to non-unique rowid. +*/ +void sqlite3RowidConstraint( + Parse *pParse, /* Parsing context */ + int onError, /* Conflict resolution algorithm */ + Table *pTab /* The table with the non-unique rowid */ +){ + char *zMsg; + int rc; + if( pTab->iPKey>=0 ){ + zMsg = sqlite3MPrintf(pParse->db, "%s.%s", pTab->zName, + pTab->aCol[pTab->iPKey].zName); + rc = SQLITE_CONSTRAINT_PRIMARYKEY; + }else{ + zMsg = sqlite3MPrintf(pParse->db, "%s.rowid", pTab->zName); + rc = SQLITE_CONSTRAINT_ROWID; + } + sqlite3HaltConstraint(pParse, rc, onError, zMsg, P4_DYNAMIC, + P5_ConstraintUnique); } /* @@ -3734,8 +4029,8 @@ static int collationMatch(const char *zColl, Index *pIndex){ assert( zColl!=0 ); for(i=0; inColumn; i++){ const char *z = pIndex->azColl[i]; - assert( z!=0 ); - if( 0==sqlite3StrICmp(z, zColl) ){ + assert( z!=0 || pIndex->aiColumn[i]<0 ); + if( pIndex->aiColumn[i]>=0 && 0==sqlite3StrICmp(z, zColl) ){ return 1; } } @@ -3854,33 +4149,47 @@ void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){ #endif /* -** Return a dynamicly allocated KeyInfo structure that can be used -** with OP_OpenRead or OP_OpenWrite to access database index pIdx. +** Return a KeyInfo structure that is appropriate for the given Index. ** -** If successful, a pointer to the new structure is returned. In this case -** the caller is responsible for calling sqlite3DbFree(db, ) on the returned -** pointer. If an error occurs (out of memory or missing collation -** sequence), NULL is returned and the state of pParse updated to reflect -** the error. +** The KeyInfo structure for an index is cached in the Index object. +** So there might be multiple references to the returned pointer. The +** caller should not try to modify the KeyInfo object. +** +** The caller should invoke sqlite3KeyInfoUnref() on the returned object +** when it has finished using it. */ -KeyInfo *sqlite3IndexKeyinfo(Parse *pParse, Index *pIdx){ - int i; - int nCol = pIdx->nColumn; - KeyInfo *pKey; - - pKey = sqlite3KeyInfoAlloc(pParse->db, nCol); - if( pKey ){ - for(i=0; iazColl[i]; - assert( zColl ); - pKey->aColl[i] = sqlite3LocateCollSeq(pParse, zColl); - pKey->aSortOrder[i] = pIdx->aSortOrder[i]; +KeyInfo *sqlite3KeyInfoOfIndex(Parse *pParse, Index *pIdx){ + if( pParse->nErr ) return 0; +#ifndef SQLITE_OMIT_SHARED_CACHE + if( pIdx->pKeyInfo && pIdx->pKeyInfo->db!=pParse->db ){ + sqlite3KeyInfoUnref(pIdx->pKeyInfo); + pIdx->pKeyInfo = 0; + } +#endif + if( pIdx->pKeyInfo==0 ){ + int i; + int nCol = pIdx->nColumn; + int nKey = pIdx->nKeyCol; + KeyInfo *pKey; + if( pIdx->uniqNotNull ){ + pKey = sqlite3KeyInfoAlloc(pParse->db, nKey, nCol-nKey); + }else{ + pKey = sqlite3KeyInfoAlloc(pParse->db, nCol, 0); + } + if( pKey ){ + assert( sqlite3KeyInfoIsWriteable(pKey) ); + for(i=0; iazColl[i]; + if( NEVER(zColl==0) ) zColl = "BINARY"; + pKey->aColl[i] = sqlite3LocateCollSeq(pParse, zColl); + pKey->aSortOrder[i] = pIdx->aSortOrder[i]; + } + if( pParse->nErr ){ + sqlite3KeyInfoUnref(pKey); + }else{ + pIdx->pKeyInfo = pKey; + } } } - - if( pParse->nErr ){ - sqlite3DbFree(pParse->db, pKey); - pKey = 0; - } - return pKey; + return sqlite3KeyInfoRef(pIdx->pKeyInfo); } diff --git a/src/delete.c b/src/delete.c index f52c0c67f6..9ebb56ecaa 100644 --- a/src/delete.c +++ b/src/delete.c @@ -134,7 +134,7 @@ Expr *sqlite3LimitWhere( ExprList *pOrderBy, /* The ORDER BY clause. May be null */ Expr *pLimit, /* The LIMIT clause. May be null */ Expr *pOffset, /* The OFFSET clause. May be null */ - char *zStmtType /* Either DELETE or UPDATE. For error messages. */ + char *zStmtType /* Either DELETE or UPDATE. For err msgs. */ ){ Expr *pWhereRowid = NULL; /* WHERE rowid .. */ Expr *pInClause = NULL; /* WHERE rowid IN ( select ) */ @@ -209,7 +209,8 @@ limit_where_cleanup_2: sqlite3ExprDelete(pParse->db, pOffset); return 0; } -#endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */ +#endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) */ + /* && !defined(SQLITE_OMIT_SUBQUERY) */ /* ** Generate code for a DELETE FROM statement. @@ -230,7 +231,9 @@ void sqlite3DeleteFrom( int i; /* Loop counter */ WhereInfo *pWInfo; /* Information about the WHERE clause */ Index *pIdx; /* For looping over indices of the table */ - int iCur; /* VDBE Cursor number for pTab */ + int iTabCur; /* Cursor number for the table */ + int iDataCur; /* VDBE cursor for the canonical data source */ + int iIdxCur; /* Cursor number of the first index */ sqlite3 *db; /* Main database structure */ AuthContext sContext; /* Authorization context */ NameContext sNC; /* Name context to resolve expressions in */ @@ -295,7 +298,7 @@ void sqlite3DeleteFrom( /* Assign cursor number to the table and all its indices. */ assert( pTabList->nSrc==1 ); - iCur = pTabList->a[0].iCursor = pParse->nTab++; + iTabCur = pTabList->a[0].iCursor = pParse->nTab++; for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ pParse->nTab++; } @@ -320,7 +323,8 @@ void sqlite3DeleteFrom( */ #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) if( isView ){ - sqlite3MaterializeView(pParse, pTab, pWhere, iCur); + sqlite3MaterializeView(pParse, pTab, pWhere, iTabCur); + iDataCur = iIdxCur = iTabCur; } #endif @@ -358,18 +362,74 @@ void sqlite3DeleteFrom( ){ assert( !isView ); sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName); - sqlite3VdbeAddOp4(v, OP_Clear, pTab->tnum, iDb, memCnt, - pTab->zName, P4_STATIC); + if( HasRowid(pTab) ){ + sqlite3VdbeAddOp4(v, OP_Clear, pTab->tnum, iDb, memCnt, + pTab->zName, P4_STATIC); + } for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ assert( pIdx->pSchema==pTab->pSchema ); sqlite3VdbeAddOp2(v, OP_Clear, pIdx->tnum, iDb); } }else #endif /* SQLITE_OMIT_TRUNCATE_OPTIMIZATION */ - /* The usual case: There is a WHERE clause so we have to scan through - ** the table and pick which records to delete. - */ - { + if( !HasRowid(pTab) ){ + /* There is a WHERE clause on a WITHOUT ROWID table. + */ + Index *pPk; /* The PRIMARY KEY index on the table */ + int iPk; /* First of nPk memory cells holding PRIMARY KEY value */ + int iEph; /* Ephemeral table holding all primary key values */ + int iKey; /* Key value inserting into iEph */ + i16 nPk; /* Number of components of the PRIMARY KEY */ + + pPk = sqlite3PrimaryKeyIndex(pTab); + assert( pPk!=0 ); + nPk = pPk->nKeyCol; + iPk = pParse->nMem+1; + pParse->nMem += nPk; + iKey = ++pParse->nMem; + iEph = pParse->nTab++; + + sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iEph, nPk); + sqlite3VdbeSetP4KeyInfo(pParse, pPk); + pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0, 0, 0, 0); + if( pWInfo==0 ) goto delete_from_cleanup; + for(i=0; iaiColumn[i],iPk+i); + } + sqlite3VdbeAddOp4(v, OP_MakeRecord, iPk, nPk, iKey, + sqlite3IndexAffinityStr(v, pPk), P4_TRANSIENT); + sqlite3VdbeAddOp2(v, OP_IdxInsert, iEph, iKey); + if( db->flags & SQLITE_CountRows ){ + sqlite3VdbeAddOp2(v, OP_AddImm, memCnt, 1); + } + sqlite3WhereEnd(pWInfo); + + /* Open cursors for all indices of the table. + */ + sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, + iTabCur, &iDataCur, &iIdxCur); + + /* Loop over the primary keys to be deleted. */ + addr = sqlite3VdbeAddOp1(v, OP_Rewind, iEph); + sqlite3VdbeAddOp2(v, OP_RowKey, iEph, iPk); + + /* Delete the row */ + sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur, + iPk, 0, 1, OE_Default, 0); + + /* End of the delete loop */ + sqlite3VdbeAddOp2(v, OP_Next, iEph, addr+1); + sqlite3VdbeJumpHere(v, addr); + + /* Close the cursors open on the table and its indexes. */ + assert( iDataCur>=iIdxCur ); + for(i=0, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){ + sqlite3VdbeAddOp1(v, OP_Close, iIdxCur+i); + } + }else{ + /* There is a WHERE clause on a rowid table. Run a loop that extracts + ** all rowids to be deleted into a RowSet. + */ int iRowSet = ++pParse->nMem; /* Register for rowset of rows to delete */ int iRowid = ++pParse->nMem; /* Used for storing rowid values. */ int regRowid; /* Actual register containing rowids */ @@ -381,7 +441,7 @@ void sqlite3DeleteFrom( pParse, pTabList, pWhere, 0, 0, WHERE_DUPLICATES_OK, 0 ); if( pWInfo==0 ) goto delete_from_cleanup; - regRowid = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iCur, iRowid, 0); + regRowid = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iTabCur, iRowid, 0); sqlite3VdbeAddOp2(v, OP_RowSetAdd, iRowSet, regRowid); if( db->flags & SQLITE_CountRows ){ sqlite3VdbeAddOp2(v, OP_AddImm, memCnt, 1); @@ -398,7 +458,10 @@ void sqlite3DeleteFrom( ** only effect this statement has is to fire the INSTEAD OF ** triggers. */ if( !isView ){ - sqlite3OpenTableAndIndices(pParse, pTab, iCur, OP_OpenWrite); + sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, iTabCur, + &iDataCur, &iIdxCur); + assert( iDataCur==iTabCur ); + assert( iIdxCur==iDataCur+1 ); } addr = sqlite3VdbeAddOp3(v, OP_RowSetRead, iRowSet, end, iRowid); @@ -415,7 +478,8 @@ void sqlite3DeleteFrom( #endif { int count = (pParse->nested==0); /* True to count changes */ - sqlite3GenerateRowDelete(pParse, pTab, iCur, iRowid, count, pTrigger, OE_Default); + sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur, + iRowid, 1, count, OE_Default, 0); } /* End of the delete loop */ @@ -424,10 +488,10 @@ void sqlite3DeleteFrom( /* Close the cursors open on the table and its indexes. */ if( !isView && !IsVirtual(pTab) ){ - for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){ - sqlite3VdbeAddOp2(v, OP_Close, iCur + i, pIdx->tnum); + sqlite3VdbeAddOp1(v, OP_Close, iDataCur); + for(i=0, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){ + sqlite3VdbeAddOp1(v, OP_Close, iIdxCur + i); } - sqlite3VdbeAddOp1(v, OP_Close, iCur); } } @@ -467,44 +531,52 @@ delete_from_cleanup: /* ** This routine generates VDBE code that causes a single row of a -** single table to be deleted. +** single table to be deleted. Both the original table entry and +** all indices are removed. ** -** The VDBE must be in a particular state when this routine is called. -** These are the requirements: +** Preconditions: ** -** 1. A read/write cursor pointing to pTab, the table containing the row -** to be deleted, must be opened as cursor number $iCur. +** 1. iDataCur is an open cursor on the btree that is the canonical data +** store for the table. (This will be either the table itself, +** in the case of a rowid table, or the PRIMARY KEY index in the case +** of a WITHOUT ROWID table.) ** ** 2. Read/write cursors for all indices of pTab must be open as -** cursor number base+i for the i-th index. +** cursor number iIdxCur+i for the i-th index. ** -** 3. The record number of the row to be deleted must be stored in -** memory cell iRowid. -** -** This routine generates code to remove both the table record and all -** index entries that point to that record. +** 3. The primary key for the row to be deleted must be stored in a +** sequence of nPk memory cells starting at iPk. If nPk==0 that means +** that a search record formed from OP_MakeRecord is contained in the +** single memory location iPk. */ void sqlite3GenerateRowDelete( Parse *pParse, /* Parsing context */ Table *pTab, /* Table containing the row to be deleted */ - int iCur, /* Cursor number for the table */ - int iRowid, /* Memory cell that contains the rowid to delete */ - int count, /* If non-zero, increment the row change counter */ Trigger *pTrigger, /* List of triggers to (potentially) fire */ - int onconf /* Default ON CONFLICT policy for triggers */ + int iDataCur, /* Cursor from which column data is extracted */ + int iIdxCur, /* First index cursor */ + int iPk, /* First memory cell containing the PRIMARY KEY */ + i16 nPk, /* Number of PRIMARY KEY memory cells */ + u8 count, /* If non-zero, increment the row change counter */ + u8 onconf, /* Default ON CONFLICT policy for triggers */ + u8 bNoSeek /* iDataCur is already pointing to the row to delete */ ){ Vdbe *v = pParse->pVdbe; /* Vdbe */ int iOld = 0; /* First register in OLD.* array */ int iLabel; /* Label resolved to end of generated code */ + u8 opSeek; /* Seek opcode */ /* Vdbe is guaranteed to have been allocated by this stage. */ assert( v ); + VdbeModuleComment((v, "BEGIN: GenRowDel(%d,%d,%d,%d)", + iDataCur, iIdxCur, iPk, (int)nPk)); /* Seek cursor iCur to the row to delete. If this row no longer exists ** (this can happen if a trigger program has already deleted it), do ** not attempt to delete it or fire any DELETE triggers. */ iLabel = sqlite3VdbeMakeLabel(v); - sqlite3VdbeAddOp3(v, OP_NotExists, iCur, iLabel, iRowid); + opSeek = HasRowid(pTab) ? OP_NotExists : OP_NotFound; + if( !bNoSeek ) sqlite3VdbeAddOp4Int(v, opSeek, iDataCur, iLabel, iPk, nPk); /* If there are any triggers to fire, allocate a range of registers to ** use for the old.* references in the triggers. */ @@ -523,10 +595,10 @@ void sqlite3GenerateRowDelete( /* Populate the OLD.* pseudo-table register array. These values will be ** used by any BEFORE and AFTER triggers that exist. */ - sqlite3VdbeAddOp2(v, OP_Copy, iRowid, iOld); + sqlite3VdbeAddOp2(v, OP_Copy, iPk, iOld); for(iCol=0; iColnCol; iCol++){ if( mask==0xffffffff || mask&(1<pSelect==0 ){ - sqlite3GenerateRowIndexDelete(pParse, pTab, iCur, 0); - sqlite3VdbeAddOp2(v, OP_Delete, iCur, (count?OPFLAG_NCHANGE:0)); + sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur, 0); + sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, (count?OPFLAG_NCHANGE:0)); sqlite3VdbeChangeP4(v, -1, (char*)pTab, P4_TABLE); } @@ -577,49 +649,61 @@ void sqlite3GenerateRowDelete( ** trigger programs were invoked. Or if a trigger program throws a ** RAISE(IGNORE) exception. */ sqlite3VdbeResolveLabel(v, iLabel); + VdbeModuleComment((v, "END: GenRowDel()")); } /* ** This routine generates VDBE code that causes the deletion of all -** index entries associated with a single row of a single table. +** index entries associated with a single row of a single table, pTab ** -** The VDBE must be in a particular state when this routine is called. -** These are the requirements: +** Preconditions: ** -** 1. A read/write cursor pointing to pTab, the table containing the row -** to be deleted, must be opened as cursor number "iCur". +** 1. A read/write cursor "iDataCur" must be open on the canonical storage +** btree for the table pTab. (This will be either the table itself +** for rowid tables or to the primary key index for WITHOUT ROWID +** tables.) ** ** 2. Read/write cursors for all indices of pTab must be open as -** cursor number iCur+i for the i-th index. +** cursor number iIdxCur+i for the i-th index. (The pTab->pIndex +** index is the 0-th index.) ** -** 3. The "iCur" cursor must be pointing to the row that is to be -** deleted. +** 3. The "iDataCur" cursor must be already be positioned on the row +** that is to be deleted. */ void sqlite3GenerateRowIndexDelete( Parse *pParse, /* Parsing and code generating context */ Table *pTab, /* Table containing the row to be deleted */ - int iCur, /* Cursor number for the table */ + int iDataCur, /* Cursor of table holding data. */ + int iIdxCur, /* First index cursor */ int *aRegIdx /* Only delete if aRegIdx!=0 && aRegIdx[i]>0 */ ){ - int i; - Index *pIdx; - int r1; - int iPartIdxLabel; - Vdbe *v = pParse->pVdbe; + int i; /* Index loop counter */ + int r1; /* Register holding an index key */ + int iPartIdxLabel; /* Jump destination for skipping partial index entries */ + Index *pIdx; /* Current index */ + Vdbe *v; /* The prepared statement under construction */ + Index *pPk; /* PRIMARY KEY index, or NULL for rowid tables */ - for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){ - if( aRegIdx!=0 && aRegIdx[i-1]==0 ) continue; - r1 = sqlite3GenerateIndexKey(pParse, pIdx, iCur, 0, 0, &iPartIdxLabel); - sqlite3VdbeAddOp3(v, OP_IdxDelete, iCur+i, r1, pIdx->nColumn+1); + v = pParse->pVdbe; + pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab); + for(i=0, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){ + assert( iIdxCur+i!=iDataCur || pPk==pIdx ); + if( aRegIdx!=0 && aRegIdx[i]==0 ) continue; + if( pIdx==pPk ) continue; + VdbeModuleComment((v, "GenRowIdxDel for %s", pIdx->zName)); + r1 = sqlite3GenerateIndexKey(pParse, pIdx, iDataCur, 0, 1, &iPartIdxLabel); + sqlite3VdbeAddOp3(v, OP_IdxDelete, iIdxCur+i, r1, + pIdx->uniqNotNull ? pIdx->nKeyCol : pIdx->nColumn); sqlite3VdbeResolveLabel(v, iPartIdxLabel); } } /* -** Generate code that will assemble an index key and put it in register +** Generate code that will assemble an index key and stores it in register ** regOut. The key with be for index pIdx which is an index on pTab. ** iCur is the index of a cursor open on the pTab table and pointing to -** the entry that needs indexing. +** the entry that needs indexing. If pTab is a WITHOUT ROWID table, then +** iCur must be the cursor of the PRIMARY KEY index. ** ** Return a register number which is the first in a block of ** registers that holds the elements of the index key. The @@ -636,9 +720,9 @@ void sqlite3GenerateRowIndexDelete( int sqlite3GenerateIndexKey( Parse *pParse, /* Parsing context */ Index *pIdx, /* The index for which to generate a key */ - int iCur, /* Cursor number for the pIdx->pTable table */ - int regOut, /* Write the new index key to this register */ - int doMakeRec, /* Run the OP_MakeRecord instruction if true */ + int iDataCur, /* Cursor number from which to take column data */ + int regOut, /* Put the new key into this register if not 0 */ + int prefixOnly, /* Compute only a unique prefix of the key */ int *piPartIdxLabel /* OUT: Jump to this label to skip partial index */ ){ Vdbe *v = pParse->pVdbe; @@ -646,30 +730,32 @@ int sqlite3GenerateIndexKey( Table *pTab = pIdx->pTable; int regBase; int nCol; + Index *pPk; if( piPartIdxLabel ){ if( pIdx->pPartIdxWhere ){ *piPartIdxLabel = sqlite3VdbeMakeLabel(v); - pParse->iPartIdxTab = iCur; + pParse->iPartIdxTab = iDataCur; sqlite3ExprIfFalse(pParse, pIdx->pPartIdxWhere, *piPartIdxLabel, SQLITE_JUMPIFNULL); }else{ *piPartIdxLabel = 0; } } - nCol = pIdx->nColumn; - regBase = sqlite3GetTempRange(pParse, nCol+1); - sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regBase+nCol); + nCol = (prefixOnly && pIdx->uniqNotNull) ? pIdx->nKeyCol : pIdx->nColumn; + regBase = sqlite3GetTempRange(pParse, nCol); + pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab); for(j=0; jaiColumn[j]; - if( idx==pTab->iPKey ){ - sqlite3VdbeAddOp2(v, OP_SCopy, regBase+nCol, regBase+j); + i16 idx = pIdx->aiColumn[j]; + if( pPk ) idx = sqlite3ColumnOfIndex(pPk, idx); + if( idx<0 || idx==pTab->iPKey ){ + sqlite3VdbeAddOp2(v, OP_Rowid, iDataCur, regBase+j); }else{ - sqlite3VdbeAddOp3(v, OP_Column, iCur, idx, regBase+j); - sqlite3ColumnDefault(v, pTab, idx, -1); + sqlite3VdbeAddOp3(v, OP_Column, iDataCur, idx, regBase+j); + sqlite3ColumnDefault(v, pTab, pIdx->aiColumn[j], -1); } } - if( doMakeRec ){ + if( regOut ){ const char *zAff; if( pTab->pSelect || OptimizationDisabled(pParse->db, SQLITE_IdxRealAsInt) @@ -678,9 +764,9 @@ int sqlite3GenerateIndexKey( }else{ zAff = sqlite3IndexAffinityStr(v, pIdx); } - sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol+1, regOut); + sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regOut); sqlite3VdbeChangeP4(v, -1, zAff, P4_TRANSIENT); } - sqlite3ReleaseTempRange(pParse, regBase, nCol+1); + sqlite3ReleaseTempRange(pParse, regBase, nCol); return regBase; } diff --git a/src/expr.c b/src/expr.c index eb2f545639..7e72b44f96 100644 --- a/src/expr.c +++ b/src/expr.c @@ -1532,8 +1532,8 @@ int sqlite3FindInIndex(Parse *pParse, Expr *pX, int *prNotFound){ sqlite3 *db = pParse->db; /* Database connection */ Table *pTab; /* Table . */ Expr *pExpr; /* Expression */ - int iCol; /* Index of column */ - int iDb; /* Database idx for pTab */ + i16 iCol; /* Index of column */ + i16 iDb; /* Database idx for pTab */ assert( p ); /* Because of isCandidateForInOpt(p) */ assert( p->pEList!=0 ); /* Because of isCandidateForInOpt(p) */ @@ -1541,7 +1541,7 @@ int sqlite3FindInIndex(Parse *pParse, Expr *pX, int *prNotFound){ assert( p->pSrc!=0 ); /* Because of isCandidateForInOpt(p) */ pTab = p->pSrc->a[0].pTab; pExpr = p->pEList->a[0].pExpr; - iCol = pExpr->iColumn; + iCol = (i16)pExpr->iColumn; /* Code an OP_VerifyCookie and OP_TableLock for
. */ iDb = sqlite3SchemaToIndex(db, pTab->pSchema); @@ -1579,16 +1579,11 @@ int sqlite3FindInIndex(Parse *pParse, Expr *pX, int *prNotFound){ for(pIdx=pTab->pIndex; pIdx && eType==0 && affinity_ok; pIdx=pIdx->pNext){ if( (pIdx->aiColumn[0]==iCol) && sqlite3FindCollSeq(db, ENC(db), pIdx->azColl[0], 0)==pReq - && (!mustBeUnique || (pIdx->nColumn==1 && pIdx->onError!=OE_None)) + && (!mustBeUnique || (pIdx->nKeyCol==1 && pIdx->onError!=OE_None)) ){ - int iAddr; - char *pKey; - - pKey = (char *)sqlite3IndexKeyinfo(pParse, pIdx); - iAddr = sqlite3CodeOnce(pParse); - - sqlite3VdbeAddOp4(v, OP_OpenRead, iTab, pIdx->tnum, iDb, - pKey,P4_KEYINFO_HANDOFF); + int iAddr = sqlite3CodeOnce(pParse); + sqlite3VdbeAddOp3(v, OP_OpenRead, iTab, pIdx->tnum, iDb); + sqlite3VdbeSetP4KeyInfo(pParse, pIdx); VdbeComment((v, "%s", pIdx->zName)); assert( IN_INDEX_INDEX_DESC == IN_INDEX_INDEX_ASC+1 ); eType = IN_INDEX_INDEX_ASC + pIdx->aSortOrder[0]; @@ -1728,7 +1723,7 @@ int sqlite3CodeSubselect( pExpr->iTable = pParse->nTab++; addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pExpr->iTable, !isRowid); if( rMayHaveNull==0 ) sqlite3VdbeChangeP5(v, BTREE_UNORDERED); - pKeyInfo = isRowid ? 0 : sqlite3KeyInfoAlloc(pParse->db, 1); + pKeyInfo = isRowid ? 0 : sqlite3KeyInfoAlloc(pParse->db, 1, 1); if( ExprHasProperty(pExpr, EP_xIsSelect) ){ /* Case 1: expr IN (SELECT ...) @@ -1746,13 +1741,14 @@ int sqlite3CodeSubselect( pExpr->x.pSelect->iLimit = 0; testcase( pKeyInfo==0 ); /* Caused by OOM in sqlite3KeyInfoAlloc() */ if( sqlite3Select(pParse, pExpr->x.pSelect, &dest) ){ - sqlite3DbFree(pParse->db, pKeyInfo); + sqlite3KeyInfoUnref(pKeyInfo); return 0; } pEList = pExpr->x.pSelect->pEList; assert( pKeyInfo!=0 ); /* OOM will cause exit after sqlite3Select() */ assert( pEList!=0 ); assert( pEList->nExpr>0 ); + assert( sqlite3KeyInfoIsWriteable(pKeyInfo) ); pKeyInfo->aColl[0] = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft, pEList->a[0].pExpr); }else if( ALWAYS(pExpr->x.pList!=0) ){ @@ -1772,6 +1768,7 @@ int sqlite3CodeSubselect( affinity = SQLITE_AFF_NONE; } if( pKeyInfo ){ + assert( sqlite3KeyInfoIsWriteable(pKeyInfo) ); pKeyInfo->aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft); } @@ -1813,7 +1810,7 @@ int sqlite3CodeSubselect( sqlite3ReleaseTempReg(pParse, r2); } if( pKeyInfo ){ - sqlite3VdbeChangeP4(v, addr, (void *)pKeyInfo, P4_KEYINFO_HANDOFF); + sqlite3VdbeChangeP4(v, addr, (void *)pKeyInfo, P4_KEYINFO); } break; } @@ -2214,15 +2211,19 @@ static void sqlite3ExprCachePinRegister(Parse *pParse, int iReg){ void sqlite3ExprCodeGetColumnOfTable( Vdbe *v, /* The VDBE under construction */ Table *pTab, /* The table containing the value */ - int iTabCur, /* The cursor for this table */ + int iTabCur, /* The table cursor. Or the PK cursor for WITHOUT ROWID */ int iCol, /* Index of the column to extract */ - int regOut /* Extract the valud into this register */ + int regOut /* Extract the value into this register */ ){ if( iCol<0 || iCol==pTab->iPKey ){ sqlite3VdbeAddOp2(v, OP_Rowid, iTabCur, regOut); }else{ int op = IsVirtual(pTab) ? OP_VColumn : OP_Column; - sqlite3VdbeAddOp3(v, op, iTabCur, iCol, regOut); + int x = iCol; + if( !HasRowid(pTab) ){ + x = sqlite3ColumnOfIndex(sqlite3PrimaryKeyIndex(pTab), iCol); + } + sqlite3VdbeAddOp3(v, op, iTabCur, x, regOut); } if( iCol>=0 ){ sqlite3ColumnDefault(v, pTab, iCol, regOut); @@ -2968,7 +2969,7 @@ int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){ v, OP_Halt, SQLITE_OK, OE_Ignore, 0, pExpr->u.zToken,0); }else{ sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_TRIGGER, - pExpr->affinity, pExpr->u.zToken, 0); + pExpr->affinity, pExpr->u.zToken, 0, 0); } break; diff --git a/src/fkey.c b/src/fkey.c index 5c49ded876..1cb6cb0d42 100644 --- a/src/fkey.c +++ b/src/fkey.c @@ -225,7 +225,7 @@ int sqlite3FkLocateIndex( } for(pIdx=pParent->pIndex; pIdx; pIdx=pIdx->pNext){ - if( pIdx->nColumn==nCol && pIdx->onError!=OE_None ){ + if( pIdx->nKeyCol==nCol && pIdx->onError!=OE_None ){ /* pIdx is a UNIQUE index (or a PRIMARY KEY) and has the right number ** of columns. If each indexed column corresponds to a foreign key ** column of pFKey, then this index is a winner. */ @@ -248,7 +248,7 @@ int sqlite3FkLocateIndex( ** the default collation sequences for each column. */ int i, j; for(i=0; iaiColumn[i]; /* Index of column in parent tbl */ + i16 iCol = pIdx->aiColumn[i]; /* Index of column in parent tbl */ char *zDfltColl; /* Def. collation for column */ char *zIdxCol; /* Name of indexed column */ @@ -379,10 +379,9 @@ static void fkLookupParent( int nCol = pFKey->nCol; int regTemp = sqlite3GetTempRange(pParse, nCol); int regRec = sqlite3GetTempReg(pParse); - KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx); sqlite3VdbeAddOp3(v, OP_OpenRead, iCur, pIdx->tnum, iDb); - sqlite3VdbeChangeP4(v, -1, (char*)pKey, P4_KEYINFO_HANDOFF); + sqlite3VdbeSetP4KeyInfo(pParse, pIdx); for(i=0; i0 && pFKey->isDeferred==0 ){ sqlite3ParseToplevel(pParse)->mayAbort = 1; @@ -445,6 +443,62 @@ static void fkLookupParent( sqlite3VdbeAddOp1(v, OP_Close, iCur); } + +/* +** Return an Expr object that refers to a memory register corresponding +** to column iCol of table pTab. +** +** regBase is the first of an array of register that contains the data +** for pTab. regBase itself holds the rowid. regBase+1 holds the first +** column. regBase+2 holds the second column, and so forth. +*/ +static Expr *exprTableRegister( + Parse *pParse, /* Parsing and code generating context */ + Table *pTab, /* The table whose content is at r[regBase]... */ + int regBase, /* Contents of table pTab */ + i16 iCol /* Which column of pTab is desired */ +){ + Expr *pExpr; + Column *pCol; + const char *zColl; + sqlite3 *db = pParse->db; + + pExpr = sqlite3Expr(db, TK_REGISTER, 0); + if( pExpr ){ + if( iCol>=0 && iCol!=pTab->iPKey ){ + pCol = &pTab->aCol[iCol]; + pExpr->iTable = regBase + iCol + 1; + pExpr->affinity = pCol->affinity; + zColl = pCol->zColl; + if( zColl==0 ) zColl = db->pDfltColl->zName; + pExpr = sqlite3ExprAddCollateString(pParse, pExpr, zColl); + }else{ + pExpr->iTable = regBase; + pExpr->affinity = SQLITE_AFF_INTEGER; + } + } + return pExpr; +} + +/* +** Return an Expr object that refers to column iCol of table pTab which +** has cursor iCur. +*/ +static Expr *exprTableColumn( + sqlite3 *db, /* The database connection */ + Table *pTab, /* The table whose column is desired */ + int iCursor, /* The open cursor on the table */ + i16 iCol /* The column that is wanted */ +){ + Expr *pExpr = sqlite3Expr(db, TK_COLUMN, 0); + if( pExpr ){ + pExpr->pTab = pTab; + pExpr->iTable = iCursor; + pExpr->iColumn = iCol; + } + return pExpr; +} + /* ** This function is called to generate code executed when a row is deleted ** from the parent table of foreign key constraint pFKey and, if pFKey is @@ -460,13 +514,13 @@ static void fkLookupParent( ** -------------------------------------------------------------------------- ** DELETE immediate Increment the "immediate constraint counter". ** Or, if the ON (UPDATE|DELETE) action is RESTRICT, -** throw a "foreign key constraint failed" exception. +** throw a "FOREIGN KEY constraint failed" exception. ** ** INSERT immediate Decrement the "immediate constraint counter". ** ** DELETE deferred Increment the "deferred constraint counter". ** Or, if the ON (UPDATE|DELETE) action is RESTRICT, -** throw a "foreign key constraint failed" exception. +** throw a "FOREIGN KEY constraint failed" exception. ** ** INSERT deferred Decrement the "deferred constraint counter". ** @@ -475,12 +529,12 @@ static void fkLookupParent( */ static void fkScanChildren( Parse *pParse, /* Parse context */ - SrcList *pSrc, /* SrcList containing the table to scan */ - Table *pTab, - Index *pIdx, /* Foreign key index */ - FKey *pFKey, /* Foreign key relationship */ + SrcList *pSrc, /* The child table to be scanned */ + Table *pTab, /* The parent table */ + Index *pIdx, /* Index on parent covering the foreign key */ + FKey *pFKey, /* The foreign key linking pSrc to pTab */ int *aiCol, /* Map from pIdx cols to child table cols */ - int regData, /* Referenced table data starts here */ + int regData, /* Parent row data starts here */ int nIncr /* Amount to increment deferred counter by */ ){ sqlite3 *db = pParse->db; /* Database handle */ @@ -491,7 +545,9 @@ static void fkScanChildren( int iFkIfZero = 0; /* Address of OP_FkIfZero */ Vdbe *v = sqlite3GetVdbe(pParse); - assert( !pIdx || pIdx->pTable==pTab ); + assert( pIdx==0 || pIdx->pTable==pTab ); + assert( pIdx==0 || pIdx->nKeyCol==pFKey->nCol ); + assert( pIdx!=0 || pFKey->nCol==1 ); if( nIncr<0 ){ iFkIfZero = sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, 0); @@ -509,29 +565,11 @@ static void fkScanChildren( Expr *pLeft; /* Value from parent table row */ Expr *pRight; /* Column ref to child table */ Expr *pEq; /* Expression (pLeft = pRight) */ - int iCol; /* Index of column in child table */ + i16 iCol; /* Index of column in child table */ const char *zCol; /* Name of column in child table */ - pLeft = sqlite3Expr(db, TK_REGISTER, 0); - if( pLeft ){ - /* Set the collation sequence and affinity of the LHS of each TK_EQ - ** expression to the parent key column defaults. */ - if( pIdx ){ - Column *pCol; - const char *zColl; - iCol = pIdx->aiColumn[i]; - pCol = &pTab->aCol[iCol]; - if( pTab->iPKey==iCol ) iCol = -1; - pLeft->iTable = regData+iCol+1; - pLeft->affinity = pCol->affinity; - zColl = pCol->zColl; - if( zColl==0 ) zColl = db->pDfltColl->zName; - pLeft = sqlite3ExprAddCollateString(pParse, pLeft, zColl); - }else{ - pLeft->iTable = regData; - pLeft->affinity = SQLITE_AFF_INTEGER; - } - } + iCol = pIdx ? pIdx->aiColumn[i] : -1; + pLeft = exprTableRegister(pParse, pTab, regData, iCol); iCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom; assert( iCol>=0 ); zCol = pFKey->pFrom->aCol[iCol].zName; @@ -540,24 +578,38 @@ static void fkScanChildren( pWhere = sqlite3ExprAnd(db, pWhere, pEq); } - /* If the child table is the same as the parent table, and this scan - ** is taking place as part of a DELETE operation (operation D.2), omit the - ** row being deleted from the scan by adding ($rowid != rowid) to the WHERE - ** clause, where $rowid is the rowid of the row being deleted. */ + /* If the child table is the same as the parent table, then add terms + ** to the WHERE clause that prevent this entry from being scanned. + ** The added WHERE clause terms are like this: + ** + ** $current_rowid!=rowid + ** NOT( $current_a==a AND $current_b==b AND ... ) + ** + ** The first form is used for rowid tables. The second form is used + ** for WITHOUT ROWID tables. In the second form, the primary key is + ** (a,b,...) + */ if( pTab==pFKey->pFrom && nIncr>0 ){ - Expr *pEq; /* Expression (pLeft = pRight) */ + Expr *pNe; /* Expression (pLeft != pRight) */ Expr *pLeft; /* Value from parent table row */ Expr *pRight; /* Column ref to child table */ - pLeft = sqlite3Expr(db, TK_REGISTER, 0); - pRight = sqlite3Expr(db, TK_COLUMN, 0); - if( pLeft && pRight ){ - pLeft->iTable = regData; - pLeft->affinity = SQLITE_AFF_INTEGER; - pRight->iTable = pSrc->a[0].iCursor; - pRight->iColumn = -1; + if( HasRowid(pTab) ){ + pLeft = exprTableRegister(pParse, pTab, regData, -1); + pRight = exprTableColumn(db, pTab, pSrc->a[0].iCursor, -1); + pNe = sqlite3PExpr(pParse, TK_NE, pLeft, pRight, 0); + }else{ + Expr *pEq, *pAll = 0; + Index *pPk = sqlite3PrimaryKeyIndex(pTab); + for(i=0; inKeyCol; i++){ + i16 iCol = pIdx->aiColumn[i]; + pLeft = exprTableRegister(pParse, pTab, regData, iCol); + pRight = exprTableColumn(db, pTab, pSrc->a[0].iCursor, iCol); + pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight, 0); + pAll = sqlite3ExprAnd(db, pAll, pEq); + } + pNe = sqlite3PExpr(pParse, TK_NOT, pAll, 0, 0); } - pEq = sqlite3PExpr(pParse, TK_NE, pLeft, pRight, 0); - pWhere = sqlite3ExprAnd(db, pWhere, pEq); + pWhere = sqlite3ExprAnd(db, pWhere, pNe); } /* Resolve the references in the WHERE clause. */ @@ -587,8 +639,8 @@ static void fkScanChildren( } /* -** This function returns a pointer to the head of a linked list of FK -** constraints for which table pTab is the parent table. For example, +** This function returns a linked list of FKey objects (connected by +** FKey.pNextTo) holding all children of table pTab. For example, ** given the following schema: ** ** CREATE TABLE t1(a PRIMARY KEY); @@ -679,8 +731,7 @@ void sqlite3FkDropTable(Parse *pParse, SrcList *pName, Table *pTab){ if( (db->flags & SQLITE_DeferFKs)==0 ){ sqlite3VdbeAddOp2(v, OP_FkIfZero, 0, sqlite3VdbeCurrentAddr(v)+2); sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_FOREIGNKEY, - OE_Abort, "foreign key constraint failed", P4_STATIC - ); + OE_Abort, 0, P4_STATIC, P5_ConstraintFK); } if( iSkip ){ @@ -890,7 +941,8 @@ void sqlite3FkCheck( sqlite3DbFree(db, aiFree); } - /* Loop through all the foreign key constraints that refer to this table */ + /* Loop through all the foreign key constraints that refer to this table. + ** (the "child" constraints) */ for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){ Index *pIdx = 0; /* Foreign key index for pFKey */ SrcList *pSrc; @@ -915,9 +967,8 @@ void sqlite3FkCheck( } assert( aiCol || pFKey->nCol==1 ); - /* Create a SrcList structure containing a single table (the table - ** the foreign key that refers to this table is attached to). This - ** is required for the sqlite3WhereXXX() interface. */ + /* Create a SrcList structure containing the child table. We need the + ** child table as a SrcList for sqlite3WhereBegin() */ pSrc = sqlite3SrcListAppend(db, 0, 0, 0); if( pSrc ){ struct SrcList_item *pItem = pSrc->a; @@ -966,7 +1017,7 @@ u32 sqlite3FkOldmask( Index *pIdx = 0; sqlite3FkLocateIndex(pParse, pTab, p, &pIdx, 0); if( pIdx ){ - for(i=0; inColumn; i++) mask |= COLUMN_MASK(pIdx->aiColumn[i]); + for(i=0; inKeyCol; i++) mask |= COLUMN_MASK(pIdx->aiColumn[i]); } } } @@ -1158,7 +1209,7 @@ static Trigger *fkActionTrigger( tFrom.z = zFrom; tFrom.n = nFrom; - pRaise = sqlite3Expr(db, TK_RAISE, "foreign key constraint failed"); + pRaise = sqlite3Expr(db, TK_RAISE, "FOREIGN KEY constraint failed"); if( pRaise ){ pRaise->affinity = OE_Abort; } diff --git a/src/func.c b/src/func.c index e2ab68f030..c9962f6d91 100644 --- a/src/func.c +++ b/src/func.c @@ -138,8 +138,8 @@ static void absFunc(sqlite3_context *context, int argc, sqlite3_value **argv){ i64 iVal = sqlite3_value_int64(argv[0]); if( iVal<0 ){ if( (iVal<<1)==0 ){ - /* IMP: R-35460-15084 If X is the integer -9223372036854775807 then - ** abs(X) throws an integer overflow error since there is no + /* IMP: R-31676-45509 If X is the integer -9223372036854775808 + ** then abs(X) throws an integer overflow error since there is no ** equivalent positive 64-bit two complement value. */ sqlite3_result_error(context, "integer overflow", -1); return; diff --git a/src/insert.c b/src/insert.c index 96ca2b69ba..1c89a38af5 100644 --- a/src/insert.c +++ b/src/insert.c @@ -15,10 +15,16 @@ #include "sqliteInt.h" /* -** Generate code that will open a table for reading. +** Generate code that will +** +** (1) acquire a lock for table pTab then +** (2) open pTab as cursor iCur. +** +** If pTab is a WITHOUT ROWID table, then it is the PRIMARY KEY index +** for that table that is actually opened. */ void sqlite3OpenTable( - Parse *p, /* Generate code into this VDBE */ + Parse *pParse, /* Generate code into this VDBE */ int iCur, /* The cursor number of the table */ int iDb, /* The database index in sqlite3.aDb[] */ Table *pTab, /* The table to be opened */ @@ -26,12 +32,21 @@ void sqlite3OpenTable( ){ Vdbe *v; assert( !IsVirtual(pTab) ); - v = sqlite3GetVdbe(p); + v = sqlite3GetVdbe(pParse); assert( opcode==OP_OpenWrite || opcode==OP_OpenRead ); - sqlite3TableLock(p, iDb, pTab->tnum, (opcode==OP_OpenWrite)?1:0, pTab->zName); - sqlite3VdbeAddOp3(v, opcode, iCur, pTab->tnum, iDb); - sqlite3VdbeChangeP4(v, -1, SQLITE_INT_TO_PTR(pTab->nCol), P4_INT32); - VdbeComment((v, "%s", pTab->zName)); + sqlite3TableLock(pParse, iDb, pTab->tnum, + (opcode==OP_OpenWrite)?1:0, pTab->zName); + if( HasRowid(pTab) ){ + sqlite3VdbeAddOp4Int(v, opcode, iCur, pTab->tnum, iDb, pTab->nCol); + VdbeComment((v, "%s", pTab->zName)); + }else{ + Index *pPk = sqlite3PrimaryKeyIndex(pTab); + assert( pPk!=0 ); + assert( pPk->tnum=pTab->tnum ); + sqlite3VdbeAddOp3(v, opcode, iCur, pPk->tnum, iDb); + sqlite3VdbeSetP4KeyInfo(pParse, pPk); + VdbeComment((v, "%s", pTab->zName)); + } } /* @@ -67,15 +82,15 @@ const char *sqlite3IndexAffinityStr(Vdbe *v, Index *pIdx){ int n; Table *pTab = pIdx->pTable; sqlite3 *db = sqlite3VdbeDb(v); - pIdx->zColAff = (char *)sqlite3DbMallocRaw(0, pIdx->nColumn+2); + pIdx->zColAff = (char *)sqlite3DbMallocRaw(0, pIdx->nColumn+1); if( !pIdx->zColAff ){ db->mallocFailed = 1; return 0; } for(n=0; nnColumn; n++){ - pIdx->zColAff[n] = pTab->aCol[pIdx->aiColumn[n]].affinity; + i16 x = pIdx->aiColumn[n]; + pIdx->zColAff[n] = x<0 ? SQLITE_AFF_INTEGER : pTab->aCol[x].affinity; } - pIdx->zColAff[n++] = SQLITE_AFF_INTEGER; pIdx->zColAff[n] = 0; } @@ -421,7 +436,7 @@ static int xferOptimization( ); /* -** This routine is call to handle SQL of the following forms: +** This routine is called to handle SQL of the following forms: ** ** insert into TABLE (IDLIST) values(EXPRLIST) ** insert into TABLE (IDLIST) select @@ -436,12 +451,12 @@ static int xferOptimization( ** data for the insert. ** ** The code generated follows one of four templates. For a simple -** select with data coming from a VALUES clause, the code executes +** insert with data coming from a VALUES clause, the code executes ** once straight down through. Pseudo-code follows (we call this ** the "1st template"): ** ** open write cursor to
and its indices -** puts VALUES clause expressions onto the stack +** put VALUES clause expressions into registers ** write the resulting record into
** cleanup ** @@ -539,8 +554,9 @@ void sqlite3Insert( Index *pIdx; /* For looping over indices of the table */ int nColumn; /* Number of columns in the data */ int nHidden = 0; /* Number of hidden columns if TABLE is virtual */ - int baseCur = 0; /* VDBE Cursor number for pTab */ - int keyColumn = -1; /* Column that is the INTEGER PRIMARY KEY */ + int iDataCur = 0; /* VDBE cursor that is the main data repository */ + int iIdxCur = 0; /* First index cursor */ + int ipkColumn = -1; /* Column that is the INTEGER PRIMARY KEY */ int endOfLoop; /* Label for the end of the insertion loop */ int useTempTable = 0; /* Store SELECT results in intermediate table */ int srcTab = 0; /* Data comes from this temporary cursor if >=0 */ @@ -551,6 +567,7 @@ void sqlite3Insert( int iDb; /* Index of database holding TABLE */ Db *pDb; /* The database containing table being inserted into */ int appendFlag = 0; /* True if the insert is likely to be an append */ + int withoutRowid; /* 0 for normal table. 1 for WITHOUT ROWID table */ /* Register allocations */ int regFromSelect = 0;/* Base register for data coming from SELECT */ @@ -590,6 +607,7 @@ void sqlite3Insert( if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){ goto insert_cleanup; } + withoutRowid = !HasRowid(pTab); /* Figure out if we have any triggers and if the table being ** inserted into is a view @@ -609,16 +627,13 @@ void sqlite3Insert( assert( (pTrigger && tmask) || (pTrigger==0 && tmask==0) ); /* If pTab is really a view, make sure it has been initialized. - ** ViewGetColumnNames() is a no-op if pTab is not a view (or virtual - ** module table). + ** ViewGetColumnNames() is a no-op if pTab is not a view. */ if( sqlite3ViewGetColumnNames(pParse, pTab) ){ goto insert_cleanup; } - /* Ensure that: - * (a) the table is not read-only, - * (b) that if it is a view then ON INSERT triggers exist + /* Cannot insert into a read-only table. */ if( sqlite3IsReadOnly(pParse, pTab, tmask) ){ goto insert_cleanup; @@ -659,8 +674,7 @@ void sqlite3Insert( ** co-routine is the common header to the 3rd and 4th templates. */ if( pSelect ){ - /* Data is coming from a SELECT. Generate a co-routine to run that - ** SELECT. */ + /* Data is coming from a SELECT. Generate a co-routine to run the SELECT */ int rc = sqlite3CodeCoroutine(pParse, pSelect, &dest); if( rc ) goto insert_cleanup; @@ -672,7 +686,7 @@ void sqlite3Insert( /* Set useTempTable to TRUE if the result of the SELECT statement ** should be written into a temporary table (template 4). Set to - ** FALSE if each* row of the SELECT can be written directly into + ** FALSE if each output row of the SELECT can be written directly into ** the destination table (template 3). ** ** A temp table must be used if the table being updated is also one @@ -755,11 +769,11 @@ void sqlite3Insert( ** remember the column indices. ** ** If the table has an INTEGER PRIMARY KEY column and that column - ** is named in the IDLIST, then record in the keyColumn variable - ** the index into IDLIST of the primary key column. keyColumn is + ** is named in the IDLIST, then record in the ipkColumn variable + ** the index into IDLIST of the primary key column. ipkColumn is ** the index of the primary key as it appears in IDLIST, not as - ** is appears in the original table. (The index of the primary - ** key in the original table is pTab->iPKey.) + ** is appears in the original table. (The index of the INTEGER + ** PRIMARY KEY in the original table is pTab->iPKey.) */ if( pColumn ){ for(i=0; inId; i++){ @@ -770,14 +784,14 @@ void sqlite3Insert( if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){ pColumn->a[i].idx = j; if( j==pTab->iPKey ){ - keyColumn = i; + ipkColumn = i; assert( !withoutRowid ); } break; } } if( j>=pTab->nCol ){ - if( sqlite3IsRowid(pColumn->a[i].zName) ){ - keyColumn = i; + if( sqlite3IsRowid(pColumn->a[i].zName) && !withoutRowid ){ + ipkColumn = i; }else{ sqlite3ErrorMsg(pParse, "table %S has no column named %s", pTabList, 0, pColumn->a[i].zName); @@ -789,11 +803,11 @@ void sqlite3Insert( } /* If there is no IDLIST term but the table has an integer primary - ** key, the set the keyColumn variable to the primary key column index - ** in the original table definition. + ** key, the set the ipkColumn variable to the integer primary key + ** column index in the original table definition. */ if( pColumn==0 && nColumn>0 ){ - keyColumn = pTab->iPKey; + ipkColumn = pTab->iPKey; } /* Initialize the count of rows to be inserted @@ -806,9 +820,8 @@ void sqlite3Insert( /* If this is not a view, open the table and and all indices */ if( !isView ){ int nIdx; - - baseCur = pParse->nTab; - nIdx = sqlite3OpenTableAndIndices(pParse, pTab, baseCur, OP_OpenWrite); + nIdx = sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, -1, + &iDataCur, &iIdxCur); aRegIdx = sqlite3DbMallocRaw(db, sizeof(int)*(nIdx+1)); if( aRegIdx==0 ){ goto insert_cleanup; @@ -868,15 +881,16 @@ void sqlite3Insert( ** we do not know what the unique ID will be (because the insert has ** not happened yet) so we substitute a rowid of -1 */ - if( keyColumn<0 ){ + if( ipkColumn<0 ){ sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols); }else{ int j1; + assert( !withoutRowid ); if( useTempTable ){ - sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regCols); + sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regCols); }else{ assert( pSelect==0 ); /* Otherwise useTempTable is true */ - sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regCols); + sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regCols); } j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols); sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols); @@ -926,29 +940,27 @@ void sqlite3Insert( sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1); } - /* Push the record number for the new entry onto the stack. The - ** record number is a randomly generate integer created by NewRowid - ** except when the table has an INTEGER PRIMARY KEY column, in which - ** case the record number is the same as that column. + /* Compute the content of the next row to insert into a range of + ** registers beginning at regIns. */ if( !isView ){ if( IsVirtual(pTab) ){ /* The row that the VUpdate opcode will delete: none */ sqlite3VdbeAddOp2(v, OP_Null, 0, regIns); } - if( keyColumn>=0 ){ + if( ipkColumn>=0 ){ if( useTempTable ){ - sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regRowid); + sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regRowid); }else if( pSelect ){ - sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+keyColumn, regRowid); + sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+ipkColumn, regRowid); }else{ VdbeOp *pOp; - sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regRowid); + sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regRowid); pOp = sqlite3VdbeGetOp(v, -1); if( ALWAYS(pOp) && pOp->opcode==OP_Null && !IsVirtual(pTab) ){ appendFlag = 1; pOp->opcode = OP_NewRowid; - pOp->p1 = baseCur; + pOp->p1 = iDataCur; pOp->p2 = regRowid; pOp->p3 = regAutoinc; } @@ -960,7 +972,7 @@ void sqlite3Insert( int j1; if( !IsVirtual(pTab) ){ j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid); - sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc); + sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc); sqlite3VdbeJumpHere(v, j1); }else{ j1 = sqlite3VdbeCurrentAddr(v); @@ -968,15 +980,15 @@ void sqlite3Insert( } sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid); } - }else if( IsVirtual(pTab) ){ + }else if( IsVirtual(pTab) || withoutRowid ){ sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid); }else{ - sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc); + sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc); appendFlag = 1; } autoIncStep(pParse, regAutoinc, regRowid); - /* Push onto the stack, data for all columns of the new entry, beginning + /* Compute data for all columns of the new entry, beginning ** with the first column. */ nHidden = 0; @@ -984,8 +996,8 @@ void sqlite3Insert( int iRegStore = regRowid+1+i; if( i==pTab->iPKey ){ /* The value of the INTEGER PRIMARY KEY column is always a NULL. - ** Whenever this column is read, the record number will be substituted - ** in its place. So will fill this column with a NULL to avoid + ** Whenever this column is read, the rowid will be substituted + ** in its place. Hence, fill this column with a NULL to avoid ** taking up data space with information that will never be used. */ sqlite3VdbeAddOp2(v, OP_Null, 0, iRegStore); continue; @@ -1028,13 +1040,12 @@ void sqlite3Insert( #endif { int isReplace; /* Set to true if constraints may cause a replace */ - sqlite3GenerateConstraintChecks(pParse, pTab, baseCur, regIns, aRegIdx, - keyColumn>=0, 0, onError, endOfLoop, &isReplace + sqlite3GenerateConstraintChecks(pParse, pTab, aRegIdx, iDataCur, iIdxCur, + regIns, 0, ipkColumn>=0, onError, endOfLoop, &isReplace ); sqlite3FkCheck(pParse, pTab, 0, regIns, 0, 0); - sqlite3CompleteInsertion( - pParse, pTab, baseCur, regIns, aRegIdx, 0, appendFlag, isReplace==0 - ); + sqlite3CompleteInsertion(pParse, pTab, iDataCur, iIdxCur, + regIns, aRegIdx, 0, appendFlag, isReplace==0); } } @@ -1065,9 +1076,9 @@ void sqlite3Insert( if( !IsVirtual(pTab) && !isView ){ /* Close all tables opened */ - sqlite3VdbeAddOp1(v, OP_Close, baseCur); - for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){ - sqlite3VdbeAddOp1(v, OP_Close, idx+baseCur); + if( iDataCurpIndex; pIdx; pIdx=pIdx->pNext, idx++){ + sqlite3VdbeAddOp1(v, OP_Close, idx+iIdxCur); } } @@ -1112,36 +1123,48 @@ insert_cleanup: #undef tmask #endif - /* -** Generate code to do constraint checks prior to an INSERT or an UPDATE. +** Generate code to do constraint checks prior to an INSERT or an UPDATE +** on table pTab. ** -** The input is a range of consecutive registers as follows: +** The regNewData parameter is the first register in a range that contains +** the data to be inserted or the data after the update. There will be +** pTab->nCol+1 registers in this range. The first register (the one +** that regNewData points to) will contain the new rowid, or NULL in the +** case of a WITHOUT ROWID table. The second register in the range will +** contain the content of the first table column. The third register will +** contain the content of the second table column. And so forth. ** -** 1. The rowid of the row after the update. +** The regOldData parameter is similar to regNewData except that it contains +** the data prior to an UPDATE rather than afterwards. regOldData is zero +** for an INSERT. This routine can distinguish between UPDATE and INSERT by +** checking regOldData for zero. ** -** 2. The data in the first column of the entry after the update. +** For an UPDATE, the pkChng boolean is true if the true primary key (the +** rowid for a normal table or the PRIMARY KEY for a WITHOUT ROWID table) +** might be modified by the UPDATE. If pkChng is false, then the key of +** the iDataCur content table is guaranteed to be unchanged by the UPDATE. ** -** i. Data from middle columns... +** For an INSERT, the pkChng boolean indicates whether or not the rowid +** was explicitly specified as part of the INSERT statement. If pkChng +** is zero, it means that the either rowid is computed automatically or +** that the table is a WITHOUT ROWID table and has no rowid. On an INSERT, +** pkChng will only be true if the INSERT statement provides an integer +** value for either the rowid column or its INTEGER PRIMARY KEY alias. ** -** N. The data in the last column of the entry after the update. -** -** The regRowid parameter is the index of the register containing (1). -** -** If isUpdate is true and rowidChng is non-zero, then rowidChng contains -** the address of a register containing the rowid before the update takes -** place. isUpdate is true for UPDATEs and false for INSERTs. If isUpdate -** is false, indicating an INSERT statement, then a non-zero rowidChng -** indicates that the rowid was explicitly specified as part of the -** INSERT statement. If rowidChng is false, it means that the rowid is -** computed automatically in an insert or that the rowid value is not -** modified by an update. -** -** The code generated by this routine store new index entries into +** The code generated by this routine will store new index entries into ** registers identified by aRegIdx[]. No index entry is created for ** indices where aRegIdx[i]==0. The order of indices in aRegIdx[] is ** the same as the order of indices on the linked list of indices -** attached to the table. +** at pTab->pIndex. +** +** The caller must have already opened writeable cursors on the main +** table and all applicable indices (that is to say, all indices for which +** aRegIdx[] is not zero). iDataCur is the cursor for the main table when +** inserting or updating a rowid table, or the cursor for the PRIMARY KEY +** index when operating on a WITHOUT ROWID table. iIdxCur is the cursor +** for the first index in the pTab->pIndex list. Cursors for other indices +** are at iIdxCur+N for the N-th element of the pTab->pIndex list. ** ** This routine also generates code to check constraints. NOT NULL, ** CHECK, and UNIQUE constraints are all checked. If a constraint fails, @@ -1151,22 +1174,23 @@ insert_cleanup: ** Constraint type Action What Happens ** --------------- ---------- ---------------------------------------- ** any ROLLBACK The current transaction is rolled back and -** sqlite3_exec() returns immediately with a +** sqlite3_step() returns immediately with a ** return code of SQLITE_CONSTRAINT. ** ** any ABORT Back out changes from the current command ** only (do not do a complete rollback) then -** cause sqlite3_exec() to return immediately +** cause sqlite3_step() to return immediately ** with SQLITE_CONSTRAINT. ** -** any FAIL Sqlite3_exec() returns immediately with a +** any FAIL Sqlite3_step() returns immediately with a ** return code of SQLITE_CONSTRAINT. The ** transaction is not rolled back and any -** prior changes are retained. +** changes to prior rows are retained. ** -** any IGNORE The record number and data is popped from -** the stack and there is an immediate jump -** to label ignoreDest. +** any IGNORE The attempt in insert or update the current +** row is skipped, without throwing an error. +** Processing continues with the next row. +** (There is an immediate jump to ignoreDest.) ** ** NOT NULL REPLACE The NULL value is replace by the default ** value for that column. If the default value @@ -1181,44 +1205,57 @@ insert_cleanup: ** Or if overrideError==OE_Default, then the pParse->onError parameter ** is used. Or if pParse->onError==OE_Default then the onError value ** for the constraint is used. -** -** The calling routine must open a read/write cursor for pTab with -** cursor number "baseCur". All indices of pTab must also have open -** read/write cursors with cursor number baseCur+i for the i-th cursor. -** Except, if there is no possibility of a REPLACE action then -** cursors do not need to be open for indices where aRegIdx[i]==0. */ void sqlite3GenerateConstraintChecks( - Parse *pParse, /* The parser context */ - Table *pTab, /* the table into which we are inserting */ - int baseCur, /* Index of a read/write cursor pointing at pTab */ - int regRowid, /* Index of the range of input registers */ - int *aRegIdx, /* Register used by each index. 0 for unused indices */ - int rowidChng, /* True if the rowid might collide with existing entry */ - int isUpdate, /* True for UPDATE, False for INSERT */ - int overrideError, /* Override onError to this if not OE_Default */ - int ignoreDest, /* Jump to this label on an OE_Ignore resolution */ - int *pbMayReplace /* OUT: Set to true if constraint may cause a replace */ + Parse *pParse, /* The parser context */ + Table *pTab, /* The table being inserted or updated */ + int *aRegIdx, /* Use register aRegIdx[i] for index i. 0 for unused */ + int iDataCur, /* Canonical data cursor (main table or PK index) */ + int iIdxCur, /* First index cursor */ + int regNewData, /* First register in a range holding values to insert */ + int regOldData, /* Previous content. 0 for INSERTs */ + u8 pkChng, /* Non-zero if the rowid or PRIMARY KEY changed */ + u8 overrideError, /* Override onError to this if not OE_Default */ + int ignoreDest, /* Jump to this label on an OE_Ignore resolution */ + int *pbMayReplace /* OUT: Set to true if constraint may cause a replace */ ){ - int i; /* loop counter */ - Vdbe *v; /* VDBE under constrution */ - int nCol; /* Number of columns */ - int onError; /* Conflict resolution strategy */ - int j1; /* Addresss of jump instruction */ - int j2 = 0, j3; /* Addresses of jump instructions */ - int regData; /* Register containing first data column */ - int iCur; /* Table cursor number */ + Vdbe *v; /* VDBE under constrution */ Index *pIdx; /* Pointer to one of the indices */ + Index *pPk = 0; /* The PRIMARY KEY index */ sqlite3 *db; /* Database connection */ + int i; /* loop counter */ + int ix; /* Index loop counter */ + int nCol; /* Number of columns */ + int onError; /* Conflict resolution strategy */ + int j1; /* Addresss of jump instruction */ int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */ - int regOldRowid = (rowidChng && isUpdate) ? rowidChng : regRowid; + int nPkField; /* Number of fields in PRIMARY KEY. 1 for ROWID tables */ + int ipkTop = 0; /* Top of the rowid change constraint check */ + int ipkBottom = 0; /* Bottom of the rowid change constraint check */ + u8 isUpdate; /* True if this is an UPDATE operation */ + isUpdate = regOldData!=0; db = pParse->db; v = sqlite3GetVdbe(pParse); assert( v!=0 ); assert( pTab->pSelect==0 ); /* This table is not a VIEW */ nCol = pTab->nCol; - regData = regRowid + 1; + + /* pPk is the PRIMARY KEY index for WITHOUT ROWID tables and NULL for + ** normal rowid tables. nPkField is the number of key fields in the + ** pPk index or 1 for a rowid table. In other words, nPkField is the + ** number of fields in the true primary key of the table. */ + if( HasRowid(pTab) ){ + pPk = 0; + nPkField = 1; + }else{ + pPk = sqlite3PrimaryKeyIndex(pTab); + nPkField = pPk->nKeyCol; + } + + /* Record that this module has started */ + VdbeModuleComment((v, "BEGIN: GenCnstCks(%d,%d,%d,%d,%d)", + iDataCur, iIdxCur, regNewData, regOldData, pkChng)); /* Test all NOT NULL constraints. */ @@ -1241,24 +1278,24 @@ void sqlite3GenerateConstraintChecks( switch( onError ){ case OE_Abort: sqlite3MayAbort(pParse); + /* Fall through */ case OE_Rollback: case OE_Fail: { - char *zMsg; - sqlite3VdbeAddOp3(v, OP_HaltIfNull, - SQLITE_CONSTRAINT_NOTNULL, onError, regData+i); - zMsg = sqlite3MPrintf(db, "%s.%s may not be NULL", - pTab->zName, pTab->aCol[i].zName); - sqlite3VdbeChangeP4(v, -1, zMsg, P4_DYNAMIC); + char *zMsg = sqlite3MPrintf(db, "%s.%s", pTab->zName, + pTab->aCol[i].zName); + sqlite3VdbeAddOp4(v, OP_HaltIfNull, SQLITE_CONSTRAINT_NOTNULL, onError, + regNewData+1+i, zMsg, P4_DYNAMIC); + sqlite3VdbeChangeP5(v, P5_ConstraintNotNull); break; } case OE_Ignore: { - sqlite3VdbeAddOp2(v, OP_IsNull, regData+i, ignoreDest); + sqlite3VdbeAddOp2(v, OP_IsNull, regNewData+1+i, ignoreDest); break; } default: { assert( onError==OE_Replace ); - j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regData+i); - sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regData+i); + j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regNewData+1+i); + sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regNewData+1+i); sqlite3VdbeJumpHere(v, j1); break; } @@ -1270,7 +1307,7 @@ void sqlite3GenerateConstraintChecks( #ifndef SQLITE_OMIT_CHECK if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){ ExprList *pCheck = pTab->pCheck; - pParse->ckBase = regData; + pParse->ckBase = regNewData+1; onError = overrideError!=OE_Default ? overrideError : OE_Abort; for(i=0; inExpr; i++){ int allOk = sqlite3VdbeMakeLabel(v); @@ -1278,37 +1315,58 @@ void sqlite3GenerateConstraintChecks( if( onError==OE_Ignore ){ sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest); }else{ - char *zConsName = pCheck->a[i].zName; + char *zName = pCheck->a[i].zName; + if( zName==0 ) zName = pTab->zName; if( onError==OE_Replace ) onError = OE_Abort; /* IMP: R-15569-63625 */ - if( zConsName ){ - zConsName = sqlite3MPrintf(db, "constraint %s failed", zConsName); - }else{ - zConsName = 0; - } sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_CHECK, - onError, zConsName, P4_DYNAMIC); + onError, zName, P4_TRANSIENT, + P5_ConstraintCheck); } sqlite3VdbeResolveLabel(v, allOk); } } #endif /* !defined(SQLITE_OMIT_CHECK) */ - /* If we have an INTEGER PRIMARY KEY, make sure the primary key - ** of the new record does not previously exist. Except, if this - ** is an UPDATE and the primary key is not changing, that is OK. + /* If rowid is changing, make sure the new rowid does not previously + ** exist in the table. */ - if( rowidChng ){ + if( pkChng && pPk==0 ){ + int addrRowidOk = sqlite3VdbeMakeLabel(v); + + /* Figure out what action to take in case of a rowid collision */ onError = pTab->keyConf; if( overrideError!=OE_Default ){ onError = overrideError; }else if( onError==OE_Default ){ onError = OE_Abort; } - + if( isUpdate ){ - j2 = sqlite3VdbeAddOp3(v, OP_Eq, regRowid, 0, rowidChng); + /* pkChng!=0 does not mean that the rowid has change, only that + ** it might have changed. Skip the conflict logic below if the rowid + ** is unchanged. */ + sqlite3VdbeAddOp3(v, OP_Eq, regNewData, addrRowidOk, regOldData); } - j3 = sqlite3VdbeAddOp3(v, OP_NotExists, baseCur, 0, regRowid); + + /* If the response to a rowid conflict is REPLACE but the response + ** to some other UNIQUE constraint is FAIL or IGNORE, then we need + ** to defer the running of the rowid conflict checking until after + ** the UNIQUE constraints have run. + */ + if( onError==OE_Replace && overrideError!=OE_Replace ){ + for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ + if( pIdx->onError==OE_Ignore || pIdx->onError==OE_Fail ){ + ipkTop = sqlite3VdbeAddOp0(v, OP_Goto); + break; + } + } + } + + /* Check to see if the new rowid already exists in the table. Skip + ** the following conflict logic if it does not. */ + sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, addrRowidOk, regNewData); + + /* Generate code that deals with a rowid collision */ switch( onError ){ default: { onError = OE_Abort; @@ -1317,8 +1375,7 @@ void sqlite3GenerateConstraintChecks( case OE_Rollback: case OE_Abort: case OE_Fail: { - sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_PRIMARYKEY, - onError, "PRIMARY KEY must be unique", P4_STATIC); + sqlite3RowidConstraint(pParse, onError, pTab); break; } case OE_Replace: { @@ -1350,78 +1407,100 @@ void sqlite3GenerateConstraintChecks( } if( pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0) ){ sqlite3MultiWrite(pParse); - sqlite3GenerateRowDelete( - pParse, pTab, baseCur, regRowid, 0, pTrigger, OE_Replace - ); + sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur, + regNewData, 1, 0, OE_Replace, 1); }else{ #ifdef SQLITE_ENABLE_PREUPDATE_HOOK - /* This OP_Delete opcode fires the pre-update-hook only. It does - ** not modify the b-tree. It is more efficient to let the coming - ** OP_Insert replace the existing entry than it is to delete the - ** existing entry and then insert a new one. */ - sqlite3VdbeAddOp2(v, OP_Delete, baseCur, OPFLAG_ISNOOP); - sqlite3VdbeChangeP4(v, -1, (char *)pTab, P4_TABLE); + if( HasRowid(pTab) ){ + /* This OP_Delete opcode fires the pre-update-hook only. It does + ** not modify the b-tree. It is more efficient to let the coming + ** OP_Insert replace the existing entry than it is to delete the + ** existing entry and then insert a new one. */ + sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, OPFLAG_ISNOOP); + sqlite3VdbeChangeP4(v, -1, (char *)pTab, P4_TABLE); + } #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */ if( pTab->pIndex ){ sqlite3MultiWrite(pParse); - sqlite3GenerateRowIndexDelete(pParse, pTab, baseCur, 0); + sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur, 0); } } seenReplace = 1; break; } case OE_Ignore: { - assert( seenReplace==0 ); + /*assert( seenReplace==0 );*/ sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest); break; } } - sqlite3VdbeJumpHere(v, j3); - if( isUpdate ){ - sqlite3VdbeJumpHere(v, j2); + sqlite3VdbeResolveLabel(v, addrRowidOk); + if( ipkTop ){ + ipkBottom = sqlite3VdbeAddOp0(v, OP_Goto); + sqlite3VdbeJumpHere(v, ipkTop); } } /* Test all UNIQUE constraints by creating entries for each UNIQUE ** index and making sure that duplicate entries do not already exist. - ** Add the new records to the indices as we go. + ** Compute the revised record entries for indices as we go. + ** + ** This loop also handles the case of the PRIMARY KEY index for a + ** WITHOUT ROWID table. */ - for(iCur=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, iCur++){ - int regIdx; - int regR; - int addrSkipRow = 0; + for(ix=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, ix++){ + int regIdx; /* Range of registers hold conent for pIdx */ + int regR; /* Range of registers holding conflicting PK */ + int iThisCur; /* Cursor for this UNIQUE index */ + int addrUniqueOk; /* Jump here if the UNIQUE constraint is satisfied */ - if( aRegIdx[iCur]==0 ) continue; /* Skip unused indices */ + if( aRegIdx[ix]==0 ) continue; /* Skip indices that do not change */ + iThisCur = iIdxCur+ix; + addrUniqueOk = sqlite3VdbeMakeLabel(v); + /* Skip partial indices for which the WHERE clause is not true */ if( pIdx->pPartIdxWhere ){ - sqlite3VdbeAddOp2(v, OP_Null, 0, aRegIdx[iCur]); - addrSkipRow = sqlite3VdbeMakeLabel(v); - pParse->ckBase = regData; - sqlite3ExprIfFalse(pParse, pIdx->pPartIdxWhere, addrSkipRow, + sqlite3VdbeAddOp2(v, OP_Null, 0, aRegIdx[ix]); + pParse->ckBase = regNewData+1; + sqlite3ExprIfFalse(pParse, pIdx->pPartIdxWhere, addrUniqueOk, SQLITE_JUMPIFNULL); pParse->ckBase = 0; } - /* Create a key for accessing the index entry */ - regIdx = sqlite3GetTempRange(pParse, pIdx->nColumn+1); + /* Create a record for this index entry as it should appear after + ** the insert or update. Store that record in the aRegIdx[ix] register + */ + regIdx = sqlite3GetTempRange(pParse, pIdx->nColumn); for(i=0; inColumn; i++){ - int idx = pIdx->aiColumn[i]; - if( idx==pTab->iPKey ){ - sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i); + int iField = pIdx->aiColumn[i]; + int x; + if( iField<0 || iField==pTab->iPKey ){ + x = regNewData; }else{ - sqlite3VdbeAddOp2(v, OP_SCopy, regData+idx, regIdx+i); + x = iField + regNewData + 1; } + sqlite3VdbeAddOp2(v, OP_SCopy, x, regIdx+i); + VdbeComment((v, "%s", iField<0 ? "rowid" : pTab->aCol[iField].zName)); } - sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i); - sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn+1, aRegIdx[iCur]); + sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn, aRegIdx[ix]); sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v, pIdx), P4_TRANSIENT); - sqlite3ExprCacheAffinityChange(pParse, regIdx, pIdx->nColumn+1); + VdbeComment((v, "for %s", pIdx->zName)); + sqlite3ExprCacheAffinityChange(pParse, regIdx, pIdx->nColumn); - /* Find out what action to take in case there is an indexing conflict */ + /* In an UPDATE operation, if this index is the PRIMARY KEY index + ** of a WITHOUT ROWID table and there has been no change the + ** primary key, then no collision is possible. The collision detection + ** logic below can all be skipped. */ + if( isUpdate && pPk==pIdx && pkChng==0 ){ + sqlite3VdbeResolveLabel(v, addrUniqueOk); + continue; + } + + /* Find out what action to take in case there is a uniqueness conflict */ onError = pIdx->onError; if( onError==OE_None ){ - sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1); - sqlite3VdbeResolveLabel(v, addrSkipRow); + sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn); + sqlite3VdbeResolveLabel(v, addrUniqueOk); continue; /* pIdx is not a UNIQUE index */ } if( overrideError!=OE_Default ){ @@ -1429,18 +1508,57 @@ void sqlite3GenerateConstraintChecks( }else if( onError==OE_Default ){ onError = OE_Abort; } - if( seenReplace ){ - if( onError==OE_Ignore ) onError = OE_Replace; - else if( onError==OE_Fail ) onError = OE_Abort; - } /* Check to see if the new index entry will be unique */ - regR = sqlite3GetTempReg(pParse); - sqlite3VdbeAddOp2(v, OP_SCopy, regOldRowid, regR); - j3 = sqlite3VdbeAddOp4(v, OP_IsUnique, baseCur+iCur+1, 0, - regR, SQLITE_INT_TO_PTR(regIdx), - P4_INT32); - sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1); + sqlite3VdbeAddOp4Int(v, OP_NoConflict, iThisCur, addrUniqueOk, + regIdx, pIdx->nKeyCol); + + /* Generate code to handle collisions */ + regR = (pIdx==pPk) ? regIdx : sqlite3GetTempRange(pParse, nPkField); + if( HasRowid(pTab) ){ + sqlite3VdbeAddOp2(v, OP_IdxRowid, iThisCur, regR); + /* Conflict only if the rowid of the existing index entry + ** is different from old-rowid */ + if( isUpdate ){ + sqlite3VdbeAddOp3(v, OP_Eq, regR, addrUniqueOk, regOldData); + } + }else{ + int x; + /* Extract the PRIMARY KEY from the end of the index entry and + ** store it in registers regR..regR+nPk-1 */ + if( (isUpdate || onError==OE_Replace) && pIdx!=pPk ){ + for(i=0; inKeyCol; i++){ + x = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[i]); + sqlite3VdbeAddOp3(v, OP_Column, iThisCur, x, regR+i); + VdbeComment((v, "%s.%s", pTab->zName, + pTab->aCol[pPk->aiColumn[i]].zName)); + } + } + if( isUpdate ){ + /* If currently processing the PRIMARY KEY of a WITHOUT ROWID + ** table, only conflict if the new PRIMARY KEY values are actually + ** different from the old. + ** + ** For a UNIQUE index, only conflict if the PRIMARY KEY values + ** of the matched index row are different from the original PRIMARY + ** KEY values of this row before the update. */ + int addrJump = sqlite3VdbeCurrentAddr(v)+pPk->nKeyCol; + int op = OP_Ne; + int regCmp = (pIdx->autoIndex==2 ? regIdx : regR); + + for(i=0; inKeyCol; i++){ + char *p4 = (char*)sqlite3LocateCollSeq(pParse, pPk->azColl[i]); + x = pPk->aiColumn[i]; + if( i==(pPk->nKeyCol-1) ){ + addrJump = addrUniqueOk; + op = OP_Eq; + } + sqlite3VdbeAddOp4(v, op, + regOldData+1+x, addrJump, regCmp+i, p4, P4_COLLSEQ + ); + } + } + } /* Generate code that executes if the new index entry is not unique */ assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail @@ -1449,30 +1567,10 @@ void sqlite3GenerateConstraintChecks( case OE_Rollback: case OE_Abort: case OE_Fail: { - int j; - StrAccum errMsg; - const char *zSep; - char *zErr; - - sqlite3StrAccumInit(&errMsg, 0, 0, 200); - errMsg.db = db; - zSep = pIdx->nColumn>1 ? "columns " : "column "; - for(j=0; jnColumn; j++){ - char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName; - sqlite3StrAccumAppend(&errMsg, zSep, -1); - zSep = ", "; - sqlite3StrAccumAppend(&errMsg, zCol, -1); - } - sqlite3StrAccumAppend(&errMsg, - pIdx->nColumn>1 ? " are not unique" : " is not unique", -1); - zErr = sqlite3StrAccumFinish(&errMsg); - sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_UNIQUE, - onError, zErr, 0); - sqlite3DbFree(errMsg.db, zErr); + sqlite3UniqueConstraint(pParse, onError, pIdx); break; } case OE_Ignore: { - assert( seenReplace==0 ); sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest); break; } @@ -1483,27 +1581,29 @@ void sqlite3GenerateConstraintChecks( if( db->flags&SQLITE_RecTriggers ){ pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0); } - sqlite3GenerateRowDelete( - pParse, pTab, baseCur, regR, 0, pTrigger, OE_Replace - ); + sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur, + regR, nPkField, 0, OE_Replace, pIdx==pPk); seenReplace = 1; break; } } - sqlite3VdbeJumpHere(v, j3); - sqlite3VdbeResolveLabel(v, addrSkipRow); - sqlite3ReleaseTempReg(pParse, regR); + sqlite3VdbeResolveLabel(v, addrUniqueOk); + sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn); + if( regR!=regIdx ) sqlite3ReleaseTempRange(pParse, regR, nPkField); + } + if( ipkTop ){ + sqlite3VdbeAddOp2(v, OP_Goto, 0, ipkTop+1); + sqlite3VdbeJumpHere(v, ipkBottom); } - if( pbMayReplace ){ - *pbMayReplace = seenReplace; - } + *pbMayReplace = seenReplace; + VdbeModuleComment((v, "END: GenCnstCks(%d)", seenReplace)); } /* ** This routine generates code to finish the INSERT or UPDATE operation ** that was started by a prior call to sqlite3GenerateConstraintChecks. -** A consecutive range of registers starting at regRowid contains the +** A consecutive range of registers starting at regNewData contains the ** rowid and the content to be inserted. ** ** The arguments to this routine should be the same as the first six @@ -1512,19 +1612,20 @@ void sqlite3GenerateConstraintChecks( void sqlite3CompleteInsertion( Parse *pParse, /* The parser context */ Table *pTab, /* the table into which we are inserting */ - int baseCur, /* Index of a read/write cursor pointing at pTab */ - int regRowid, /* Range of content */ + int iDataCur, /* Cursor of the canonical data source */ + int iIdxCur, /* First index cursor */ + int regNewData, /* Range of content */ int *aRegIdx, /* Register used by each index. 0 for unused indices */ int isUpdate, /* True for UPDATE, False for INSERT */ int appendBias, /* True if this is likely to be an append */ int useSeekResult /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */ ){ - int i; - Vdbe *v; - Index *pIdx; - u8 pik_flags; - int regData; - int regRec; + Vdbe *v; /* Prepared statements under construction */ + Index *pIdx; /* An index being inserted or updated */ + u8 pik_flags; /* flag values passed to the btree insert */ + int regData; /* Content registers (after the rowid) */ + int regRec; /* Register holding assemblied record for the table */ + int i; /* Loop counter */ v = sqlite3GetVdbe(pParse); assert( v!=0 ); @@ -1534,12 +1635,17 @@ void sqlite3CompleteInsertion( if( pIdx->pPartIdxWhere ){ sqlite3VdbeAddOp2(v, OP_IsNull, aRegIdx[i], sqlite3VdbeCurrentAddr(v)+2); } - sqlite3VdbeAddOp2(v, OP_IdxInsert, baseCur+i+1, aRegIdx[i]); - if( useSeekResult ){ - sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT); + sqlite3VdbeAddOp2(v, OP_IdxInsert, iIdxCur+i, aRegIdx[i]); + pik_flags = 0; + if( useSeekResult ) pik_flags = OPFLAG_USESEEKRESULT; + if( pIdx->autoIndex==2 && !HasRowid(pTab) ){ + assert( pParse->nested==0 ); + pik_flags |= OPFLAG_NCHANGE; } + if( pik_flags ) sqlite3VdbeChangeP5(v, pik_flags); } - regData = regRowid + 1; + if( !HasRowid(pTab) ) return; + regData = regNewData + 1; regRec = sqlite3GetTempReg(pParse); sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec); sqlite3TableAffinityStr(v, pTab); @@ -1556,7 +1662,7 @@ void sqlite3CompleteInsertion( if( useSeekResult ){ pik_flags |= OPFLAG_USESEEKRESULT; } - sqlite3VdbeAddOp3(v, OP_Insert, baseCur, regRec, regRowid); + sqlite3VdbeAddOp3(v, OP_Insert, iDataCur, regRec, regNewData); if( !pParse->nested ){ sqlite3VdbeChangeP4(v, -1, (char *)pTab, P4_TABLE); } @@ -1564,39 +1670,63 @@ void sqlite3CompleteInsertion( } /* -** Generate code that will open cursors for a table and for all -** indices of that table. The "baseCur" parameter is the cursor number used -** for the table. Indices are opened on subsequent cursors. +** Allocate cursors for the pTab table and all its indices and generate +** code to open and initialized those cursors. ** -** Return the number of indices on the table. +** The cursor for the object that contains the complete data (normally +** the table itself, but the PRIMARY KEY index in the case of a WITHOUT +** ROWID table) is returned in *piDataCur. The first index cursor is +** returned in *piIdxCur. The number of indices is returned. +** +** Use iBase as the first cursor (either the *piDataCur for rowid tables +** or the first index for WITHOUT ROWID tables) if it is non-negative. +** If iBase is negative, then allocate the next available cursor. +** +** For a rowid table, *piDataCur will be exactly one less than *piIdxCur. +** For a WITHOUT ROWID table, *piDataCur will be somewhere in the range +** of *piIdxCurs, depending on where the PRIMARY KEY index appears on the +** pTab->pIndex list. */ int sqlite3OpenTableAndIndices( Parse *pParse, /* Parsing context */ Table *pTab, /* Table to be opened */ - int baseCur, /* Cursor number assigned to the table */ - int op /* OP_OpenRead or OP_OpenWrite */ + int op, /* OP_OpenRead or OP_OpenWrite */ + int iBase, /* Use this for the table cursor, if there is one */ + int *piDataCur, /* Write the database source cursor number here */ + int *piIdxCur /* Write the first index cursor number here */ ){ int i; int iDb; Index *pIdx; Vdbe *v; - if( IsVirtual(pTab) ) return 0; + assert( op==OP_OpenRead || op==OP_OpenWrite ); + if( IsVirtual(pTab) ){ + *piDataCur = 0; + *piIdxCur = 1; + return 0; + } iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema); v = sqlite3GetVdbe(pParse); assert( v!=0 ); - sqlite3OpenTable(pParse, baseCur, iDb, pTab, op); - for(i=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){ - KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx); + if( iBase<0 ) iBase = pParse->nTab; + if( HasRowid(pTab) ){ + *piDataCur = iBase++; + sqlite3OpenTable(pParse, *piDataCur, iDb, pTab, op); + }else{ + sqlite3TableLock(pParse, iDb, pTab->tnum, op==OP_OpenWrite, pTab->zName); + } + *piIdxCur = iBase; + for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){ + int iIdxCur = iBase++; assert( pIdx->pSchema==pTab->pSchema ); - sqlite3VdbeAddOp4(v, op, i+baseCur, pIdx->tnum, iDb, - (char*)pKey, P4_KEYINFO_HANDOFF); + if( pIdx->autoIndex==2 && !HasRowid(pTab) ) *piDataCur = iIdxCur; + sqlite3VdbeAddOp3(v, op, iIdxCur, pIdx->tnum, iDb); + sqlite3VdbeSetP4KeyInfo(pParse, pIdx); VdbeComment((v, "%s", pIdx->zName)); } - if( pParse->nTabnTab = baseCur+i; - } - return i-1; + if( iBase>pParse->nTab ) pParse->nTab = iBase; + return i; } @@ -1641,13 +1771,13 @@ static int xferCompatibleIndex(Index *pDest, Index *pSrc){ int i; assert( pDest && pSrc ); assert( pDest->pTable!=pSrc->pTable ); - if( pDest->nColumn!=pSrc->nColumn ){ + if( pDest->nKeyCol!=pSrc->nKeyCol ){ return 0; /* Different number of columns */ } if( pDest->onError!=pSrc->onError ){ return 0; /* Different conflict resolution strategies */ } - for(i=0; inColumn; i++){ + for(i=0; inKeyCol; i++){ if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){ return 0; /* Different columns indexed */ } @@ -1706,10 +1836,9 @@ static int xferOptimization( int iDbSrc; /* The database of pSrc */ int iSrc, iDest; /* Cursors from source and destination */ int addr1, addr2; /* Loop addresses */ - int emptyDestTest; /* Address of test for empty pDest */ - int emptySrcTest; /* Address of test for empty pSrc */ + int emptyDestTest = 0; /* Address of test for empty pDest */ + int emptySrcTest = 0; /* Address of test for empty pSrc */ Vdbe *v; /* The VDBE we are building */ - KeyInfo *pKey; /* Key information for an index */ int regAutoinc; /* Memory register used by AUTOINC */ int destHasUniqueIdx = 0; /* True if pDest has a UNIQUE index */ int regData, regRowid; /* Registers holding data and rowid */ @@ -1779,6 +1908,9 @@ static int xferOptimization( if( pSrc==pDest ){ return 0; /* tab1 and tab2 may not be the same table */ } + if( HasRowid(pDest)!=HasRowid(pSrc) ){ + return 0; /* source and destination must both be WITHOUT ROWID or not */ + } #ifndef SQLITE_OMIT_VIRTUALTABLE if( pSrc->tabFlags & TF_Virtual ){ return 0; /* tab2 must not be a virtual table */ @@ -1849,7 +1981,10 @@ static int xferOptimization( iSrc = pParse->nTab++; iDest = pParse->nTab++; regAutoinc = autoIncBegin(pParse, iDbDest, pDest); + regData = sqlite3GetTempReg(pParse); + regRowid = sqlite3GetTempReg(pParse); sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite); + assert( HasRowid(pDest) || destHasUniqueIdx ); if( (pDest->iPKey<0 && pDest->pIndex!=0) /* (1) */ || destHasUniqueIdx /* (2) */ || (onError!=OE_Abort && onError!=OE_Rollback) /* (3) */ @@ -1871,45 +2006,43 @@ static int xferOptimization( addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0); emptyDestTest = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0); sqlite3VdbeJumpHere(v, addr1); - }else{ - emptyDestTest = 0; } - sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead); - emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); - regData = sqlite3GetTempReg(pParse); - regRowid = sqlite3GetTempReg(pParse); - if( pDest->iPKey>=0 ){ - addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid); - addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid); - sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_PRIMARYKEY, - onError, "PRIMARY KEY must be unique", P4_STATIC); - sqlite3VdbeJumpHere(v, addr2); - autoIncStep(pParse, regAutoinc, regRowid); - }else if( pDest->pIndex==0 ){ - addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid); + if( HasRowid(pSrc) ){ + sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead); + emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); + if( pDest->iPKey>=0 ){ + addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid); + addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid); + sqlite3RowidConstraint(pParse, onError, pDest); + sqlite3VdbeJumpHere(v, addr2); + autoIncStep(pParse, regAutoinc, regRowid); + }else if( pDest->pIndex==0 ){ + addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid); + }else{ + addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid); + assert( (pDest->tabFlags & TF_Autoincrement)==0 ); + } + sqlite3VdbeAddOp2(v, OP_RowData, iSrc, regData); + sqlite3VdbeAddOp3(v, OP_Insert, iDest, regData, regRowid); + sqlite3VdbeChangeP5(v, OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND); + sqlite3VdbeChangeP4(v, -1, (char*)pDest, P4_TABLE); + sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1); + sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0); + sqlite3VdbeAddOp2(v, OP_Close, iDest, 0); }else{ - addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid); - assert( (pDest->tabFlags & TF_Autoincrement)==0 ); + sqlite3TableLock(pParse, iDbDest, pDest->tnum, 1, pDest->zName); + sqlite3TableLock(pParse, iDbSrc, pSrc->tnum, 0, pSrc->zName); } - sqlite3VdbeAddOp2(v, OP_RowData, iSrc, regData); - sqlite3VdbeAddOp3(v, OP_Insert, iDest, regData, regRowid); - sqlite3VdbeChangeP5(v, OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND); - sqlite3VdbeChangeP4(v, -1, (char *)pDest, P4_TABLE); - sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1); for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){ for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){ if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break; } assert( pSrcIdx ); - sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0); - sqlite3VdbeAddOp2(v, OP_Close, iDest, 0); - pKey = sqlite3IndexKeyinfo(pParse, pSrcIdx); - sqlite3VdbeAddOp4(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc, - (char*)pKey, P4_KEYINFO_HANDOFF); + sqlite3VdbeAddOp3(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc); + sqlite3VdbeSetP4KeyInfo(pParse, pSrcIdx); VdbeComment((v, "%s", pSrcIdx->zName)); - pKey = sqlite3IndexKeyinfo(pParse, pDestIdx); - sqlite3VdbeAddOp4(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest, - (char*)pKey, P4_KEYINFO_HANDOFF); + sqlite3VdbeAddOp3(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest); + sqlite3VdbeSetP4KeyInfo(pParse, pDestIdx); sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR); VdbeComment((v, "%s", pDestIdx->zName)); addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); @@ -1917,12 +2050,12 @@ static int xferOptimization( sqlite3VdbeAddOp3(v, OP_IdxInsert, iDest, regData, 1); sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1); sqlite3VdbeJumpHere(v, addr1); + sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0); + sqlite3VdbeAddOp2(v, OP_Close, iDest, 0); } sqlite3VdbeJumpHere(v, emptySrcTest); sqlite3ReleaseTempReg(pParse, regRowid); sqlite3ReleaseTempReg(pParse, regData); - sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0); - sqlite3VdbeAddOp2(v, OP_Close, iDest, 0); if( emptyDestTest ){ sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0); sqlite3VdbeJumpHere(v, emptyDestTest); diff --git a/src/main.c b/src/main.c index a85dfa5eb4..653c8f1f1c 100644 --- a/src/main.c +++ b/src/main.c @@ -1135,6 +1135,7 @@ const char *sqlite3ErrName(int rc){ case SQLITE_CONSTRAINT_VTAB: zName = "SQLITE_CONSTRAINT_VTAB"; break; case SQLITE_CONSTRAINT_FUNCTION: zName = "SQLITE_CONSTRAINT_FUNCTION"; break; + case SQLITE_CONSTRAINT_ROWID: zName = "SQLITE_CONSTRAINT_ROWID"; break; case SQLITE_MISMATCH: zName = "SQLITE_MISMATCH"; break; case SQLITE_MISUSE: zName = "SQLITE_MISUSE"; break; case SQLITE_NOLFS: zName = "SQLITE_NOLFS"; break; @@ -1971,6 +1972,32 @@ const char *sqlite3_errstr(int rc){ return sqlite3ErrStr(rc); } +/* +** Invalidate all cached KeyInfo objects for database connection "db" +*/ +static void invalidateCachedKeyInfo(sqlite3 *db){ + Db *pDb; /* A single database */ + int iDb; /* The database index number */ + HashElem *k; /* For looping over tables in pDb */ + Table *pTab; /* A table in the database */ + Index *pIdx; /* Each index */ + + for(iDb=0, pDb=db->aDb; iDbnDb; iDb++, pDb++){ + if( pDb->pBt==0 ) continue; + sqlite3BtreeEnter(pDb->pBt); + for(k=sqliteHashFirst(&pDb->pSchema->tblHash); k; k=sqliteHashNext(k)){ + pTab = (Table*)sqliteHashData(k); + for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ + if( pIdx->pKeyInfo && pIdx->pKeyInfo->db==db ){ + sqlite3KeyInfoUnref(pIdx->pKeyInfo); + pIdx->pKeyInfo = 0; + } + } + } + sqlite3BtreeLeave(pDb->pBt); + } +} + /* ** Create a new collating function for database "db". The name is zName ** and the encoding is enc. @@ -2015,6 +2042,7 @@ static int createCollation( return SQLITE_BUSY; } sqlite3ExpirePreparedStatements(db); + invalidateCachedKeyInfo(db); /* If collation sequence pColl was created directly by a call to ** sqlite3_create_collation, and not generated by synthCollSeq(), diff --git a/src/os_unix.c b/src/os_unix.c index cd8cec0046..501b1b769d 100644 --- a/src/os_unix.c +++ b/src/os_unix.c @@ -1890,7 +1890,9 @@ end_unlock: ** the requested locking level, this routine is a no-op. */ static int unixUnlock(sqlite3_file *id, int eFileLock){ +#if SQLITE_MAX_MMAP_SIZE>0 assert( eFileLock==SHARED_LOCK || ((unixFile *)id)->nFetchOut==0 ); +#endif return posixUnlock(id, eFileLock, 0); } diff --git a/src/os_win.c b/src/os_win.c index c6c567c00c..a2f5513a2b 100644 --- a/src/os_win.c +++ b/src/os_win.c @@ -59,6 +59,13 @@ must be defined." #endif +/* +** This constant should already be defined (in the "WinDef.h" SDK file). +*/ +#ifndef MAX_PATH +# define MAX_PATH (260) +#endif + /* ** Maximum pathname length (in chars) for Win32. This should normally be ** MAX_PATH. @@ -67,17 +74,24 @@ # define SQLITE_WIN32_MAX_PATH_CHARS (MAX_PATH) #endif +/* +** This constant should already be defined (in the "WinNT.h" SDK file). +*/ +#ifndef UNICODE_STRING_MAX_CHARS +# define UNICODE_STRING_MAX_CHARS (32767) +#endif + /* ** Maximum pathname length (in chars) for WinNT. This should normally be -** 32767. +** UNICODE_STRING_MAX_CHARS. */ #ifndef SQLITE_WINNT_MAX_PATH_CHARS -# define SQLITE_WINNT_MAX_PATH_CHARS (32767) +# define SQLITE_WINNT_MAX_PATH_CHARS (UNICODE_STRING_MAX_CHARS) #endif /* ** Maximum pathname length (in bytes) for Win32. The MAX_PATH macro is in -** characters, so we allocate 3 bytes per character assuming worst-case of +** characters, so we allocate 4 bytes per character assuming worst-case of ** 4-bytes-per-character for UTF8. */ #ifndef SQLITE_WIN32_MAX_PATH_BYTES @@ -86,7 +100,7 @@ /* ** Maximum pathname length (in bytes) for WinNT. This should normally be -** 32767 * sizeof(WCHAR). +** UNICODE_STRING_MAX_CHARS * sizeof(WCHAR). */ #ifndef SQLITE_WINNT_MAX_PATH_BYTES # define SQLITE_WINNT_MAX_PATH_BYTES \ @@ -117,14 +131,10 @@ #endif /* -** Returns the string that should be used as the directory separator. +** Returns the character that should be used as the directory separator. */ -#ifndef winGetDirDep -# ifdef __CYGWIN__ -# define winGetDirDep() "/" -# else -# define winGetDirDep() "\\" -# endif +#ifndef winGetDirSep +# define winGetDirSep() '\\' #endif /* @@ -316,30 +326,41 @@ struct winFile { typedef struct winMemData winMemData; struct winMemData { #ifndef NDEBUG - u32 magic; /* Magic number to detect structure corruption. */ + u32 magic1; /* Magic number to detect structure corruption. */ #endif HANDLE hHeap; /* The handle to our heap. */ BOOL bOwned; /* Do we own the heap (i.e. destroy it on shutdown)? */ +#ifndef NDEBUG + u32 magic2; /* Magic number to detect structure corruption. */ +#endif }; #ifndef NDEBUG -#define WINMEM_MAGIC 0x42b2830b +#define WINMEM_MAGIC1 0x42b2830b +#define WINMEM_MAGIC2 0xbd4d7cf4 #endif static struct winMemData win_mem_data = { #ifndef NDEBUG - WINMEM_MAGIC, + WINMEM_MAGIC1, #endif NULL, FALSE +#ifndef NDEBUG + ,WINMEM_MAGIC2 +#endif }; #ifndef NDEBUG -#define winMemAssertMagic() assert( win_mem_data.magic==WINMEM_MAGIC ) +#define winMemAssertMagic1() assert( win_mem_data.magic1==WINMEM_MAGIC1 ) +#define winMemAssertMagic2() assert( win_mem_data.magic2==WINMEM_MAGIC2 ) +#define winMemAssertMagic() winMemAssertMagic1(); winMemAssertMagic2(); #else #define winMemAssertMagic() #endif -#define winMemGetHeap() win_mem_data.hHeap +#define winMemGetDataPtr() &win_mem_data +#define winMemGetHeap() win_mem_data.hHeap +#define winMemGetOwned() win_mem_data.bOwned static void *winMemMalloc(int nBytes); static void winMemFree(void *pPrior); @@ -736,13 +757,21 @@ static struct win_syscall { #define osHeapValidate ((BOOL(WINAPI*)(HANDLE,DWORD, \ LPCVOID))aSyscall[42].pCurrent) +#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT + { "HeapCompact", (SYSCALL)HeapCompact, 0 }, +#else + { "HeapCompact", (SYSCALL)0, 0 }, +#endif + +#define osHeapCompact ((UINT(WINAPI*)(HANDLE,DWORD))aSyscall[43].pCurrent) + #if defined(SQLITE_WIN32_HAS_ANSI) && !defined(SQLITE_OMIT_LOAD_EXTENSION) { "LoadLibraryA", (SYSCALL)LoadLibraryA, 0 }, #else { "LoadLibraryA", (SYSCALL)0, 0 }, #endif -#define osLoadLibraryA ((HMODULE(WINAPI*)(LPCSTR))aSyscall[43].pCurrent) +#define osLoadLibraryA ((HMODULE(WINAPI*)(LPCSTR))aSyscall[44].pCurrent) #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \ !defined(SQLITE_OMIT_LOAD_EXTENSION) @@ -751,7 +780,7 @@ static struct win_syscall { { "LoadLibraryW", (SYSCALL)0, 0 }, #endif -#define osLoadLibraryW ((HMODULE(WINAPI*)(LPCWSTR))aSyscall[44].pCurrent) +#define osLoadLibraryW ((HMODULE(WINAPI*)(LPCWSTR))aSyscall[45].pCurrent) #if !SQLITE_OS_WINRT { "LocalFree", (SYSCALL)LocalFree, 0 }, @@ -759,7 +788,7 @@ static struct win_syscall { { "LocalFree", (SYSCALL)0, 0 }, #endif -#define osLocalFree ((HLOCAL(WINAPI*)(HLOCAL))aSyscall[45].pCurrent) +#define osLocalFree ((HLOCAL(WINAPI*)(HLOCAL))aSyscall[46].pCurrent) #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT { "LockFile", (SYSCALL)LockFile, 0 }, @@ -769,7 +798,7 @@ static struct win_syscall { #ifndef osLockFile #define osLockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \ - DWORD))aSyscall[46].pCurrent) + DWORD))aSyscall[47].pCurrent) #endif #if !SQLITE_OS_WINCE @@ -780,7 +809,7 @@ static struct win_syscall { #ifndef osLockFileEx #define osLockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD,DWORD, \ - LPOVERLAPPED))aSyscall[47].pCurrent) + LPOVERLAPPED))aSyscall[48].pCurrent) #endif #if SQLITE_OS_WINCE || (!SQLITE_OS_WINRT && !defined(SQLITE_OMIT_WAL)) @@ -790,26 +819,26 @@ static struct win_syscall { #endif #define osMapViewOfFile ((LPVOID(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \ - SIZE_T))aSyscall[48].pCurrent) + SIZE_T))aSyscall[49].pCurrent) { "MultiByteToWideChar", (SYSCALL)MultiByteToWideChar, 0 }, #define osMultiByteToWideChar ((int(WINAPI*)(UINT,DWORD,LPCSTR,int,LPWSTR, \ - int))aSyscall[49].pCurrent) + int))aSyscall[50].pCurrent) { "QueryPerformanceCounter", (SYSCALL)QueryPerformanceCounter, 0 }, #define osQueryPerformanceCounter ((BOOL(WINAPI*)( \ - LARGE_INTEGER*))aSyscall[50].pCurrent) + LARGE_INTEGER*))aSyscall[51].pCurrent) { "ReadFile", (SYSCALL)ReadFile, 0 }, #define osReadFile ((BOOL(WINAPI*)(HANDLE,LPVOID,DWORD,LPDWORD, \ - LPOVERLAPPED))aSyscall[51].pCurrent) + LPOVERLAPPED))aSyscall[52].pCurrent) { "SetEndOfFile", (SYSCALL)SetEndOfFile, 0 }, -#define osSetEndOfFile ((BOOL(WINAPI*)(HANDLE))aSyscall[52].pCurrent) +#define osSetEndOfFile ((BOOL(WINAPI*)(HANDLE))aSyscall[53].pCurrent) #if !SQLITE_OS_WINRT { "SetFilePointer", (SYSCALL)SetFilePointer, 0 }, @@ -818,7 +847,7 @@ static struct win_syscall { #endif #define osSetFilePointer ((DWORD(WINAPI*)(HANDLE,LONG,PLONG, \ - DWORD))aSyscall[53].pCurrent) + DWORD))aSyscall[54].pCurrent) #if !SQLITE_OS_WINRT { "Sleep", (SYSCALL)Sleep, 0 }, @@ -826,12 +855,12 @@ static struct win_syscall { { "Sleep", (SYSCALL)0, 0 }, #endif -#define osSleep ((VOID(WINAPI*)(DWORD))aSyscall[54].pCurrent) +#define osSleep ((VOID(WINAPI*)(DWORD))aSyscall[55].pCurrent) { "SystemTimeToFileTime", (SYSCALL)SystemTimeToFileTime, 0 }, #define osSystemTimeToFileTime ((BOOL(WINAPI*)(CONST SYSTEMTIME*, \ - LPFILETIME))aSyscall[55].pCurrent) + LPFILETIME))aSyscall[56].pCurrent) #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT { "UnlockFile", (SYSCALL)UnlockFile, 0 }, @@ -841,7 +870,7 @@ static struct win_syscall { #ifndef osUnlockFile #define osUnlockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \ - DWORD))aSyscall[56].pCurrent) + DWORD))aSyscall[57].pCurrent) #endif #if !SQLITE_OS_WINCE @@ -851,7 +880,7 @@ static struct win_syscall { #endif #define osUnlockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \ - LPOVERLAPPED))aSyscall[57].pCurrent) + LPOVERLAPPED))aSyscall[58].pCurrent) #if SQLITE_OS_WINCE || !defined(SQLITE_OMIT_WAL) { "UnmapViewOfFile", (SYSCALL)UnmapViewOfFile, 0 }, @@ -859,17 +888,17 @@ static struct win_syscall { { "UnmapViewOfFile", (SYSCALL)0, 0 }, #endif -#define osUnmapViewOfFile ((BOOL(WINAPI*)(LPCVOID))aSyscall[58].pCurrent) +#define osUnmapViewOfFile ((BOOL(WINAPI*)(LPCVOID))aSyscall[59].pCurrent) { "WideCharToMultiByte", (SYSCALL)WideCharToMultiByte, 0 }, #define osWideCharToMultiByte ((int(WINAPI*)(UINT,DWORD,LPCWSTR,int,LPSTR,int, \ - LPCSTR,LPBOOL))aSyscall[59].pCurrent) + LPCSTR,LPBOOL))aSyscall[60].pCurrent) { "WriteFile", (SYSCALL)WriteFile, 0 }, #define osWriteFile ((BOOL(WINAPI*)(HANDLE,LPCVOID,DWORD,LPDWORD, \ - LPOVERLAPPED))aSyscall[60].pCurrent) + LPOVERLAPPED))aSyscall[61].pCurrent) #if SQLITE_OS_WINRT { "CreateEventExW", (SYSCALL)CreateEventExW, 0 }, @@ -878,7 +907,7 @@ static struct win_syscall { #endif #define osCreateEventExW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,LPCWSTR, \ - DWORD,DWORD))aSyscall[61].pCurrent) + DWORD,DWORD))aSyscall[62].pCurrent) #if !SQLITE_OS_WINRT { "WaitForSingleObject", (SYSCALL)WaitForSingleObject, 0 }, @@ -887,7 +916,7 @@ static struct win_syscall { #endif #define osWaitForSingleObject ((DWORD(WINAPI*)(HANDLE, \ - DWORD))aSyscall[62].pCurrent) + DWORD))aSyscall[63].pCurrent) #if SQLITE_OS_WINRT { "WaitForSingleObjectEx", (SYSCALL)WaitForSingleObjectEx, 0 }, @@ -896,7 +925,7 @@ static struct win_syscall { #endif #define osWaitForSingleObjectEx ((DWORD(WINAPI*)(HANDLE,DWORD, \ - BOOL))aSyscall[63].pCurrent) + BOOL))aSyscall[64].pCurrent) #if SQLITE_OS_WINRT { "SetFilePointerEx", (SYSCALL)SetFilePointerEx, 0 }, @@ -905,7 +934,7 @@ static struct win_syscall { #endif #define osSetFilePointerEx ((BOOL(WINAPI*)(HANDLE,LARGE_INTEGER, \ - PLARGE_INTEGER,DWORD))aSyscall[64].pCurrent) + PLARGE_INTEGER,DWORD))aSyscall[65].pCurrent) #if SQLITE_OS_WINRT { "GetFileInformationByHandleEx", (SYSCALL)GetFileInformationByHandleEx, 0 }, @@ -914,7 +943,7 @@ static struct win_syscall { #endif #define osGetFileInformationByHandleEx ((BOOL(WINAPI*)(HANDLE, \ - FILE_INFO_BY_HANDLE_CLASS,LPVOID,DWORD))aSyscall[65].pCurrent) + FILE_INFO_BY_HANDLE_CLASS,LPVOID,DWORD))aSyscall[66].pCurrent) #if SQLITE_OS_WINRT && !defined(SQLITE_OMIT_WAL) { "MapViewOfFileFromApp", (SYSCALL)MapViewOfFileFromApp, 0 }, @@ -923,7 +952,7 @@ static struct win_syscall { #endif #define osMapViewOfFileFromApp ((LPVOID(WINAPI*)(HANDLE,ULONG,ULONG64, \ - SIZE_T))aSyscall[66].pCurrent) + SIZE_T))aSyscall[67].pCurrent) #if SQLITE_OS_WINRT { "CreateFile2", (SYSCALL)CreateFile2, 0 }, @@ -932,7 +961,7 @@ static struct win_syscall { #endif #define osCreateFile2 ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD,DWORD, \ - LPCREATEFILE2_EXTENDED_PARAMETERS))aSyscall[67].pCurrent) + LPCREATEFILE2_EXTENDED_PARAMETERS))aSyscall[68].pCurrent) #if SQLITE_OS_WINRT && !defined(SQLITE_OMIT_LOAD_EXTENSION) { "LoadPackagedLibrary", (SYSCALL)LoadPackagedLibrary, 0 }, @@ -941,7 +970,7 @@ static struct win_syscall { #endif #define osLoadPackagedLibrary ((HMODULE(WINAPI*)(LPCWSTR, \ - DWORD))aSyscall[68].pCurrent) + DWORD))aSyscall[69].pCurrent) #if SQLITE_OS_WINRT { "GetTickCount64", (SYSCALL)GetTickCount64, 0 }, @@ -949,7 +978,7 @@ static struct win_syscall { { "GetTickCount64", (SYSCALL)0, 0 }, #endif -#define osGetTickCount64 ((ULONGLONG(WINAPI*)(VOID))aSyscall[69].pCurrent) +#define osGetTickCount64 ((ULONGLONG(WINAPI*)(VOID))aSyscall[70].pCurrent) #if SQLITE_OS_WINRT { "GetNativeSystemInfo", (SYSCALL)GetNativeSystemInfo, 0 }, @@ -958,7 +987,7 @@ static struct win_syscall { #endif #define osGetNativeSystemInfo ((VOID(WINAPI*)( \ - LPSYSTEM_INFO))aSyscall[70].pCurrent) + LPSYSTEM_INFO))aSyscall[71].pCurrent) #if defined(SQLITE_WIN32_HAS_ANSI) { "OutputDebugStringA", (SYSCALL)OutputDebugStringA, 0 }, @@ -966,7 +995,7 @@ static struct win_syscall { { "OutputDebugStringA", (SYSCALL)0, 0 }, #endif -#define osOutputDebugStringA ((VOID(WINAPI*)(LPCSTR))aSyscall[71].pCurrent) +#define osOutputDebugStringA ((VOID(WINAPI*)(LPCSTR))aSyscall[72].pCurrent) #if defined(SQLITE_WIN32_HAS_WIDE) { "OutputDebugStringW", (SYSCALL)OutputDebugStringW, 0 }, @@ -974,11 +1003,11 @@ static struct win_syscall { { "OutputDebugStringW", (SYSCALL)0, 0 }, #endif -#define osOutputDebugStringW ((VOID(WINAPI*)(LPCWSTR))aSyscall[72].pCurrent) +#define osOutputDebugStringW ((VOID(WINAPI*)(LPCWSTR))aSyscall[73].pCurrent) { "GetProcessHeap", (SYSCALL)GetProcessHeap, 0 }, -#define osGetProcessHeap ((HANDLE(WINAPI*)(VOID))aSyscall[73].pCurrent) +#define osGetProcessHeap ((HANDLE(WINAPI*)(VOID))aSyscall[74].pCurrent) #if SQLITE_OS_WINRT && !defined(SQLITE_OMIT_WAL) { "CreateFileMappingFromApp", (SYSCALL)CreateFileMappingFromApp, 0 }, @@ -987,7 +1016,7 @@ static struct win_syscall { #endif #define osCreateFileMappingFromApp ((HANDLE(WINAPI*)(HANDLE, \ - LPSECURITY_ATTRIBUTES,ULONG,ULONG64,LPCWSTR))aSyscall[74].pCurrent) + LPSECURITY_ATTRIBUTES,ULONG,ULONG64,LPCWSTR))aSyscall[75].pCurrent) }; /* End of the overrideable system calls */ @@ -1074,6 +1103,94 @@ static const char *winNextSystemCall(sqlite3_vfs *p, const char *zName){ return 0; } +#ifdef SQLITE_WIN32_MALLOC +/* +** If a Win32 native heap has been configured, this function will attempt to +** compact it. Upon success, SQLITE_OK will be returned. Upon failure, one +** of SQLITE_NOMEM, SQLITE_ERROR, or SQLITE_NOTFOUND will be returned. The +** "pnLargest" argument, if non-zero, will be used to return the size of the +** largest committed free block in the heap, in bytes. +*/ +int sqlite3_win32_compact_heap(LPUINT pnLargest){ + int rc = SQLITE_OK; + UINT nLargest = 0; + HANDLE hHeap; + + winMemAssertMagic(); + hHeap = winMemGetHeap(); + assert( hHeap!=0 ); + assert( hHeap!=INVALID_HANDLE_VALUE ); +#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE) + assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) ); +#endif +#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT + if( (nLargest=osHeapCompact(hHeap, SQLITE_WIN32_HEAP_FLAGS))==0 ){ + DWORD lastErrno = osGetLastError(); + if( lastErrno==NO_ERROR ){ + sqlite3_log(SQLITE_NOMEM, "failed to HeapCompact (no space), heap=%p", + (void*)hHeap); + rc = SQLITE_NOMEM; + }else{ + sqlite3_log(SQLITE_ERROR, "failed to HeapCompact (%lu), heap=%p", + osGetLastError(), (void*)hHeap); + rc = SQLITE_ERROR; + } + } +#else + sqlite3_log(SQLITE_NOTFOUND, "failed to HeapCompact, heap=%p", + (void*)hHeap); + rc = SQLITE_NOTFOUND; +#endif + if( pnLargest ) *pnLargest = nLargest; + return rc; +} + +/* +** If a Win32 native heap has been configured, this function will attempt to +** destroy and recreate it. If the Win32 native heap is not isolated and/or +** the sqlite3_memory_used() function does not return zero, SQLITE_BUSY will +** be returned and no changes will be made to the Win32 native heap. +*/ +int sqlite3_win32_reset_heap(){ + int rc; + MUTEX_LOGIC( sqlite3_mutex *pMaster; ) /* The main static mutex */ + MUTEX_LOGIC( sqlite3_mutex *pMem; ) /* The memsys static mutex */ + MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); ) + MUTEX_LOGIC( pMem = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM); ) + sqlite3_mutex_enter(pMaster); + sqlite3_mutex_enter(pMem); + winMemAssertMagic(); + if( winMemGetHeap()!=NULL && winMemGetOwned() && sqlite3_memory_used()==0 ){ + /* + ** At this point, there should be no outstanding memory allocations on + ** the heap. Also, since both the master and memsys locks are currently + ** being held by us, no other function (i.e. from another thread) should + ** be able to even access the heap. Attempt to destroy and recreate our + ** isolated Win32 native heap now. + */ + assert( winMemGetHeap()!=NULL ); + assert( winMemGetOwned() ); + assert( sqlite3_memory_used()==0 ); + winMemShutdown(winMemGetDataPtr()); + assert( winMemGetHeap()==NULL ); + assert( !winMemGetOwned() ); + assert( sqlite3_memory_used()==0 ); + rc = winMemInit(winMemGetDataPtr()); + assert( rc!=SQLITE_OK || winMemGetHeap()!=NULL ); + assert( rc!=SQLITE_OK || winMemGetOwned() ); + assert( rc!=SQLITE_OK || sqlite3_memory_used()==0 ); + }else{ + /* + ** The Win32 native heap cannot be modified because it may be in use. + */ + rc = SQLITE_BUSY; + } + sqlite3_mutex_leave(pMem); + sqlite3_mutex_leave(pMaster); + return rc; +} +#endif /* SQLITE_WIN32_MALLOC */ + /* ** This function outputs the specified (ANSI) string to the Win32 debugger ** (if available). @@ -1182,7 +1299,7 @@ static void *winMemMalloc(int nBytes){ assert( hHeap!=0 ); assert( hHeap!=INVALID_HANDLE_VALUE ); #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE) - assert ( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) ); + assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) ); #endif assert( nBytes>=0 ); p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes); @@ -1204,7 +1321,7 @@ static void winMemFree(void *pPrior){ assert( hHeap!=0 ); assert( hHeap!=INVALID_HANDLE_VALUE ); #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE) - assert ( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) ); + assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) ); #endif if( !pPrior ) return; /* Passing NULL to HeapFree is undefined. */ if( !osHeapFree(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) ){ @@ -1225,7 +1342,7 @@ static void *winMemRealloc(void *pPrior, int nBytes){ assert( hHeap!=0 ); assert( hHeap!=INVALID_HANDLE_VALUE ); #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE) - assert ( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) ); + assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) ); #endif assert( nBytes>=0 ); if( !pPrior ){ @@ -1253,7 +1370,7 @@ static int winMemSize(void *p){ assert( hHeap!=0 ); assert( hHeap!=INVALID_HANDLE_VALUE ); #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE) - assert ( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) ); + assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, p) ); #endif if( !p ) return 0; n = osHeapSize(hHeap, SQLITE_WIN32_HEAP_FLAGS, p); @@ -1279,7 +1396,8 @@ static int winMemInit(void *pAppData){ winMemData *pWinMemData = (winMemData *)pAppData; if( !pWinMemData ) return SQLITE_ERROR; - assert( pWinMemData->magic==WINMEM_MAGIC ); + assert( pWinMemData->magic1==WINMEM_MAGIC1 ); + assert( pWinMemData->magic2==WINMEM_MAGIC2 ); #if !SQLITE_OS_WINRT && SQLITE_WIN32_HEAP_CREATE if( !pWinMemData->hHeap ){ @@ -1321,6 +1439,9 @@ static void winMemShutdown(void *pAppData){ winMemData *pWinMemData = (winMemData *)pAppData; if( !pWinMemData ) return; + assert( pWinMemData->magic1==WINMEM_MAGIC1 ); + assert( pWinMemData->magic2==WINMEM_MAGIC2 ); + if( pWinMemData->hHeap ){ assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE ); #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE) @@ -3990,12 +4111,21 @@ static void *winConvertFromUtf8Filename(const char *zFilename){ /* ** This function returns non-zero if the specified UTF-8 string buffer -** ends with a directory separator character. +** ends with a directory separator character or one was successfully +** added to it. */ -static int winEndsInDirSep(char *zBuf){ +static int winMakeEndInDirSep(int nBuf, char *zBuf){ if( zBuf ){ int nLen = sqlite3Strlen30(zBuf); - return nLen>0 && winIsDirSep(zBuf[nLen-1]); + if( nLen>0 ){ + if( winIsDirSep(zBuf[nLen-1]) ){ + return 1; + }else if( nLen+1mxPathname; - zBuf = sqlite3MallocZero( nBuf+2 ); + nMax = pVfs->mxPathname; nBuf = nMax + 2; + zBuf = sqlite3MallocZero( nBuf ); if( !zBuf ){ OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n")); return SQLITE_IOERR_NOMEM; @@ -4033,11 +4164,21 @@ static int winGetTempname(sqlite3_vfs *pVfs, char **pzBuf){ ** has been explicitly set by the application; otherwise, use the one ** configured by the operating system. */ - assert( nBuf>30 ); + nDir = nMax - (nPre + 15); + assert( nDir>0 ); if( sqlite3_temp_directory ){ - sqlite3_snprintf(nBuf-30, zBuf, "%s%s", sqlite3_temp_directory, - winEndsInDirSep(sqlite3_temp_directory) ? "" : - winGetDirDep()); + int nDirLen = sqlite3Strlen30(sqlite3_temp_directory); + if( nDirLen>0 ){ + if( !winIsDirSep(sqlite3_temp_directory[nDirLen-1]) ){ + nDirLen++; + } + if( nDirLen>nDir ){ + sqlite3_free(zBuf); + OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n")); + return winLogError(SQLITE_ERROR, 0, "winGetTempname1", 0); + } + sqlite3_snprintf(nMax, zBuf, "%s", sqlite3_temp_directory); + } } #if defined(__CYGWIN__) else{ @@ -4066,8 +4207,8 @@ static int winGetTempname(sqlite3_vfs *pVfs, char **pzBuf){ if( zDir==0 ) continue; /* If the path starts with a drive letter followed by the colon ** character, assume it is already a native Win32 path; otherwise, - ** it must be converted to a native Win32 path prior via the Cygwin - ** API prior to using it. + ** it must be converted to a native Win32 path via the Cygwin API + ** prior to using it. */ if( winIsDriveLetterAndColon(zDir) ){ zConverted = winConvertFromUtf8Filename(zDir); @@ -4077,13 +4218,13 @@ static int winGetTempname(sqlite3_vfs *pVfs, char **pzBuf){ return SQLITE_IOERR_NOMEM; } if( winIsDir(zConverted) ){ - sqlite3_snprintf(nBuf-30, zBuf, "%s", zDir); + sqlite3_snprintf(nMax, zBuf, "%s", zDir); sqlite3_free(zConverted); break; } sqlite3_free(zConverted); }else{ - zConverted = sqlite3MallocZero( nBuf+1 ); + zConverted = sqlite3MallocZero( nMax+1 ); if( !zConverted ){ sqlite3_free(zBuf); OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n")); @@ -4091,12 +4232,12 @@ static int winGetTempname(sqlite3_vfs *pVfs, char **pzBuf){ } if( cygwin_conv_path( osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A, zDir, - zConverted, nBuf+1)<0 ){ + zConverted, nMax+1)<0 ){ sqlite3_free(zConverted); sqlite3_free(zBuf); OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_CONVPATH\n")); return winLogError(SQLITE_IOERR_CONVPATH, (DWORD)errno, - "winGetTempname1", zDir); + "winGetTempname2", zDir); } if( winIsDir(zConverted) ){ /* At this point, we know the candidate directory exists and should @@ -4111,12 +4252,12 @@ static int winGetTempname(sqlite3_vfs *pVfs, char **pzBuf){ OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n")); return SQLITE_IOERR_NOMEM; } - sqlite3_snprintf(nBuf-30, zBuf, "%s", zUtf8); + sqlite3_snprintf(nMax, zBuf, "%s", zUtf8); sqlite3_free(zUtf8); sqlite3_free(zConverted); break; }else{ - sqlite3_snprintf(nBuf-30, zBuf, "%s", zConverted); + sqlite3_snprintf(nMax, zBuf, "%s", zConverted); sqlite3_free(zConverted); break; } @@ -4128,22 +4269,22 @@ static int winGetTempname(sqlite3_vfs *pVfs, char **pzBuf){ #elif !SQLITE_OS_WINRT && !defined(__CYGWIN__) else if( osIsNT() ){ char *zMulti; - LPWSTR zWidePath = sqlite3MallocZero( nBuf*sizeof(WCHAR) ); + LPWSTR zWidePath = sqlite3MallocZero( nMax*sizeof(WCHAR) ); if( !zWidePath ){ sqlite3_free(zBuf); OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n")); return SQLITE_IOERR_NOMEM; } - if( osGetTempPathW(nBuf, zWidePath)==0 ){ + if( osGetTempPathW(nMax, zWidePath)==0 ){ sqlite3_free(zWidePath); sqlite3_free(zBuf); OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_GETTEMPPATH\n")); return winLogError(SQLITE_IOERR_GETTEMPPATH, osGetLastError(), - "winGetTempname1", 0); + "winGetTempname2", 0); } zMulti = winUnicodeToUtf8(zWidePath); if( zMulti ){ - sqlite3_snprintf(nBuf-30, zBuf, "%s", zMulti); + sqlite3_snprintf(nMax, zBuf, "%s", zMulti); sqlite3_free(zMulti); sqlite3_free(zWidePath); }else{ @@ -4156,21 +4297,21 @@ static int winGetTempname(sqlite3_vfs *pVfs, char **pzBuf){ #ifdef SQLITE_WIN32_HAS_ANSI else{ char *zUtf8; - char *zMbcsPath = sqlite3MallocZero( nBuf ); + char *zMbcsPath = sqlite3MallocZero( nMax ); if( !zMbcsPath ){ sqlite3_free(zBuf); OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n")); return SQLITE_IOERR_NOMEM; } - if( osGetTempPathA(nBuf, zMbcsPath)==0 ){ + if( osGetTempPathA(nMax, zMbcsPath)==0 ){ sqlite3_free(zBuf); OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_GETTEMPPATH\n")); return winLogError(SQLITE_IOERR_GETTEMPPATH, osGetLastError(), - "winGetTempname2", 0); + "winGetTempname3", 0); } zUtf8 = sqlite3_win32_mbcs_to_utf8(zMbcsPath); if( zUtf8 ){ - sqlite3_snprintf(nBuf-30, zBuf, "%s", zUtf8); + sqlite3_snprintf(nMax, zBuf, "%s", zUtf8); sqlite3_free(zUtf8); }else{ sqlite3_free(zBuf); @@ -4181,18 +4322,36 @@ static int winGetTempname(sqlite3_vfs *pVfs, char **pzBuf){ #endif /* SQLITE_WIN32_HAS_ANSI */ #endif /* !SQLITE_OS_WINRT */ - /* Check that the output buffer is large enough for the temporary file - ** name. If it is not, return SQLITE_ERROR. + /* + ** Check to make sure the temporary directory ends with an appropriate + ** separator. If it does not and there is not enough space left to add + ** one, fail. */ - nLen = sqlite3Strlen30(zBuf); - - if( (nLen + sqlite3Strlen30(SQLITE_TEMP_FILE_PREFIX) + 18) >= nBuf ){ + if( !winMakeEndInDirSep(nDir+1, zBuf) ){ sqlite3_free(zBuf); OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n")); - return winLogError(SQLITE_ERROR, 0, "winGetTempname3", 0); + return winLogError(SQLITE_ERROR, 0, "winGetTempname4", 0); } - sqlite3_snprintf(nBuf-18-nLen, zBuf+nLen, SQLITE_TEMP_FILE_PREFIX); + /* + ** Check that the output buffer is large enough for the temporary file + ** name in the following format: + ** + ** "/etilqs_XXXXXXXXXXXXXXX\0\0" + ** + ** If not, return SQLITE_ERROR. The number 17 is used here in order to + ** account for the space used by the 15 character random suffix and the + ** two trailing NUL characters. The final directory separator character + ** has already added if it was not already present. + */ + nLen = sqlite3Strlen30(zBuf); + if( (nLen + nPre + 17) > nBuf ){ + sqlite3_free(zBuf); + OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n")); + return winLogError(SQLITE_ERROR, 0, "winGetTempname5", 0); + } + + sqlite3_snprintf(nBuf-16-nLen, zBuf+nLen, SQLITE_TEMP_FILE_PREFIX); j = sqlite3Strlen30(zBuf); sqlite3_randomness(15, &zBuf[j]); @@ -4247,7 +4406,7 @@ static int winOpen( int *pOutFlags /* Status return flags */ ){ HANDLE h; - DWORD lastErrno; + DWORD lastErrno = 0; DWORD dwDesiredAccess; DWORD dwShareMode; DWORD dwCreationDisposition; @@ -4538,7 +4697,7 @@ static int winDelete( int cnt = 0; int rc; DWORD attr; - DWORD lastErrno; + DWORD lastErrno = 0; void *zConverted; UNUSED_PARAMETER(pVfs); UNUSED_PARAMETER(syncDir); @@ -4646,7 +4805,7 @@ static int winAccess( ){ DWORD attr; int rc = 0; - DWORD lastErrno; + DWORD lastErrno = 0; void *zConverted; UNUSED_PARAMETER(pVfs); @@ -4792,8 +4951,8 @@ static int winFullPathname( return winLogError(SQLITE_CANTOPEN_CONVPATH, (DWORD)errno, "winFullPathname1", zRelative); } - sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%s%s", - sqlite3_data_directory, winGetDirDep(), zOut); + sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s", + sqlite3_data_directory, winGetDirSep(), zOut); sqlite3_free(zOut); }else{ if( cygwin_conv_path(CCP_POSIX_TO_WIN_A, zRelative, zFull, nFull)<0 ){ @@ -4815,8 +4974,8 @@ static int winFullPathname( ** for converting the relative path name to an absolute ** one by prepending the data directory and a backslash. */ - sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%s%s", - sqlite3_data_directory, winGetDirDep(), zRelative); + sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s", + sqlite3_data_directory, winGetDirSep(), zRelative); }else{ sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zRelative); } @@ -4848,8 +5007,8 @@ static int winFullPathname( ** for converting the relative path name to an absolute ** one by prepending the data directory and a backslash. */ - sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%s%s", - sqlite3_data_directory, winGetDirDep(), zRelative); + sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s", + sqlite3_data_directory, winGetDirSep(), zRelative); return SQLITE_OK; } zConverted = winConvertFromUtf8Filename(zRelative); @@ -5187,7 +5346,7 @@ int sqlite3_os_init(void){ /* Double-check that the aSyscall[] array has been constructed ** correctly. See ticket [bb3a86e890c8e96ab] */ - assert( ArraySize(aSyscall)==75 ); + assert( ArraySize(aSyscall)==76 ); /* get memory map allocation granularity */ memset(&winSysInfo, 0, sizeof(SYSTEM_INFO)); diff --git a/src/parse.y b/src/parse.y index 1e8d7f751c..07e607dcf9 100644 --- a/src/parse.y +++ b/src/parse.y @@ -163,13 +163,23 @@ ifnotexists(A) ::= IF NOT EXISTS. {A = 1;} temp(A) ::= TEMP. {A = 1;} %endif SQLITE_OMIT_TEMPDB temp(A) ::= . {A = 0;} -create_table_args ::= LP columnlist conslist_opt(X) RP(Y). { - sqlite3EndTable(pParse,&X,&Y,0); +create_table_args ::= LP columnlist conslist_opt(X) RP(E) table_options(F). { + sqlite3EndTable(pParse,&X,&E,F,0); } create_table_args ::= AS select(S). { - sqlite3EndTable(pParse,0,0,S); + sqlite3EndTable(pParse,0,0,0,S); sqlite3SelectDelete(pParse->db, S); } +%type table_options {u8} +table_options(A) ::= . {A = 0;} +table_options(A) ::= WITHOUT nm(X). { + if( X.n==5 && sqlite3_strnicmp(X.z,"rowid",5)==0 ){ + A = TF_WithoutRowid; + }else{ + A = 0; + sqlite3ErrorMsg(pParse, "unknown table option: %.*s", X.n, X.z); + } +} columnlist ::= columnlist COMMA column. columnlist ::= column. @@ -205,7 +215,7 @@ id(A) ::= INDEXED(X). {A = X;} CONFLICT DATABASE DEFERRED DESC DETACH EACH END EXCLUSIVE EXPLAIN FAIL FOR IGNORE IMMEDIATE INITIALLY INSTEAD LIKE_KW MATCH NO PLAN QUERY KEY OF OFFSET PRAGMA RAISE RELEASE REPLACE RESTRICT ROW ROLLBACK - SAVEPOINT TEMP TRIGGER VACUUM VIEW VIRTUAL + SAVEPOINT TEMP TRIGGER VACUUM VIEW VIRTUAL WITHOUT %ifdef SQLITE_OMIT_COMPOUND_SELECT EXCEPT INTERSECT UNION %endif SQLITE_OMIT_COMPOUND_SELECT @@ -573,7 +583,7 @@ indexed_opt(A) ::= NOT INDEXED. {A.z=0; A.n=1;} %type using_opt {IdList*} %destructor using_opt {sqlite3IdListDelete(pParse->db, $$);} -using_opt(U) ::= USING LP inscollist(L) RP. {U = L;} +using_opt(U) ::= USING LP idlist(L) RP. {U = L;} using_opt(U) ::= . {U = 0;} @@ -740,14 +750,14 @@ valuelist(A) ::= valuelist(X) COMMA LP exprlist(Y) RP. { %type inscollist_opt {IdList*} %destructor inscollist_opt {sqlite3IdListDelete(pParse->db, $$);} -%type inscollist {IdList*} -%destructor inscollist {sqlite3IdListDelete(pParse->db, $$);} +%type idlist {IdList*} +%destructor idlist {sqlite3IdListDelete(pParse->db, $$);} inscollist_opt(A) ::= . {A = 0;} -inscollist_opt(A) ::= LP inscollist(X) RP. {A = X;} -inscollist(A) ::= inscollist(X) COMMA nm(Y). +inscollist_opt(A) ::= LP idlist(X) RP. {A = X;} +idlist(A) ::= idlist(X) COMMA nm(Y). {A = sqlite3IdListAppend(pParse->db,X,&Y);} -inscollist(A) ::= nm(Y). +idlist(A) ::= nm(Y). {A = sqlite3IdListAppend(pParse->db,0,&Y);} /////////////////////////// Expression Processing ///////////////////////////// @@ -1227,7 +1237,7 @@ trigger_time(A) ::= . { A = TK_BEFORE; } %destructor trigger_event {sqlite3IdListDelete(pParse->db, $$.b);} trigger_event(A) ::= DELETE|INSERT(OP). {A.a = @OP; A.b = 0;} trigger_event(A) ::= UPDATE(OP). {A.a = @OP; A.b = 0;} -trigger_event(A) ::= UPDATE OF inscollist(X). {A.a = TK_UPDATE; A.b = X;} +trigger_event(A) ::= UPDATE OF idlist(X). {A.a = TK_UPDATE; A.b = X;} foreach_clause ::= . foreach_clause ::= FOR EACH ROW. diff --git a/src/pragma.c b/src/pragma.c index b130ba461d..9211a2cb07 100644 --- a/src/pragma.c +++ b/src/pragma.c @@ -1425,8 +1425,7 @@ void sqlite3Pragma( int i, k; int nHidden = 0; Column *pCol; - Index *pPk; - for(pPk=pTab->pIndex; pPk && pPk->autoIndex!=2; pPk=pPk->pNext){} + Index *pPk = sqlite3PrimaryKeyIndex(pTab); sqlite3VdbeSetNumCols(v, 6); pParse->nMem = 6; sqlite3CodeVerifySchema(pParse, iDb); @@ -1509,8 +1508,8 @@ void sqlite3Pragma( sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seqno", SQLITE_STATIC); sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "cid", SQLITE_STATIC); sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "name", SQLITE_STATIC); - for(i=0; inColumn; i++){ - int cnum = pIdx->aiColumn[i]; + for(i=0; inKeyCol; i++){ + i16 cnum = pIdx->aiColumn[i]; sqlite3VdbeAddOp2(v, OP_Integer, i, 1); sqlite3VdbeAddOp2(v, OP_Integer, cnum, 2); assert( pTab->nCol>cnum ); @@ -1681,9 +1680,8 @@ void sqlite3Pragma( if( pIdx==0 ){ sqlite3OpenTable(pParse, i, iDb, pParent, OP_OpenRead); }else{ - KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx); sqlite3VdbeAddOp3(v, OP_OpenRead, i, pIdx->tnum, iDb); - sqlite3VdbeChangeP4(v, -1, (char*)pKey, P4_KEYINFO_HANDOFF); + sqlite3VdbeSetP4KeyInfo(pParse, pIdx); } }else{ k = 0; @@ -1847,16 +1845,20 @@ void sqlite3Pragma( for(x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){ Table *pTab = sqliteHashData(x); Index *pIdx; - sqlite3VdbeAddOp2(v, OP_Integer, pTab->tnum, 2+cnt); - cnt++; + if( HasRowid(pTab) ){ + sqlite3VdbeAddOp2(v, OP_Integer, pTab->tnum, 2+cnt); + VdbeComment((v, "%s", pTab->zName)); + cnt++; + } for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ sqlite3VdbeAddOp2(v, OP_Integer, pIdx->tnum, 2+cnt); + VdbeComment((v, "%s", pIdx->zName)); cnt++; } } /* Make sure sufficient number of registers have been allocated */ - pParse->nMem = MAX( pParse->nMem, cnt+7 ); + pParse->nMem = MAX( pParse->nMem, cnt+8 ); /* Do the b-tree integrity checks */ sqlite3VdbeAddOp3(v, OP_IntegrityCk, 2, cnt, 1); @@ -1874,58 +1876,60 @@ void sqlite3Pragma( */ for(x=sqliteHashFirst(pTbls); x && !isQuick; x=sqliteHashNext(x)){ Table *pTab = sqliteHashData(x); - Index *pIdx; + Index *pIdx, *pPk; int loopTop; + int iDataCur, iIdxCur; if( pTab->pIndex==0 ) continue; + pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab); addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1); /* Stop if out of errors */ sqlite3VdbeAddOp2(v, OP_Halt, 0, 0); sqlite3VdbeJumpHere(v, addr); sqlite3ExprCacheClear(pParse); - sqlite3OpenTableAndIndices(pParse, pTab, 1, OP_OpenRead); + sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenRead, + 1, &iDataCur, &iIdxCur); + sqlite3VdbeAddOp2(v, OP_Integer, 0, 7); for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){ - sqlite3VdbeAddOp2(v, OP_Integer, 0, 7+j); /* index entries counter */ + sqlite3VdbeAddOp2(v, OP_Integer, 0, 8+j); /* index entries counter */ } - pParse->nMem = MAX(pParse->nMem, 7+j); - loopTop = sqlite3VdbeAddOp2(v, OP_Rewind, 1, 0) + 1; + pParse->nMem = MAX(pParse->nMem, 8+j); + sqlite3VdbeAddOp2(v, OP_Rewind, iDataCur, 0); + loopTop = sqlite3VdbeAddOp2(v, OP_AddImm, 7, 1); for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){ - int jmp2, jmp3; + int jmp2, jmp3, jmp4; int r1; - static const VdbeOpList idxErr[] = { - { OP_AddImm, 1, -1, 0}, - { OP_String8, 0, 3, 0}, /* 1 */ - { OP_Rowid, 1, 4, 0}, - { OP_String8, 0, 5, 0}, /* 3 */ - { OP_String8, 0, 6, 0}, /* 4 */ - { OP_Concat, 4, 3, 3}, - { OP_Concat, 5, 3, 3}, - { OP_Concat, 6, 3, 3}, - { OP_ResultRow, 3, 1, 0}, - { OP_IfPos, 1, 0, 0}, /* 9 */ - { OP_Halt, 0, 0, 0}, - }; - r1 = sqlite3GenerateIndexKey(pParse, pIdx, 1, 3, 0, &jmp3); - sqlite3VdbeAddOp2(v, OP_AddImm, 7+j, 1); /* increment entry count */ - jmp2 = sqlite3VdbeAddOp4Int(v, OP_Found, j+2, 0, r1, pIdx->nColumn+1); - addr = sqlite3VdbeAddOpList(v, ArraySize(idxErr), idxErr); - sqlite3VdbeChangeP4(v, addr+1, "rowid ", P4_STATIC); - sqlite3VdbeChangeP4(v, addr+3, " missing from index ", P4_STATIC); - sqlite3VdbeChangeP4(v, addr+4, pIdx->zName, P4_TRANSIENT); - sqlite3VdbeJumpHere(v, addr+9); + if( pPk==pIdx ) continue; + r1 = sqlite3GenerateIndexKey(pParse, pIdx, iDataCur, 0, 0, &jmp3); + sqlite3VdbeAddOp2(v, OP_AddImm, 8+j, 1); /* increment entry count */ + jmp2 = sqlite3VdbeAddOp4Int(v, OP_Found, iIdxCur+j, 0, r1, + pIdx->nColumn); + sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1); /* Decrement error limit */ + sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, "row ", P4_STATIC); + sqlite3VdbeAddOp3(v, OP_Concat, 7, 3, 3); + sqlite3VdbeAddOp4(v, OP_String8, 0, 4, 0, " missing from index ", + P4_STATIC); + sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 3); + sqlite3VdbeAddOp4(v, OP_String8, 0, 4, 0, pIdx->zName, P4_TRANSIENT); + sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 3); + sqlite3VdbeAddOp2(v, OP_ResultRow, 3, 1); + jmp4 = sqlite3VdbeAddOp1(v, OP_IfPos, 1); + sqlite3VdbeAddOp0(v, OP_Halt); + sqlite3VdbeJumpHere(v, jmp4); sqlite3VdbeJumpHere(v, jmp2); sqlite3VdbeResolveLabel(v, jmp3); } - sqlite3VdbeAddOp2(v, OP_Next, 1, loopTop); + sqlite3VdbeAddOp2(v, OP_Next, iDataCur, loopTop); sqlite3VdbeJumpHere(v, loopTop-1); #ifndef SQLITE_OMIT_BTREECOUNT sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, "wrong # of entries in index ", P4_STATIC); for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){ + if( pPk==pIdx ) continue; addr = sqlite3VdbeCurrentAddr(v); sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr+2); sqlite3VdbeAddOp2(v, OP_Halt, 0, 0); - sqlite3VdbeAddOp2(v, OP_Count, j+2, 3); - sqlite3VdbeAddOp3(v, OP_Eq, 7+j, addr+8, 3); + sqlite3VdbeAddOp2(v, OP_Count, iIdxCur+j, 3); + sqlite3VdbeAddOp3(v, OP_Eq, 8+j, addr+8, 3); sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1); sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pIdx->zName, P4_TRANSIENT); sqlite3VdbeAddOp3(v, OP_Concat, 3, 2, 7); diff --git a/src/resolve.c b/src/resolve.c index 92fbaaf15a..b41f234429 100644 --- a/src/resolve.c +++ b/src/resolve.c @@ -226,7 +226,9 @@ static int lookupName( struct SrcList_item *pMatch = 0; /* The matching pSrcList item */ NameContext *pTopNC = pNC; /* First namecontext in the list */ Schema *pSchema = 0; /* Schema of the expression */ - int isTrigger = 0; + int isTrigger = 0; /* True if resolved to a trigger column */ + Table *pTab = 0; /* Table hold the row */ + Column *pCol; /* A column of pTab */ assert( pNC ); /* the name context cannot be NULL. */ assert( zCol ); /* The Z in X.Y.Z cannot be NULL */ @@ -267,9 +269,6 @@ static int lookupName( if( pSrcList ){ for(i=0, pItem=pSrcList->a; inSrc; i++, pItem++){ - Table *pTab; - Column *pCol; - pTab = pItem->pTab; assert( pTab!=0 && pTab->zName!=0 ); assert( pTab->nCol>0 ); @@ -329,9 +328,8 @@ static int lookupName( /* If we have not already resolved the name, then maybe ** it is a new.* or old.* trigger argument reference */ - if( zDb==0 && zTab!=0 && cnt==0 && pParse->pTriggerTab!=0 ){ + if( zDb==0 && zTab!=0 && cntTab==0 && pParse->pTriggerTab!=0 ){ int op = pParse->eTriggerOp; - Table *pTab = 0; assert( op==TK_DELETE || op==TK_UPDATE || op==TK_INSERT ); if( op!=TK_DELETE && sqlite3StrICmp("new",zTab) == 0 ){ pExpr->iTable = 1; @@ -345,8 +343,7 @@ static int lookupName( int iCol; pSchema = pTab->pSchema; cntTab++; - for(iCol=0; iColnCol; iCol++){ - Column *pCol = &pTab->aCol[iCol]; + for(iCol=0, pCol=pTab->aCol; iColnCol; iCol++, pCol++){ if( sqlite3StrICmp(pCol->zName, zCol)==0 ){ if( iCol==pTab->iPKey ){ iCol = -1; @@ -354,7 +351,7 @@ static int lookupName( break; } } - if( iCol>=pTab->nCol && sqlite3IsRowid(zCol) ){ + if( iCol>=pTab->nCol && sqlite3IsRowid(zCol) && HasRowid(pTab) ){ iCol = -1; /* IMP: R-44911-55124 */ } if( iColnCol ){ @@ -381,7 +378,8 @@ static int lookupName( /* ** Perhaps the name is a reference to the ROWID */ - if( cnt==0 && cntTab==1 && sqlite3IsRowid(zCol) ){ + assert( pTab!=0 || cntTab==0 ); + if( cnt==0 && cntTab==1 && sqlite3IsRowid(zCol) && HasRowid(pTab) ){ cnt = 1; pExpr->iColumn = -1; /* IMP: R-44911-55124 */ pExpr->affinity = SQLITE_AFF_INTEGER; diff --git a/src/select.c b/src/select.c index badd6249a2..02730ac123 100644 --- a/src/select.c +++ b/src/select.c @@ -803,24 +803,57 @@ static void selectInnerLoop( } /* -** Allocate a KeyInfo object sufficient for an index of N columns. -** -** Actually, always allocate one extra column for the rowid at the end -** of the index. So the KeyInfo returned will have space sufficient for -** N+1 columns. +** Allocate a KeyInfo object sufficient for an index of N key columns and +** X extra columns. */ -KeyInfo *sqlite3KeyInfoAlloc(sqlite3 *db, int N){ - KeyInfo *p = sqlite3DbMallocZero(db, - sizeof(KeyInfo) + (N+1)*(sizeof(CollSeq*)+1)); +KeyInfo *sqlite3KeyInfoAlloc(sqlite3 *db, int N, int X){ + KeyInfo *p = sqlite3DbMallocZero(0, + sizeof(KeyInfo) + (N+X)*(sizeof(CollSeq*)+1)); if( p ){ - p->aSortOrder = (u8*)&p->aColl[N+1]; + p->aSortOrder = (u8*)&p->aColl[N+X]; p->nField = (u16)N; + p->nXField = (u16)X; p->enc = ENC(db); p->db = db; + p->nRef = 1; + }else{ + db->mallocFailed = 1; } return p; } +/* +** Deallocate a KeyInfo object +*/ +void sqlite3KeyInfoUnref(KeyInfo *p){ + if( p ){ + assert( p->nRef>0 ); + p->nRef--; + if( p->nRef==0 ) sqlite3DbFree(0, p); + } +} + +/* +** Make a new pointer to a KeyInfo object +*/ +KeyInfo *sqlite3KeyInfoRef(KeyInfo *p){ + if( p ){ + assert( p->nRef>0 ); + p->nRef++; + } + return p; +} + +#ifdef SQLITE_DEBUG +/* +** Return TRUE if a KeyInfo object can be change. The KeyInfo object +** can only be changed if this is just a single reference to the object. +** +** This routine is used only inside of assert() statements. +*/ +int sqlite3KeyInfoIsWriteable(KeyInfo *p){ return p->nRef==1; } +#endif /* SQLITE_DEBUG */ + /* ** Given an expression list, generate a KeyInfo structure that records ** the collating sequence for each expression in that expression list. @@ -833,8 +866,7 @@ KeyInfo *sqlite3KeyInfoAlloc(sqlite3 *db, int N){ ** ** Space to hold the KeyInfo structure is obtain from malloc. The calling ** function is responsible for seeing that this structure is eventually -** freed. Add the KeyInfo structure to the P4 field of an opcode using -** P4_KEYINFO_HANDOFF is the usual way of dealing with this. +** freed. */ static KeyInfo *keyInfoFromExprList(Parse *pParse, ExprList *pList){ int nExpr; @@ -844,8 +876,9 @@ static KeyInfo *keyInfoFromExprList(Parse *pParse, ExprList *pList){ int i; nExpr = pList->nExpr; - pInfo = sqlite3KeyInfoAlloc(db, nExpr); + pInfo = sqlite3KeyInfoAlloc(db, nExpr, 1); if( pInfo ){ + assert( sqlite3KeyInfoIsWriteable(pInfo) ); for(i=0, pItem=pList->a; ipExpr); @@ -1988,7 +2021,7 @@ static int multiSelect( assert( p->pRightmost==p ); nCol = p->pEList->nExpr; - pKeyInfo = sqlite3KeyInfoAlloc(db, nCol); + pKeyInfo = sqlite3KeyInfoAlloc(db, nCol, 1); if( !pKeyInfo ){ rc = SQLITE_NOMEM; goto multi_select_end; @@ -2010,11 +2043,12 @@ static int multiSelect( break; } sqlite3VdbeChangeP2(v, addr, nCol); - sqlite3VdbeChangeP4(v, addr, (char*)pKeyInfo, P4_KEYINFO); + sqlite3VdbeChangeP4(v, addr, (char*)sqlite3KeyInfoRef(pKeyInfo), + P4_KEYINFO); pLoop->addrOpenEphm[i] = -1; } } - sqlite3DbFree(db, pKeyInfo); + sqlite3KeyInfoUnref(pKeyInfo); } multi_select_end: @@ -2053,7 +2087,6 @@ static int generateOutputSubroutine( int regReturn, /* The return address register */ int regPrev, /* Previous result register. No uniqueness if 0 */ KeyInfo *pKeyInfo, /* For comparing with previous entry */ - int p4type, /* The p4 type for pKeyInfo */ int iBreak /* Jump here if we hit the LIMIT */ ){ Vdbe *v = pParse->pVdbe; @@ -2069,7 +2102,7 @@ static int generateOutputSubroutine( int j1, j2; j1 = sqlite3VdbeAddOp1(v, OP_IfNot, regPrev); j2 = sqlite3VdbeAddOp4(v, OP_Compare, pIn->iSdst, regPrev+1, pIn->nSdst, - (char*)pKeyInfo, p4type); + (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO); sqlite3VdbeAddOp3(v, OP_Jump, j2+2, iContinue, j2+2); sqlite3VdbeJumpHere(v, j1); sqlite3VdbeAddOp3(v, OP_Copy, pIn->iSdst, regPrev+1, pIn->nSdst-1); @@ -2367,7 +2400,7 @@ static int multiSelectOrderBy( assert( pItem->iOrderByCol>0 && pItem->iOrderByCol<=p->pEList->nExpr ); aPermute[i] = pItem->iOrderByCol - 1; } - pKeyMerge = sqlite3KeyInfoAlloc(db, nOrderBy); + pKeyMerge = sqlite3KeyInfoAlloc(db, nOrderBy, 1); if( pKeyMerge ){ for(i=0; ia[i].pExpr = sqlite3ExprAddCollateString(pParse, pTerm, pColl->zName); } + assert( sqlite3KeyInfoIsWriteable(pKeyMerge) ); pKeyMerge->aColl[i] = pColl; pKeyMerge->aSortOrder[i] = pOrderBy->a[i].sortOrder; } @@ -2405,8 +2439,9 @@ static int multiSelectOrderBy( regPrev = pParse->nMem+1; pParse->nMem += nExpr+1; sqlite3VdbeAddOp2(v, OP_Integer, 0, regPrev); - pKeyDup = sqlite3KeyInfoAlloc(db, nExpr); + pKeyDup = sqlite3KeyInfoAlloc(db, nExpr, 1); if( pKeyDup ){ + assert( sqlite3KeyInfoIsWriteable(pKeyDup) ); for(i=0; iaColl[i] = multiSelectCollSeq(pParse, p, i); pKeyDup->aSortOrder[i] = 0; @@ -2488,7 +2523,7 @@ static int multiSelectOrderBy( VdbeNoopComment((v, "Output routine for A")); addrOutA = generateOutputSubroutine(pParse, p, &destA, pDest, regOutA, - regPrev, pKeyDup, P4_KEYINFO_HANDOFF, labelEnd); + regPrev, pKeyDup, labelEnd); /* Generate a subroutine that outputs the current row of the B ** select as the next output row of the compound select. @@ -2497,8 +2532,9 @@ static int multiSelectOrderBy( VdbeNoopComment((v, "Output routine for B")); addrOutB = generateOutputSubroutine(pParse, p, &destB, pDest, regOutB, - regPrev, pKeyDup, P4_KEYINFO_STATIC, labelEnd); + regPrev, pKeyDup, labelEnd); } + sqlite3KeyInfoUnref(pKeyDup); /* Generate a subroutine to run when the results from select A ** are exhausted and only data in select B remains. @@ -2577,7 +2613,7 @@ static int multiSelectOrderBy( sqlite3VdbeResolveLabel(v, labelCmpr); sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY); sqlite3VdbeAddOp4(v, OP_Compare, destA.iSdst, destB.iSdst, nOrderBy, - (char*)pKeyMerge, P4_KEYINFO_HANDOFF); + (char*)pKeyMerge, P4_KEYINFO); sqlite3VdbeChangeP5(v, OPFLAG_PERMUTE); sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB); @@ -3803,7 +3839,7 @@ static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){ }else{ KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->x.pList); sqlite3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0, - (char*)pKeyInfo, P4_KEYINFO_HANDOFF); + (char*)pKeyInfo, P4_KEYINFO); } } } @@ -4258,7 +4294,7 @@ int sqlite3Select( p->addrOpenEphm[2] = addrSortIndex = sqlite3VdbeAddOp4(v, OP_OpenEphemeral, pOrderBy->iECursor, pOrderBy->nExpr+2, 0, - (char*)pKeyInfo, P4_KEYINFO_HANDOFF); + (char*)pKeyInfo, P4_KEYINFO); }else{ addrSortIndex = -1; } @@ -4286,7 +4322,7 @@ int sqlite3Select( sDistinct.addrTnct = sqlite3VdbeAddOp4(v, OP_OpenEphemeral, sDistinct.tabTnct, 0, 0, (char*)keyInfoFromExprList(pParse, p->pEList), - P4_KEYINFO_HANDOFF); + P4_KEYINFO); sqlite3VdbeChangeP5(v, BTREE_UNORDERED); sDistinct.eTnctType = WHERE_DISTINCT_UNORDERED; }else{ @@ -4410,7 +4446,7 @@ int sqlite3Select( pKeyInfo = keyInfoFromExprList(pParse, pGroupBy); addrSortingIdx = sqlite3VdbeAddOp4(v, OP_SorterOpen, sAggInfo.sortingIdx, sAggInfo.nSortingColumn, - 0, (char*)pKeyInfo, P4_KEYINFO_HANDOFF); + 0, (char*)pKeyInfo, P4_KEYINFO); /* Initialize memory locations used by GROUP BY aggregate processing */ @@ -4524,7 +4560,7 @@ int sqlite3Select( } } sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr, - (char*)pKeyInfo, P4_KEYINFO); + (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO); j1 = sqlite3VdbeCurrentAddr(v); sqlite3VdbeAddOp3(v, OP_Jump, j1+1, 0, j1+1); @@ -4650,13 +4686,13 @@ int sqlite3Select( } if( pBest ){ iRoot = pBest->tnum; - pKeyInfo = sqlite3IndexKeyinfo(pParse, pBest); + pKeyInfo = sqlite3KeyInfoOfIndex(pParse, pBest); } /* Open a read-only cursor, execute the OP_Count, close the cursor. */ - sqlite3VdbeAddOp3(v, OP_OpenRead, iCsr, iRoot, iDb); + sqlite3VdbeAddOp4Int(v, OP_OpenRead, iCsr, iRoot, iDb, 1); if( pKeyInfo ){ - sqlite3VdbeChangeP4(v, -1, (char *)pKeyInfo, P4_KEYINFO_HANDOFF); + sqlite3VdbeChangeP4(v, -1, (char *)pKeyInfo, P4_KEYINFO); } sqlite3VdbeAddOp2(v, OP_Count, iCsr, sAggInfo.aFunc[0].iMem); sqlite3VdbeAddOp1(v, OP_Close, iCsr); diff --git a/src/shell.c b/src/shell.c index 26c38c59ea..c3aee04633 100644 --- a/src/shell.c +++ b/src/shell.c @@ -86,21 +86,38 @@ extern int pclose(FILE*); #define isatty(x) 1 #endif -/* True if the timer is enabled */ -static int enableTimer = 0; - /* ctype macros that work with signed characters */ #define IsSpace(X) isspace((unsigned char)X) #define IsDigit(X) isdigit((unsigned char)X) #define ToLower(X) (char)tolower((unsigned char)X) + +/* True if the timer is enabled */ +static int enableTimer = 0; + +/* Return the current wall-clock time */ +static sqlite3_int64 timeOfDay(void){ + static sqlite3_vfs *clockVfs = 0; + sqlite3_int64 t; + if( clockVfs==0 ) clockVfs = sqlite3_vfs_find(0); + if( clockVfs->iVersion>=1 && clockVfs->xCurrentTimeInt64!=0 ){ + clockVfs->xCurrentTimeInt64(clockVfs, &t); + }else{ + double r; + clockVfs->xCurrentTime(clockVfs, &r); + t = (sqlite3_int64)(r*86400000.0); + } + return t; +} + #if !defined(_WIN32) && !defined(WIN32) && !defined(_WRS_KERNEL) \ && !defined(__minux) #include #include /* Saved resource information for the beginning of an operation */ -static struct rusage sBegin; +static struct rusage sBegin; /* CPU time at start */ +static sqlite3_int64 iBegin; /* Wall-clock time at start */ /* ** Begin timing an operation @@ -108,6 +125,7 @@ static struct rusage sBegin; static void beginTimer(void){ if( enableTimer ){ getrusage(RUSAGE_SELF, &sBegin); + iBegin = timeOfDay(); } } @@ -123,8 +141,10 @@ static double timeDiff(struct timeval *pStart, struct timeval *pEnd){ static void endTimer(void){ if( enableTimer ){ struct rusage sEnd; + sqlite3_int64 iEnd = timeOfDay(); getrusage(RUSAGE_SELF, &sEnd); - printf("CPU Time: user %f sys %f\n", + printf("Run Time: real %.3f user %f sys %f\n", + (iEnd - iBegin)*0.001, timeDiff(&sBegin.ru_utime, &sEnd.ru_utime), timeDiff(&sBegin.ru_stime, &sEnd.ru_stime)); } @@ -142,6 +162,7 @@ static void endTimer(void){ static HANDLE hProcess; static FILETIME ftKernelBegin; static FILETIME ftUserBegin; +static sqlite3_int64 ftWallBegin; typedef BOOL (WINAPI *GETPROCTIMES)(HANDLE, LPFILETIME, LPFILETIME, LPFILETIME, LPFILETIME); static GETPROCTIMES getProcessTimesAddr = NULL; @@ -179,6 +200,7 @@ static void beginTimer(void){ if( enableTimer && getProcessTimesAddr ){ FILETIME ftCreation, ftExit; getProcessTimesAddr(hProcess, &ftCreation, &ftExit, &ftKernelBegin, &ftUserBegin); + ftWallBegin = timeOfDay(); } } @@ -195,8 +217,10 @@ static double timeDiff(FILETIME *pStart, FILETIME *pEnd){ static void endTimer(void){ if( enableTimer && getProcessTimesAddr){ FILETIME ftCreation, ftExit, ftKernelEnd, ftUserEnd; + sqlite3_int64 ftWallEnd = timeOfDay(); getProcessTimesAddr(hProcess, &ftCreation, &ftExit, &ftKernelEnd, &ftUserEnd); - printf("CPU Time: user %f sys %f\n", + printf("Run Time: real %.3f user %f sys %f\n", + (ftWallEnd - ftWallBegin)*0.001, timeDiff(&ftUserBegin, &ftUserEnd), timeDiff(&ftKernelBegin, &ftKernelEnd)); } diff --git a/src/sqlite.h.in b/src/sqlite.h.in index 8b1c14bf83..6372ee392a 100644 --- a/src/sqlite.h.in +++ b/src/sqlite.h.in @@ -496,6 +496,7 @@ int sqlite3_exec( #define SQLITE_CONSTRAINT_TRIGGER (SQLITE_CONSTRAINT | (7<<8)) #define SQLITE_CONSTRAINT_UNIQUE (SQLITE_CONSTRAINT | (8<<8)) #define SQLITE_CONSTRAINT_VTAB (SQLITE_CONSTRAINT | (9<<8)) +#define SQLITE_CONSTRAINT_ROWID (SQLITE_CONSTRAINT |(10<<8)) #define SQLITE_NOTICE_RECOVER_WAL (SQLITE_NOTICE | (1<<8)) #define SQLITE_NOTICE_RECOVER_ROLLBACK (SQLITE_NOTICE | (2<<8)) #define SQLITE_WARNING_AUTOINDEX (SQLITE_WARNING | (1<<8)) @@ -1781,19 +1782,21 @@ int sqlite3_extended_result_codes(sqlite3*, int onoff); /* ** CAPI3REF: Last Insert Rowid ** -** ^Each entry in an SQLite table has a unique 64-bit signed +** ^Each entry in most SQLite tables (except for [WITHOUT ROWID] tables) +** has a unique 64-bit signed ** integer key called the [ROWID | "rowid"]. ^The rowid is always available ** as an undeclared column named ROWID, OID, or _ROWID_ as long as those ** names are not also used by explicitly declared columns. ^If ** the table has a column of type [INTEGER PRIMARY KEY] then that column ** is another alias for the rowid. ** -** ^This routine returns the [rowid] of the most recent -** successful [INSERT] into the database from the [database connection] -** in the first argument. ^As of SQLite version 3.7.7, this routines -** records the last insert rowid of both ordinary tables and [virtual tables]. -** ^If no successful [INSERT]s -** have ever occurred on that database connection, zero is returned. +** ^The sqlite3_last_insert_rowid(D) interface returns the [rowid] of the +** most recent successful [INSERT] into a rowid table or [virtual table] +** on database connection D. +** ^Inserts into [WITHOUT ROWID] tables are not recorded. +** ^If no successful [INSERT]s into rowid tables +** have ever occurred on the database connection D, +** then sqlite3_last_insert_rowid(D) returns zero. ** ** ^(If an [INSERT] occurs within a trigger or within a [virtual table] ** method, then this routine will return the [rowid] of the inserted @@ -4810,12 +4813,13 @@ void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*); ** ** ^The sqlite3_update_hook() interface registers a callback function ** with the [database connection] identified by the first argument -** to be invoked whenever a row is updated, inserted or deleted. +** to be invoked whenever a row is updated, inserted or deleted in +** a rowid table. ** ^Any callback set by a previous call to this function ** for the same database connection is overridden. ** ** ^The second argument is a pointer to the function to invoke when a -** row is updated, inserted or deleted. +** row is updated, inserted or deleted in a rowid table. ** ^The first argument to the callback is a copy of the third argument ** to sqlite3_update_hook(). ** ^The second callback argument is one of [SQLITE_INSERT], [SQLITE_DELETE], @@ -4828,6 +4832,7 @@ void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*); ** ** ^(The update hook is not invoked when internal system tables are ** modified (i.e. sqlite_master and sqlite_sequence).)^ +** ^The update hook is not invoked when [WITHOUT ROWID] tables are modified. ** ** ^In the current implementation, the update hook ** is not invoked when duplication rows are deleted because of an @@ -5285,10 +5290,22 @@ struct sqlite3_module { ** the correct order to satisfy the ORDER BY clause so that no separate ** sorting step is required. ** -** ^The estimatedCost value is an estimate of the cost of doing the -** particular lookup. A full scan of a table with N entries should have -** a cost of N. A binary search of a table of N entries should have a -** cost of approximately log(N). +** ^The estimatedCost value is an estimate of the cost of a particular +** strategy. A cost of N indicates that the cost of the strategy is similar +** to a linear scan of an SQLite table with N rows. A cost of log(N) +** indicates that the expense of the operation is similar to that of a +** binary search on a unique indexed field of an SQLite table with N rows. +** +** ^The estimatedRows value is an estimate of the number of rows that +** will be returned by the strategy. +** +** IMPORTANT: The estimatedRows field was added to the sqlite3_index_info +** structure for SQLite version 3.8.2. If a virtual table extension is +** used with an SQLite version earlier than 3.8.2, the results of attempting +** to read or write the estimatedRows field are undefined (but are likely +** to included crashing the application). The estimatedRows field should +** therefore only be used if [sqlite3_libversion_number()] returns a +** value greater than or equal to 3008002. */ struct sqlite3_index_info { /* Inputs */ @@ -5313,7 +5330,8 @@ struct sqlite3_index_info { char *idxStr; /* String, possibly obtained from sqlite3_malloc */ int needToFreeIdxStr; /* Free idxStr using sqlite3_free() if true */ int orderByConsumed; /* True if output is already ordered */ - double estimatedCost; /* Estimated cost of using this index */ + double estimatedCost; /* Estimated cost of using this index */ + sqlite3_int64 estimatedRows; /* Estimated number of rows returned */ }; /* @@ -5517,6 +5535,9 @@ typedef struct sqlite3_blob sqlite3_blob; ** interface. Use the [UPDATE] SQL command to change the size of a ** blob. ** +** ^The [sqlite3_blob_open()] interface will fail for a [WITHOUT ROWID] +** table. Incremental BLOB I/O is not possible on [WITHOUT ROWID] tables. +** ** ^The [sqlite3_bind_zeroblob()] and [sqlite3_result_zeroblob()] interfaces ** and the built-in [zeroblob] SQL function can be used, if desired, ** to create an empty, zero-filled blob in which to read or write using diff --git a/src/sqliteInt.h b/src/sqliteInt.h index ae33b448d9..e702c59ee4 100644 --- a/src/sqliteInt.h +++ b/src/sqliteInt.h @@ -217,6 +217,13 @@ # undef NDEBUG #endif +/* +** Enable SQLITE_ENABLE_EXPLAIN_COMMENTS if SQLITE_DEBUG is turned on. +*/ +#if !defined(SQLITE_ENABLE_EXPLAIN_COMMENTS) && defined(SQLITE_DEBUG) +# define SQLITE_ENABLE_EXPLAIN_COMMENTS 1 +#endif + /* ** The testcase() macro is used to aid in coverage testing. When ** doing coverage testing, the condition inside the argument to @@ -1419,6 +1426,7 @@ struct Table { #define TF_HasPrimaryKey 0x04 /* Table has a primary key */ #define TF_Autoincrement 0x08 /* Integer primary key is autoincrement */ #define TF_Virtual 0x10 /* Is a virtual table */ +#define TF_WithoutRowid 0x20 /* No rowid used. PRIMARY KEY is the key */ /* @@ -1434,6 +1442,9 @@ struct Table { # define IsHiddenColumn(X) 0 #endif +/* Does the table have a rowid */ +#define HasRowid(X) (((X)->tabFlags & TF_WithoutRowid)==0) + /* ** Each foreign key constraint is an instance of the following structure. ** @@ -1448,26 +1459,35 @@ struct Table { ** ); ** ** For foreign key "fk1", the from-table is "ex1" and the to-table is "ex2". +** Equivalent names: +** +** from-table == child-table +** to-table == parent-table ** ** Each REFERENCES clause generates an instance of the following structure ** which is attached to the from-table. The to-table need not exist when ** the from-table is created. The existence of the to-table is not checked. +** +** The list of all parents for child Table X is held at X.pFKey. +** +** A list of all children for a table named Z (which might not even exist) +** is held in Schema.fkeyHash with a hash key of Z. */ struct FKey { Table *pFrom; /* Table containing the REFERENCES clause (aka: Child) */ - FKey *pNextFrom; /* Next foreign key in pFrom */ + FKey *pNextFrom; /* Next FKey with the same in pFrom. Next parent of pFrom */ char *zTo; /* Name of table that the key points to (aka: Parent) */ - FKey *pNextTo; /* Next foreign key on table named zTo */ - FKey *pPrevTo; /* Previous foreign key on table named zTo */ + FKey *pNextTo; /* Next with the same zTo. Next child of zTo. */ + FKey *pPrevTo; /* Previous with the same zTo */ int nCol; /* Number of columns in this key */ /* EV: R-30323-21917 */ - u8 isDeferred; /* True if constraint checking is deferred till COMMIT */ - u8 aAction[2]; /* ON DELETE and ON UPDATE actions, respectively */ - Trigger *apTrigger[2]; /* Triggers for aAction[] actions */ - struct sColMap { /* Mapping of columns in pFrom to columns in zTo */ - int iFrom; /* Index of column in pFrom */ - char *zCol; /* Name of column in zTo. If 0 use PRIMARY KEY */ - } aCol[1]; /* One entry for each of nCol column s */ + u8 isDeferred; /* True if constraint checking is deferred till COMMIT */ + u8 aAction[2]; /* ON DELETE and ON UPDATE actions, respectively */ + Trigger *apTrigger[2];/* Triggers for aAction[] actions */ + struct sColMap { /* Mapping of columns in pFrom to columns in zTo */ + int iFrom; /* Index of column in pFrom */ + char *zCol; /* Name of column in zTo. If NULL use PRIMARY KEY */ + } aCol[1]; /* One entry for each of nCol columns */ }; /* @@ -1520,9 +1540,11 @@ struct FKey { ** for the rowid at the end. */ struct KeyInfo { - sqlite3 *db; /* The database connection */ + u32 nRef; /* Number of references to this KeyInfo object */ u8 enc; /* Text encoding - one of the SQLITE_UTF* values */ - u16 nField; /* Maximum index for aColl[] and aSortOrder[] */ + u16 nField; /* Number of key columns in the index */ + u16 nXField; /* Number of columns beyond the key columns */ + sqlite3 *db; /* The database connection */ u8 *aSortOrder; /* Sort order for each column. */ CollSeq *aColl[1]; /* Collating sequence for each term of the key */ }; @@ -1545,7 +1567,6 @@ struct UnpackedRecord { KeyInfo *pKeyInfo; /* Collation and sort-order information */ u16 nField; /* Number of entries in apMem[] */ u8 flags; /* Boolean settings. UNPACKED_... below */ - i64 rowid; /* Used by UNPACKED_PREFIX_SEARCH */ Mem *aMem; /* Values */ }; @@ -1554,7 +1575,6 @@ struct UnpackedRecord { */ #define UNPACKED_INCRKEY 0x01 /* Make this key an epsilon larger */ #define UNPACKED_PREFIX_MATCH 0x02 /* A prefix match is considered OK */ -#define UNPACKED_PREFIX_SEARCH 0x04 /* Ignore final (rowid) field */ /* ** Each SQL index is represented in memory by an @@ -1584,7 +1604,7 @@ struct UnpackedRecord { */ struct Index { char *zName; /* Name of this index */ - int *aiColumn; /* Which columns are used by this index. 1st is 0 */ + i16 *aiColumn; /* Which columns are used by this index. 1st is 0 */ tRowcnt *aiRowEst; /* From ANALYZE: Est. rows selected by each column */ Table *pTable; /* The SQL table being indexed */ char *zColAff; /* String defining the affinity of each column */ @@ -1593,13 +1613,17 @@ struct Index { u8 *aSortOrder; /* for each column: True==DESC, False==ASC */ char **azColl; /* Array of collation sequence names for index */ Expr *pPartIdxWhere; /* WHERE clause for partial indices */ + KeyInfo *pKeyInfo; /* A KeyInfo object suitable for this index */ int tnum; /* DB Page containing root of this index */ LogEst szIdxRow; /* Estimated average row size in bytes */ - u16 nColumn; /* Number of columns in table used by this index */ + u16 nKeyCol; /* Number of columns forming the key */ + u16 nColumn; /* Number of columns stored in the index */ u8 onError; /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */ unsigned autoIndex:2; /* 1==UNIQUE, 2==PRIMARY KEY, 0==CREATE INDEX */ unsigned bUnordered:1; /* Use this index for == or IN queries only */ unsigned uniqNotNull:1; /* True if UNIQUE and NOT NULL for all columns */ + unsigned isResized:1; /* True if resizeIndexObject() has been called */ + unsigned isCovering:1; /* True if this is a covering index */ #ifdef SQLITE_ENABLE_STAT3_OR_STAT4 int nSample; /* Number of elements in aSample[] */ int nSampleCol; /* Size of IndexSample.anEq[] and so on */ @@ -2278,6 +2302,8 @@ struct Parse { /* Information used while coding trigger programs. */ Parse *pToplevel; /* Parse structure for main program (or NULL) */ Table *pTriggerTab; /* Table triggers are being coded for */ + int addrCrTab; /* Address of OP_CreateTable opcode on CREATE TABLE */ + int addrSkipPK; /* Address of instruction to skip PRIMARY KEY index */ u32 nQueryLoop; /* Est number of iterations of a query (10*log2(N)) */ u32 oldmask; /* Mask of old.* columns referenced */ u32 newmask; /* Mask of new.* columns referenced */ @@ -2290,6 +2316,7 @@ struct Parse { int nVar; /* Number of '?' variables seen in the SQL so far */ int nzVar; /* Number of available slots in azVar[] */ + u8 iPkSortOrder; /* ASC or DESC for INTEGER PRIMARY KEY */ u8 explain; /* True if the EXPLAIN flag is found on the query */ #ifndef SQLITE_OMIT_VIRTUALTABLE u8 declareVtab; /* True if inside sqlite3_declare_vtab() */ @@ -2303,7 +2330,6 @@ struct Parse { #endif char **azVar; /* Pointers to names of parameters */ Vdbe *pReprepare; /* VM being reprepared (sqlite3Reprepare()) */ - int *aAlias; /* Register used to hold aliased result */ const char *zTail; /* All SQL text past the last semicolon parsed */ Table *pNewTable; /* A table being constructed by CREATE TABLE */ Trigger *pNewTrigger; /* Trigger under construct by a CREATE TRIGGER */ @@ -2776,6 +2802,8 @@ void sqlite3BeginParse(Parse*,int); void sqlite3CommitInternalChanges(sqlite3*); Table *sqlite3ResultSetOfSelect(Parse*,Select*); void sqlite3OpenMasterTable(Parse *, int); +Index *sqlite3PrimaryKeyIndex(Table*); +i16 sqlite3ColumnOfIndex(Index*, i16); void sqlite3StartTable(Parse*,Token*,Token*,int,int,int,int); void sqlite3AddColumn(Parse*,Token*); void sqlite3AddNotNull(Parse*, int); @@ -2784,7 +2812,7 @@ void sqlite3AddCheckConstraint(Parse*, Expr*); void sqlite3AddColumnType(Parse*,Token*); void sqlite3AddDefaultValue(Parse*,ExprSpan*); void sqlite3AddCollateType(Parse*, Token*); -void sqlite3EndTable(Parse*,Token*,Token*,Select*); +void sqlite3EndTable(Parse*,Token*,Token*,u8,Select*); int sqlite3ParseUri(const char*,const char*,unsigned int*, sqlite3_vfs**,char**,char **); Btree *sqlite3DbNameToBtree(sqlite3*,const char*); @@ -2837,6 +2865,7 @@ void sqlite3SrcListShiftJoinType(SrcList*); void sqlite3SrcListAssignCursors(Parse*, SrcList*); void sqlite3IdListDelete(sqlite3*, IdList*); void sqlite3SrcListDelete(sqlite3*, SrcList*); +Index *sqlite3AllocateIndexObject(sqlite3*,i16,int,char**); Index *sqlite3CreateIndex(Parse*,Token*,Token*,SrcList*,ExprList*,int,Token*, Expr*, int, int); void sqlite3DropIndex(Parse*, SrcList*, int); @@ -2859,7 +2888,7 @@ int sqlite3WhereIsDistinct(WhereInfo*); int sqlite3WhereIsOrdered(WhereInfo*); int sqlite3WhereContinueLabel(WhereInfo*); int sqlite3WhereBreakLabel(WhereInfo*); -int sqlite3WhereOkOnePass(WhereInfo*); +int sqlite3WhereOkOnePass(WhereInfo*, int*); int sqlite3ExprCodeGetColumn(Parse*, Table*, int, int, int, u8); void sqlite3ExprCodeGetColumnOfTable(Vdbe*, Table*, int, int, int); void sqlite3ExprCodeMove(Parse*, int, int, int); @@ -2913,17 +2942,19 @@ int sqlite3ExprCanBeNull(const Expr*); void sqlite3ExprCodeIsNullJump(Vdbe*, const Expr*, int, int); int sqlite3ExprNeedsNoAffinityChange(const Expr*, char); int sqlite3IsRowid(const char*); -void sqlite3GenerateRowDelete(Parse*, Table*, int, int, int, Trigger *, int); -void sqlite3GenerateRowIndexDelete(Parse*, Table*, int, int*); +void sqlite3GenerateRowDelete(Parse*,Table*,Trigger*,int,int,int,i16,u8,u8,u8); +void sqlite3GenerateRowIndexDelete(Parse*, Table*, int, int, int*); int sqlite3GenerateIndexKey(Parse*, Index*, int, int, int, int*); -void sqlite3GenerateConstraintChecks(Parse*,Table*,int,int, - int*,int,int,int,int,int*); -void sqlite3CompleteInsertion(Parse*, Table*, int, int, int*, int, int, int); -int sqlite3OpenTableAndIndices(Parse*, Table*, int, int); +void sqlite3GenerateConstraintChecks(Parse*,Table*,int*,int,int,int,int, + u8,u8,int,int*); +void sqlite3CompleteInsertion(Parse*,Table*,int,int,int,int*,int,int,int); +int sqlite3OpenTableAndIndices(Parse*, Table*, int, int, int*, int*); void sqlite3BeginWriteOperation(Parse*, int, int); void sqlite3MultiWrite(Parse*); void sqlite3MayAbort(Parse*); -void sqlite3HaltConstraint(Parse*, int, int, char*, int); +void sqlite3HaltConstraint(Parse*, int, int, char*, i8, u8); +void sqlite3UniqueConstraint(Parse*, int, Index*); +void sqlite3RowidConstraint(Parse*, int, Table*); Expr *sqlite3ExprDup(sqlite3*,Expr*,int); ExprList *sqlite3ExprListDup(sqlite3*,ExprList*,int); SrcList *sqlite3SrcListDup(sqlite3*,SrcList*,int); @@ -3141,8 +3172,13 @@ void sqlite3MinimumFileFormat(Parse*, int, int); void sqlite3SchemaClear(void *); Schema *sqlite3SchemaGet(sqlite3 *, Btree *); int sqlite3SchemaToIndex(sqlite3 *db, Schema *); -KeyInfo *sqlite3KeyInfoAlloc(sqlite3*,int); -KeyInfo *sqlite3IndexKeyinfo(Parse *, Index *); +KeyInfo *sqlite3KeyInfoAlloc(sqlite3*,int,int); +void sqlite3KeyInfoUnref(KeyInfo*); +KeyInfo *sqlite3KeyInfoRef(KeyInfo*); +KeyInfo *sqlite3KeyInfoOfIndex(Parse*, Index*); +#ifdef SQLITE_DEBUG +int sqlite3KeyInfoIsWriteable(KeyInfo*); +#endif int sqlite3CreateFunc(sqlite3 *, const char *, int, int, void *, void (*)(sqlite3_context*,int,sqlite3_value **), void (*)(sqlite3_context*,int,sqlite3_value **), void (*)(sqlite3_context*), diff --git a/src/test6.c b/src/test6.c index 2020885c46..6ea03b0f1c 100644 --- a/src/test6.c +++ b/src/test6.c @@ -621,7 +621,7 @@ static int cfOpen( pWrapper->flags = flags; } if( rc==SQLITE_OK ){ - pWrapper->nData = (4096 + pWrapper->iSize); + pWrapper->nData = (int)(4096 + pWrapper->iSize); pWrapper->zData = crash_malloc(pWrapper->nData); if( pWrapper->zData ){ /* os_unix.c contains an assert() that fails if the caller attempts @@ -637,7 +637,7 @@ static int cfOpen( memset(pWrapper->zData, 0, pWrapper->nData); for(iOff=0; iOffiSize; iOff += 512){ - int nRead = pWrapper->iSize - (int)iOff; + int nRead = (int)(pWrapper->iSize - iOff); if( nRead>512 ) nRead = 512; if( isDb && iOff==PENDING_BYTE ) continue; rc = sqlite3OsRead(pReal, &pWrapper->zData[iOff], nRead, iOff); diff --git a/src/test_config.c b/src/test_config.c index c64222b373..a624a43dbb 100644 --- a/src/test_config.c +++ b/src/test_config.c @@ -258,12 +258,7 @@ static void set_options(Tcl_Interp *interp){ #endif Tcl_SetVar2(interp, "sqlite_options", "conflict", "1", TCL_GLOBAL_ONLY); - -#if SQLITE_OS_UNIX Tcl_SetVar2(interp, "sqlite_options", "crashtest", "1", TCL_GLOBAL_ONLY); -#else - Tcl_SetVar2(interp, "sqlite_options", "crashtest", "0", TCL_GLOBAL_ONLY); -#endif #ifdef SQLITE_OMIT_DATETIME_FUNCS Tcl_SetVar2(interp, "sqlite_options", "datetime", "0", TCL_GLOBAL_ONLY); diff --git a/src/test_multiplex.c b/src/test_multiplex.c index 624541b32a..45a1edfbbe 100644 --- a/src/test_multiplex.c +++ b/src/test_multiplex.c @@ -755,9 +755,11 @@ static int multiplexRead( multiplexConn *p = (multiplexConn*)pConn; multiplexGroup *pGroup = p->pGroup; int rc = SQLITE_OK; - multiplexEnter(); + int nMutex = 0; + multiplexEnter(); nMutex++; if( !pGroup->bEnabled ){ sqlite3_file *pSubOpen = multiplexSubOpen(pGroup, 0, &rc, NULL, 0); + multiplexLeave(); nMutex--; if( pSubOpen==0 ){ rc = SQLITE_IOERR_READ; }else{ @@ -766,7 +768,10 @@ static int multiplexRead( }else{ while( iAmt > 0 ){ int i = (int)(iOfst / pGroup->szChunk); - sqlite3_file *pSubOpen = multiplexSubOpen(pGroup, i, &rc, NULL, 1); + sqlite3_file *pSubOpen; + if( nMutex==0 ){ multiplexEnter(); nMutex++; } + pSubOpen = multiplexSubOpen(pGroup, i, &rc, NULL, 1); + multiplexLeave(); nMutex--; if( pSubOpen ){ int extra = ((int)(iOfst % pGroup->szChunk) + iAmt) - pGroup->szChunk; if( extra<0 ) extra = 0; @@ -783,7 +788,8 @@ static int multiplexRead( } } } - multiplexLeave(); + assert( nMutex==0 || nMutex==1 ); + if( nMutex ) multiplexLeave(); return rc; } diff --git a/src/test_stat.c b/src/test_stat.c index d4c902b5ea..615df3d80f 100644 --- a/src/test_stat.c +++ b/src/test_stat.c @@ -397,6 +397,7 @@ static int statNext(sqlite3_vtab_cursor *pCursor){ sqlite3_free(pCsr->zPath); pCsr->zPath = 0; +statNextRestart: if( pCsr->aPage[0].pPg==0 ){ rc = sqlite3_step(pCsr->pStmt); if( rc==SQLITE_ROW ){ @@ -448,11 +449,11 @@ static int statNext(sqlite3_vtab_cursor *pCursor){ p->iCell++; } - while( !p->iRightChildPg || p->iCell>p->nCell ){ + if( !p->iRightChildPg || p->iCell>p->nCell ){ statClearPage(p); if( pCsr->iPage==0 ) return statNext(pCursor); pCsr->iPage--; - p = &pCsr->aPage[pCsr->iPage]; + goto statNextRestart; /* Tail recursion */ } pCsr->iPage++; assert( p==&pCsr->aPage[pCsr->iPage-1] ); diff --git a/src/tokenize.c b/src/tokenize.c index d26157f7d2..f27929ea5b 100644 --- a/src/tokenize.c +++ b/src/tokenize.c @@ -506,7 +506,6 @@ abort_parse: sqlite3DeleteTrigger(db, pParse->pNewTrigger); for(i=pParse->nzVar-1; i>=0; i--) sqlite3DbFree(db, pParse->azVar[i]); sqlite3DbFree(db, pParse->azVar); - sqlite3DbFree(db, pParse->aAlias); while( pParse->pAinc ){ AutoincInfo *p = pParse->pAinc; pParse->pAinc = p->pNext; diff --git a/src/trigger.c b/src/trigger.c index 774711f0f5..607b831243 100644 --- a/src/trigger.c +++ b/src/trigger.c @@ -784,7 +784,7 @@ static int codeTriggerProgram( return 0; } -#ifdef SQLITE_DEBUG +#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS /* ** This function is used to add VdbeComment() annotations to a VDBE ** program. It is not used in production code, only for debugging. diff --git a/src/update.c b/src/update.c index 2e5d935389..d355d7153c 100644 --- a/src/update.c +++ b/src/update.c @@ -95,18 +95,22 @@ void sqlite3Update( ){ int i, j; /* Loop counters */ Table *pTab; /* The table to be updated */ - int addr = 0; /* VDBE instruction address of the start of the loop */ + int addrTop = 0; /* VDBE instruction address of the start of the loop */ WhereInfo *pWInfo; /* Information about the WHERE clause */ Vdbe *v; /* The virtual database engine */ Index *pIdx; /* For looping over indices */ + Index *pPk; /* The PRIMARY KEY index for WITHOUT ROWID tables */ int nIdx; /* Number of indices that need updating */ - int iCur; /* VDBE Cursor number of pTab */ + int iDataCur; /* Cursor for the canonical data btree */ + int iIdxCur; /* Cursor for the first index */ sqlite3 *db; /* The database structure */ int *aRegIdx = 0; /* One register assigned to each index to be updated */ int *aXRef = 0; /* aXRef[i] is the index in pChanges->a[] of the ** an expression for the i-th column of the table. ** aXRef[i]==-1 if the i-th column is not changed. */ - int chngRowid; /* True if the record number is being changed */ + u8 chngPk; /* PRIMARY KEY changed in a WITHOUT ROWID table */ + u8 chngRowid; /* Rowid changed in a normal table */ + u8 chngKey; /* Either chngPk or chngRowid */ Expr *pRowidExpr = 0; /* Expression defining the new record number */ int openAll = 0; /* True if all indices need to be opened */ AuthContext sContext; /* The authorization context */ @@ -114,6 +118,8 @@ void sqlite3Update( int iDb; /* Database containing the table being updated */ int okOnePass; /* True for one-pass algorithm without the FIFO */ int hasFK; /* True if foreign key processing is required */ + int labelBreak; /* Jump here to break out of UPDATE loop */ + int labelContinue; /* Jump here to continue next step of UPDATE loop */ #ifndef SQLITE_OMIT_TRIGGER int isView; /* True when updating a view (INSTEAD OF trigger) */ @@ -121,6 +127,9 @@ void sqlite3Update( int tmask; /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */ #endif int newmask; /* Mask of NEW.* columns accessed by BEFORE triggers */ + int iEph = 0; /* Ephemeral table holding all primary key values */ + int nKey = 0; /* Number of elements in regKey for WITHOUT ROWID */ + int aiCurOnePass[2]; /* The write cursors opened by WHERE_ONEPASS */ /* Register Allocations */ int regRowCount = 0; /* A count of rows changed */ @@ -129,6 +138,7 @@ void sqlite3Update( int regNew; /* Content of the NEW.* table in triggers */ int regOld = 0; /* Content of OLD.* table in triggers */ int regRowSet = 0; /* Rowset of rows to be updated */ + int regKey = 0; /* composite PRIMARY KEY value */ memset(&sContext, 0, sizeof(sContext)); db = pParse->db; @@ -175,8 +185,14 @@ void sqlite3Update( ** need to occur right after the database cursor. So go ahead and ** allocate enough space, just in case. */ - pTabList->a[0].iCursor = iCur = pParse->nTab++; - for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ + pTabList->a[0].iCursor = iDataCur = pParse->nTab++; + iIdxCur = iDataCur+1; + pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab); + for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){ + if( pIdx->autoIndex==2 && pPk!=0 ){ + iDataCur = pParse->nTab; + pTabList->a[0].iCursor = iDataCur; + } pParse->nTab++; } @@ -191,7 +207,7 @@ void sqlite3Update( ** column to be updated, make sure we have authorization to change ** that column. */ - chngRowid = 0; + chngRowid = chngPk = 0; for(i=0; inExpr; i++){ if( sqlite3ResolveExprNames(&sNC, pChanges->a[i].pExpr) ){ goto update_cleanup; @@ -201,13 +217,15 @@ void sqlite3Update( if( j==pTab->iPKey ){ chngRowid = 1; pRowidExpr = pChanges->a[i].pExpr; + }else if( pPk && (pTab->aCol[j].colFlags & COLFLAG_PRIMKEY)!=0 ){ + chngPk = 1; } aXRef[j] = i; break; } } if( j>=pTab->nCol ){ - if( sqlite3IsRowid(pChanges->a[i].zName) ){ + if( pPk==0 && sqlite3IsRowid(pChanges->a[i].zName) ){ j = -1; chngRowid = 1; pRowidExpr = pChanges->a[i].pExpr; @@ -231,26 +249,29 @@ void sqlite3Update( } #endif } + assert( (chngRowid & chngPk)==0 ); + assert( chngRowid==0 || chngRowid==1 ); + assert( chngPk==0 || chngPk==1 ); + chngKey = chngRowid + chngPk; - hasFK = sqlite3FkRequired(pParse, pTab, aXRef, chngRowid); + hasFK = sqlite3FkRequired(pParse, pTab, aXRef, chngKey); /* Allocate memory for the array aRegIdx[]. There is one entry in the ** array for each index associated with table being updated. Fill in ** the value with a register number for indices that are to be used ** and with zero for unused indices. */ - for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){} if( nIdx>0 ){ aRegIdx = sqlite3DbMallocRaw(db, sizeof(Index*) * nIdx ); if( aRegIdx==0 ) goto update_cleanup; } for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){ int reg; - if( hasFK || chngRowid || pIdx->pPartIdxWhere ){ + if( chngKey || hasFK || pIdx->pPartIdxWhere || pIdx==pPk ){ reg = ++pParse->nMem; }else{ reg = 0; - for(i=0; inColumn; i++){ + for(i=0; inKeyCol; i++){ if( aXRef[pIdx->aiColumn[i]]>=0 ){ reg = ++pParse->nMem; break; @@ -280,11 +301,11 @@ void sqlite3Update( /* Allocate required registers. */ regRowSet = ++pParse->nMem; regOldRowid = regNewRowid = ++pParse->nMem; - if( pTrigger || hasFK ){ + if( chngPk || pTrigger || hasFK ){ regOld = pParse->nMem + 1; pParse->nMem += pTab->nCol; } - if( chngRowid || pTrigger || hasFK ){ + if( chngKey || pTrigger || hasFK ){ regNewRowid = ++pParse->nMem; } regNew = pParse->nMem + 1; @@ -300,7 +321,7 @@ void sqlite3Update( */ #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) if( isView ){ - sqlite3MaterializeView(pParse, pTab, pWhere, iCur); + sqlite3MaterializeView(pParse, pTab, pWhere, iDataCur); } #endif @@ -313,24 +334,58 @@ void sqlite3Update( /* Begin the database scan */ - sqlite3VdbeAddOp3(v, OP_Null, 0, regRowSet, regOldRowid); - pWInfo = sqlite3WhereBegin( - pParse, pTabList, pWhere, 0, 0, WHERE_ONEPASS_DESIRED, 0 - ); - if( pWInfo==0 ) goto update_cleanup; - okOnePass = sqlite3WhereOkOnePass(pWInfo); + if( HasRowid(pTab) ){ + sqlite3VdbeAddOp3(v, OP_Null, 0, regRowSet, regOldRowid); + pWInfo = sqlite3WhereBegin( + pParse, pTabList, pWhere, 0, 0, WHERE_ONEPASS_DESIRED, iIdxCur + ); + if( pWInfo==0 ) goto update_cleanup; + okOnePass = sqlite3WhereOkOnePass(pWInfo, aiCurOnePass); + + /* Remember the rowid of every item to be updated. + */ + sqlite3VdbeAddOp2(v, OP_Rowid, iDataCur, regOldRowid); + if( !okOnePass ){ + sqlite3VdbeAddOp2(v, OP_RowSetAdd, regRowSet, regOldRowid); + } + + /* End the database scan loop. + */ + sqlite3WhereEnd(pWInfo); + }else{ + int iPk; /* First of nPk memory cells holding PRIMARY KEY value */ + i16 nPk; /* Number of components of the PRIMARY KEY */ + int addrOpen; /* Address of the OpenEphemeral instruction */ - /* Remember the rowid of every item to be updated. - */ - sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regOldRowid); - if( !okOnePass ){ - sqlite3VdbeAddOp2(v, OP_RowSetAdd, regRowSet, regOldRowid); + assert( pPk!=0 ); + nPk = pPk->nKeyCol; + iPk = pParse->nMem+1; + pParse->nMem += nPk; + regKey = ++pParse->nMem; + iEph = pParse->nTab++; + sqlite3VdbeAddOp2(v, OP_Null, 0, iPk); + addrOpen = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iEph, nPk); + sqlite3VdbeSetP4KeyInfo(pParse, pPk); + pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0, 0, + WHERE_ONEPASS_DESIRED, iIdxCur); + if( pWInfo==0 ) goto update_cleanup; + okOnePass = sqlite3WhereOkOnePass(pWInfo, aiCurOnePass); + for(i=0; iaiColumn[i], + iPk+i); + } + if( okOnePass ){ + sqlite3VdbeChangeToNoop(v, addrOpen); + nKey = nPk; + regKey = iPk; + }else{ + sqlite3VdbeAddOp4(v, OP_MakeRecord, iPk, nPk, regKey, + sqlite3IndexAffinityStr(v, pPk), P4_TRANSIENT); + sqlite3VdbeAddOp2(v, OP_IdxInsert, iEph, regKey); + } + sqlite3WhereEnd(pWInfo); } - /* End the database scan loop. - */ - sqlite3WhereEnd(pWInfo); - /* Initialize the count of updated rows */ if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab ){ @@ -338,6 +393,7 @@ void sqlite3Update( sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount); } + labelBreak = sqlite3VdbeMakeLabel(v); if( !isView ){ /* ** Open every index that needs updating. Note that if any @@ -345,7 +401,10 @@ void sqlite3Update( ** action, then we need to open all indices because we might need ** to be deleting some records. */ - if( !okOnePass ) sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenWrite); + if( !okOnePass && HasRowid(pTab) ){ + sqlite3OpenTable(pParse, iDataCur, iDb, pTab, OP_OpenWrite); + } + sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName); if( onError==OE_Replace ){ openAll = 1; }else{ @@ -358,55 +417,67 @@ void sqlite3Update( } } for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){ + int iThisCur = iIdxCur+i; assert( aRegIdx ); - if( openAll || aRegIdx[i]>0 ){ - KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx); - sqlite3VdbeAddOp4(v, OP_OpenWrite, iCur+i+1, pIdx->tnum, iDb, - (char*)pKey, P4_KEYINFO_HANDOFF); - assert( pParse->nTab>iCur+i+1 ); + if( (openAll || aRegIdx[i]>0) + && iThisCur!=aiCurOnePass[1] + ){ + assert( iThisCur!=aiCurOnePass[0] ); + sqlite3VdbeAddOp3(v, OP_OpenWrite, iThisCur, pIdx->tnum, iDb); + sqlite3VdbeSetP4KeyInfo(pParse, pIdx); + assert( pParse->nTab>iThisCur ); + VdbeComment((v, "%s", pIdx->zName)); + if( okOnePass && pPk && iThisCur==iDataCur ){ + sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelBreak, + regKey, nKey); + } } } } /* Top of the update loop */ if( okOnePass ){ - int a1 = sqlite3VdbeAddOp1(v, OP_NotNull, regOldRowid); - addr = sqlite3VdbeAddOp0(v, OP_Goto); - sqlite3VdbeJumpHere(v, a1); + labelContinue = labelBreak; + sqlite3VdbeAddOp2(v, OP_IsNull, pPk ? regKey : regOldRowid, labelBreak); + }else if( pPk ){ + labelContinue = sqlite3VdbeMakeLabel(v); + sqlite3VdbeAddOp2(v, OP_Rewind, iEph, labelBreak); + addrTop = sqlite3VdbeAddOp2(v, OP_RowKey, iEph, regKey); + sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelContinue, regKey, 0); }else{ - addr = sqlite3VdbeAddOp3(v, OP_RowSetRead, regRowSet, 0, regOldRowid); + labelContinue = sqlite3VdbeAddOp3(v, OP_RowSetRead, regRowSet, labelBreak, + regOldRowid); + sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, labelContinue, regOldRowid); } - /* Make cursor iCur point to the record that is being updated. If - ** this record does not exist for some reason (deleted by a trigger, - ** for example, then jump to the next iteration of the RowSet loop. */ - sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, regOldRowid); - /* If the record number will change, set register regNewRowid to ** contain the new value. If the record number is not being modified, ** then regNewRowid is the same register as regOldRowid, which is ** already populated. */ - assert( chngRowid || pTrigger || hasFK || regOldRowid==regNewRowid ); + assert( chngKey || pTrigger || hasFK || regOldRowid==regNewRowid ); if( chngRowid ){ sqlite3ExprCode(pParse, pRowidExpr, regNewRowid); sqlite3VdbeAddOp1(v, OP_MustBeInt, regNewRowid); } - /* If there are triggers on this table, populate an array of registers - ** with the required old.* column data. */ - if( hasFK || pTrigger ){ + /* Compute the old pre-UPDATE content of the row being changed, if that + ** information is needed */ + if( chngPk || hasFK || pTrigger ){ u32 oldmask = (hasFK ? sqlite3FkOldmask(pParse, pTab) : 0); oldmask |= sqlite3TriggerColmask(pParse, pTrigger, pChanges, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onError ); for(i=0; inCol; i++){ - if( aXRef[i]<0 || oldmask==0xffffffff || (i<32 && (oldmask & (1<aCol[i].colFlags & COLFLAG_PRIMKEY)!=0 + ){ + sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, regOld+i); }else{ sqlite3VdbeAddOp2(v, OP_Null, 0, regOld+i); } } - if( chngRowid==0 ){ + if( chngRowid==0 && pPk==0 ){ sqlite3VdbeAddOp2(v, OP_Copy, regOldRowid, regNewRowid); } } @@ -443,8 +514,7 @@ void sqlite3Update( */ testcase( i==31 ); testcase( i==32 ); - sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regNew+i); - sqlite3ColumnDefault(v, pTab, i, regNew+i); + sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, regNew+i); } } } @@ -456,7 +526,7 @@ void sqlite3Update( sqlite3VdbeAddOp2(v, OP_Affinity, regNew, pTab->nCol); sqlite3TableAffinityStr(v, pTab); sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges, - TRIGGER_BEFORE, pTab, regOldRowid, onError, addr); + TRIGGER_BEFORE, pTab, regOldRowid, onError, labelContinue); /* The row-trigger may have deleted the row being updated. In this ** case, jump to the next row. No updates or AFTER triggers are @@ -464,7 +534,11 @@ void sqlite3Update( ** is deleted or renamed by a BEFORE trigger - is left undefined in the ** documentation. */ - sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, regOldRowid); + if( pPk ){ + sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelContinue,regKey,nKey); + }else{ + sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, labelContinue, regOldRowid); + } /* If it did not delete it, the row-trigger may still have modified ** some of the columns of the row being updated. Load the values for @@ -473,27 +547,34 @@ void sqlite3Update( */ for(i=0; inCol; i++){ if( aXRef[i]<0 && i!=pTab->iPKey ){ - sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regNew+i); - sqlite3ColumnDefault(v, pTab, i, regNew+i); + sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, regNew+i); } } } if( !isView ){ - int j1; /* Address of jump instruction */ + int j1 = 0; /* Address of jump instruction */ + int bReplace = 0; /* True if REPLACE conflict resolution might happen */ /* Do constraint checks. */ - sqlite3GenerateConstraintChecks(pParse, pTab, iCur, regNewRowid, - aRegIdx, (chngRowid?regOldRowid:0), 1, onError, addr, 0); + assert( regOldRowid>0 ); + sqlite3GenerateConstraintChecks(pParse, pTab, aRegIdx, iDataCur, iIdxCur, + regNewRowid, regOldRowid, chngKey, onError, labelContinue, &bReplace); /* Do FK constraint checks. */ if( hasFK ){ - sqlite3FkCheck(pParse, pTab, regOldRowid, 0, aXRef, chngRowid); + sqlite3FkCheck(pParse, pTab, regOldRowid, 0, aXRef, chngKey); } /* Delete the index entries associated with the current record. */ - j1 = sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regOldRowid); - sqlite3GenerateRowIndexDelete(pParse, pTab, iCur, aRegIdx); + if( bReplace || chngKey ){ + if( pPk ){ + j1 = sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, 0, regKey, nKey); + }else{ + j1 = sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, 0, regOldRowid); + } + } + sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur, aRegIdx); /* If changing the rowid value, or if there are foreign key constraints ** to process, delete the old record. Otherwise, add a noop OP_Delete @@ -505,27 +586,34 @@ void sqlite3Update( ** is the column index supplied by the user. */ assert( regNew==regNewRowid+1 ); - sqlite3VdbeAddOp3(v, OP_Delete, iCur, - OPFLAG_ISUPDATE | ((hasFK || chngRowid) ? 0 : OPFLAG_ISNOOP), + sqlite3VdbeAddOp3(v, OP_Delete, iDataCur, + OPFLAG_ISUPDATE | ((hasFK || chngKey || pPk!=0) ? 0 : OPFLAG_ISNOOP), regNewRowid ); if( !pParse->nested ){ sqlite3VdbeChangeP4(v, -1, (char*)pTab, P4_TABLE); } - sqlite3VdbeJumpHere(v, j1); + if( bReplace || chngKey ){ + if( sqlite3VdbeCurrentAddr(v)==j1+1 ){ + sqlite3VdbeChangeToNoop(v, j1); + }else{ + sqlite3VdbeJumpHere(v, j1); + } + } if( hasFK ){ - sqlite3FkCheck(pParse, pTab, 0, regNewRowid, aXRef, chngRowid); + sqlite3FkCheck(pParse, pTab, 0, regNewRowid, aXRef, chngKey); } /* Insert the new index entries and the new record. */ - sqlite3CompleteInsertion(pParse, pTab, iCur, regNewRowid, aRegIdx, 1, 0, 0); + sqlite3CompleteInsertion(pParse, pTab, iDataCur, iIdxCur, + regNewRowid, aRegIdx, 1, 0, 0); /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to ** handle rows (possibly in other tables) that refer via a foreign key ** to the row just updated. */ if( hasFK ){ - sqlite3FkActions(pParse, pTab, pChanges, regOldRowid, aXRef, chngRowid); + sqlite3FkActions(pParse, pTab, pChanges, regOldRowid, aXRef, chngKey); } } @@ -536,22 +624,29 @@ void sqlite3Update( } sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges, - TRIGGER_AFTER, pTab, regOldRowid, onError, addr); + TRIGGER_AFTER, pTab, regOldRowid, onError, labelContinue); /* Repeat the above with the next record to be updated, until ** all record selected by the WHERE clause have been updated. */ - sqlite3VdbeAddOp2(v, OP_Goto, 0, addr); - sqlite3VdbeJumpHere(v, addr); + if( okOnePass ){ + /* Nothing to do at end-of-loop for a single-pass */ + }else if( pPk ){ + sqlite3VdbeResolveLabel(v, labelContinue); + sqlite3VdbeAddOp2(v, OP_Next, iEph, addrTop); + }else{ + sqlite3VdbeAddOp2(v, OP_Goto, 0, labelContinue); + } + sqlite3VdbeResolveLabel(v, labelBreak); /* Close all tables */ for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){ assert( aRegIdx ); if( openAll || aRegIdx[i]>0 ){ - sqlite3VdbeAddOp2(v, OP_Close, iCur+i+1, 0); + sqlite3VdbeAddOp2(v, OP_Close, iIdxCur+i, 0); } } - sqlite3VdbeAddOp2(v, OP_Close, iCur, 0); + if( iDataCur0" + " AND coalesce(rootpage,1)>0" ); if( rc!=SQLITE_OK ) goto end_of_vacuum; rc = execExecSql(db, pzErrMsg, @@ -255,7 +255,7 @@ int sqlite3RunVacuum(char **pzErrMsg, sqlite3 *db){ "|| ' SELECT * FROM main.' || quote(name) || ';'" "FROM main.sqlite_master " "WHERE type = 'table' AND name!='sqlite_sequence' " - " AND rootpage>0" + " AND coalesce(rootpage,1)>0" ); if( rc!=SQLITE_OK ) goto end_of_vacuum; diff --git a/src/vdbe.c b/src/vdbe.c index 9b384b4c6d..4eb900f256 100644 --- a/src/vdbe.c +++ b/src/vdbe.c @@ -814,11 +814,13 @@ case OP_Yield: { /* in1 */ break; } -/* Opcode: HaltIfNull P1 P2 P3 P4 * +/* Opcode: HaltIfNull P1 P2 P3 P4 P5 +** Synopsis: if r[P3] null then halt ** ** Check the value in register P3. If it is NULL then Halt using ** parameter P1, P2, and P4 as if this were a Halt instruction. If the ** value in register P3 is not NULL, then this routine is a no-op. +** The P5 parameter should be 1. */ case OP_HaltIfNull: { /* in3 */ pIn3 = &aMem[pOp->p3]; @@ -826,7 +828,7 @@ case OP_HaltIfNull: { /* in3 */ /* Fall through into OP_Halt */ } -/* Opcode: Halt P1 P2 * P4 * +/* Opcode: Halt P1 P2 * P4 P5 ** ** Exit immediately. All open cursors, etc are closed ** automatically. @@ -841,11 +843,25 @@ case OP_HaltIfNull: { /* in3 */ ** ** If P4 is not null then it is an error message string. ** +** P5 is a value between 0 and 4, inclusive, that modifies the P4 string. +** +** 0: (no change) +** 1: NOT NULL contraint failed: P4 +** 2: UNIQUE constraint failed: P4 +** 3: CHECK constraint failed: P4 +** 4: FOREIGN KEY constraint failed: P4 +** +** If P5 is not zero and P4 is NULL, then everything after the ":" is +** omitted. +** ** There is an implied "Halt 0 0 0" instruction inserted at the very end of ** every program. So a jump past the last instruction of the program ** is the same as executing Halt. */ case OP_Halt: { + const char *zType; + const char *zLogFmt; + if( pOp->p1==SQLITE_OK && p->pFrame ){ /* Halt the sub-program. Return control to the parent frame. */ VdbeFrame *pFrame = p->pFrame; @@ -866,18 +882,33 @@ case OP_Halt: { aMem = p->aMem; break; } - p->rc = pOp->p1; p->errorAction = (u8)pOp->p2; p->pc = pc; - if( pOp->p4.z ){ - assert( p->rc!=SQLITE_OK ); - sqlite3SetString(&p->zErrMsg, db, "%s", pOp->p4.z); - testcase( sqlite3GlobalConfig.xLog!=0 ); - sqlite3_log(pOp->p1, "abort at %d in [%s]: %s", pc, p->zSql, pOp->p4.z); - }else if( p->rc ){ - testcase( sqlite3GlobalConfig.xLog!=0 ); - sqlite3_log(pOp->p1, "constraint failed at %d in [%s]", pc, p->zSql); + if( p->rc ){ + if( pOp->p5 ){ + static const char * const azType[] = { "NOT NULL", "UNIQUE", "CHECK", + "FOREIGN KEY" }; + assert( pOp->p5>=1 && pOp->p5<=4 ); + testcase( pOp->p5==1 ); + testcase( pOp->p5==2 ); + testcase( pOp->p5==3 ); + testcase( pOp->p5==4 ); + zType = azType[pOp->p5-1]; + }else{ + zType = 0; + } + assert( zType!=0 || pOp->p4.z!=0 ); + zLogFmt = "abort at %d in [%s]: %s"; + if( zType && pOp->p4.z ){ + sqlite3SetString(&p->zErrMsg, db, "%s constraint failed: %s", + zType, pOp->p4.z); + }else if( pOp->p4.z ){ + sqlite3SetString(&p->zErrMsg, db, "%s", pOp->p4.z); + }else{ + sqlite3SetString(&p->zErrMsg, db, "%s constraint failed", zType); + } + sqlite3_log(pOp->p1, zLogFmt, pc, p->zSql, p->zErrMsg); } rc = sqlite3VdbeHalt(p); assert( rc==SQLITE_BUSY || rc==SQLITE_OK || rc==SQLITE_ERROR ); @@ -892,6 +923,7 @@ case OP_Halt: { } /* Opcode: Integer P1 P2 * * * +** Synopsis: r[P2]=P1 ** ** The 32-bit integer value P1 is written into register P2. */ @@ -901,6 +933,7 @@ case OP_Integer: { /* out2-prerelease */ } /* Opcode: Int64 * P2 * P4 * +** Synopsis: r[P2]=P4 ** ** P4 is a pointer to a 64-bit integer value. ** Write that value into register P2. @@ -913,6 +946,7 @@ case OP_Int64: { /* out2-prerelease */ #ifndef SQLITE_OMIT_FLOATING_POINT /* Opcode: Real * P2 * P4 * +** Synopsis: r[P2]=P4 ** ** P4 is a pointer to a 64-bit floating point value. ** Write that value into register P2. @@ -926,6 +960,7 @@ case OP_Real: { /* same as TK_FLOAT, out2-prerelease */ #endif /* Opcode: String8 * P2 * P4 * +** Synopsis: r[P2]='P4' ** ** P4 points to a nul terminated UTF-8 string. This opcode is transformed ** into an OP_String before it is executed for the first time. @@ -960,6 +995,7 @@ case OP_String8: { /* same as TK_STRING, out2-prerelease */ } /* Opcode: String P1 P2 * P4 * +** Synopsis: r[P2]='P4' (len=P1) ** ** The string value P4 of length P1 (bytes) is stored in register P2. */ @@ -974,6 +1010,7 @@ case OP_String: { /* out2-prerelease */ } /* Opcode: Null P1 P2 P3 * * +** Synopsis: r[P2..P3]=NULL ** ** Write a NULL into registers P2. If P3 greater than P2, then also write ** NULL into register P3 and every register in between P2 and P3. If P3 @@ -1002,6 +1039,7 @@ case OP_Null: { /* out2-prerelease */ /* Opcode: Blob P1 P2 * P4 +** Synopsis: r[P2]=P4 (len=P1) ** ** P4 points to a blob of data P1 bytes long. Store this ** blob in register P2. @@ -1015,6 +1053,7 @@ case OP_Blob: { /* out2-prerelease */ } /* Opcode: Variable P1 P2 * P4 * +** Synopsis: r[P2]=parameter(P1,P4) ** ** Transfer the values of bound parameter P1 into register P2 ** @@ -1036,6 +1075,7 @@ case OP_Variable: { /* out2-prerelease */ } /* Opcode: Move P1 P2 P3 * * +** Synopsis: r[P2@P3]=r[P1@P3] ** ** Move the values in register P1..P1+P3 over into ** registers P2..P2+P3. Registers P1..P1+P3 are @@ -1078,6 +1118,7 @@ case OP_Move: { } /* Opcode: Copy P1 P2 P3 * * +** Synopsis: r[P2@P3]=r[P1@P3] ** ** Make a copy of registers P1..P1+P3 into registers P2..P2+P3. ** @@ -1106,6 +1147,7 @@ case OP_Copy: { } /* Opcode: SCopy P1 P2 * * * +** Synopsis: r[P2]=r[P1] ** ** Make a shallow copy of register P1 into register P2. ** @@ -1117,7 +1159,7 @@ case OP_Copy: { ** during the lifetime of the copy. Use OP_Copy to make a complete ** copy. */ -case OP_SCopy: { /* in1, out2 */ +case OP_SCopy: { /* out2 */ pIn1 = &aMem[pOp->p1]; pOut = &aMem[pOp->p2]; assert( pOut!=pIn1 ); @@ -1125,11 +1167,11 @@ case OP_SCopy: { /* in1, out2 */ #ifdef SQLITE_DEBUG if( pOut->pScopyFrom==0 ) pOut->pScopyFrom = pIn1; #endif - REGISTER_TRACE(pOp->p2, pOut); break; } /* Opcode: ResultRow P1 P2 * * * +** Synopsis: output=r[P1@P2] ** ** The registers P1 through P1+P2-1 contain a single row of ** results. This opcode causes the sqlite3_step() call to terminate @@ -1201,6 +1243,7 @@ case OP_ResultRow: { } /* Opcode: Concat P1 P2 P3 * * +** Synopsis: r[P3]=r[P2]+r[P1] ** ** Add the text in register P1 onto the end of the text in ** register P2 and store the result in register P3. @@ -1238,7 +1281,7 @@ case OP_Concat: { /* same as TK_CONCAT, in1, in2, out3 */ memcpy(pOut->z, pIn2->z, pIn2->n); } memcpy(&pOut->z[pIn2->n], pIn1->z, pIn1->n); - pOut->z[nByte] = 0; + pOut->z[nByte]=0; pOut->z[nByte+1] = 0; pOut->flags |= MEM_Term; pOut->n = (int)nByte; @@ -1248,12 +1291,14 @@ case OP_Concat: { /* same as TK_CONCAT, in1, in2, out3 */ } /* Opcode: Add P1 P2 P3 * * +** Synopsis: r[P3]=r[P1]+r[P2] ** ** Add the value in register P1 to the value in register P2 ** and store the result in register P3. ** If either input is NULL, the result is NULL. */ /* Opcode: Multiply P1 P2 P3 * * +** Synopsis: r[P3]=r[P1]*r[P2] ** ** ** Multiply the value in register P1 by the value in register P2 @@ -1261,12 +1306,14 @@ case OP_Concat: { /* same as TK_CONCAT, in1, in2, out3 */ ** If either input is NULL, the result is NULL. */ /* Opcode: Subtract P1 P2 P3 * * +** Synopsis: r[P3]=r[P2]-r[P1] ** ** Subtract the value in register P1 from the value in register P2 ** and store the result in register P3. ** If either input is NULL, the result is NULL. */ /* Opcode: Divide P1 P2 P3 * * +** Synopsis: r[P3]=r[P1]/r[P2] ** ** Divide the value in register P1 by the value in register P2 ** and store the result in register P3 (P3=P2/P1). If the value in @@ -1274,6 +1321,7 @@ case OP_Concat: { /* same as TK_CONCAT, in1, in2, out3 */ ** NULL, the result is NULL. */ /* Opcode: Remainder P1 P2 P3 * * +** Synopsis: r[P3]=r[P1]%r[P2] ** ** Compute the remainder after integer division of the value in ** register P1 by the value in register P2 and store the result in P3. @@ -1391,6 +1439,7 @@ case OP_CollSeq: { } /* Opcode: Function P1 P2 P3 P4 P5 +** Synopsis: r[P3]=func(r[P2@P5]) ** ** Invoke a user function (P4 is a pointer to a Function structure that ** defines the function) with P5 arguments taken from register P2 and @@ -1498,18 +1547,21 @@ case OP_Function: { } /* Opcode: BitAnd P1 P2 P3 * * +** Synopsis: r[P3]=r[P1]&r[P2] ** ** Take the bit-wise AND of the values in register P1 and P2 and ** store the result in register P3. ** If either input is NULL, the result is NULL. */ /* Opcode: BitOr P1 P2 P3 * * +** Synopsis: r[P3]=r[P1]|r[P2] ** ** Take the bit-wise OR of the values in register P1 and P2 and ** store the result in register P3. ** If either input is NULL, the result is NULL. */ /* Opcode: ShiftLeft P1 P2 P3 * * +** Synopsis: r[P3]=r[P2]<>r[P1] ** ** Shift the integer value in register P2 to the right by the ** number of bits specified by the integer in register P1. @@ -1576,6 +1629,7 @@ case OP_ShiftRight: { /* same as TK_RSHIFT, in1, in2, out3 */ } /* Opcode: AddImm P1 P2 * * * +** Synopsis: r[P1]=r[P1]+P2 ** ** Add the constant P2 to the value in register P1. ** The result is always an integer. @@ -1734,6 +1788,7 @@ case OP_ToReal: { /* same as TK_TO_REAL, in1 */ #endif /* !defined(SQLITE_OMIT_CAST) && !defined(SQLITE_OMIT_FLOATING_POINT) */ /* Opcode: Lt P1 P2 P3 P4 P5 +** Synopsis: if r[P1]r[P3] goto P2 ** ** This works just like the Lt opcode except that the jump is taken if ** the content of register P3 is greater than the content of ** register P1. See the Lt opcode for additional information. */ /* Opcode: Ge P1 P2 P3 P4 P5 +** Synopsis: if r[P1]>=r[P3] goto P2 ** ** This works just like the Lt opcode except that the jump is taken if ** the content of register P3 is greater than or equal to the content of @@ -1994,6 +2054,7 @@ case OP_Jump: { /* jump */ } /* Opcode: And P1 P2 P3 * * +** Synopsis: r[P3]=(r[P1] && r[P2]) ** ** Take the logical AND of the values in registers P1 and P2 and ** write the result into register P3. @@ -2003,6 +2064,7 @@ case OP_Jump: { /* jump */ ** a NULL output. */ /* Opcode: Or P1 P2 P3 * * +** Synopsis: r[P3]=(r[P1] || r[P2]) ** ** Take the logical OR of the values in register P1 and P2 and ** store the answer in register P3. @@ -2046,6 +2108,7 @@ case OP_Or: { /* same as TK_OR, in1, in2, out3 */ } /* Opcode: Not P1 P2 * * * +** Synopsis: r[P2]= !r[P1] ** ** Interpret the value in register P1 as a boolean value. Store the ** boolean complement in register P2. If the value in register P1 is @@ -2063,6 +2126,7 @@ case OP_Not: { /* same as TK_NOT, in1, out2 */ } /* Opcode: BitNot P1 P2 * * * +** Synopsis: r[P1]= ~r[P1] ** ** Interpret the content of register P1 as an integer. Store the ** ones-complement of the P1 value into register P2. If P1 holds @@ -2127,6 +2191,7 @@ case OP_IfNot: { /* jump, in1 */ } /* Opcode: IsNull P1 P2 * * * +** Synopsis: if r[P1]==NULL goto P2 ** ** Jump to P2 if the value in register P1 is NULL. */ @@ -2139,6 +2204,7 @@ case OP_IsNull: { /* same as TK_ISNULL, jump, in1 */ } /* Opcode: NotNull P1 P2 * * * +** Synopsis: if r[P1]!=NULL goto P2 ** ** Jump to P2 if the value in register P1 is not NULL. */ @@ -2151,6 +2217,7 @@ case OP_NotNull: { /* same as TK_NOTNULL, jump, in1 */ } /* Opcode: Column P1 P2 P3 P4 P5 +** Synopsis: r[P3]=PX ** ** Interpret the data that cursor P1 points to as a structure built using ** the MakeRecord instruction. (See the MakeRecord opcode for additional @@ -2251,7 +2318,8 @@ case OP_Column: { VVA_ONLY(rc =) sqlite3BtreeDataSize(pCrsr, &payloadSize); assert( rc==SQLITE_OK ); /* DataSize() cannot fail */ } - }else if( ALWAYS(pC->pseudoTableReg>0) ){ + }else{ + assert( pC->pseudoTableReg>0 ); pReg = &aMem[pC->pseudoTableReg]; if( pC->multiPseudo ){ sqlite3VdbeMemShallowCopy(pDest, pReg+p2, MEM_Ephem); @@ -2264,9 +2332,6 @@ case OP_Column: { zRec = pReg->z; pC->cacheStatus = (pOp->p5&OPFLAG_CLEARCACHE) ? CACHE_STALE : p->cacheCtr; assert( payloadSize==0 || zRec!=0 ); - }else{ - /* Consider the row to be NULL */ - payloadSize = 0; } /* If payloadSize is 0, then just store a NULL. This can happen because of @@ -2487,6 +2552,7 @@ op_column_out: } /* Opcode: Affinity P1 P2 * P4 * +** Synopsis: affinity(r[P1@P2]) ** ** Apply affinities to a range of P2 registers starting with P1. ** @@ -2513,6 +2579,7 @@ case OP_Affinity: { } /* Opcode: MakeRecord P1 P2 P3 P4 * +** Synopsis: r[P3]=mkrec(r[P1@P2]) ** ** Convert P2 registers beginning with P1 into the [record format] ** use as a data record in a database table or as a key @@ -2645,6 +2712,7 @@ case OP_MakeRecord: { } /* Opcode: Count P1 P2 * * * +** Synopsis: r[P2]=count() ** ** Store the number of entries (an integer value) in the table or index ** opened by cursor P1 in register P2 @@ -2655,11 +2723,8 @@ case OP_Count: { /* out2-prerelease */ BtCursor *pCrsr; pCrsr = p->apCsr[pOp->p1]->pCursor; - if( ALWAYS(pCrsr) ){ - rc = sqlite3BtreeCount(pCrsr, &nEntry); - }else{ - nEntry = 0; - } + assert( pCrsr ); + rc = sqlite3BtreeCount(pCrsr, &nEntry); pOut->u.i = nEntry; break; } @@ -3121,6 +3186,7 @@ case OP_VerifyCookie: { } /* Opcode: OpenRead P1 P2 P3 P4 P5 +** Synopsis: root=P2 iDb=P3 ** ** Open a read-only cursor for the database table whose root page is ** P2 in a database file. The database file is determined by P3. @@ -3151,6 +3217,7 @@ case OP_VerifyCookie: { ** See also OpenWrite. */ /* Opcode: OpenWrite P1 P2 P3 P4 P5 +** Synopsis: root=P2 iDb=P3 ** ** Open a read/write cursor named P1 on the table or index whose root ** page is P2. Or if P5!=0 use the content of register P2 to find the @@ -3227,8 +3294,9 @@ case OP_OpenWrite: { } if( pOp->p4type==P4_KEYINFO ){ pKeyInfo = pOp->p4.pKeyInfo; - pKeyInfo->enc = ENC(p->db); - nField = pKeyInfo->nField+1; + assert( pKeyInfo->enc==ENC(db) ); + assert( pKeyInfo->db==db ); + nField = pKeyInfo->nField+pKeyInfo->nXField; }else if( pOp->p4type==P4_INT32 ){ nField = pOp->p4.i; } @@ -3256,6 +3324,7 @@ case OP_OpenWrite: { } /* Opcode: OpenEphemeral P1 P2 * P4 P5 +** Synopsis: nColumn=P2 ** ** Open a new cursor P1 to a transient table. ** The cursor is always opened read/write even if @@ -3267,18 +3336,13 @@ case OP_OpenWrite: { ** if P4 is not 0. If P4 is not NULL, it points to a KeyInfo structure ** that defines the format of keys in the index. ** -** This opcode was once called OpenTemp. But that created -** confusion because the term "temp table", might refer either -** to a TEMP table at the SQL level, or to a table opened by -** this opcode. Then this opcode was call OpenVirtual. But -** that created confusion with the whole virtual-table idea. -** ** The P5 parameter can be a mask of the BTREE_* flags defined ** in btree.h. These flags control aspects of the operation of ** the btree. The BTREE_OMIT_JOURNAL and BTREE_SINGLE flags are ** added automatically. */ /* Opcode: OpenAutoindex P1 P2 * P4 * +** Synopsis: nColumn=P2 ** ** This opcode works the same as OP_OpenEphemeral. It has a ** different name to distinguish its use. Tables created using @@ -3288,13 +3352,14 @@ case OP_OpenWrite: { case OP_OpenAutoindex: case OP_OpenEphemeral: { VdbeCursor *pCx; + KeyInfo *pKeyInfo; + static const int vfsFlags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE | SQLITE_OPEN_TRANSIENT_DB; - assert( pOp->p1>=0 ); pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, 1); if( pCx==0 ) goto no_mem; @@ -3310,16 +3375,16 @@ case OP_OpenEphemeral: { ** opening it. If a transient table is required, just use the ** automatically created table with root-page 1 (an BLOB_INTKEY table). */ - if( pOp->p4.pKeyInfo ){ + if( (pKeyInfo = pOp->p4.pKeyInfo)!=0 ){ int pgno; assert( pOp->p4type==P4_KEYINFO ); rc = sqlite3BtreeCreateTable(pCx->pBt, &pgno, BTREE_BLOBKEY | pOp->p5); if( rc==SQLITE_OK ){ assert( pgno==MASTER_ROOT+1 ); - rc = sqlite3BtreeCursor(pCx->pBt, pgno, 1, - (KeyInfo*)pOp->p4.z, pCx->pCursor); - pCx->pKeyInfo = pOp->p4.pKeyInfo; - pCx->pKeyInfo->enc = ENC(p->db); + assert( pKeyInfo->db==db ); + assert( pKeyInfo->enc==ENC(db) ); + pCx->pKeyInfo = pKeyInfo; + rc = sqlite3BtreeCursor(pCx->pBt, pgno, 1, pKeyInfo, pCx->pCursor); } pCx->isTable = 0; }else{ @@ -3332,7 +3397,7 @@ case OP_OpenEphemeral: { break; } -/* Opcode: SorterOpen P1 P2 * P4 * +/* Opcode: SorterOpen P1 * * P4 * ** ** This opcode works like OP_OpenEphemeral except that it opens ** a transient index that is specifically designed to sort large @@ -3344,13 +3409,15 @@ case OP_SorterOpen: { pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, 1); if( pCx==0 ) goto no_mem; pCx->pKeyInfo = pOp->p4.pKeyInfo; - pCx->pKeyInfo->enc = ENC(p->db); + assert( pCx->pKeyInfo->db==db ); + assert( pCx->pKeyInfo->enc==ENC(db) ); pCx->isSorter = 1; rc = sqlite3VdbeSorterInit(db, pCx); break; } /* Opcode: OpenPseudo P1 P2 P3 * P5 +** Synopsis: content in r[P2@P3] ** ** Open a new cursor that points to a fake table that contains a single ** row of data. The content of that one row in the content of memory @@ -3393,6 +3460,7 @@ case OP_Close: { } /* Opcode: SeekGe P1 P2 P3 P4 * +** Synopsis: key=r[P3@P4] ** ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), ** use the value in register P3 as the key. If cursor P1 refers @@ -3406,6 +3474,7 @@ case OP_Close: { ** See also: Found, NotFound, Distinct, SeekLt, SeekGt, SeekLe */ /* Opcode: SeekGt P1 P2 P3 P4 * +** Synopsis: key=r[P3@P4] ** ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), ** use the value in register P3 as a key. If cursor P1 refers @@ -3419,6 +3488,7 @@ case OP_Close: { ** See also: Found, NotFound, Distinct, SeekLt, SeekGe, SeekLe */ /* Opcode: SeekLt P1 P2 P3 P4 * +** Synopsis: key=r[P3@P4] ** ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), ** use the value in register P3 as a key. If cursor P1 refers @@ -3432,6 +3502,7 @@ case OP_Close: { ** See also: Found, NotFound, Distinct, SeekGt, SeekGe, SeekLe */ /* Opcode: SeekLe P1 P2 P3 P4 * +** Synopsis: key=r[P3@P4] ** ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), ** use the value in register P3 as a key. If cursor P1 refers @@ -3464,139 +3535,133 @@ case OP_SeekGt: { /* jump, in3 */ assert( OP_SeekGe == OP_SeekLt+2 ); assert( OP_SeekGt == OP_SeekLt+3 ); assert( pC->isOrdered ); - if( ALWAYS(pC->pCursor!=0) ){ - oc = pOp->opcode; - pC->nullRow = 0; - if( pC->isTable ){ - /* The input value in P3 might be of any type: integer, real, string, - ** blob, or NULL. But it needs to be an integer before we can do - ** the seek, so covert it. */ - pIn3 = &aMem[pOp->p3]; - applyNumericAffinity(pIn3); - iKey = sqlite3VdbeIntValue(pIn3); - pC->rowidIsValid = 0; + assert( pC->pCursor!=0 ); + oc = pOp->opcode; + pC->nullRow = 0; + if( pC->isTable ){ + /* The input value in P3 might be of any type: integer, real, string, + ** blob, or NULL. But it needs to be an integer before we can do + ** the seek, so covert it. */ + pIn3 = &aMem[pOp->p3]; + applyNumericAffinity(pIn3); + iKey = sqlite3VdbeIntValue(pIn3); + pC->rowidIsValid = 0; - /* If the P3 value could not be converted into an integer without - ** loss of information, then special processing is required... */ - if( (pIn3->flags & MEM_Int)==0 ){ - if( (pIn3->flags & MEM_Real)==0 ){ - /* If the P3 value cannot be converted into any kind of a number, - ** then the seek is not possible, so jump to P2 */ - pc = pOp->p2 - 1; - break; - } - /* If we reach this point, then the P3 value must be a floating - ** point number. */ - assert( (pIn3->flags & MEM_Real)!=0 ); + /* If the P3 value could not be converted into an integer without + ** loss of information, then special processing is required... */ + if( (pIn3->flags & MEM_Int)==0 ){ + if( (pIn3->flags & MEM_Real)==0 ){ + /* If the P3 value cannot be converted into any kind of a number, + ** then the seek is not possible, so jump to P2 */ + pc = pOp->p2 - 1; + break; + } + /* If we reach this point, then the P3 value must be a floating + ** point number. */ + assert( (pIn3->flags & MEM_Real)!=0 ); - if( iKey==SMALLEST_INT64 && (pIn3->r<(double)iKey || pIn3->r>0) ){ - /* The P3 value is too large in magnitude to be expressed as an - ** integer. */ - res = 1; - if( pIn3->r<0 ){ - if( oc>=OP_SeekGe ){ assert( oc==OP_SeekGe || oc==OP_SeekGt ); - rc = sqlite3BtreeFirst(pC->pCursor, &res); - if( rc!=SQLITE_OK ) goto abort_due_to_error; - } - }else{ - if( oc<=OP_SeekLe ){ assert( oc==OP_SeekLt || oc==OP_SeekLe ); - rc = sqlite3BtreeLast(pC->pCursor, &res); - if( rc!=SQLITE_OK ) goto abort_due_to_error; - } + if( iKey==SMALLEST_INT64 && (pIn3->r<(double)iKey || pIn3->r>0) ){ + /* The P3 value is too large in magnitude to be expressed as an + ** integer. */ + res = 1; + if( pIn3->r<0 ){ + if( oc>=OP_SeekGe ){ assert( oc==OP_SeekGe || oc==OP_SeekGt ); + rc = sqlite3BtreeFirst(pC->pCursor, &res); + if( rc!=SQLITE_OK ) goto abort_due_to_error; } - if( res ){ - pc = pOp->p2 - 1; - } - break; - }else if( oc==OP_SeekLt || oc==OP_SeekGe ){ - /* Use the ceiling() function to convert real->int */ - if( pIn3->r > (double)iKey ) iKey++; }else{ - /* Use the floor() function to convert real->int */ - assert( oc==OP_SeekLe || oc==OP_SeekGt ); - if( pIn3->r < (double)iKey ) iKey--; + if( oc<=OP_SeekLe ){ assert( oc==OP_SeekLt || oc==OP_SeekLe ); + rc = sqlite3BtreeLast(pC->pCursor, &res); + if( rc!=SQLITE_OK ) goto abort_due_to_error; + } } - } - rc = sqlite3BtreeMovetoUnpacked(pC->pCursor, 0, (u64)iKey, 0, &res); - if( rc!=SQLITE_OK ){ - goto abort_due_to_error; - } - if( res==0 ){ - pC->rowidIsValid = 1; - pC->lastRowid = iKey; - } - }else{ - nField = pOp->p4.i; - assert( pOp->p4type==P4_INT32 ); - assert( nField>0 ); - r.pKeyInfo = pC->pKeyInfo; - r.nField = (u16)nField; - - /* The next line of code computes as follows, only faster: - ** if( oc==OP_SeekGt || oc==OP_SeekLe ){ - ** r.flags = UNPACKED_INCRKEY; - ** }else{ - ** r.flags = 0; - ** } - */ - r.flags = (u8)(UNPACKED_INCRKEY * (1 & (oc - OP_SeekLt))); - assert( oc!=OP_SeekGt || r.flags==UNPACKED_INCRKEY ); - assert( oc!=OP_SeekLe || r.flags==UNPACKED_INCRKEY ); - assert( oc!=OP_SeekGe || r.flags==0 ); - assert( oc!=OP_SeekLt || r.flags==0 ); - - r.aMem = &aMem[pOp->p3]; -#ifdef SQLITE_DEBUG - { int i; for(i=0; ipCursor, &r, 0, 0, &res); - if( rc!=SQLITE_OK ){ - goto abort_due_to_error; - } - pC->rowidIsValid = 0; - } - pC->deferredMoveto = 0; - pC->cacheStatus = CACHE_STALE; -#ifdef SQLITE_TEST - sqlite3_search_count++; -#endif - if( oc>=OP_SeekGe ){ assert( oc==OP_SeekGe || oc==OP_SeekGt ); - if( res<0 || (res==0 && oc==OP_SeekGt) ){ - rc = sqlite3BtreeNext(pC->pCursor, &res); - if( rc!=SQLITE_OK ) goto abort_due_to_error; - pC->rowidIsValid = 0; + if( res ){ + pc = pOp->p2 - 1; + } + break; + }else if( oc==OP_SeekLt || oc==OP_SeekGe ){ + /* Use the ceiling() function to convert real->int */ + if( pIn3->r > (double)iKey ) iKey++; }else{ - res = 0; - } - }else{ - assert( oc==OP_SeekLt || oc==OP_SeekLe ); - if( res>0 || (res==0 && oc==OP_SeekLt) ){ - rc = sqlite3BtreePrevious(pC->pCursor, &res); - if( rc!=SQLITE_OK ) goto abort_due_to_error; - pC->rowidIsValid = 0; - }else{ - /* res might be negative because the table is empty. Check to - ** see if this is the case. - */ - res = sqlite3BtreeEof(pC->pCursor); + /* Use the floor() function to convert real->int */ + assert( oc==OP_SeekLe || oc==OP_SeekGt ); + if( pIn3->r < (double)iKey ) iKey--; } + } + rc = sqlite3BtreeMovetoUnpacked(pC->pCursor, 0, (u64)iKey, 0, &res); + if( rc!=SQLITE_OK ){ + goto abort_due_to_error; } - assert( pOp->p2>0 ); - if( res ){ - pc = pOp->p2 - 1; + if( res==0 ){ + pC->rowidIsValid = 1; + pC->lastRowid = iKey; } }else{ - /* This happens when attempting to open the sqlite3_master table - ** for read access returns SQLITE_EMPTY. In this case always - ** take the jump (since there are no records in the table). + nField = pOp->p4.i; + assert( pOp->p4type==P4_INT32 ); + assert( nField>0 ); + r.pKeyInfo = pC->pKeyInfo; + r.nField = (u16)nField; + + /* The next line of code computes as follows, only faster: + ** if( oc==OP_SeekGt || oc==OP_SeekLe ){ + ** r.flags = UNPACKED_INCRKEY; + ** }else{ + ** r.flags = 0; + ** } */ + r.flags = (u8)(UNPACKED_INCRKEY * (1 & (oc - OP_SeekLt))); + assert( oc!=OP_SeekGt || r.flags==UNPACKED_INCRKEY ); + assert( oc!=OP_SeekLe || r.flags==UNPACKED_INCRKEY ); + assert( oc!=OP_SeekGe || r.flags==0 ); + assert( oc!=OP_SeekLt || r.flags==0 ); + + r.aMem = &aMem[pOp->p3]; +#ifdef SQLITE_DEBUG + { int i; for(i=0; ipCursor, &r, 0, 0, &res); + if( rc!=SQLITE_OK ){ + goto abort_due_to_error; + } + pC->rowidIsValid = 0; + } + pC->deferredMoveto = 0; + pC->cacheStatus = CACHE_STALE; +#ifdef SQLITE_TEST + sqlite3_search_count++; +#endif + if( oc>=OP_SeekGe ){ assert( oc==OP_SeekGe || oc==OP_SeekGt ); + if( res<0 || (res==0 && oc==OP_SeekGt) ){ + rc = sqlite3BtreeNext(pC->pCursor, &res); + if( rc!=SQLITE_OK ) goto abort_due_to_error; + pC->rowidIsValid = 0; + }else{ + res = 0; + } + }else{ + assert( oc==OP_SeekLt || oc==OP_SeekLe ); + if( res>0 || (res==0 && oc==OP_SeekLt) ){ + rc = sqlite3BtreePrevious(pC->pCursor, &res); + if( rc!=SQLITE_OK ) goto abort_due_to_error; + pC->rowidIsValid = 0; + }else{ + /* res might be negative because the table is empty. Check to + ** see if this is the case. + */ + res = sqlite3BtreeEof(pC->pCursor); + } + } + assert( pOp->p2>0 ); + if( res ){ pc = pOp->p2 - 1; } break; } /* Opcode: Seek P1 P2 * * * +** Synopsis: intkey=r[P2] ** ** P1 is an open table cursor and P2 is a rowid integer. Arrange ** for P1 to move so that it points to the rowid given by P2. @@ -3611,19 +3676,19 @@ case OP_Seek: { /* in2 */ assert( pOp->p1>=0 && pOp->p1nCursor ); pC = p->apCsr[pOp->p1]; assert( pC!=0 ); - if( ALWAYS(pC->pCursor!=0) ){ - assert( pC->isTable ); - pC->nullRow = 0; - pIn2 = &aMem[pOp->p2]; - pC->movetoTarget = sqlite3VdbeIntValue(pIn2); - pC->rowidIsValid = 0; - pC->deferredMoveto = 1; - } + assert( pC->pCursor!=0 ); + assert( pC->isTable ); + pC->nullRow = 0; + pIn2 = &aMem[pOp->p2]; + pC->movetoTarget = sqlite3VdbeIntValue(pIn2); + pC->rowidIsValid = 0; + pC->deferredMoveto = 1; break; } /* Opcode: Found P1 P2 P3 P4 * +** Synopsis: key=r[P3@P4] ** ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If ** P4>0 then register P3 is the first of P4 registers that form an unpacked @@ -3632,8 +3697,11 @@ case OP_Seek: { /* in2 */ ** Cursor P1 is on an index btree. If the record identified by P3 and P4 ** is a prefix of any entry in P1 then a jump is made to P2 and ** P1 is left pointing at the matching entry. +** +** See also: NotFound, NoConflict, NotExists. SeekGe */ /* Opcode: NotFound P1 P2 P3 P4 * +** Synopsis: key=r[P3@P4] ** ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If ** P4>0 then register P3 is the first of P4 registers that form an unpacked @@ -3645,20 +3713,41 @@ case OP_Seek: { /* in2 */ ** falls through to the next instruction and P1 is left pointing at the ** matching entry. ** -** See also: Found, NotExists, IsUnique +** See also: Found, NotExists, NoConflict */ +/* Opcode: NoConflict P1 P2 P3 P4 * +** Synopsis: key=r[P3@P4] +** +** If P4==0 then register P3 holds a blob constructed by MakeRecord. If +** P4>0 then register P3 is the first of P4 registers that form an unpacked +** record. +** +** Cursor P1 is on an index btree. If the record identified by P3 and P4 +** contains any NULL value, jump immediately to P2. If all terms of the +** record are not-NULL then a check is done to determine if any row in the +** P1 index btree has a matching key prefix. If there are no matches, jump +** immediately to P2. If there is a match, fall through and leave the P1 +** cursor pointing to the matching row. +** +** This opcode is similar to OP_NotFound with the exceptions that the +** branch is always taken if any part of the search key input is NULL. +** +** See also: NotFound, Found, NotExists +*/ +case OP_NoConflict: /* jump, in3 */ case OP_NotFound: /* jump, in3 */ case OP_Found: { /* jump, in3 */ int alreadyExists; + int ii; VdbeCursor *pC; int res; char *pFree; UnpackedRecord *pIdxKey; UnpackedRecord r; - char aTempRec[ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*3 + 7]; + char aTempRec[ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*4 + 7]; #ifdef SQLITE_TEST - sqlite3_found_count++; + if( pOp->opcode!=OP_NoConflict ) sqlite3_found_count++; #endif alreadyExists = 0; @@ -3667,39 +3756,56 @@ case OP_Found: { /* jump, in3 */ pC = p->apCsr[pOp->p1]; assert( pC!=0 ); pIn3 = &aMem[pOp->p3]; - if( ALWAYS(pC->pCursor!=0) ){ - - assert( pC->isTable==0 ); - if( pOp->p4.i>0 ){ - r.pKeyInfo = pC->pKeyInfo; - r.nField = (u16)pOp->p4.i; - r.aMem = pIn3; + assert( pC->pCursor!=0 ); + assert( pC->isTable==0 ); + if( pOp->p4.i>0 ){ + r.pKeyInfo = pC->pKeyInfo; + r.nField = (u16)pOp->p4.i; + r.aMem = pIn3; #ifdef SQLITE_DEBUG - { int i; for(i=0; ip3+i, &r.aMem[i]); + } + } #endif - r.flags = UNPACKED_PREFIX_MATCH; - pIdxKey = &r; - }else{ - pIdxKey = sqlite3VdbeAllocUnpackedRecord( - pC->pKeyInfo, aTempRec, sizeof(aTempRec), &pFree - ); - if( pIdxKey==0 ) goto no_mem; - assert( pIn3->flags & MEM_Blob ); - assert( (pIn3->flags & MEM_Zero)==0 ); /* zeroblobs already expanded */ - sqlite3VdbeRecordUnpack(pC->pKeyInfo, pIn3->n, pIn3->z, pIdxKey); - pIdxKey->flags |= UNPACKED_PREFIX_MATCH; - } - rc = sqlite3BtreeMovetoUnpacked(pC->pCursor, pIdxKey, 0, 0, &res); - if( pOp->p4.i==0 ){ - sqlite3DbFree(db, pFree); - } - if( rc!=SQLITE_OK ){ - break; - } - alreadyExists = (res==0); - pC->deferredMoveto = 0; - pC->cacheStatus = CACHE_STALE; + r.flags = UNPACKED_PREFIX_MATCH; + pIdxKey = &r; + }else{ + pIdxKey = sqlite3VdbeAllocUnpackedRecord( + pC->pKeyInfo, aTempRec, sizeof(aTempRec), &pFree + ); + if( pIdxKey==0 ) goto no_mem; + assert( pIn3->flags & MEM_Blob ); + assert( (pIn3->flags & MEM_Zero)==0 ); /* zeroblobs already expanded */ + sqlite3VdbeRecordUnpack(pC->pKeyInfo, pIn3->n, pIn3->z, pIdxKey); + pIdxKey->flags |= UNPACKED_PREFIX_MATCH; } + if( pOp->opcode==OP_NoConflict ){ + /* For the OP_NoConflict opcode, take the jump if any of the + ** input fields are NULL, since any key with a NULL will not + ** conflict */ + for(ii=0; iip2 - 1; + break; + } + } + } + rc = sqlite3BtreeMovetoUnpacked(pC->pCursor, pIdxKey, 0, 0, &res); + if( pOp->p4.i==0 ){ + sqlite3DbFree(db, pFree); + } + if( rc!=SQLITE_OK ){ + break; + } + pC->seekResult = res; + alreadyExists = (res==0); + pC->nullRow = 1-alreadyExists; + pC->deferredMoveto = 0; + pC->cacheStatus = CACHE_STALE; if( pOp->opcode==OP_Found ){ if( alreadyExists ) pc = pOp->p2 - 1; }else{ @@ -3708,106 +3814,19 @@ case OP_Found: { /* jump, in3 */ break; } -/* Opcode: IsUnique P1 P2 P3 P4 * -** -** Cursor P1 is open on an index b-tree - that is to say, a btree which -** no data and where the key are records generated by OP_MakeRecord with -** the list field being the integer ROWID of the entry that the index -** entry refers to. -** -** The P3 register contains an integer record number. Call this record -** number R. Register P4 is the first in a set of N contiguous registers -** that make up an unpacked index key that can be used with cursor P1. -** The value of N can be inferred from the cursor. N includes the rowid -** value appended to the end of the index record. This rowid value may -** or may not be the same as R. -** -** If any of the N registers beginning with register P4 contains a NULL -** value, jump immediately to P2. -** -** Otherwise, this instruction checks if cursor P1 contains an entry -** where the first (N-1) fields match but the rowid value at the end -** of the index entry is not R. If there is no such entry, control jumps -** to instruction P2. Otherwise, the rowid of the conflicting index -** entry is copied to register P3 and control falls through to the next -** instruction. -** -** See also: NotFound, NotExists, Found -*/ -case OP_IsUnique: { /* jump, in3 */ - u16 ii; - VdbeCursor *pCx; - BtCursor *pCrsr; - u16 nField; - Mem *aMx; - UnpackedRecord r; /* B-Tree index search key */ - i64 R; /* Rowid stored in register P3 */ - - pIn3 = &aMem[pOp->p3]; - aMx = &aMem[pOp->p4.i]; - /* Assert that the values of parameters P1 and P4 are in range. */ - assert( pOp->p4type==P4_INT32 ); - assert( pOp->p4.i>0 && pOp->p4.i<=(p->nMem-p->nCursor) ); - assert( pOp->p1>=0 && pOp->p1nCursor ); - - /* Find the index cursor. */ - pCx = p->apCsr[pOp->p1]; - assert( pCx->deferredMoveto==0 ); - pCx->seekResult = 0; - pCx->cacheStatus = CACHE_STALE; - pCrsr = pCx->pCursor; - - /* If any of the values are NULL, take the jump. */ - nField = pCx->pKeyInfo->nField; - for(ii=0; iip2 - 1; - pCrsr = 0; - break; - } - } - assert( (aMx[nField].flags & MEM_Null)==0 ); - - if( pCrsr!=0 ){ - /* Populate the index search key. */ - r.pKeyInfo = pCx->pKeyInfo; - r.nField = nField + 1; - r.flags = UNPACKED_PREFIX_SEARCH; - r.aMem = aMx; -#ifdef SQLITE_DEBUG - { int i; for(i=0; iu.i; - - /* Search the B-Tree index. If no conflicting record is found, jump - ** to P2. Otherwise, copy the rowid of the conflicting record to - ** register P3 and fall through to the next instruction. */ - rc = sqlite3BtreeMovetoUnpacked(pCrsr, &r, 0, 0, &pCx->seekResult); - if( (r.flags & UNPACKED_PREFIX_SEARCH) || r.rowid==R ){ - pc = pOp->p2 - 1; - }else{ - pIn3->u.i = r.rowid; - } - } - break; -} - /* Opcode: NotExists P1 P2 P3 * * +** Synopsis: intkey=r[P3] ** -** Use the content of register P3 as an integer key. If a record -** with that key does not exist in table of P1, then jump to P2. -** If the record does exist, then fall through. The cursor is left -** pointing to the record if it exists. +** P1 is the index of a cursor open on an SQL table btree (with integer +** keys). P3 is an integer rowid. If P1 does not contain a record with +** rowid P3 then jump immediately to P2. If P1 does contain a record +** with rowid P3 then leave the cursor pointing at that record and fall +** through to the next instruction. ** -** The difference between this operation and NotFound is that this -** operation assumes the key is an integer and that P1 is a table whereas -** NotFound assumes key is a blob constructed from MakeRecord and -** P1 is an index. +** The OP_NotFound opcode performs the same operation on index btrees +** (with arbitrary multi-value keys). ** -** See also: Found, NotFound, IsUnique +** See also: Found, NotFound, NoConflict */ case OP_NotExists: { /* jump, in3 */ VdbeCursor *pC; @@ -3823,32 +3842,25 @@ case OP_NotExists: { /* jump, in3 */ assert( pC->isTable ); assert( pC->pseudoTableReg==0 ); pCrsr = pC->pCursor; - if( ALWAYS(pCrsr!=0) ){ - res = 0; - iKey = pIn3->u.i; - rc = sqlite3BtreeMovetoUnpacked(pCrsr, 0, iKey, 0, &res); - pC->lastRowid = pIn3->u.i; - pC->rowidIsValid = res==0 ?1:0; - pC->nullRow = 0; - pC->cacheStatus = CACHE_STALE; - pC->deferredMoveto = 0; - if( res!=0 ){ - pc = pOp->p2 - 1; - assert( pC->rowidIsValid==0 ); - } - pC->seekResult = res; - }else{ - /* This happens when an attempt to open a read cursor on the - ** sqlite_master table returns SQLITE_EMPTY. - */ + assert( pCrsr!=0 ); + res = 0; + iKey = pIn3->u.i; + rc = sqlite3BtreeMovetoUnpacked(pCrsr, 0, iKey, 0, &res); + pC->lastRowid = pIn3->u.i; + pC->rowidIsValid = res==0 ?1:0; + pC->nullRow = 0; + pC->cacheStatus = CACHE_STALE; + pC->deferredMoveto = 0; + if( res!=0 ){ pc = pOp->p2 - 1; assert( pC->rowidIsValid==0 ); - pC->seekResult = 0; } + pC->seekResult = res; break; } /* Opcode: Sequence P1 P2 * * * +** Synopsis: r[P2]=rowid ** ** Find the next available sequence number for cursor P1. ** Write the sequence number into register P2. @@ -3864,6 +3876,7 @@ case OP_Sequence: { /* out2-prerelease */ /* Opcode: NewRowid P1 P2 P3 * * +** Synopsis: r[P2]=rowid ** ** Get a new integer record number (a.k.a "rowid") used as the key to a table. ** The record number is not previously used as a key in the database @@ -4013,6 +4026,7 @@ case OP_NewRowid: { /* out2-prerelease */ } /* Opcode: Insert P1 P2 P3 P4 P5 +** Synopsis: intkey=r[P3] data=r[P2] ** ** Write an entry into the table of cursor P1. A new entry is ** created if it doesn't already exist or the data for an existing @@ -4052,6 +4066,7 @@ case OP_NewRowid: { /* out2-prerelease */ ** for indices is OP_IdxInsert. */ /* Opcode: InsertInt P1 P2 P3 P4 P5 +** Synopsis: intkey=P3 data=r[P2] ** ** This works exactly like OP_Insert except that the key is the ** integer value P3, not the value of the integer stored in register P3. @@ -4066,7 +4081,7 @@ case OP_InsertInt: { int seekResult; /* Result of prior seek or 0 if no USESEEKRESULT flag */ const char *zDb; /* database name - used by the update hook */ Table *pTab; /* Table structure - used by update and pre-update hooks */ - int op; /* Opcode for update hook: SQLITE_UPDATE or SQLITE_INSERT */ + int op = 0; /* Opcode for update hook: SQLITE_UPDATE or SQLITE_INSERT */ pData = &aMem[pOp->p2]; assert( pOp->p1>=0 && pOp->p1nCursor ); @@ -4076,7 +4091,7 @@ case OP_InsertInt: { assert( pC->pCursor!=0 ); assert( pC->pseudoTableReg==0 ); assert( pC->isTable ); - assert( pOp->p4type==P4_TABLE || pOp->p4type==P4_NOTUSED ); + assert( pOp->p4type==P4_TABLE || pOp->p4type>=P4_STATIC ); REGISTER_TRACE(pOp->p2, pData); if( pOp->opcode==OP_Insert ){ @@ -4132,7 +4147,7 @@ case OP_InsertInt: { pC->cacheStatus = CACHE_STALE; /* Invoke the update-hook if required. */ - if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z ){ + if( rc==SQLITE_OK && db->xUpdateCallback && op ){ db->xUpdateCallback(db->pUpdateArg, op, zDb, pTab->zName, iKey); } break; @@ -4243,21 +4258,32 @@ case OP_ResetCount: { break; } -/* Opcode: SorterCompare P1 P2 P3 +/* Opcode: SorterCompare P1 P2 P3 P4 +** Synopsis: if key(P1)!=rtrim(r[P3],P4) goto P2 ** -** P1 is a sorter cursor. This instruction compares the record blob in -** register P3 with the entry that the sorter cursor currently points to. -** If, excluding the rowid fields at the end, the two records are a match, -** fall through to the next instruction. Otherwise, jump to instruction P2. +** P1 is a sorter cursor. This instruction compares a prefix of the +** the record blob in register P3 against a prefix of the entry that +** the sorter cursor currently points to. The final P4 fields of both +** the P3 and sorter record are ignored. +** +** If either P3 or the sorter contains a NULL in one of their significant +** fields (not counting the P4 fields at the end which are ignored) then +** the comparison is assumed to be equal. +** +** Fall through to next instruction if the two records compare equal to +** each other. Jump to P2 if they are different. */ case OP_SorterCompare: { VdbeCursor *pC; int res; + int nIgnore; pC = p->apCsr[pOp->p1]; assert( isSorter(pC) ); + assert( pOp->p4type==P4_INT32 ); pIn3 = &aMem[pOp->p3]; - rc = sqlite3VdbeSorterCompare(pC, pIn3, &res); + nIgnore = pOp->p4.i; + rc = sqlite3VdbeSorterCompare(pC, pIn3, nIgnore, &res); if( res ){ pc = pOp->p2-1; } @@ -4265,6 +4291,7 @@ case OP_SorterCompare: { }; /* Opcode: SorterData P1 P2 * * * +** Synopsis: r[P2]=data ** ** Write into register P2 the current sorter data for sorter cursor P1. */ @@ -4279,6 +4306,7 @@ case OP_SorterData: { } /* Opcode: RowData P1 P2 * * * +** Synopsis: r[P2]=data ** ** Write into register P2 the complete row data for cursor P1. ** There is no interpretation of the data. @@ -4289,6 +4317,7 @@ case OP_SorterData: { ** of a real table, not a pseudo-table. */ /* Opcode: RowKey P1 P2 * * * +** Synopsis: r[P2]=key ** ** Write into register P2 the complete row key for cursor P1. ** There is no interpretation of the data. @@ -4357,10 +4386,12 @@ case OP_RowData: { } pOut->enc = SQLITE_UTF8; /* In case the blob is ever cast to text */ UPDATE_MAX_BLOBSIZE(pOut); + REGISTER_TRACE(pOp->p2, pOut); break; } /* Opcode: Rowid P1 P2 * * * +** Synopsis: r[P2]=rowid ** ** Store in register P2 an integer which is the key of the table entry that ** P1 is currently point to. @@ -4446,9 +4477,8 @@ case OP_Last: { /* jump */ assert( pC!=0 ); pCrsr = pC->pCursor; res = 0; - if( ALWAYS(pCrsr!=0) ){ - rc = sqlite3BtreeLast(pCrsr, &res); - } + assert( pCrsr!=0 ); + rc = sqlite3BtreeLast(pCrsr, &res); pC->nullRow = (u8)res; pC->deferredMoveto = 0; pC->rowidIsValid = 0; @@ -4518,7 +4548,7 @@ case OP_Rewind: { /* jump */ break; } -/* Opcode: Next P1 P2 * P4 P5 +/* Opcode: Next P1 P2 * * P5 ** ** Advance cursor P1 so that it points to the next key/data pair in its ** table or index. If there are no more key/value pairs then fall through @@ -4588,6 +4618,7 @@ case OP_Next: { /* jump */ } /* Opcode: IdxInsert P1 P2 P3 * P5 +** Synopsis: key=r[P2] ** ** Register P2 holds an SQL index key made using the ** MakeRecord instructions. This opcode writes that key @@ -4613,27 +4644,28 @@ case OP_IdxInsert: { /* in2 */ pIn2 = &aMem[pOp->p2]; assert( pIn2->flags & MEM_Blob ); pCrsr = pC->pCursor; - if( ALWAYS(pCrsr!=0) ){ - assert( pC->isTable==0 ); - rc = ExpandBlob(pIn2); - if( rc==SQLITE_OK ){ - if( isSorter(pC) ){ - rc = sqlite3VdbeSorterWrite(db, pC, pIn2); - }else{ - nKey = pIn2->n; - zKey = pIn2->z; - rc = sqlite3BtreeInsert(pCrsr, zKey, nKey, "", 0, 0, pOp->p3, - ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0) - ); - assert( pC->deferredMoveto==0 ); - pC->cacheStatus = CACHE_STALE; - } + if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++; + assert( pCrsr!=0 ); + assert( pC->isTable==0 ); + rc = ExpandBlob(pIn2); + if( rc==SQLITE_OK ){ + if( isSorter(pC) ){ + rc = sqlite3VdbeSorterWrite(db, pC, pIn2); + }else{ + nKey = pIn2->n; + zKey = pIn2->z; + rc = sqlite3BtreeInsert(pCrsr, zKey, nKey, "", 0, 0, pOp->p3, + ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0) + ); + assert( pC->deferredMoveto==0 ); + pC->cacheStatus = CACHE_STALE; } } break; } /* Opcode: IdxDelete P1 P2 P3 * * +** Synopsis: key=r[P2@P3] ** ** The content of P3 registers starting at register P2 form ** an unpacked index key. This opcode removes that entry from the @@ -4651,25 +4683,26 @@ case OP_IdxDelete: { pC = p->apCsr[pOp->p1]; assert( pC!=0 ); pCrsr = pC->pCursor; - if( ALWAYS(pCrsr!=0) ){ - r.pKeyInfo = pC->pKeyInfo; - r.nField = (u16)pOp->p3; - r.flags = 0; - r.aMem = &aMem[pOp->p2]; + assert( pCrsr!=0 ); + assert( pOp->p5==0 ); + r.pKeyInfo = pC->pKeyInfo; + r.nField = (u16)pOp->p3; + r.flags = UNPACKED_PREFIX_MATCH; + r.aMem = &aMem[pOp->p2]; #ifdef SQLITE_DEBUG - { int i; for(i=0; ideferredMoveto==0 ); - pC->cacheStatus = CACHE_STALE; + rc = sqlite3BtreeMovetoUnpacked(pCrsr, &r, 0, 0, &res); + if( rc==SQLITE_OK && res==0 ){ + rc = sqlite3BtreeDelete(pCrsr); } + assert( pC->deferredMoveto==0 ); + pC->cacheStatus = CACHE_STALE; break; } /* Opcode: IdxRowid P1 P2 * * * +** Synopsis: r[P2]=rowid ** ** Write into register P2 an integer which is the last entry in the record at ** the end of the index key pointed to by cursor P1. This integer should be @@ -4686,25 +4719,25 @@ case OP_IdxRowid: { /* out2-prerelease */ pC = p->apCsr[pOp->p1]; assert( pC!=0 ); pCrsr = pC->pCursor; + assert( pCrsr!=0 ); pOut->flags = MEM_Null; - if( ALWAYS(pCrsr!=0) ){ - rc = sqlite3VdbeCursorMoveto(pC); - if( NEVER(rc) ) goto abort_due_to_error; - assert( pC->deferredMoveto==0 ); - assert( pC->isTable==0 ); - if( !pC->nullRow ){ - rc = sqlite3VdbeIdxRowid(db, pCrsr, &rowid); - if( rc!=SQLITE_OK ){ - goto abort_due_to_error; - } - pOut->u.i = rowid; - pOut->flags = MEM_Int; + rc = sqlite3VdbeCursorMoveto(pC); + if( NEVER(rc) ) goto abort_due_to_error; + assert( pC->deferredMoveto==0 ); + assert( pC->isTable==0 ); + if( !pC->nullRow ){ + rc = sqlite3VdbeIdxRowid(db, pCrsr, &rowid); + if( rc!=SQLITE_OK ){ + goto abort_due_to_error; } + pOut->u.i = rowid; + pOut->flags = MEM_Int; } break; } /* Opcode: IdxGE P1 P2 P3 P4 P5 +** Synopsis: key=r[P3@P4] ** ** The P4 register values beginning with P3 form an unpacked index ** key that omits the ROWID. Compare this key value against the index @@ -4719,6 +4752,7 @@ case OP_IdxRowid: { /* out2-prerelease */ ** the result is false whereas it would be true with IdxGT. */ /* Opcode: IdxLT P1 P2 P3 P4 P5 +** Synopsis: key=r[P3@P4] ** ** The P4 register values beginning with P3 form an unpacked index ** key that omits the ROWID. Compare this key value against the index @@ -4740,31 +4774,30 @@ case OP_IdxGE: { /* jump */ pC = p->apCsr[pOp->p1]; assert( pC!=0 ); assert( pC->isOrdered ); - if( ALWAYS(pC->pCursor!=0) ){ - assert( pC->deferredMoveto==0 ); - assert( pOp->p5==0 || pOp->p5==1 ); - assert( pOp->p4type==P4_INT32 ); - r.pKeyInfo = pC->pKeyInfo; - r.nField = (u16)pOp->p4.i; - if( pOp->p5 ){ - r.flags = UNPACKED_INCRKEY | UNPACKED_PREFIX_MATCH; - }else{ - r.flags = UNPACKED_PREFIX_MATCH; - } - r.aMem = &aMem[pOp->p3]; + assert( pC->pCursor!=0); + assert( pC->deferredMoveto==0 ); + assert( pOp->p5==0 || pOp->p5==1 ); + assert( pOp->p4type==P4_INT32 ); + r.pKeyInfo = pC->pKeyInfo; + r.nField = (u16)pOp->p4.i; + if( pOp->p5 ){ + r.flags = UNPACKED_INCRKEY | UNPACKED_PREFIX_MATCH; + }else{ + r.flags = UNPACKED_PREFIX_MATCH; + } + r.aMem = &aMem[pOp->p3]; #ifdef SQLITE_DEBUG - { int i; for(i=0; iopcode==OP_IdxLT ){ - res = -res; - }else{ - assert( pOp->opcode==OP_IdxGE ); - res++; - } - if( res>0 ){ - pc = pOp->p2 - 1 ; - } + rc = sqlite3VdbeIdxKeyCompare(pC, &r, &res); + if( pOp->opcode==OP_IdxLT ){ + res = -res; + }else{ + assert( pOp->opcode==OP_IdxGE ); + res++; + } + if( res>0 ){ + pc = pOp->p2 - 1 ; } break; } @@ -4871,6 +4904,7 @@ case OP_Clear: { } /* Opcode: CreateTable P1 P2 * * * +** Synopsis: r[P2]=root iDb=P1 ** ** Allocate a new table in the main database file if P1==0 or in the ** auxiliary database file if P1==1 or in an attached database if @@ -4884,6 +4918,7 @@ case OP_Clear: { ** See also: CreateIndex */ /* Opcode: CreateIndex P1 P2 * * * +** Synopsis: r[P2]=root iDb=P1 ** ** Allocate a new index in the main database file if P1==0 or in the ** auxiliary database file if P1==1 or in an attached database if @@ -5085,6 +5120,7 @@ case OP_IntegrityCk: { #endif /* SQLITE_OMIT_INTEGRITY_CHECK */ /* Opcode: RowSetAdd P1 P2 * * * +** Synopsis: rowset(P1)=r[P2] ** ** Insert the integer value held by register P2 into a boolean index ** held in register P1. @@ -5104,6 +5140,7 @@ case OP_RowSetAdd: { /* in1, in2 */ } /* Opcode: RowSetRead P1 P2 P3 * * +** Synopsis: r[P3]=rowset(P1) ** ** Extract the smallest value from boolean index P1 and put that value into ** register P3. Or, if boolean index P1 is initially empty, leave P3 @@ -5127,6 +5164,7 @@ case OP_RowSetRead: { /* jump, in1, out3 */ } /* Opcode: RowSetTest P1 P2 P3 P4 +** Synopsis: if r[P3] in rowset(P1) goto P2 ** ** Register P3 is assumed to hold a 64-bit integer value. If register P1 ** contains a RowSet object and that RowSet object contains @@ -5330,6 +5368,7 @@ case OP_Param: { /* out2-prerelease */ #ifndef SQLITE_OMIT_FOREIGN_KEY /* Opcode: FkCounter P1 P2 * * * +** Synopsis: fkctr[P1]+=P2 ** ** Increment a "constraint counter" by P2 (P2 may be negative or positive). ** If P1 is non-zero, the database constraint counter is incremented @@ -5348,6 +5387,7 @@ case OP_FkCounter: { } /* Opcode: FkIfZero P1 P2 * * * +** Synopsis: if fkctr[P1]==0 goto P2 ** ** This opcode tests if a foreign key constraint-counter is currently zero. ** If so, jump to instruction P2. Otherwise, fall through to the next @@ -5370,6 +5410,7 @@ case OP_FkIfZero: { /* jump */ #ifndef SQLITE_OMIT_AUTOINCREMENT /* Opcode: MemMax P1 P2 * * * +** Synopsis: r[P1]=max(r[P1],r[P2]) ** ** P1 is a register in the root frame of this VM (the root frame is ** different from the current frame if this instruction is being executed @@ -5400,6 +5441,7 @@ case OP_MemMax: { /* in2 */ #endif /* SQLITE_OMIT_AUTOINCREMENT */ /* Opcode: IfPos P1 P2 * * * +** Synopsis: if r[P1]>0 goto P2 ** ** If the value of register P1 is 1 or greater, jump to P2. ** @@ -5416,6 +5458,7 @@ case OP_IfPos: { /* jump, in1 */ } /* Opcode: IfNeg P1 P2 * * * +** Synopsis: if r[P1]<0 goto P2 ** ** If the value of register P1 is less than zero, jump to P2. ** @@ -5432,6 +5475,7 @@ case OP_IfNeg: { /* jump, in1 */ } /* Opcode: IfZero P1 P2 P3 * * +** Synopsis: r[P1]+=P3, if r[P1]==0 goto P2 ** ** The register P1 must contain an integer. Add literal P3 to the ** value in register P1. If the result is exactly 0, jump to P2. @@ -5450,6 +5494,7 @@ case OP_IfZero: { /* jump, in1 */ } /* Opcode: AggStep * P2 P3 P4 P5 +** Synopsis: accum=r[P3] step(r[P2@P5]) ** ** Execute the step function for an aggregate. The ** function has P5 arguments. P4 is a pointer to the FuncDef @@ -5513,6 +5558,7 @@ case OP_AggStep: { } /* Opcode: AggFinal P1 P2 * P4 * +** Synopsis: accum=r[P1] N=P2 ** ** Execute the finalizer function for an aggregate. P1 is ** the memory location that is the accumulator for the aggregate. @@ -5740,6 +5786,7 @@ case OP_Expire: { #ifndef SQLITE_OMIT_SHARED_CACHE /* Opcode: TableLock P1 P2 P3 P4 * +** Synopsis: iDb=P1 root=P2 write=P3 ** ** Obtain a lock on a particular table. This instruction is only used when ** the shared-cache feature is enabled. @@ -5856,6 +5903,7 @@ case OP_VOpen: { #ifndef SQLITE_OMIT_VIRTUALTABLE /* Opcode: VFilter P1 P2 P3 P4 * +** Synopsis: iPlan=r[P3] zPlan='P4' ** ** P1 is a cursor opened using VOpen. P2 is an address to jump to if ** the filtered result set is empty. @@ -5930,6 +5978,7 @@ case OP_VFilter: { /* jump */ #ifndef SQLITE_OMIT_VIRTUALTABLE /* Opcode: VColumn P1 P2 P3 * * +** Synopsis: r[P3]=vcolumn(P2) ** ** Store the value of the P2-th column of ** the row of the virtual-table that the @@ -6063,6 +6112,7 @@ case OP_VRename: { #ifndef SQLITE_OMIT_VIRTUALTABLE /* Opcode: VUpdate P1 P2 P3 P4 * +** Synopsis: data=r[P3@P2] ** ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure. ** This opcode invokes the corresponding xUpdate method. P2 values diff --git a/src/vdbe.h b/src/vdbe.h index e1db15fe2b..63ac0c3ef1 100644 --- a/src/vdbe.h +++ b/src/vdbe.h @@ -62,7 +62,7 @@ struct VdbeOp { Table *pTab; /* Used when p4type is P4_TABLE */ int (*xAdvance)(BtCursor *, int *); } p4; -#ifdef SQLITE_DEBUG +#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS char *zComment; /* Comment to improve readability */ #endif #ifdef VDBE_PROFILE @@ -119,15 +119,11 @@ typedef struct VdbeOpList VdbeOpList; #define P4_ADVANCE (-19) /* P4 is a pointer to BtreeNext() or BtreePrev() */ #define P4_TABLE (-20) /* P4 is a pointer to a Table structure */ -/* When adding a P4 argument using P4_KEYINFO, a copy of the KeyInfo structure -** is made. That copy is freed when the Vdbe is finalized. But if the -** argument is P4_KEYINFO_HANDOFF, the passed in pointer is used. It still -** gets freed when the Vdbe is finalized so it still should be obtained -** from a single sqliteMalloc(). But no copy is made and the calling -** function should *not* try to free the KeyInfo. -*/ -#define P4_KEYINFO_HANDOFF (-16) -#define P4_KEYINFO_STATIC (-17) +/* Error message codes for OP_Halt */ +#define P5_ConstraintNotNull 1 +#define P5_ConstraintUnique 2 +#define P5_ConstraintCheck 3 +#define P5_ConstraintFK 4 /* ** The Vdbe.aColName array contains 5n Mem structures, where n is the @@ -182,6 +178,7 @@ void sqlite3VdbeChangeP5(Vdbe*, u8 P5); void sqlite3VdbeJumpHere(Vdbe*, int addr); void sqlite3VdbeChangeToNoop(Vdbe*, int addr); void sqlite3VdbeChangeP4(Vdbe*, int addr, const char *zP4, int N); +void sqlite3VdbeSetP4KeyInfo(Parse*, Index*); void sqlite3VdbeUsesBtree(Vdbe*, int); VdbeOp *sqlite3VdbeGetOp(Vdbe*, int); int sqlite3VdbeMakeLabel(Vdbe*); @@ -220,15 +217,27 @@ UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(KeyInfo *, char *, int, char **); void sqlite3VdbeLinkSubProgram(Vdbe *, SubProgram *); #endif - -#ifndef NDEBUG +/* Use SQLITE_ENABLE_COMMENTS to enable generation of extra comments on +** each VDBE opcode. +** +** Use the SQLITE_ENABLE_MODULE_COMMENTS macro to see some extra no-op +** comments in VDBE programs that show key decision points in the code +** generator. +*/ +#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS void sqlite3VdbeComment(Vdbe*, const char*, ...); # define VdbeComment(X) sqlite3VdbeComment X void sqlite3VdbeNoopComment(Vdbe*, const char*, ...); # define VdbeNoopComment(X) sqlite3VdbeNoopComment X +# ifdef SQLITE_ENABLE_MODULE_COMMENTS +# define VdbeModuleComment(X) sqlite3VdbeNoopComment X +# else +# define VdbeModuleComment(X) +# endif #else # define VdbeComment(X) # define VdbeNoopComment(X) +# define VdbeModuleComment(X) #endif #endif diff --git a/src/vdbeInt.h b/src/vdbeInt.h index 43c88a8ca1..4cdd558963 100644 --- a/src/vdbeInt.h +++ b/src/vdbeInt.h @@ -82,8 +82,7 @@ struct VdbeCursor { i64 lastRowid; /* Last rowid from a Next or NextIdx operation */ VdbeSorter *pSorter; /* Sorter object for OP_SorterOpen cursors */ - /* Result of last sqlite3BtreeMoveto() done by an OP_NotExists or - ** OP_IsUnique opcode on this cursor. */ + /* Result of last sqlite3BtreeMoveto() done by an OP_NotExists */ int seekResult; /* Cached information about the header for the data record that the @@ -469,7 +468,7 @@ int sqlite3VdbeSorterRowkey(const VdbeCursor *, Mem *); int sqlite3VdbeSorterNext(sqlite3 *, const VdbeCursor *, int *); int sqlite3VdbeSorterRewind(sqlite3 *, const VdbeCursor *, int *); int sqlite3VdbeSorterWrite(sqlite3 *, const VdbeCursor *, Mem *); -int sqlite3VdbeSorterCompare(const VdbeCursor *, Mem *, int *); +int sqlite3VdbeSorterCompare(const VdbeCursor *, Mem *, int, int *); #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0 void sqlite3VdbeEnter(Vdbe*); diff --git a/src/vdbeaux.c b/src/vdbeaux.c index 19084e9990..6c42303e88 100644 --- a/src/vdbeaux.c +++ b/src/vdbeaux.c @@ -108,6 +108,17 @@ static int growOpArray(Vdbe *p){ return (pNew ? SQLITE_OK : SQLITE_NOMEM); } +#ifdef SQLITE_DEBUG +/* This routine is just a convenient place to set a breakpoint that will +** fire after each opcode is inserted and displayed using +** "PRAGMA vdbe_addoptrace=on". +*/ +static void test_addop_breakpoint(void){ + static int n = 0; + n++; +} +#endif + /* ** Add a new instruction to the list of instructions current in the ** VDBE. Return the address of the new instruction. @@ -145,10 +156,13 @@ int sqlite3VdbeAddOp3(Vdbe *p, int op, int p1, int p2, int p3){ pOp->p3 = p3; pOp->p4.p = 0; pOp->p4type = P4_NOTUSED; -#ifdef SQLITE_DEBUG +#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS pOp->zComment = 0; +#endif +#ifdef SQLITE_DEBUG if( p->db->flags & SQLITE_VdbeAddopTrace ){ sqlite3VdbePrintOp(0, i, &p->aOp[i]); + test_addop_breakpoint(); } #endif #ifdef VDBE_PROFILE @@ -524,7 +538,8 @@ int sqlite3VdbeAddOpList(Vdbe *p, int nOp, VdbeOpList const *aOp){ VdbeOp *pOut = &p->aOp[i+addr]; pOut->opcode = pIn->opcode; pOut->p1 = pIn->p1; - if( p2<0 && (sqlite3OpcodeProperty[pOut->opcode] & OPFLG_JUMP)!=0 ){ + if( p2<0 ){ + assert( sqlite3OpcodeProperty[pOut->opcode] & OPFLG_JUMP ); pOut->p2 = addr + ADDR(p2); }else{ pOut->p2 = p2; @@ -533,8 +548,10 @@ int sqlite3VdbeAddOpList(Vdbe *p, int nOp, VdbeOpList const *aOp){ pOut->p4type = P4_NOTUSED; pOut->p4.p = 0; pOut->p5 = 0; -#ifdef SQLITE_DEBUG +#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS pOut->zComment = 0; +#endif +#ifdef SQLITE_DEBUG if( p->db->flags & SQLITE_VdbeAddopTrace ){ sqlite3VdbePrintOp(0, i+addr, &p->aOp[i+addr]); } @@ -622,12 +639,14 @@ static void freeP4(sqlite3 *db, int p4type, void *p4){ case P4_REAL: case P4_INT64: case P4_DYNAMIC: - case P4_KEYINFO: - case P4_INTARRAY: - case P4_KEYINFO_HANDOFF: { + case P4_INTARRAY: { sqlite3DbFree(db, p4); break; } + case P4_KEYINFO: { + if( db->pnBytesFreed==0 ) sqlite3KeyInfoUnref((KeyInfo*)p4); + break; + } case P4_MPRINTF: { if( db->pnBytesFreed==0 ) sqlite3_free(p4); break; @@ -664,7 +683,7 @@ static void vdbeFreeOpArray(sqlite3 *db, Op *aOp, int nOp){ Op *pOp; for(pOp=aOp; pOp<&aOp[nOp]; pOp++){ freeP4(db, pOp->p4type, pOp->p4.p); -#ifdef SQLITE_DEBUG +#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS sqlite3DbFree(db, pOp->zComment); #endif } @@ -692,6 +711,7 @@ void sqlite3VdbeChangeToNoop(Vdbe *p, int addr){ freeP4(db, pOp->p4type, pOp->p4.p); memset(pOp, 0, sizeof(pOp[0])); pOp->opcode = OP_Noop; + if( addr==p->nOp-1 ) p->nOp--; } } @@ -705,14 +725,6 @@ void sqlite3VdbeChangeToNoop(Vdbe *p, int addr){ ** the string is made into memory obtained from sqlite3_malloc(). ** A value of n==0 means copy bytes of zP4 up to and including the ** first null byte. If n>0 then copy n+1 bytes of zP4. -** -** If n==P4_KEYINFO it means that zP4 is a pointer to a KeyInfo structure. -** A copy is made of the KeyInfo structure into memory obtained from -** sqlite3_malloc, to be freed when the Vdbe is finalized. -** n==P4_KEYINFO_HANDOFF indicates that zP4 points to a KeyInfo structure -** stored in memory that the caller has obtained from sqlite3_malloc. The -** caller should not free the allocation, it will be freed when the Vdbe is -** finalized. ** ** Other values of n (P4_STATIC, P4_COLLSEQ etc.) indicate that zP4 points ** to a string or structure that is guaranteed to exist for the lifetime of @@ -727,7 +739,7 @@ void sqlite3VdbeChangeP4(Vdbe *p, int addr, const char *zP4, int n){ db = p->db; assert( p->magic==VDBE_MAGIC_INIT ); if( p->aOp==0 || db->mallocFailed ){ - if ( n!=P4_KEYINFO && n!=P4_VTAB ) { + if( n!=P4_VTAB ){ freeP4(db, n, (void*)*(char**)&zP4); } return; @@ -750,19 +762,6 @@ void sqlite3VdbeChangeP4(Vdbe *p, int addr, const char *zP4, int n){ pOp->p4.p = 0; pOp->p4type = P4_NOTUSED; }else if( n==P4_KEYINFO ){ - KeyInfo *pOrig, *pNew; - - pOrig = (KeyInfo*)zP4; - pOp->p4.pKeyInfo = pNew = sqlite3KeyInfoAlloc(db, pOrig->nField); - if( pNew ){ - memcpy(pNew->aColl, pOrig->aColl, pOrig->nField*sizeof(pNew->aColl[0])); - memcpy(pNew->aSortOrder, pOrig->aSortOrder, pOrig->nField); - pOp->p4type = P4_KEYINFO; - }else{ - p->db->mallocFailed = 1; - pOp->p4type = P4_NOTUSED; - } - }else if( n==P4_KEYINFO_HANDOFF ){ pOp->p4.p = (void*)zP4; pOp->p4type = P4_KEYINFO; }else if( n==P4_VTAB ){ @@ -780,7 +779,19 @@ void sqlite3VdbeChangeP4(Vdbe *p, int addr, const char *zP4, int n){ } } -#ifndef NDEBUG +/* +** Set the P4 on the most recently added opcode to the KeyInfo for the +** index given. +*/ +void sqlite3VdbeSetP4KeyInfo(Parse *pParse, Index *pIdx){ + Vdbe *v = pParse->pVdbe; + assert( v!=0 ); + assert( pIdx!=0 ); + sqlite3VdbeChangeP4(v, -1, (char*)sqlite3KeyInfoOfIndex(pParse, pIdx), + P4_KEYINFO); +} + +#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS /* ** Change the comment on the most recently coded instruction. Or ** insert a No-op and add the comment to that new instruction. This @@ -855,6 +866,81 @@ VdbeOp *sqlite3VdbeGetOp(Vdbe *p, int addr){ } } +#if defined(SQLITE_ENABLE_EXPLAIN_COMMENTS) +/* +** Return an integer value for one of the parameters to the opcode pOp +** determined by character c. +*/ +static int translateP(char c, const Op *pOp){ + if( c=='1' ) return pOp->p1; + if( c=='2' ) return pOp->p2; + if( c=='3' ) return pOp->p3; + if( c=='4' ) return pOp->p4.i; + return pOp->p5; +} + +/* +** Compute a string for the "comment" field of a VDBE opcode listing +*/ +static int displayComment( + const Op *pOp, /* The opcode to be commented */ + const char *zP4, /* Previously obtained value for P4 */ + char *zTemp, /* Write result here */ + int nTemp /* Space available in zTemp[] */ +){ + const char *zOpName; + const char *zSynopsis; + int nOpName; + int ii, jj; + zOpName = sqlite3OpcodeName(pOp->opcode); + nOpName = sqlite3Strlen30(zOpName); + if( zOpName[nOpName+1] ){ + int seenCom = 0; + char c; + zSynopsis = zOpName += nOpName + 1; + for(ii=jj=0; jjzComment); + seenCom = 1; + }else{ + int v1 = translateP(c, pOp); + int v2; + sqlite3_snprintf(nTemp-jj, zTemp+jj, "%d", v1); + if( strncmp(zSynopsis+ii+1, "@P", 2)==0 ){ + ii += 3; + jj += sqlite3Strlen30(zTemp+jj); + v2 = translateP(zSynopsis[ii], pOp); + if( v2>1 ) sqlite3_snprintf(nTemp-jj, zTemp+jj, "..%d", v1+v2-1); + }else if( strncmp(zSynopsis+ii+1, "..P3", 4)==0 && pOp->p3==0 ){ + ii += 4; + } + } + jj += sqlite3Strlen30(zTemp+jj); + }else{ + zTemp[jj++] = c; + } + } + if( !seenCom && jjzComment ){ + sqlite3_snprintf(nTemp-jj, zTemp+jj, "; %s", pOp->zComment); + jj += sqlite3Strlen30(zTemp+jj); + } + if( jjzComment ){ + sqlite3_snprintf(nTemp, zTemp, "%s", pOp->zComment); + jj = sqlite3Strlen30(zTemp); + }else{ + zTemp[0] = 0; + jj = 0; + } + return jj; +} +#endif /* SQLITE_DEBUG */ + + #if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) \ || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG) /* @@ -865,17 +951,20 @@ static char *displayP4(Op *pOp, char *zTemp, int nTemp){ char *zP4 = zTemp; assert( nTemp>=20 ); switch( pOp->p4type ){ - case P4_KEYINFO_STATIC: case P4_KEYINFO: { int i, j; KeyInfo *pKeyInfo = pOp->p4.pKeyInfo; assert( pKeyInfo->aSortOrder!=0 ); - sqlite3_snprintf(nTemp, zTemp, "keyinfo(%d", pKeyInfo->nField); + sqlite3_snprintf(nTemp, zTemp, "k(%d", pKeyInfo->nField); i = sqlite3Strlen30(zTemp); for(j=0; jnField; j++){ CollSeq *pColl = pKeyInfo->aColl[j]; const char *zColl = pColl ? pColl->zName : "nil"; int n = sqlite3Strlen30(zColl); + if( n==6 && memcmp(zColl,"BINARY",6)==0 ){ + zColl = "B"; + n = 1; + } if( i+n>nTemp-6 ){ memcpy(&zTemp[i],",...",4); break; @@ -1048,16 +1137,18 @@ void sqlite3VdbeLeave(Vdbe *p){ void sqlite3VdbePrintOp(FILE *pOut, int pc, Op *pOp){ char *zP4; char zPtr[50]; - static const char *zFormat1 = "%4d %-13s %4d %4d %4d %-4s %.2X %s\n"; + char zCom[100]; + static const char *zFormat1 = "%4d %-13s %4d %4d %4d %-13s %.2X %s\n"; if( pOut==0 ) pOut = stdout; zP4 = displayP4(pOp, zPtr, sizeof(zPtr)); +#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS + displayComment(pOp, zP4, zCom, sizeof(zCom)); +#else + zCom[0] = 0 +#endif fprintf(pOut, zFormat1, pc, sqlite3OpcodeName(pOp->opcode), pOp->p1, pOp->p2, pOp->p3, zP4, pOp->p5, -#ifdef SQLITE_DEBUG - pOp->zComment ? pOp->zComment : "" -#else - "" -#endif + zCom ); fflush(pOut); } @@ -1203,7 +1294,7 @@ int sqlite3VdbeList( rc = SQLITE_ERROR; sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(p->rc)); }else{ - char *z; + char *zP4; Op *pOp; if( inOp ){ /* The output line number is small enough that we are still in the @@ -1226,7 +1317,7 @@ int sqlite3VdbeList( pMem++; pMem->flags = MEM_Static|MEM_Str|MEM_Term; - pMem->z = (char*)sqlite3OpcodeName(pOp->opcode); /* Opcode */ + pMem->z = (char*)sqlite3OpcodeName(pOp->opcode); /* Opcode */ assert( pMem->z!=0 ); pMem->n = sqlite3Strlen30(pMem->z); pMem->type = SQLITE_TEXT; @@ -1273,9 +1364,9 @@ int sqlite3VdbeList( return SQLITE_ERROR; } pMem->flags = MEM_Dyn|MEM_Str|MEM_Term; - z = displayP4(pOp, pMem->z, 32); - if( z!=pMem->z ){ - sqlite3VdbeMemSetStr(pMem, z, -1, SQLITE_UTF8, 0); + zP4 = displayP4(pOp, pMem->z, 32); + if( zP4!=pMem->z ){ + sqlite3VdbeMemSetStr(pMem, zP4, -1, SQLITE_UTF8, 0); }else{ assert( pMem->z!=0 ); pMem->n = sqlite3Strlen30(pMem->z); @@ -1296,19 +1387,19 @@ int sqlite3VdbeList( pMem->enc = SQLITE_UTF8; pMem++; -#ifdef SQLITE_DEBUG - if( pOp->zComment ){ - pMem->flags = MEM_Str|MEM_Term; - pMem->z = pOp->zComment; - pMem->n = sqlite3Strlen30(pMem->z); - pMem->enc = SQLITE_UTF8; - pMem->type = SQLITE_TEXT; - }else -#endif - { - pMem->flags = MEM_Null; /* Comment */ - pMem->type = SQLITE_NULL; +#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS + if( sqlite3VdbeMemGrow(pMem, 500, 0) ){ + assert( p->db->mallocFailed ); + return SQLITE_ERROR; } + pMem->flags = MEM_Dyn|MEM_Str|MEM_Term; + pMem->n = displayComment(pOp, zP4, pMem->z, 500); + pMem->type = SQLITE_TEXT; + pMem->enc = SQLITE_UTF8; +#else + pMem->flags = MEM_Null; /* Comment */ + pMem->type = SQLITE_NULL; +#endif } p->nResColumn = 8 - 4*(p->explain-1); @@ -2099,7 +2190,7 @@ int sqlite3VdbeCheckFk(Vdbe *p, int deferred){ ){ p->rc = SQLITE_CONSTRAINT_FOREIGNKEY; p->errorAction = OE_Abort; - sqlite3SetString(&p->zErrMsg, db, "foreign key constraint failed"); + sqlite3SetString(&p->zErrMsg, db, "FOREIGN KEY constraint failed"); return SQLITE_ERROR; } return SQLITE_OK; @@ -3031,7 +3122,7 @@ int sqlite3VdbeRecordCompare( idx1 = getVarint32(aKey1, szHdr1); d1 = szHdr1; - assert( pKeyInfo->nField+1>=pPKey2->nField ); + assert( pKeyInfo->nField+pKeyInfo->nXField>=pPKey2->nField ); assert( pKeyInfo->aSortOrder!=0 ); while( idx1nField ){ u32 serial_type1; @@ -3060,24 +3151,9 @@ int sqlite3VdbeRecordCompare( rc = sqlite3MemCompare(&mem1, &pPKey2->aMem[i], pKeyInfo->aColl[i]); if( rc!=0 ){ assert( mem1.zMalloc==0 ); /* See comment below */ - - /* Invert the result if we are using DESC sort order. */ if( pKeyInfo->aSortOrder[i] ){ - rc = -rc; + rc = -rc; /* Invert the result for DESC sort order. */ } - - /* If the PREFIX_SEARCH flag is set and all fields except the final - ** rowid field were equal, then clear the PREFIX_SEARCH flag and set - ** pPKey2->rowid to the value of the rowid field in (pKey1, nKey1). - ** This is used by the OP_IsUnique opcode. - */ - if( (pPKey2->flags & UNPACKED_PREFIX_SEARCH) && i==(pPKey2->nField-1) ){ - assert( idx1==szHdr1 && rc ); - assert( mem1.flags & MEM_Int ); - pPKey2->flags &= ~UNPACKED_PREFIX_SEARCH; - pPKey2->rowid = mem1.u.i; - } - return rc; } i++; diff --git a/src/vdbeblob.c b/src/vdbeblob.c index 044e7a8977..ee660603e1 100644 --- a/src/vdbeblob.c +++ b/src/vdbeblob.c @@ -180,6 +180,10 @@ int sqlite3_blob_open( pTab = 0; sqlite3ErrorMsg(pParse, "cannot open virtual table: %s", zTable); } + if( pTab && !HasRowid(pTab) ){ + pTab = 0; + sqlite3ErrorMsg(pParse, "cannot open table without rowid: %s", zTable); + } #ifndef SQLITE_OMIT_VIEW if( pTab && pTab->pSelect ){ pTab = 0; @@ -239,7 +243,7 @@ int sqlite3_blob_open( #endif for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ int j; - for(j=0; jnColumn; j++){ + for(j=0; jnKeyCol; j++){ if( pIdx->aiColumn[j]==iCol ){ zFault = "indexed"; } diff --git a/src/vdbemem.c b/src/vdbemem.c index b549c4a31a..c4bae54fd1 100644 --- a/src/vdbemem.c +++ b/src/vdbemem.c @@ -1031,15 +1031,15 @@ static sqlite3_value *valueNew(sqlite3 *db, struct ValueNewStat4Ctx *p){ Index *pIdx = p->pIdx; /* Index being probed */ int nByte; /* Bytes of space to allocate */ int i; /* Counter variable */ - int nCol = pIdx->nColumn+1; /* Number of index columns including rowid */ + int nCol = pIdx->nColumn; /* Number of index columns including rowid */ nByte = sizeof(Mem) * nCol + sizeof(UnpackedRecord); pRec = (UnpackedRecord*)sqlite3DbMallocZero(db, nByte); if( pRec ){ - pRec->pKeyInfo = sqlite3IndexKeyinfo(p->pParse, pIdx); + pRec->pKeyInfo = sqlite3KeyInfoOfIndex(p->pParse, pIdx); if( pRec->pKeyInfo ){ - assert( pRec->pKeyInfo->nField+1==nCol ); - pRec->pKeyInfo->enc = ENC(db); + assert( pRec->pKeyInfo->nField+pRec->pKeyInfo->nXField==nCol ); + assert( pRec->pKeyInfo->enc==ENC(db) ); pRec->flags = UNPACKED_PREFIX_MATCH; pRec->aMem = (Mem *)&pRec[1]; for(i=0; ipKeyInfo->nField+1; + int nCol = pRec->pKeyInfo->nField+pRec->pKeyInfo->nXField; Mem *aMem = pRec->aMem; sqlite3 *db = aMem[0].db; for(i=0; ipKeyInfo); + sqlite3KeyInfoUnref(pRec->pKeyInfo); sqlite3DbFree(db, pRec); } } diff --git a/src/vdbesort.c b/src/vdbesort.c index c8709bdafd..3e4cad5b4a 100644 --- a/src/vdbesort.c +++ b/src/vdbesort.c @@ -386,7 +386,7 @@ static int vdbeSorterIterInit( */ static void vdbeSorterCompare( const VdbeCursor *pCsr, /* Cursor object (for pKeyInfo) */ - int bOmitRowid, /* Ignore rowid field at end of keys */ + int nIgnore, /* Ignore the last nIgnore fields */ const void *pKey1, int nKey1, /* Left side of comparison */ const void *pKey2, int nKey2, /* Right side of comparison */ int *pRes /* OUT: Result of comparison */ @@ -400,8 +400,8 @@ static void vdbeSorterCompare( sqlite3VdbeRecordUnpack(pKeyInfo, nKey2, pKey2, r2); } - if( bOmitRowid ){ - r2->nField = pKeyInfo->nField; + if( nIgnore ){ + r2->nField = pKeyInfo->nField - nIgnore; assert( r2->nField>0 ); for(i=0; inField; i++){ if( r2->aMem[i].flags & MEM_Null ){ @@ -1027,12 +1027,13 @@ int sqlite3VdbeSorterRowkey(const VdbeCursor *pCsr, Mem *pOut){ int sqlite3VdbeSorterCompare( const VdbeCursor *pCsr, /* Sorter cursor */ Mem *pVal, /* Value to compare to current sorter key */ + int nIgnore, /* Ignore this many fields at the end */ int *pRes /* OUT: Result of comparison */ ){ VdbeSorter *pSorter = pCsr->pSorter; void *pKey; int nKey; /* Sorter key to compare pVal with */ pKey = vdbeSorterRowkey(pSorter, &nKey); - vdbeSorterCompare(pCsr, 1, pVal->z, pVal->n, pKey, nKey, pRes); + vdbeSorterCompare(pCsr, nIgnore, pVal->z, pVal->n, pKey, nKey, pRes); return SQLITE_OK; } diff --git a/src/where.c b/src/where.c index 304732db67..efbd310975 100644 --- a/src/where.c +++ b/src/where.c @@ -409,6 +409,7 @@ struct WhereInfo { int iContinue; /* Jump here to continue with next record */ int iBreak; /* Jump here to break out of the loop */ int savedNQueryLoop; /* pParse->nQueryLoop outside the WHERE loop */ + int aiCurOnePass[2]; /* OP_OpenWrite cursors for the ONEPASS opt */ WhereMaskSet sMaskSet; /* Map cursor numbers to bitmasks */ WhereClause sWC; /* Decomposition of the WHERE clause */ WhereLevel a[1]; /* Information about each nest loop in WHERE */ @@ -501,8 +502,19 @@ int sqlite3WhereBreakLabel(WhereInfo *pWInfo){ ** Return TRUE if an UPDATE or DELETE statement can operate directly on ** the rowids returned by a WHERE clause. Return FALSE if doing an ** UPDATE or DELETE might change subsequent WHERE clause results. +** +** If the ONEPASS optimization is used (if this routine returns true) +** then also write the indices of open cursors used by ONEPASS +** into aiCur[0] and aiCur[1]. iaCur[0] gets the cursor of the data +** table and iaCur[1] gets the cursor used by an auxiliary index. +** Either value may be -1, indicating that cursor is not used. +** Any cursors returned will have been opened for writing. +** +** aiCur[0] and aiCur[1] both get -1 if the where-clause logic is +** unable to use the ONEPASS optimization. */ -int sqlite3WhereOkOnePass(WhereInfo *pWInfo){ +int sqlite3WhereOkOnePass(WhereInfo *pWInfo, int *aiCur){ + memcpy(aiCur, pWInfo->aiCurOnePass, sizeof(int)*2); return pWInfo->okOnePass; } @@ -971,7 +983,7 @@ static WhereTerm *whereScanInit( if( pIdx && iColumn>=0 ){ pScan->idxaff = pIdx->pTable->aCol[iColumn].affinity; for(j=0; pIdx->aiColumn[j]!=iColumn; j++){ - if( NEVER(j>=pIdx->nColumn) ) return 0; + if( NEVER(j>=pIdx->nKeyCol) ) return 0; } pScan->zCollName = pIdx->azColl[j]; }else{ @@ -1901,16 +1913,16 @@ static int isDistinctRedundant( */ for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ if( pIdx->onError==OE_None ) continue; - for(i=0; inColumn; i++){ - int iCol = pIdx->aiColumn[i]; + for(i=0; inKeyCol; i++){ + i16 iCol = pIdx->aiColumn[i]; if( 0==findTerm(pWC, iBase, iCol, ~(Bitmask)0, WO_EQ, pIdx) ){ int iIdxCol = findIndexCol(pParse, pDistinct, iBase, pIdx, i); - if( iIdxCol<0 || pTab->aCol[pIdx->aiColumn[i]].notNull==0 ){ + if( iIdxCol<0 || pTab->aCol[iCol].notNull==0 ){ break; } } } - if( i==pIdx->nColumn ){ + if( i==pIdx->nKeyCol ){ /* This index implies that the DISTINCT qualifier is redundant. */ return 1; } @@ -1966,6 +1978,7 @@ static void TRACE_IDX_OUTPUTS(sqlite3_index_info *p){ sqlite3DebugPrintf(" idxStr=%s\n", p->idxStr); sqlite3DebugPrintf(" orderByConsumed=%d\n", p->orderByConsumed); sqlite3DebugPrintf(" estimatedCost=%g\n", p->estimatedCost); + sqlite3DebugPrintf(" estimatedRows=%lld\n", p->estimatedRows); } #else #define TRACE_IDX_INPUTS(A) @@ -2008,15 +2021,13 @@ static void constructAutomaticIndex( Bitmask notReady, /* Mask of cursors that are not available */ WhereLevel *pLevel /* Write new index here */ ){ - int nColumn; /* Number of columns in the constructed index */ + int nKeyCol; /* Number of columns in the constructed index */ WhereTerm *pTerm; /* A single term of the WHERE clause */ WhereTerm *pWCEnd; /* End of pWC->a[] */ - int nByte; /* Byte of memory needed for pIdx */ Index *pIdx; /* Object describing the transient index */ Vdbe *v; /* Prepared statement under construction */ int addrInit; /* Address of the initialization bypass jump */ Table *pTable; /* The table being indexed */ - KeyInfo *pKeyinfo; /* Key information for the index */ int addrTop; /* Top of the index fill loop */ int regRecord; /* Register holding an index record */ int n; /* Column counter */ @@ -2024,6 +2035,7 @@ static void constructAutomaticIndex( int mxBitCol; /* Maximum column in pSrc->colUsed */ CollSeq *pColl; /* Collating sequence to on a column */ WhereLoop *pLoop; /* The Loop object */ + char *zNotUsed; /* Extra space on the end of pIdx */ Bitmask idxCols; /* Bitmap of columns used for indexing */ Bitmask extraCols; /* Bitmap of additional columns */ u8 sentWarning = 0; /* True if a warnning has been issued */ @@ -2036,7 +2048,7 @@ static void constructAutomaticIndex( /* Count the number of columns that will be added to the index ** and used to match WHERE clause constraints */ - nColumn = 0; + nKeyCol = 0; pTable = pSrc->pTab; pWCEnd = &pWC->a[pWC->nTerm]; pLoop = pLevel->pWLoop; @@ -2054,14 +2066,14 @@ static void constructAutomaticIndex( sentWarning = 1; } if( (idxCols & cMask)==0 ){ - if( whereLoopResize(pParse->db, pLoop, nColumn+1) ) return; - pLoop->aLTerm[nColumn++] = pTerm; + if( whereLoopResize(pParse->db, pLoop, nKeyCol+1) ) return; + pLoop->aLTerm[nKeyCol++] = pTerm; idxCols |= cMask; } } } - assert( nColumn>0 ); - pLoop->u.btree.nEq = pLoop->nLTerm = nColumn; + assert( nKeyCol>0 ); + pLoop->u.btree.nEq = pLoop->nLTerm = nKeyCol; pLoop->wsFlags = WHERE_COLUMN_EQ | WHERE_IDX_ONLY | WHERE_INDEXED | WHERE_AUTO_INDEX; @@ -2078,26 +2090,18 @@ static void constructAutomaticIndex( testcase( pTable->nCol==BMS-1 ); testcase( pTable->nCol==BMS-2 ); for(i=0; icolUsed & MASKBIT(BMS-1) ){ - nColumn += pTable->nCol - BMS + 1; + nKeyCol += pTable->nCol - BMS + 1; } pLoop->wsFlags |= WHERE_COLUMN_EQ | WHERE_IDX_ONLY; /* Construct the Index object to describe this index */ - nByte = sizeof(Index); - nByte += nColumn*sizeof(int); /* Index.aiColumn */ - nByte += nColumn*sizeof(char*); /* Index.azColl */ - nByte += nColumn; /* Index.aSortOrder */ - pIdx = sqlite3DbMallocZero(pParse->db, nByte); + pIdx = sqlite3AllocateIndexObject(pParse->db, nKeyCol+1, 0, &zNotUsed); if( pIdx==0 ) return; pLoop->u.btree.pIndex = pIdx; - pIdx->azColl = (char**)&pIdx[1]; - pIdx->aiColumn = (int*)&pIdx->azColl[nColumn]; - pIdx->aSortOrder = (u8*)&pIdx->aiColumn[nColumn]; pIdx->zName = "auto-index"; - pIdx->nColumn = nColumn; pIdx->pTable = pTable; n = 0; idxCols = 0; @@ -2135,20 +2139,21 @@ static void constructAutomaticIndex( n++; } } - assert( n==nColumn ); + assert( n==nKeyCol ); + pIdx->aiColumn[n] = -1; + pIdx->azColl[n] = "BINARY"; /* Create the automatic index */ - pKeyinfo = sqlite3IndexKeyinfo(pParse, pIdx); assert( pLevel->iIdxCur>=0 ); pLevel->iIdxCur = pParse->nTab++; - sqlite3VdbeAddOp4(v, OP_OpenAutoindex, pLevel->iIdxCur, nColumn+1, 0, - (char*)pKeyinfo, P4_KEYINFO_HANDOFF); + sqlite3VdbeAddOp2(v, OP_OpenAutoindex, pLevel->iIdxCur, nKeyCol+1); + sqlite3VdbeSetP4KeyInfo(pParse, pIdx); VdbeComment((v, "for %s", pTable->zName)); /* Fill the automatic index with content */ addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, pLevel->iTabCur); regRecord = sqlite3GetTempReg(pParse); - sqlite3GenerateIndexKey(pParse, pIdx, pLevel->iTabCur, regRecord, 1, 0); + sqlite3GenerateIndexKey(pParse, pIdx, pLevel->iTabCur, regRecord, 0, 0); sqlite3VdbeAddOp2(v, OP_IdxInsert, pLevel->iIdxCur, regRecord); sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT); sqlite3VdbeAddOp2(v, OP_Next, pLevel->iTabCur, addrTop+1); @@ -2395,7 +2400,7 @@ static void whereKeyStats( iUpper = i>=pIdx->nSample ? pIdx->aiRowEst[0] : aSample[i].anLt[iCol]; iLower = aSample[i-1].anEq[iCol] + aSample[i-1].anLt[iCol]; } - aStat[1] = (pIdx->nColumn>iCol ? pIdx->aAvgEq[iCol] : 1); + aStat[1] = (pIdx->nKeyCol>iCol ? pIdx->aAvgEq[iCol] : 1); if( iLower>=iUpper ){ iGap = 0; }else{ @@ -2495,7 +2500,7 @@ static int whereRangeScanEst( tRowcnt iLower; tRowcnt iUpper; - if( nEq==p->nColumn ){ + if( nEq==p->nKeyCol ){ aff = SQLITE_AFF_INTEGER; }else{ aff = p->pTable->aCol[p->aiColumn[nEq]].affinity; @@ -2613,7 +2618,7 @@ static int whereEqualScanEst( int bOk; assert( nEq>=1 ); - assert( nEq<=(p->nColumn+1) ); + assert( nEq<=(p->nKeyCol+1) ); assert( p->aSample!=0 ); assert( p->nSample>0 ); assert( pBuilder->nRecValidp->nColumn ){ + if( nEq>p->nKeyCol ){ *pnRow = 1; return SQLITE_OK; } @@ -3013,7 +3018,7 @@ static char *explainIndexRange(sqlite3 *db, WhereLoop *pLoop, Table *pTab){ int nEq = pLoop->u.btree.nEq; int i, j; Column *aCol = pTab->aCol; - int *aiColumn = pIndex->aiColumn; + i16 *aiColumn = pIndex->aiColumn; StrAccum txt; if( nEq==0 && (pLoop->wsFlags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))==0 ){ @@ -3023,17 +3028,17 @@ static char *explainIndexRange(sqlite3 *db, WhereLoop *pLoop, Table *pTab){ txt.db = db; sqlite3StrAccumAppend(&txt, " (", 2); for(i=0; inColumn ) ? "rowid" : aCol[aiColumn[i]].zName; + char *z = (i==pIndex->nKeyCol ) ? "rowid" : aCol[aiColumn[i]].zName; explainAppendTerm(&txt, i, z, "="); } j = i; if( pLoop->wsFlags&WHERE_BTM_LIMIT ){ - char *z = (j==pIndex->nColumn ) ? "rowid" : aCol[aiColumn[j]].zName; + char *z = (j==pIndex->nKeyCol ) ? "rowid" : aCol[aiColumn[j]].zName; explainAppendTerm(&txt, i++, z, ">"); } if( pLoop->wsFlags&WHERE_TOP_LIMIT ){ - char *z = (j==pIndex->nColumn ) ? "rowid" : aCol[aiColumn[j]].zName; + char *z = (j==pIndex->nKeyCol ) ? "rowid" : aCol[aiColumn[j]].zName; explainAppendTerm(&txt, i, z, "<"); } sqlite3StrAccumAppend(&txt, ")", 1); @@ -3160,7 +3165,7 @@ static Bitmask codeOneLoopStart( bRev = (pWInfo->revMask>>iLevel)&1; omitTable = (pLoop->wsFlags & WHERE_IDX_ONLY)!=0 && (pWInfo->wctrlFlags & WHERE_FORCE_TABLE)==0; - VdbeNoopComment((v, "Begin Join Loop %d", iLevel)); + VdbeNoopComment((v, "Begin WHERE-Loop %d: %s", iLevel,pTabItem->pTab->zName)); /* Create labels for the "break" and "continue" instructions ** for the current loop. Jump to addrBrk to break out of a loop. @@ -3417,7 +3422,7 @@ static Bitmask codeOneLoopStart( */ if( (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)!=0 && (pWInfo->bOBSat!=0) - && (pIdx->nColumn>nEq) + && (pIdx->nKeyCol>nEq) ){ /* assert( pOrderBy->nExpr==1 ); */ /* assert( pOrderBy->a[0].pExpr->iColumn==pIdx->aiColumn[nEq] ); */ @@ -3450,8 +3455,8 @@ static Bitmask codeOneLoopStart( ** a forward order scan on a descending index, interchange the ** start and end terms (pRangeStart and pRangeEnd). */ - if( (nEqnColumn && bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC)) - || (bRev && pIdx->nColumn==nEq) + if( (nEqnKeyCol && bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC)) + || (bRev && pIdx->nKeyCol==nEq) ){ SWAP(WhereTerm *, pRangeEnd, pRangeStart); } @@ -3560,11 +3565,22 @@ static Bitmask codeOneLoopStart( /* Seek the table cursor, if required */ disableTerm(pLevel, pRangeStart); disableTerm(pLevel, pRangeEnd); - if( !omitTable ){ + if( omitTable ){ + /* pIdx is a covering index. No need to access the main table. */ + }else if( HasRowid(pIdx->pTable) ){ iRowidReg = iReleaseReg = sqlite3GetTempReg(pParse); sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, iRowidReg); sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg); sqlite3VdbeAddOp2(v, OP_Seek, iCur, iRowidReg); /* Deferred seek */ + }else{ + Index *pPk = sqlite3PrimaryKeyIndex(pIdx->pTable); + iRowidReg = sqlite3GetTempRange(pParse, pPk->nKeyCol); + for(j=0; jnKeyCol; j++){ + k = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[j]); + sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, k, iRowidReg+j); + } + sqlite3VdbeAddOp4Int(v, OP_NotFound, iCur, addrCont, + iRowidReg, pPk->nKeyCol); } /* Record the instruction used to terminate the loop. Disable @@ -3991,6 +4007,7 @@ static void whereLoopClearUnion(sqlite3 *db, WhereLoop *p){ p->u.vtab.idxStr = 0; }else if( (p->wsFlags & WHERE_AUTO_INDEX)!=0 && p->u.btree.pIndex!=0 ){ sqlite3DbFree(db, p->u.btree.pIndex->zColAff); + sqlite3KeyInfoUnref(p->u.btree.pIndex->pKeyInfo); sqlite3DbFree(db, p->u.btree.pIndex); p->u.btree.pIndex = 0; } @@ -4290,8 +4307,8 @@ static int whereLoopAddBtreeIndex( } if( pProbe->bUnordered ) opMask &= ~(WO_GT|WO_GE|WO_LT|WO_LE); - assert( pNew->u.btree.nEq<=pProbe->nColumn ); - if( pNew->u.btree.nEq < pProbe->nColumn ){ + assert( pNew->u.btree.nEq<=pProbe->nKeyCol ); + if( pNew->u.btree.nEq < pProbe->nKeyCol ){ iCol = pProbe->aiColumn[pNew->u.btree.nEq]; nRowEst = sqlite3LogEst(pProbe->aiRowEst[pNew->u.btree.nEq+1]); if( nRowEst==0 && pProbe->onError==OE_None ) nRowEst = 1; @@ -4348,7 +4365,7 @@ static int whereLoopAddBtreeIndex( pNew->wsFlags |= WHERE_COLUMN_EQ; if( iCol<0 || (pProbe->onError!=OE_None && nInMul==0 - && pNew->u.btree.nEq==pProbe->nColumn-1) + && pNew->u.btree.nEq==pProbe->nKeyCol-1) ){ assert( (pNew->wsFlags & WHERE_COLUMN_IN)==0 || iCol<0 ); pNew->wsFlags |= WHERE_ONEROW; @@ -4414,7 +4431,7 @@ static int whereLoopAddBtreeIndex( whereLoopOutputAdjust(pBuilder->pWC, pNew); rc = whereLoopInsert(pBuilder, pNew); if( (pNew->wsFlags & WHERE_TOP_LIMIT)==0 - && pNew->u.btree.nEq<(pProbe->nColumn + (pProbe->zName!=0)) + && pNew->u.btree.nEq<(pProbe->nKeyCol + (pProbe->zName!=0)) ){ whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nInMul+nIn); } @@ -4453,7 +4470,7 @@ static int indexMightHelpWithOrderBy( Expr *pExpr = sqlite3ExprSkipCollate(pOB->a[ii].pExpr); if( pExpr->op!=TK_COLUMN ) return 0; if( pExpr->iTable==iCursor ){ - for(jj=0; jjnColumn; jj++){ + for(jj=0; jjnKeyCol; jj++){ if( pExpr->iColumn==pIndex->aiColumn[jj] ) return 1; } } @@ -4470,10 +4487,11 @@ static Bitmask columnsInIndex(Index *pIdx){ int j; for(j=pIdx->nColumn-1; j>=0; j--){ int x = pIdx->aiColumn[j]; - assert( x>=0 ); - testcase( x==BMS-1 ); - testcase( x==BMS-2 ); - if( x=0 ){ + testcase( x==BMS-1 ); + testcase( x==BMS-2 ); + if( xpIndex ){ /* An INDEXED BY clause specifies a particular index to use */ pProbe = pSrc->pIndex; + }else if( !HasRowid(pTab) ){ + pProbe = pTab->pIndex; }else{ /* There is no INDEXED BY clause. Create a fake Index object in local ** variable sPk to represent the rowid primary key index. Make this @@ -4533,7 +4553,7 @@ static int whereLoopAddBtree( ** indices to follow */ Index *pFirst; /* First of real indices on the table */ memset(&sPk, 0, sizeof(Index)); - sPk.nColumn = 1; + sPk.nKeyCol = 1; sPk.aiColumn = &aiColumnPk; sPk.aiRowEst = aiRowEstPk; sPk.onError = OE_Replace; @@ -4558,6 +4578,7 @@ static int whereLoopAddBtree( && pSrc->pIndex==0 && !pSrc->viaCoroutine && !pSrc->notIndexed + && HasRowid(pTab) && !pSrc->isCorrelated ){ /* Generate auto-index WhereLoops */ @@ -4620,14 +4641,21 @@ static int whereLoopAddBtree( pNew->nOut = rSize; if( rc ) break; }else{ - Bitmask m = pSrc->colUsed & ~columnsInIndex(pProbe); - pNew->wsFlags = (m==0) ? (WHERE_IDX_ONLY|WHERE_INDEXED) : WHERE_INDEXED; + Bitmask m; + if( pProbe->isCovering ){ + pNew->wsFlags = WHERE_IDX_ONLY | WHERE_INDEXED; + m = 0; + }else{ + m = pSrc->colUsed & ~columnsInIndex(pProbe); + pNew->wsFlags = (m==0) ? (WHERE_IDX_ONLY|WHERE_INDEXED) : WHERE_INDEXED; + } /* Full scan via index */ if( b + || !HasRowid(pTab) || ( m==0 && pProbe->bUnordered==0 - && pProbe->szIdxRowszTabRow + && (pProbe->szIdxRowszTabRow) && (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 && sqlite3GlobalConfig.bUseCis && OptimizationEnabled(pWInfo->pParse->db, SQLITE_CoverIdxScan) @@ -4643,7 +4671,6 @@ static int whereLoopAddBtree( pNew->rRun = sqlite3LogEstAdd(rSize,rLogSize) + 1 + (15*pProbe->szIdxRow)/pTab->szTabRow; }else{ - assert( b!=0 ); /* TUNING: Cost of scanning a non-covering index is (N+1)*log2(N) ** which we will simplify to just N*log2(N) */ pNew->rRun = rSize + rLogSize; @@ -4761,6 +4788,7 @@ static int whereLoopAddVirtual( pIdxInfo->needToFreeIdxStr = 0; pIdxInfo->orderByConsumed = 0; pIdxInfo->estimatedCost = SQLITE_BIG_DBL / (double)2; + pIdxInfo->estimatedRows = 25; rc = vtabBestIndex(pParse, pTab, pIdxInfo); if( rc ) goto whereLoopAddVtab_exit; pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint; @@ -4820,8 +4848,7 @@ static int whereLoopAddVirtual( && pIdxInfo->orderByConsumed); pNew->rSetup = 0; pNew->rRun = sqlite3LogEstFromDouble(pIdxInfo->estimatedCost); - /* TUNING: Every virtual table query returns 25 rows */ - pNew->nOut = 46; assert( 46==sqlite3LogEst(25) ); + pNew->nOut = sqlite3LogEst(pIdxInfo->estimatedRows); whereLoopInsert(pBuilder, pNew); if( pNew->u.vtab.needFree ){ sqlite3_free(pNew->u.vtab.idxStr); @@ -4859,6 +4886,7 @@ static int whereLoopAddOr(WhereLoopBuilder *pBuilder, Bitmask mExtra){ pNew = pBuilder->pNew; memset(&sSum, 0, sizeof(sSum)); pItem = pWInfo->pTabList->a + pNew->iTab; + if( !HasRowid(pItem->pTab) ) return SQLITE_OK; iCur = pItem->iCursor; for(pTerm=pWC->a; pTermwsFlags & WHERE_ONEROW)==0 ){ if( pLoop->wsFlags & WHERE_IPK ){ pIndex = 0; - nColumn = 0; + nKeyCol = 0; + nColumn = 1; }else if( (pIndex = pLoop->u.btree.pIndex)==0 || pIndex->bUnordered ){ return 0; }else{ + nKeyCol = pIndex->nKeyCol; nColumn = pIndex->nColumn; + assert( nColumn==nKeyCol+1 || !HasRowid(pIndex->pTable) ); + assert( pIndex->aiColumn[nColumn-1]==(-1) || !HasRowid(pIndex->pTable)); isOrderDistinct = pIndex->onError!=OE_None; } @@ -5113,7 +5146,7 @@ static int wherePathSatisfiesOrderBy( */ rev = revSet = 0; distinctColumns = 0; - for(j=0; j<=nColumn; j++){ + for(j=0; jaiColumn[j]; revIdx = pIndex->aSortOrder[j]; if( iColumn==pIndex->pTable->iPKey ) iColumn = -1; }else{ - /* The ROWID column at the end */ - assert( j==nColumn ); iColumn = -1; revIdx = 0; } /* An unconstrained column that might be NULL means that this - ** WhereLoop is not well-ordered + ** WhereLoop is not well-ordered */ if( isOrderDistinct && iColumn>=0 @@ -5194,7 +5224,7 @@ static int wherePathSatisfiesOrderBy( } }else{ /* No match found */ - if( j==0 || jaLTermSpace)==4 ); if( pIdx->onError==OE_None || pIdx->pPartIdxWhere!=0 - || pIdx->nColumn>ArraySize(pLoop->aLTermSpace) + || pIdx->nKeyCol>ArraySize(pLoop->aLTermSpace) ) continue; - for(j=0; jnColumn; j++){ + for(j=0; jnKeyCol; j++){ pTerm = findTerm(pWC, iCur, pIdx->aiColumn[j], 0, WO_EQ, pIdx); if( pTerm==0 ) break; pLoop->aLTerm[j] = pTerm; } - if( j!=pIdx->nColumn ) continue; + if( j!=pIdx->nKeyCol ) continue; pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_ONEROW|WHERE_INDEXED; - if( (pItem->colUsed & ~columnsInIndex(pIdx))==0 ){ + if( pIdx->isCovering || (pItem->colUsed & ~columnsInIndex(pIdx))==0 ){ pLoop->wsFlags |= WHERE_IDX_ONLY; } pLoop->nLTerm = j; @@ -5677,6 +5707,14 @@ static int whereShortCut(WhereLoopBuilder *pBuilder){ ** if the WHERE_GROUPBY flag is set in wctrlFlags) of a SELECT statement ** if there is one. If there is no ORDER BY clause or if this routine ** is called from an UPDATE or DELETE statement, then pOrderBy is NULL. +** +** The iIdxCur parameter is the cursor number of an index. If +** WHERE_ONETABLE_ONLY is set, iIdxCur is the cursor number of an index +** to use for OR clause processing. The WHERE clause should use this +** specific cursor. If WHERE_ONEPASS_DESIRED is set, then iIdxCur is +** the first cursor in an array of cursors for all indices. iIdxCur should +** be used to compute the appropriate cursor depending on which index is +** used. */ WhereInfo *sqlite3WhereBegin( Parse *pParse, /* The parser context */ @@ -5742,6 +5780,7 @@ WhereInfo *sqlite3WhereBegin( pWInfo = 0; goto whereBeginError; } + pWInfo->aiCurOnePass[0] = pWInfo->aiCurOnePass[1] = -1; pWInfo->nLevel = nTabList; pWInfo->pParse = pParse; pWInfo->pTabList = pTabList; @@ -5973,7 +6012,9 @@ WhereInfo *sqlite3WhereBegin( if( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0 && (pWInfo->a[0].pWLoop->wsFlags & WHERE_ONEROW)!=0 ){ pWInfo->okOnePass = 1; - pWInfo->a[0].pWLoop->wsFlags &= ~WHERE_IDX_ONLY; + if( HasRowid(pTabList->a[0].pTab) ){ + pWInfo->a[0].pWLoop->wsFlags &= ~WHERE_IDX_ONLY; + } } /* Open all tables in the pTabList and any indices selected for @@ -6003,11 +6044,16 @@ WhereInfo *sqlite3WhereBegin( #endif if( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 && (wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0 ){ - int op = pWInfo->okOnePass ? OP_OpenWrite : OP_OpenRead; + int op = OP_OpenRead; + if( pWInfo->okOnePass ){ + op = OP_OpenWrite; + pWInfo->aiCurOnePass[0] = pTabItem->iCursor; + }; sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op); + assert( pTabItem->iCursor==pLevel->iTabCur ); testcase( !pWInfo->okOnePass && pTab->nCol==BMS-1 ); testcase( !pWInfo->okOnePass && pTab->nCol==BMS ); - if( !pWInfo->okOnePass && pTab->nColokOnePass && pTab->nColcolUsed; int n = 0; for(; b; b=b>>1, n++){} @@ -6020,13 +6066,30 @@ WhereInfo *sqlite3WhereBegin( } if( pLoop->wsFlags & WHERE_INDEXED ){ Index *pIx = pLoop->u.btree.pIndex; - KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIx); - /* FIXME: As an optimization use pTabItem->iCursor if WHERE_IDX_ONLY */ - int iIndexCur = pLevel->iIdxCur = iIdxCur ? iIdxCur : pParse->nTab++; + int iIndexCur; + int op = OP_OpenRead; + /* iIdxCur is always set if to a positive value if ONEPASS is possible */ + assert( iIdxCur!=0 || (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 ); + if( pWInfo->okOnePass ){ + Index *pJ = pTabItem->pTab->pIndex; + iIndexCur = iIdxCur; + assert( wctrlFlags & WHERE_ONEPASS_DESIRED ); + while( ALWAYS(pJ) && pJ!=pIx ){ + iIndexCur++; + pJ = pJ->pNext; + } + op = OP_OpenWrite; + pWInfo->aiCurOnePass[1] = iIndexCur; + }else if( iIdxCur && (wctrlFlags & WHERE_ONETABLE_ONLY)!=0 ){ + iIndexCur = iIdxCur; + }else{ + iIndexCur = pParse->nTab++; + } + pLevel->iIdxCur = iIndexCur; assert( pIx->pSchema==pTab->pSchema ); assert( iIndexCur>=0 ); - sqlite3VdbeAddOp4(v, OP_OpenRead, iIndexCur, pIx->tnum, iDb, - (char*)pKey, P4_KEYINFO_HANDOFF); + sqlite3VdbeAddOp3(v, op, iIndexCur, pIx->tnum, iDb); + sqlite3VdbeSetP4KeyInfo(pParse, pIx); VdbeComment((v, "%s", pIx->zName)); } sqlite3CodeVerifySchema(pParse, iDb); @@ -6121,6 +6184,8 @@ void sqlite3WhereEnd(WhereInfo *pWInfo){ } sqlite3VdbeJumpHere(v, addr); } + VdbeNoopComment((v, "End WHERE-Loop %d: %s", i, + pWInfo->pTabList->a[pLevel->iFrom].pTab->zName)); } /* The "break" point is here, just past the end of the outer loop. @@ -6128,8 +6193,6 @@ void sqlite3WhereEnd(WhereInfo *pWInfo){ */ sqlite3VdbeResolveLabel(v, pWInfo->iBreak); - /* Close all of the cursors that were opened by sqlite3WhereBegin. - */ assert( pWInfo->nLevel<=pTabList->nSrc ); for(i=0, pLevel=pWInfo->a; inLevel; i++, pLevel++){ Index *pIdx = 0; @@ -6137,6 +6200,12 @@ void sqlite3WhereEnd(WhereInfo *pWInfo){ Table *pTab = pTabItem->pTab; assert( pTab!=0 ); pLoop = pLevel->pWLoop; + + /* Close all of the cursors that were opened by sqlite3WhereBegin. + ** Except, do not close cursors that will be reused by the OR optimization + ** (WHERE_OMIT_OPEN_CLOSE). And do not close the OP_OpenWrite cursors + ** created for the ONEPASS optimization. + */ if( (pTab->tabFlags & TF_Ephemeral)==0 && pTab->pSelect==0 && (pWInfo->wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0 @@ -6145,7 +6214,10 @@ void sqlite3WhereEnd(WhereInfo *pWInfo){ if( !pWInfo->okOnePass && (ws & WHERE_IDX_ONLY)==0 ){ sqlite3VdbeAddOp1(v, OP_Close, pTabItem->iCursor); } - if( (ws & WHERE_INDEXED)!=0 && (ws & (WHERE_IPK|WHERE_AUTO_INDEX))==0 ){ + if( (ws & WHERE_INDEXED)!=0 + && (ws & (WHERE_IPK|WHERE_AUTO_INDEX))==0 + && pLevel->iIdxCur!=pWInfo->aiCurOnePass[1] + ){ sqlite3VdbeAddOp1(v, OP_Close, pLevel->iIdxCur); } } @@ -6167,7 +6239,7 @@ void sqlite3WhereEnd(WhereInfo *pWInfo){ pIdx = pLevel->u.pCovidx; } if( pIdx && !db->mallocFailed ){ - int k, j, last; + int k, last; VdbeOp *pOp; last = sqlite3VdbeCurrentAddr(v); @@ -6176,14 +6248,18 @@ void sqlite3WhereEnd(WhereInfo *pWInfo){ for(; kp1!=pLevel->iTabCur ) continue; if( pOp->opcode==OP_Column ){ - for(j=0; jnColumn; j++){ - if( pOp->p2==pIdx->aiColumn[j] ){ - pOp->p2 = j; - pOp->p1 = pLevel->iIdxCur; - break; - } + int x = pOp->p2; + assert( pIdx->pTable==pTab ); + if( !HasRowid(pTab) ){ + Index *pPk = sqlite3PrimaryKeyIndex(pTab); + x = pPk->aiColumn[x]; } - assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 || jnColumn ); + x = sqlite3ColumnOfIndex(pIdx, x); + if( x>=0 ){ + pOp->p2 = x; + pOp->p1 = pLevel->iIdxCur; + } + assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 || x>=0 ); }else if( pOp->opcode==OP_Rowid ){ pOp->p1 = pLevel->iIdxCur; pOp->opcode = OP_IdxRowid; diff --git a/test/alter.test b/test/alter.test index 1ccea22624..557162f837 100644 --- a/test/alter.test +++ b/test/alter.test @@ -860,5 +860,19 @@ foreach {tn tbl} $system_table_list { } [list 1 "table $tbl may not be altered"] } +#------------------------------------------------------------------------ +# Verify that ALTER TABLE works on tables with the WITHOUT rowid option. +# +do_execsql_test alter-16.1 { + CREATE TABLE t16a(a TEXT, b REAL, c INT, PRIMARY KEY(a,b)) WITHOUT rowid; + INSERT INTO t16a VALUES('abc',1.25,99); + ALTER TABLE t16a ADD COLUMN d TEXT DEFAULT 'xyzzy'; + INSERT INTO t16a VALUES('cba',5.5,98,'fizzle'); + SELECT * FROM t16a ORDER BY a; +} {abc 1.25 99 xyzzy cba 5.5 98 fizzle} +do_execsql_test alter-16.2 { + ALTER TABLE t16a RENAME TO t16a_rn; + SELECT * FROM t16a_rn ORDER BY a; +} {abc 1.25 99 xyzzy cba 5.5 98 fizzle} finish_test diff --git a/test/autovacuum.test b/test/autovacuum.test index bba40e3013..9ee2cd0fa8 100644 --- a/test/autovacuum.test +++ b/test/autovacuum.test @@ -526,7 +526,7 @@ do_test autovacuum-4.2 { catchsql { CREATE UNIQUE INDEX av1_i ON av1(a); } -} {1 {indexed columns are not unique}} +} {1 {UNIQUE constraint failed: av1.a}} do_test autovacuum-4.3 { execsql { SELECT sum(a) FROM av1; diff --git a/test/backcompat.test b/test/backcompat.test index dd40fed23a..fdc2410b7a 100644 --- a/test/backcompat.test +++ b/test/backcompat.test @@ -200,6 +200,42 @@ do_allbackcompat_test { do_test backcompat-1.2.7 { sql1 { PRAGMA integrity_check } } {ok} do_test backcompat-1.2.8 { sql2 { PRAGMA integrity_check } } {ok} + + do_test backcompat-2.1 { + sql1 { + CREATE TABLE t2(a UNIQUE, b PRIMARY KEY, c UNIQUE); + INSERT INTO t2 VALUES(1,9,5); + INSERT INTO t2 VALUES(5,5,1); + INSERT INTO t2 VALUES(9,1,9); + SELECT * FROM t2 ORDER BY a; + } + } {1 9 5 5 5 1 9 1 9} + do_test backcompat-2.2 { + sql2 { + SELECT * FROM sqlite_master WHERE rootpage=-1; + SELECT * FROM t2 ORDER BY a; + } + } {1 9 5 5 5 1 9 1 9} + do_test backcompat-2.3 { + sql1 { + SELECT * FROM t2 ORDER BY b; + } + } {9 1 9 5 5 1 1 9 5} + do_test backcompat-2.4 { + sql2 { + SELECT * FROM t2 ORDER BY b; + } + } {9 1 9 5 5 1 1 9 5} + do_test backcompat-2.5 { + sql1 { + SELECT * FROM t2 ORDER BY c; + } + } {5 5 1 1 9 5 9 1 9} + do_test backcompat-2.6 { + sql2 { + SELECT * FROM t2 ORDER BY c; + } + } {5 5 1 1 9 5 9 1 9} } foreach k [lsort [array names ::incompatible]] { puts "ERROR: Detected journal incompatibility with version $k" diff --git a/test/capi2.test b/test/capi2.test index 20ee3401bf..39f50dd079 100644 --- a/test/capi2.test +++ b/test/capi2.test @@ -237,7 +237,7 @@ do_test capi2-3.13b {db changes} {0} do_test capi2-3.14 { list [sqlite3_finalize $VM] [sqlite3_errmsg $DB] \ [sqlite3_extended_errcode $DB] -} {SQLITE_CONSTRAINT {column a is not unique} SQLITE_CONSTRAINT_UNIQUE} +} {SQLITE_CONSTRAINT {UNIQUE constraint failed: t1.a} SQLITE_CONSTRAINT_UNIQUE} do_test capi2-3.15 { set VM [sqlite3_prepare $DB {CREATE TABLE t2(a NOT NULL, b)} -1 TAIL] set TAIL @@ -261,7 +261,7 @@ do_test capi2-3.18 { do_test capi2-3.19 { list [sqlite3_finalize $VM] [sqlite3_errmsg $DB] \ [sqlite3_extended_errcode $DB] -} {SQLITE_CONSTRAINT {t2.a may not be NULL} SQLITE_CONSTRAINT_NOTNULL} +} {SQLITE_CONSTRAINT {NOT NULL constraint failed: t2.a} SQLITE_CONSTRAINT_NOTNULL} do_test capi2-3.20 { execsql { @@ -555,7 +555,7 @@ do_test capi2-6.27 { INSERT INTO t1 VALUES(2,4,5); SELECT * FROM t1; } -} {1 {column a is not unique}} +} {1 {UNIQUE constraint failed: t1.a}} do_test capi2-6.28 { list [sqlite3_step $VM1] \ [sqlite3_column_count $VM1] \ diff --git a/test/check.test b/test/check.test index f7ebc2cb4c..02b99f2ac9 100644 --- a/test/check.test +++ b/test/check.test @@ -41,7 +41,7 @@ do_test check-1.3 { catchsql { INSERT INTO t1 VALUES(6,7); } -} {1 {constraint failed}} +} {1 {CHECK constraint failed: t1}} do_test check-1.4 { execsql { SELECT * FROM t1; @@ -51,7 +51,7 @@ do_test check-1.5 { catchsql { INSERT INTO t1 VALUES(4,3); } -} {1 {constraint failed}} +} {1 {CHECK constraint failed: t1}} do_test check-1.6 { execsql { SELECT * FROM t1; @@ -88,7 +88,7 @@ do_test check-1.12 { catchsql { UPDATE t1 SET x=7 WHERE x==2 } -} {1 {constraint failed}} +} {1 {CHECK constraint failed: t1}} do_test check-1.13 { execsql { SELECT * FROM t1; @@ -98,7 +98,7 @@ do_test check-1.14 { catchsql { UPDATE t1 SET x=5 WHERE x==2 } -} {1 {constraint failed}} +} {1 {CHECK constraint failed: t1}} do_test check-1.15 { execsql { SELECT * FROM t1; @@ -142,17 +142,17 @@ do_test check-2.4 { catchsql { INSERT INTO t2 VALUES(1.1, NULL, NULL); } -} {1 {constraint one failed}} +} {1 {CHECK constraint failed: one}} do_test check-2.5 { catchsql { INSERT INTO t2 VALUES(NULL, 5, NULL); } -} {1 {constraint two failed}} +} {1 {CHECK constraint failed: two}} do_test check-2.6 { catchsql { INSERT INTO t2 VALUES(NULL, NULL, 3.14159); } -} {1 {constraint three failed}} +} {1 {CHECK constraint failed: three}} # Undocumented behavior: The CONSTRAINT name clause can follow a constraint. # Such a clause is ignored. But the parser must accept it for backwards @@ -172,7 +172,7 @@ do_test check-2.11 { catchsql { INSERT INTO t2b VALUES('xyzzy','hi',5); } -} {1 {constraint failed}} +} {1 {CHECK constraint failed: t2b}} do_test check-2.12 { execsql { CREATE TABLE t2c( @@ -188,7 +188,7 @@ do_test check-2.13 { catchsql { INSERT INTO t2c VALUES('xyzzy',7,8); } -} {1 {constraint x_two failed}} +} {1 {CHECK constraint failed: x_two}} do_test check-2.cleanup { execsql { DROP TABLE IF EXISTS t2b; @@ -256,7 +256,7 @@ do_test check-3.9 { catchsql { INSERT INTO t3 VALUES(111,222,333); } -} {1 {constraint failed}} +} {1 {CHECK constraint failed: t3}} do_test check-4.1 { execsql { @@ -298,7 +298,7 @@ do_test check-4.6 { catchsql { UPDATE t4 SET x=0, y=1; } -} {1 {constraint failed}} +} {1 {CHECK constraint failed: t4}} do_test check-4.7 { execsql { SELECT * FROM t4; @@ -316,7 +316,7 @@ do_test check-4.9 { PRAGMA ignore_check_constraints=OFF; UPDATE t4 SET x=0, y=2; } -} {1 {constraint failed}} +} {1 {CHECK constraint failed: t4}} ifcapable vacuum { do_test check_4.10 { catchsql { @@ -367,7 +367,7 @@ do_test check-6.5 { catchsql { UPDATE OR FAIL t1 SET x=7-x, y=y+1; } -} {1 {constraint failed}} +} {1 {CHECK constraint failed: t1}} do_test check-6.6 { execsql { SELECT * FROM t1; @@ -379,7 +379,7 @@ do_test check-6.7 { INSERT INTO t1 VALUES(1,30.0); INSERT OR ROLLBACK INTO t1 VALUES(8,40.0); } -} {1 {constraint failed}} +} {1 {CHECK constraint failed: t1}} do_test check-6.8 { catchsql { COMMIT; @@ -398,7 +398,7 @@ do_test check-6.12 { catchsql { REPLACE INTO t1 VALUES(6,7); } -} {1 {constraint failed}} +} {1 {CHECK constraint failed: t1}} do_test check-6.13 { execsql {SELECT * FROM t1} } {3 12.0 2 20.0} @@ -426,7 +426,8 @@ db func myfunc myfunc do_execsql_test 7.1 { CREATE TABLE t6(a CHECK (myfunc(a))) } do_execsql_test 7.2 { INSERT INTO t6 VALUES(9) } -do_catchsql_test 7.3 { INSERT INTO t6 VALUES(11) } {1 {constraint failed}} +do_catchsql_test 7.3 { INSERT INTO t6 VALUES(11) } \ + {1 {CHECK constraint failed: t6}} do_test 7.4 { sqlite3 db2 test.db @@ -449,7 +450,7 @@ do_test 7.7 { do_test 7.8 { db2 func myfunc myfunc catchsql { INSERT INTO t6 VALUES(12) } db2 -} {1 {constraint failed}} +} {1 {CHECK constraint failed: t6}} # 2013-08-02: Silently ignore database name qualifiers in CHECK constraints. # diff --git a/test/collate4.test b/test/collate4.test index 5ae1e7b930..2ddf53d58b 100644 --- a/test/collate4.test +++ b/test/collate4.test @@ -473,7 +473,7 @@ do_test collate4-3.1 { INSERT INTO collate4t1 VALUES('abc'); INSERT INTO collate4t1 VALUES('ABC'); } -} {1 {column a is not unique}} +} {1 {UNIQUE constraint failed: collate4t1.a}} do_test collate4-3.2 { execsql { SELECT * FROM collate4t1; @@ -483,13 +483,13 @@ do_test collate4-3.3 { catchsql { INSERT INTO collate4t1 SELECT upper(a) FROM collate4t1; } -} {1 {column a is not unique}} +} {1 {UNIQUE constraint failed: collate4t1.a}} do_test collate4-3.4 { catchsql { INSERT INTO collate4t1 VALUES(1); UPDATE collate4t1 SET a = 'abc'; } -} {1 {column a is not unique}} +} {1 {UNIQUE constraint failed: collate4t1.a}} do_test collate4-3.5 { execsql { DROP TABLE collate4t1; @@ -501,7 +501,7 @@ do_test collate4-3.6 { INSERT INTO collate4t1 VALUES('abc'); INSERT INTO collate4t1 VALUES('ABC'); } -} {1 {column a is not unique}} +} {1 {UNIQUE constraint failed: collate4t1.a}} do_test collate4-3.7 { execsql { SELECT * FROM collate4t1; @@ -511,13 +511,13 @@ do_test collate4-3.8 { catchsql { INSERT INTO collate4t1 SELECT upper(a) FROM collate4t1; } -} {1 {column a is not unique}} +} {1 {UNIQUE constraint failed: collate4t1.a}} do_test collate4-3.9 { catchsql { INSERT INTO collate4t1 VALUES(1); UPDATE collate4t1 SET a = 'abc'; } -} {1 {column a is not unique}} +} {1 {UNIQUE constraint failed: collate4t1.a}} do_test collate4-3.10 { execsql { DROP TABLE collate4t1; @@ -530,7 +530,7 @@ do_test collate4-3.11 { INSERT INTO collate4t1 VALUES('abc'); INSERT INTO collate4t1 VALUES('ABC'); } -} {1 {column a is not unique}} +} {1 {UNIQUE constraint failed: collate4t1.a}} do_test collate4-3.12 { execsql { SELECT * FROM collate4t1; @@ -540,13 +540,13 @@ do_test collate4-3.13 { catchsql { INSERT INTO collate4t1 SELECT upper(a) FROM collate4t1; } -} {1 {column a is not unique}} +} {1 {UNIQUE constraint failed: collate4t1.a}} do_test collate4-3.14 { catchsql { INSERT INTO collate4t1 VALUES(1); UPDATE collate4t1 SET a = 'abc'; } -} {1 {column a is not unique}} +} {1 {UNIQUE constraint failed: collate4t1.a}} do_test collate4-3.15 { execsql { diff --git a/test/conflict.test b/test/conflict.test index 6576959607..af5668ed72 100644 --- a/test/conflict.test +++ b/test/conflict.test @@ -242,7 +242,7 @@ foreach {i conf1 cmd t0 t1 t2} { 15 {} {INSERT OR ABORT} 1 {} 1 16 {} {INSERT OR ROLLBACK} 1 {} {} } { - if {$t0} {set t1 {t1.c may not be NULL}} + if {$t0} {set t1 {NOT NULL constraint failed: t1.c}} do_test conflict-5.$i { if {$conf1!=""} {set conf1 "ON CONFLICT $conf1"} set r0 [catch {execsql [subst { @@ -306,7 +306,7 @@ foreach {i conf1 cmd t0 t1 t2 t3 t4} { 15 {} {UPDATE OR ABORT} 1 {1 2 3 4} 1 0 1 16 {} {UPDATE OR ROLLBACK} 1 {1 2 3 4} 0 0 0 } { - if {$t0} {set t1 {column a is not unique}} + if {$t0} {set t1 {UNIQUE constraint failed: t1.a}} if {[info exists TEMP_STORE] && $TEMP_STORE==3} { set t3 0 } else { @@ -493,13 +493,13 @@ do_test conflict-9.5 { INSERT INTO t2 VALUES(3,1,3,3,3); SELECT * FROM t2; } -} {1 {column b is not unique}} +} {1 {UNIQUE constraint failed: t2.b}} do_test conflict-9.6 { catchsql { UPDATE t2 SET b=b+1 WHERE b=1; SELECT * FROM t2; } -} {1 {column b is not unique}} +} {1 {UNIQUE constraint failed: t2.b}} do_test conflict-9.7 { catchsql { BEGIN; @@ -507,7 +507,7 @@ do_test conflict-9.7 { INSERT INTO t2 VALUES(3,1,3,3,3); SELECT * FROM t2; } -} {1 {column b is not unique}} +} {1 {UNIQUE constraint failed: t2.b}} do_test conflict-9.8 { execsql {COMMIT} execsql {SELECT * FROM t3} @@ -519,7 +519,7 @@ do_test conflict-9.9 { UPDATE t2 SET b=b+1 WHERE b=1; SELECT * FROM t2; } -} {1 {column b is not unique}} +} {1 {UNIQUE constraint failed: t2.b}} do_test conflict-9.10 { execsql {COMMIT} execsql {SELECT * FROM t3} @@ -529,13 +529,13 @@ do_test conflict-9.11 { INSERT INTO t2 VALUES(3,3,3,1,3); SELECT * FROM t2; } -} {1 {column d is not unique}} +} {1 {UNIQUE constraint failed: t2.d}} do_test conflict-9.12 { catchsql { UPDATE t2 SET d=d+1 WHERE d=1; SELECT * FROM t2; } -} {1 {column d is not unique}} +} {1 {UNIQUE constraint failed: t2.d}} do_test conflict-9.13 { catchsql { BEGIN; @@ -543,7 +543,7 @@ do_test conflict-9.13 { INSERT INTO t2 VALUES(3,3,3,1,3); SELECT * FROM t2; } -} {1 {column d is not unique}} +} {1 {UNIQUE constraint failed: t2.d}} do_test conflict-9.14 { execsql {COMMIT} execsql {SELECT * FROM t3} @@ -555,7 +555,7 @@ do_test conflict-9.15 { UPDATE t2 SET d=d+1 WHERE d=1; SELECT * FROM t2; } -} {1 {column d is not unique}} +} {1 {UNIQUE constraint failed: t2.d}} do_test conflict-9.16 { execsql {COMMIT} execsql {SELECT * FROM t3} @@ -565,13 +565,13 @@ do_test conflict-9.17 { INSERT INTO t2 VALUES(3,3,3,3,1); SELECT * FROM t2; } -} {1 {column e is not unique}} +} {1 {UNIQUE constraint failed: t2.e}} do_test conflict-9.18 { catchsql { UPDATE t2 SET e=e+1 WHERE e=1; SELECT * FROM t2; } -} {1 {column e is not unique}} +} {1 {UNIQUE constraint failed: t2.e}} do_test conflict-9.19 { catchsql { BEGIN; @@ -579,7 +579,7 @@ do_test conflict-9.19 { INSERT INTO t2 VALUES(3,3,3,3,1); SELECT * FROM t2; } -} {1 {column e is not unique}} +} {1 {UNIQUE constraint failed: t2.e}} verify_ex_errcode conflict-9.21b SQLITE_CONSTRAINT_UNIQUE do_test conflict-9.20 { catch {execsql {COMMIT}} @@ -592,7 +592,7 @@ do_test conflict-9.21 { UPDATE t2 SET e=e+1 WHERE e=1; SELECT * FROM t2; } -} {1 {column e is not unique}} +} {1 {UNIQUE constraint failed: t2.e}} verify_ex_errcode conflict-9.21b SQLITE_CONSTRAINT_UNIQUE do_test conflict-9.22 { catch {execsql {COMMIT}} @@ -782,7 +782,7 @@ do_test conflict-12.3 { catchsql { UPDATE t5 SET a=a+1 WHERE a=1; } -} {1 {PRIMARY KEY must be unique}} +} {1 {UNIQUE constraint failed: t5.a}} verify_ex_errcode conflict-12.3b SQLITE_CONSTRAINT_PRIMARYKEY do_test conflict-12.4 { execsql { @@ -790,6 +790,14 @@ do_test conflict-12.4 { SELECT * FROM t5; } } {2 one} +do_test conflict-12.5 { + catchsql { + CREATE TABLE t5b(x); + INSERT INTO t5b(rowid, x) VALUES(1,10),(2,11); + UPDATE t5b SET rowid=rowid+1 WHERE x=10; + } +} {1 {UNIQUE constraint failed: t5b.rowid}} +verify_ex_errcode conflict-12.5b SQLITE_CONSTRAINT_ROWID # Ticket [c38baa3d969eab7946dc50ba9d9b4f0057a19437] @@ -804,7 +812,7 @@ do_test conflict-13.1 { catchsql { REPLACE INTO t13 VALUES(2); } -} {1 {constraint failed}} +} {1 {CHECK constraint failed: t13}} verify_ex_errcode conflict-13.1b SQLITE_CONSTRAINT_CHECK do_test conflict-13.2 { execsql { diff --git a/test/conflict2.test b/test/conflict2.test new file mode 100644 index 0000000000..23fbf9da7c --- /dev/null +++ b/test/conflict2.test @@ -0,0 +1,850 @@ +# 2013-11-04 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# +# This file implements tests for the conflict resolution extension +# in WITHOUT ROWID tables +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +ifcapable !conflict { + finish_test + return +} + +# Create tables for the first group of tests. +# +do_test conflict2-1.0 { + execsql { + CREATE TABLE t1(a, b, c, PRIMARY KEY(a,b)) WITHOUT rowid; + CREATE TABLE t2(x); + SELECT c FROM t1 ORDER BY c; + } +} {} + +# Six columns of configuration data as follows: +# +# i The reference number of the test +# cmd An INSERT or REPLACE command to execute against table t1 +# t0 True if there is an error from $cmd +# t1 Content of "c" column of t1 assuming no error in $cmd +# t2 Content of "x" column of t2 +# t3 Number of temporary files created by this test +# +foreach {i cmd t0 t1 t2 t3} { + 1 INSERT 1 {} 1 0 + 2 {INSERT OR IGNORE} 0 3 1 0 + 3 {INSERT OR REPLACE} 0 4 1 0 + 4 REPLACE 0 4 1 0 + 5 {INSERT OR FAIL} 1 {} 1 0 + 6 {INSERT OR ABORT} 1 {} 1 0 + 7 {INSERT OR ROLLBACK} 1 {} {} 0 +} { + do_test conflict2-1.$i { + set ::sqlite_opentemp_count 0 + set r0 [catch {execsql [subst { + DELETE FROM t1; + DELETE FROM t2; + INSERT INTO t1 VALUES(1,2,3); + BEGIN; + INSERT INTO t2 VALUES(1); + $cmd INTO t1 VALUES(1,2,4); + }]} r1] + catch {execsql {COMMIT}} + if {$r0} {set r1 {}} {set r1 [execsql {SELECT c FROM t1}]} + set r2 [execsql {SELECT x FROM t2}] + set r3 $::sqlite_opentemp_count + list $r0 $r1 $r2 $r3 + } [list $t0 $t1 $t2 $t3] +} + +# Create tables for the first group of tests. +# +do_test conflict2-2.0 { + execsql { + DROP TABLE t1; + DROP TABLE t2; + CREATE TABLE t1(a INTEGER PRIMARY KEY, b, c, UNIQUE(a,b)) WITHOUT rowid; + CREATE TABLE t2(x); + SELECT c FROM t1 ORDER BY c; + } +} {} + +# Six columns of configuration data as follows: +# +# i The reference number of the test +# cmd An INSERT or REPLACE command to execute against table t1 +# t0 True if there is an error from $cmd +# t1 Content of "c" column of t1 assuming no error in $cmd +# t2 Content of "x" column of t2 +# +foreach {i cmd t0 t1 t2} { + 1 INSERT 1 {} 1 + 2 {INSERT OR IGNORE} 0 3 1 + 3 {INSERT OR REPLACE} 0 4 1 + 4 REPLACE 0 4 1 + 5 {INSERT OR FAIL} 1 {} 1 + 6 {INSERT OR ABORT} 1 {} 1 + 7 {INSERT OR ROLLBACK} 1 {} {} +} { + do_test conflict2-2.$i { + set r0 [catch {execsql [subst { + DELETE FROM t1; + DELETE FROM t2; + INSERT INTO t1 VALUES(1,2,3); + BEGIN; + INSERT INTO t2 VALUES(1); + $cmd INTO t1 VALUES(1,2,4); + }]} r1] + catch {execsql {COMMIT}} + if {$r0} {set r1 {}} {set r1 [execsql {SELECT c FROM t1}]} + set r2 [execsql {SELECT x FROM t2}] + list $r0 $r1 $r2 + } [list $t0 $t1 $t2] +} + +# Create tables for the first group of tests. +# +do_test conflict2-3.0 { + execsql { + DROP TABLE t1; + DROP TABLE t2; + CREATE TABLE t1(a, b, c INTEGER, PRIMARY KEY(c), UNIQUE(a,b)) WITHOUT rowid; + CREATE TABLE t2(x); + SELECT c FROM t1 ORDER BY c; + } +} {} + +# Six columns of configuration data as follows: +# +# i The reference number of the test +# cmd An INSERT or REPLACE command to execute against table t1 +# t0 True if there is an error from $cmd +# t1 Content of "c" column of t1 assuming no error in $cmd +# t2 Content of "x" column of t2 +# +foreach {i cmd t0 t1 t2} { + 1 INSERT 1 {} 1 + 2 {INSERT OR IGNORE} 0 3 1 + 3 {INSERT OR REPLACE} 0 4 1 + 4 REPLACE 0 4 1 + 5 {INSERT OR FAIL} 1 {} 1 + 6 {INSERT OR ABORT} 1 {} 1 + 7 {INSERT OR ROLLBACK} 1 {} {} +} { + do_test conflict2-3.$i { + set r0 [catch {execsql [subst { + DELETE FROM t1; + DELETE FROM t2; + INSERT INTO t1 VALUES(1,2,3); + BEGIN; + INSERT INTO t2 VALUES(1); + $cmd INTO t1 VALUES(1,2,4); + }]} r1] + catch {execsql {COMMIT}} + if {$r0} {set r1 {}} {set r1 [execsql {SELECT c FROM t1}]} + set r2 [execsql {SELECT x FROM t2}] + list $r0 $r1 $r2 + } [list $t0 $t1 $t2] +} + +do_test conflict2-4.0 { + execsql { + DROP TABLE t2; + CREATE TABLE t2(x); + SELECT x FROM t2; + } +} {} + +# Six columns of configuration data as follows: +# +# i The reference number of the test +# conf1 The conflict resolution algorithm on the UNIQUE constraint +# cmd An INSERT or REPLACE command to execute against table t1 +# t0 True if there is an error from $cmd +# t1 Content of "c" column of t1 assuming no error in $cmd +# t2 Content of "x" column of t2 +# +foreach {i conf1 cmd t0 t1 t2} { + 1 {} INSERT 1 {} 1 + 2 REPLACE INSERT 0 4 1 + 3 IGNORE INSERT 0 3 1 + 4 FAIL INSERT 1 {} 1 + 5 ABORT INSERT 1 {} 1 + 6 ROLLBACK INSERT 1 {} {} + 7 REPLACE {INSERT OR IGNORE} 0 3 1 + 8 IGNORE {INSERT OR REPLACE} 0 4 1 + 9 FAIL {INSERT OR IGNORE} 0 3 1 + 10 ABORT {INSERT OR REPLACE} 0 4 1 + 11 ROLLBACK {INSERT OR IGNORE } 0 3 1 +} { + do_test conflict2-4.$i { + if {$conf1!=""} {set conf1 "ON CONFLICT $conf1"} + set r0 [catch {execsql [subst { + DROP TABLE t1; + CREATE TABLE t1(a,b,c,PRIMARY KEY(a,b) $conf1) WITHOUT rowid; + DELETE FROM t2; + INSERT INTO t1 VALUES(1,2,3); + BEGIN; + INSERT INTO t2 VALUES(1); + $cmd INTO t1 VALUES(1,2,4); + }]} r1] + catch {execsql {COMMIT}} + if {$r0} {set r1 {}} {set r1 [execsql {SELECT c FROM t1}]} + set r2 [execsql {SELECT x FROM t2}] + list $r0 $r1 $r2 + } [list $t0 $t1 $t2] +} + +do_test conflict2-5.0 { + execsql { + DROP TABLE t2; + CREATE TABLE t2(x); + SELECT x FROM t2; + } +} {} + +# Six columns of configuration data as follows: +# +# i The reference number of the test +# conf1 The conflict resolution algorithm on the NOT NULL constraint +# cmd An INSERT or REPLACE command to execute against table t1 +# t0 True if there is an error from $cmd +# t1 Content of "c" column of t1 assuming no error in $cmd +# t2 Content of "x" column of t2 +# +foreach {i conf1 cmd t0 t1 t2} { + 1 {} INSERT 1 {} 1 + 2 REPLACE INSERT 0 5 1 + 3 IGNORE INSERT 0 {} 1 + 4 FAIL INSERT 1 {} 1 + 5 ABORT INSERT 1 {} 1 + 6 ROLLBACK INSERT 1 {} {} + 7 REPLACE {INSERT OR IGNORE} 0 {} 1 + 8 IGNORE {INSERT OR REPLACE} 0 5 1 + 9 FAIL {INSERT OR IGNORE} 0 {} 1 + 10 ABORT {INSERT OR REPLACE} 0 5 1 + 11 ROLLBACK {INSERT OR IGNORE} 0 {} 1 + 12 {} {INSERT OR IGNORE} 0 {} 1 + 13 {} {INSERT OR REPLACE} 0 5 1 + 14 {} {INSERT OR FAIL} 1 {} 1 + 15 {} {INSERT OR ABORT} 1 {} 1 + 16 {} {INSERT OR ROLLBACK} 1 {} {} +} { + if {$t0} {set t1 {NOT NULL constraint failed: t1.c}} + do_test conflict2-5.$i { + if {$conf1!=""} {set conf1 "ON CONFLICT $conf1"} + set r0 [catch {execsql [subst { + DROP TABLE t1; + CREATE TABLE t1(a,b,c NOT NULL $conf1 DEFAULT 5); + DELETE FROM t2; + BEGIN; + INSERT INTO t2 VALUES(1); + $cmd INTO t1 VALUES(1,2,NULL); + }]} r1] + catch {execsql {COMMIT}} + if {!$r0} {set r1 [execsql {SELECT c FROM t1}]} + set r2 [execsql {SELECT x FROM t2}] + list $r0 $r1 $r2 + } [list $t0 $t1 $t2] +} + +do_test conflict2-6.0 { + execsql { + DROP TABLE t2; + CREATE TABLE t2(a,b,c); + INSERT INTO t2 VALUES(1,2,1); + INSERT INTO t2 VALUES(2,3,2); + INSERT INTO t2 VALUES(3,4,1); + INSERT INTO t2 VALUES(4,5,4); + SELECT c FROM t2 ORDER BY b; + CREATE TABLE t3(x); + INSERT INTO t3 VALUES(1); + } +} {1 2 1 4} + +# Six columns of configuration data as follows: +# +# i The reference number of the test +# conf1 The conflict resolution algorithm on the UNIQUE constraint +# cmd An UPDATE command to execute against table t1 +# t0 True if there is an error from $cmd +# t1 Content of "b" column of t1 assuming no error in $cmd +# t2 Content of "x" column of t3 +# t3 Number of temporary files for tables +# t4 Number of temporary files for statement journals +# +# Update: Since temporary table files are now opened lazily, and none +# of the following tests use large quantities of data, t3 is always 0. +# +foreach {i conf1 cmd t0 t1 t2 t3 t4} { + 1 {} UPDATE 1 {6 7 8 9} 1 0 1 + 2 REPLACE UPDATE 0 {7 6 9} 1 0 0 + 3 IGNORE UPDATE 0 {6 7 3 9} 1 0 0 + 4 FAIL UPDATE 1 {6 7 3 4} 1 0 0 + 5 ABORT UPDATE 1 {1 2 3 4} 1 0 1 + 6 ROLLBACK UPDATE 1 {1 2 3 4} 0 0 0 + 7 REPLACE {UPDATE OR IGNORE} 0 {6 7 3 9} 1 0 0 + 8 IGNORE {UPDATE OR REPLACE} 0 {7 6 9} 1 0 1 + 9 FAIL {UPDATE OR IGNORE} 0 {6 7 3 9} 1 0 0 + 10 ABORT {UPDATE OR REPLACE} 0 {7 6 9} 1 0 1 + 11 ROLLBACK {UPDATE OR IGNORE} 0 {6 7 3 9} 1 0 0 + 12 {} {UPDATE OR IGNORE} 0 {6 7 3 9} 1 0 0 + 13 {} {UPDATE OR REPLACE} 0 {7 6 9} 1 0 1 + 14 {} {UPDATE OR FAIL} 1 {6 7 3 4} 1 0 0 + 15 {} {UPDATE OR ABORT} 1 {1 2 3 4} 1 0 1 + 16 {} {UPDATE OR ROLLBACK} 1 {1 2 3 4} 0 0 0 +} { + if {$t0} {set t1 {UNIQUE constraint failed: t1.a}} + if {[info exists TEMP_STORE] && $TEMP_STORE==3} { + set t3 0 + } else { + set t3 [expr {$t3+$t4}] + } + do_test conflict2-6.$i { + db close + sqlite3 db test.db + if {$conf1!=""} {set conf1 "ON CONFLICT $conf1"} + execsql {pragma temp_store=file} + set ::sqlite_opentemp_count 0 + set r0 [catch {execsql [subst { + DROP TABLE t1; + CREATE TABLE t1(a,b,c, PRIMARY KEY(a) $conf1) WITHOUT rowid; + INSERT INTO t1 SELECT * FROM t2; + UPDATE t3 SET x=0; + BEGIN; + $cmd t3 SET x=1; + $cmd t1 SET b=b*2; + $cmd t1 SET a=c+5; + }]} r1] + catch {execsql {COMMIT}} + if {!$r0} {set r1 [execsql {SELECT a FROM t1 ORDER BY b}]} + set r2 [execsql {SELECT x FROM t3}] + list $r0 $r1 $r2 $::sqlite_opentemp_count + } [list $t0 $t1 $t2 $t3] +} + +# Test to make sure a lot of IGNOREs don't cause a stack overflow +# +do_test conflict2-7.1 { + execsql { + DROP TABLE t1; + DROP TABLE t2; + DROP TABLE t3; + CREATE TABLE t1(a PRIMARY KEY, b) without rowid; + } + for {set i 1} {$i<=50} {incr i} { + execsql "INSERT into t1 values($i,[expr {$i+1}]);" + } + execsql { + SELECT count(*), min(a), max(b) FROM t1; + } +} {50 1 51} +do_test conflict2-7.2 { + execsql { + PRAGMA count_changes=on; + UPDATE OR IGNORE t1 SET a=1000; + } +} {1} +do_test conflict2-7.2.1 { + db changes +} {1} +do_test conflict2-7.3 { + execsql { + SELECT b FROM t1 WHERE a=1000; + } +} {2} +do_test conflict2-7.4 { + execsql { + SELECT count(*) FROM t1; + } +} {50} +do_test conflict2-7.5 { + execsql { + PRAGMA count_changes=on; + UPDATE OR REPLACE t1 SET a=1001; + } +} {50} +do_test conflict2-7.5.1 { + db changes +} {50} +do_test conflict2-7.7 { + execsql { + SELECT count(*) FROM t1; + } +} {1} + +# Update for version 3: A SELECT statement no longer resets the change +# counter (Test result changes from 0 to 50). +do_test conflict2-7.7.1 { + db changes +} {50} + +# Make sure the row count is right for rows that are ignored on +# an insert. +# +do_test conflict2-8.1 { + execsql { + DELETE FROM t1; + INSERT INTO t1 VALUES(1,2); + } + execsql { + INSERT OR IGNORE INTO t1 VALUES(2,3); + } +} {1} +do_test conflict2-8.1.1 { + db changes +} {1} +do_test conflict2-8.2 { + execsql { + INSERT OR IGNORE INTO t1 VALUES(2,4); + } +} {0} +do_test conflict2-8.2.1 { + db changes +} {0} +do_test conflict2-8.3 { + execsql { + INSERT OR REPLACE INTO t1 VALUES(2,4); + } +} {1} +do_test conflict2-8.3.1 { + db changes +} {1} +do_test conflict2-8.4 { + execsql { + INSERT OR IGNORE INTO t1 SELECT * FROM t1; + } +} {0} +do_test conflict2-8.4.1 { + db changes +} {0} +do_test conflict2-8.5 { + execsql { + INSERT OR IGNORE INTO t1 SELECT a+2,b+2 FROM t1; + } +} {2} +do_test conflict2-8.5.1 { + db changes +} {2} +do_test conflict2-8.6 { + execsql { + INSERT OR IGNORE INTO t1 SELECT a+3,b+3 FROM t1; + } +} {3} +do_test conflict2-8.6.1 { + db changes +} {3} + +integrity_check conflict2-8.99 + +do_test conflict2-9.1 { + execsql { + PRAGMA count_changes=0; + CREATE TABLE t2( + a INTEGER PRIMARY KEY ON CONFLICT IGNORE, + b INTEGER UNIQUE ON CONFLICT FAIL, + c INTEGER UNIQUE ON CONFLICT REPLACE, + d INTEGER UNIQUE ON CONFLICT ABORT, + e INTEGER UNIQUE ON CONFLICT ROLLBACK + ) WITHOUT rowid; + CREATE TABLE t3(x); + INSERT INTO t3 VALUES(1); + SELECT * FROM t3; + } +} {1} +do_test conflict2-9.2 { + catchsql { + INSERT INTO t2 VALUES(1,1,1,1,1); + INSERT INTO t2 VALUES(2,2,2,2,2); + SELECT * FROM t2; + } +} {0 {1 1 1 1 1 2 2 2 2 2}} +do_test conflict2-9.3 { + catchsql { + INSERT INTO t2 VALUES(1,3,3,3,3); + SELECT * FROM t2; + } +} {0 {1 1 1 1 1 2 2 2 2 2}} +do_test conflict2-9.4 { + catchsql { + UPDATE t2 SET a=a+1 WHERE a=1; + SELECT * FROM t2; + } +} {0 {1 1 1 1 1 2 2 2 2 2}} +do_test conflict2-9.5 { + catchsql { + INSERT INTO t2 VALUES(3,1,3,3,3); + } +} {1 {UNIQUE constraint failed: t2.b}} +do_test conflict2-9.5b { + db eval {SELECT * FROM t2;} +} {1 1 1 1 1 2 2 2 2 2} +do_test conflict2-9.6 { + catchsql { + UPDATE t2 SET b=b+1 WHERE b=1; + SELECT * FROM t2; + } +} {1 {UNIQUE constraint failed: t2.b}} +do_test conflict2-9.6b { + db eval {SELECT * FROM t2;} +} {1 1 1 1 1 2 2 2 2 2} +do_test conflict2-9.7 { + catchsql { + BEGIN; + UPDATE t3 SET x=x+1; + INSERT INTO t2 VALUES(3,1,3,3,3); + SELECT * FROM t2; + } +} {1 {UNIQUE constraint failed: t2.b}} +do_test conflict2-9.8 { + execsql {COMMIT} + execsql {SELECT * FROM t3} +} {2} +do_test conflict2-9.9 { + catchsql { + BEGIN; + UPDATE t3 SET x=x+1; + UPDATE t2 SET b=b+1 WHERE b=1; + SELECT * FROM t2; + } +} {1 {UNIQUE constraint failed: t2.b}} +do_test conflict2-9.10 { + execsql {COMMIT} + execsql {SELECT * FROM t3} +} {3} +do_test conflict2-9.11 { + catchsql { + INSERT INTO t2 VALUES(3,3,3,1,3); + SELECT * FROM t2; + } +} {1 {UNIQUE constraint failed: t2.d}} +do_test conflict2-9.12 { + catchsql { + UPDATE t2 SET d=d+1 WHERE d=1; + SELECT * FROM t2; + } +} {1 {UNIQUE constraint failed: t2.d}} +do_test conflict2-9.13 { + catchsql { + BEGIN; + UPDATE t3 SET x=x+1; + INSERT INTO t2 VALUES(3,3,3,1,3); + SELECT * FROM t2; + } +} {1 {UNIQUE constraint failed: t2.d}} +do_test conflict2-9.14 { + execsql {COMMIT} + execsql {SELECT * FROM t3} +} {4} +do_test conflict2-9.15 { + catchsql { + BEGIN; + UPDATE t3 SET x=x+1; + UPDATE t2 SET d=d+1 WHERE d=1; + SELECT * FROM t2; + } +} {1 {UNIQUE constraint failed: t2.d}} +do_test conflict2-9.16 { + execsql {COMMIT} + execsql {SELECT * FROM t3} +} {5} +do_test conflict2-9.17 { + catchsql { + INSERT INTO t2 VALUES(3,3,3,3,1); + SELECT * FROM t2; + } +} {1 {UNIQUE constraint failed: t2.e}} +do_test conflict2-9.18 { + catchsql { + UPDATE t2 SET e=e+1 WHERE e=1; + SELECT * FROM t2; + } +} {1 {UNIQUE constraint failed: t2.e}} +do_test conflict2-9.19 { + catchsql { + BEGIN; + UPDATE t3 SET x=x+1; + INSERT INTO t2 VALUES(3,3,3,3,1); + SELECT * FROM t2; + } +} {1 {UNIQUE constraint failed: t2.e}} +verify_ex_errcode conflict2-9.21b SQLITE_CONSTRAINT_UNIQUE +do_test conflict2-9.20 { + catch {execsql {COMMIT}} + execsql {SELECT * FROM t3} +} {5} +do_test conflict2-9.21 { + catchsql { + BEGIN; + UPDATE t3 SET x=x+1; + UPDATE t2 SET e=e+1 WHERE e=1; + SELECT * FROM t2; + } +} {1 {UNIQUE constraint failed: t2.e}} +verify_ex_errcode conflict2-9.21b SQLITE_CONSTRAINT_UNIQUE +do_test conflict2-9.22 { + catch {execsql {COMMIT}} + execsql {SELECT * FROM t3} +} {5} +do_test conflict2-9.23 { + catchsql { + INSERT INTO t2 VALUES(3,3,1,3,3); + SELECT * FROM t2; + } +} {0 {2 2 2 2 2 3 3 1 3 3}} +do_test conflict2-9.24 { + catchsql { + UPDATE t2 SET c=c-1 WHERE c=2; + SELECT * FROM t2; + } +} {0 {2 2 1 2 2}} +do_test conflict2-9.25 { + catchsql { + BEGIN; + UPDATE t3 SET x=x+1; + INSERT INTO t2 VALUES(3,3,1,3,3); + SELECT * FROM t2; + } +} {0 {3 3 1 3 3}} +do_test conflict2-9.26 { + catch {execsql {COMMIT}} + execsql {SELECT * FROM t3} +} {6} + +do_test conflict2-10.1 { + catchsql { + DELETE FROM t1; + BEGIN; + INSERT OR ROLLBACK INTO t1 VALUES(1,2); + INSERT OR ROLLBACK INTO t1 VALUES(1,3); + COMMIT; + } + execsql {SELECT * FROM t1} +} {} +do_test conflict2-10.2 { + catchsql { + CREATE TABLE t4(x); + CREATE UNIQUE INDEX t4x ON t4(x); + BEGIN; + INSERT OR ROLLBACK INTO t4 VALUES(1); + INSERT OR ROLLBACK INTO t4 VALUES(1); + COMMIT; + } + execsql {SELECT * FROM t4} +} {} + +# Ticket #1171. Make sure statement rollbacks do not +# damage the database. +# +do_test conflict2-11.1 { + execsql { + -- Create a database object (pages 2, 3 of the file) + BEGIN; + CREATE TABLE abc(a PRIMARY KEY, b, c) WITHOUT rowid; + INSERT INTO abc VALUES(1, 2, 3); + INSERT INTO abc VALUES(4, 5, 6); + INSERT INTO abc VALUES(7, 8, 9); + COMMIT; + } + + + # Set a small cache size so that changes will spill into + # the database file. + execsql { + PRAGMA cache_size = 10; + } + + # Make lots of changes. Because of the small cache, some + # (most?) of these changes will spill into the disk file. + # In other words, some of the changes will not be held in + # cache. + # + execsql { + BEGIN; + -- Make sure the pager is in EXCLUSIVE state. + CREATE TABLE def(d, e, f); + INSERT INTO def VALUES + ('xxxxxxxxxxxxxxx', 'yyyyyyyyyyyyyyyy', 'zzzzzzzzzzzzzzzz'); + INSERT INTO def SELECT * FROM def; + INSERT INTO def SELECT * FROM def; + INSERT INTO def SELECT * FROM def; + INSERT INTO def SELECT * FROM def; + INSERT INTO def SELECT * FROM def; + INSERT INTO def SELECT * FROM def; + INSERT INTO def SELECT * FROM def; + DELETE FROM abc WHERE a = 4; + } + + # Execute a statement that does a statement rollback due to + # a constraint failure. + # + catchsql { + INSERT INTO abc SELECT 10, 20, 30 FROM def; + } + + # Rollback the database. Verify that the state of the ABC table + # is unchanged from the beginning of the transaction. In other words, + # make sure the DELETE on table ABC that occurred within the transaction + # had no effect. + # + execsql { + ROLLBACK; + SELECT * FROM abc; + } +} {1 2 3 4 5 6 7 8 9} +integrity_check conflict2-11.2 + +# Repeat test conflict2-11.1 but this time commit. +# +do_test conflict2-11.3 { + execsql { + BEGIN; + -- Make sure the pager is in EXCLUSIVE state. + UPDATE abc SET a=a+1; + CREATE TABLE def(d, e, f); + INSERT INTO def VALUES + ('xxxxxxxxxxxxxxx', 'yyyyyyyyyyyyyyyy', 'zzzzzzzzzzzzzzzz'); + INSERT INTO def SELECT * FROM def; + INSERT INTO def SELECT * FROM def; + INSERT INTO def SELECT * FROM def; + INSERT INTO def SELECT * FROM def; + INSERT INTO def SELECT * FROM def; + INSERT INTO def SELECT * FROM def; + INSERT INTO def SELECT * FROM def; + DELETE FROM abc WHERE a = 4; + } + catchsql { + INSERT INTO abc SELECT 10, 20, 30 FROM def; + } + execsql { + ROLLBACK; + SELECT * FROM abc; + } +} {1 2 3 4 5 6 7 8 9} +# Repeat test conflict2-11.1 but this time commit. +# +do_test conflict2-11.5 { + execsql { + BEGIN; + -- Make sure the pager is in EXCLUSIVE state. + CREATE TABLE def(d, e, f); + INSERT INTO def VALUES + ('xxxxxxxxxxxxxxx', 'yyyyyyyyyyyyyyyy', 'zzzzzzzzzzzzzzzz'); + INSERT INTO def SELECT * FROM def; + INSERT INTO def SELECT * FROM def; + INSERT INTO def SELECT * FROM def; + INSERT INTO def SELECT * FROM def; + INSERT INTO def SELECT * FROM def; + INSERT INTO def SELECT * FROM def; + INSERT INTO def SELECT * FROM def; + DELETE FROM abc WHERE a = 4; + } + catchsql { + INSERT INTO abc SELECT 10, 20, 30 FROM def; + } + execsql { + COMMIT; + SELECT * FROM abc; + } +} {1 2 3 7 8 9} +integrity_check conflict2-11.6 + +# Make sure UPDATE OR REPLACE works on tables that have only +# an INTEGER PRIMARY KEY. +# +do_test conflict2-12.1 { + execsql { + CREATE TABLE t5(a INTEGER PRIMARY KEY, b text) WITHOUT rowid; + INSERT INTO t5 VALUES(1,'one'); + INSERT INTO t5 VALUES(2,'two'); + SELECT * FROM t5 + } +} {1 one 2 two} +do_test conflict2-12.2 { + execsql { + UPDATE OR IGNORE t5 SET a=a+1 WHERE a=1; + SELECT * FROM t5; + } +} {1 one 2 two} +do_test conflict2-12.3 { + catchsql { + UPDATE t5 SET a=a+1 WHERE a=1; + } +} {1 {UNIQUE constraint failed: t5.a}} +verify_ex_errcode conflict2-12.3b SQLITE_CONSTRAINT_PRIMARYKEY +do_test conflict2-12.4 { + execsql { + UPDATE OR REPLACE t5 SET a=a+1 WHERE a=1; + SELECT * FROM t5; + } +} {2 one} + + +# Ticket [c38baa3d969eab7946dc50ba9d9b4f0057a19437] +# REPLACE works like ABORT on a CHECK constraint. +# +do_test conflict2-13.1 { + execsql { + CREATE TABLE t13(a PRIMARY KEY CHECK(a!=2)) WITHOUT rowid; + BEGIN; + REPLACE INTO t13 VALUES(1); + } + catchsql { + REPLACE INTO t13 VALUES(2); + } +} {1 {CHECK constraint failed: t13}} +verify_ex_errcode conflict2-13.1b SQLITE_CONSTRAINT_CHECK +do_test conflict2-13.2 { + execsql { + REPLACE INTO t13 VALUES(3); + COMMIT; + SELECT * FROM t13; + } +} {1 3} + +# Test for an unreleased bug in the REPLACE conflict resolution +# discovered on 2013-11-09. +# +do_execsql_test conflict2-14.1 { + DROP TABLE IF EXISTS t1; + CREATE TABLE t1( + x TEXT PRIMARY KEY NOT NULL, + y TEXT NOT NULL, + z INTEGER + ); + INSERT INTO t1 VALUES('alpha','beta',1); + CREATE UNIQUE INDEX t1xy ON t1(x,y); + REPLACE INTO t1(x,y,z) VALUES('alpha','gamma',1); + PRAGMA integrity_check; + SELECT x,y FROM t1 INDEXED BY t1xy; + SELECT x,y,z FROM t1 NOT INDEXED; +} {ok alpha gamma alpha gamma 1} +do_execsql_test conflict2-14.2 { + DROP TABLE IF EXISTS t1; + CREATE TABLE t1( + x TEXT PRIMARY KEY NOT NULL, + y TEXT NOT NULL, + z INTEGER + ) WITHOUT ROWID; + INSERT INTO t1 VALUES('alpha','beta',1); + CREATE UNIQUE INDEX t1xy ON t1(x,y); + REPLACE INTO t1(x,y,z) VALUES('alpha','gamma',1); + PRAGMA integrity_check; + SELECT x,y FROM t1 INDEXED BY t1xy; + SELECT x,y,z FROM t1 NOT INDEXED; +} {ok alpha gamma alpha gamma 1} + + + +finish_test diff --git a/test/conflict3.test b/test/conflict3.test new file mode 100644 index 0000000000..b51a55ee71 --- /dev/null +++ b/test/conflict3.test @@ -0,0 +1,356 @@ +# 2013-11-05 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# +# This file implements tests for the conflict resolution extension +# to SQLite. +# +# This file focuses on making sure that combinations of REPLACE, +# IGNORE, and FAIL conflict resolution play well together. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +ifcapable !conflict { + finish_test + return +} + +do_execsql_test conflict-1.1 { + CREATE TABLE t1( + a INTEGER PRIMARY KEY ON CONFLICT REPLACE, + b UNIQUE ON CONFLICT IGNORE, + c UNIQUE ON CONFLICT FAIL + ); + INSERT INTO t1(a,b,c) VALUES(1,2,3), (2,3,4); + SELECT a,b,c FROM t1 ORDER BY a; +} {1 2 3 2 3 4} + +# Insert a row that conflicts on column B. The insert should be ignored. +# +do_execsql_test conflict-1.2 { + INSERT INTO t1(a,b,c) VALUES(3,2,5); + SELECT a,b,c FROM t1 ORDER BY a; +} {1 2 3 2 3 4} + +# Insert two rows where the second conflicts on C. The first row show go +# and and then there should be a constraint error. +# +do_test conflict-1.3 { + catchsql {INSERT INTO t1(a,b,c) VALUES(4,5,6), (5,6,4);} +} {1 {UNIQUE constraint failed: t1.c}} +do_execsql_test conflict-1.4 { + SELECT a,b,c FROM t1 ORDER BY a; +} {1 2 3 2 3 4 4 5 6} + +# Replete the tests above, but this time on a table non-INTEGER primary key. +# +do_execsql_test conflict-2.1 { + DROP TABLE t1; + CREATE TABLE t1( + a INT PRIMARY KEY ON CONFLICT REPLACE, + b UNIQUE ON CONFLICT IGNORE, + c UNIQUE ON CONFLICT FAIL + ); + INSERT INTO t1(a,b,c) VALUES(1,2,3), (2,3,4); + SELECT a,b,c FROM t1 ORDER BY a; +} {1 2 3 2 3 4} + +# Insert a row that conflicts on column B. The insert should be ignored. +# +do_execsql_test conflict-2.2 { + INSERT INTO t1(a,b,c) VALUES(3,2,5); + SELECT a,b,c FROM t1 ORDER BY a; +} {1 2 3 2 3 4} + +# Insert two rows where the second conflicts on C. The first row show go +# and and then there should be a constraint error. +# +do_test conflict-2.3 { + catchsql {INSERT INTO t1(a,b,c) VALUES(4,5,6), (5,6,4);} +} {1 {UNIQUE constraint failed: t1.c}} +do_execsql_test conflict-2.4 { + SELECT a,b,c FROM t1 ORDER BY a; +} {1 2 3 2 3 4 4 5 6} + +# Replete again on a WITHOUT ROWID table. +# +do_execsql_test conflict-3.1 { + DROP TABLE t1; + CREATE TABLE t1( + a INT PRIMARY KEY ON CONFLICT REPLACE, + b UNIQUE ON CONFLICT IGNORE, + c UNIQUE ON CONFLICT FAIL + ) WITHOUT ROWID; + INSERT INTO t1(a,b,c) VALUES(1,2,3), (2,3,4); + SELECT a,b,c FROM t1 ORDER BY a; +} {1 2 3 2 3 4} + +# Insert a row that conflicts on column B. The insert should be ignored. +# +do_execsql_test conflict-3.2 { + INSERT INTO t1(a,b,c) VALUES(3,2,5); + SELECT a,b,c FROM t1 ORDER BY a; +} {1 2 3 2 3 4} + +# Insert two rows where the second conflicts on C. The first row show go +# and and then there should be a constraint error. +# +do_test conflict-3.3 { + catchsql {INSERT INTO t1(a,b,c) VALUES(4,5,6), (5,6,4);} +} {1 {UNIQUE constraint failed: t1.c}} +do_execsql_test conflict-3.4 { + SELECT a,b,c FROM t1 ORDER BY a; +} {1 2 3 2 3 4 4 5 6} + +# Arrange the table rows in a different order and repeat. +# +do_execsql_test conflict-4.1 { + DROP TABLE t1; + CREATE TABLE t1( + b UNIQUE ON CONFLICT IGNORE, + c UNIQUE ON CONFLICT FAIL, + a INT PRIMARY KEY ON CONFLICT REPLACE + ) WITHOUT ROWID; + INSERT INTO t1(a,b,c) VALUES(1,2,3), (2,3,4); + SELECT a,b,c FROM t1 ORDER BY a; +} {1 2 3 2 3 4} + +# Insert a row that conflicts on column B. The insert should be ignored. +# +do_execsql_test conflict-4.2 { + INSERT INTO t1(a,b,c) VALUES(3,2,5); + SELECT a,b,c FROM t1 ORDER BY a; +} {1 2 3 2 3 4} + +# Insert two rows where the second conflicts on C. The first row show go +# and and then there should be a constraint error. +# +do_test conflict-4.3 { + catchsql {INSERT INTO t1(a,b,c) VALUES(4,5,6), (5,6,4);} +} {1 {UNIQUE constraint failed: t1.c}} +do_execsql_test conflict-4.4 { + SELECT a,b,c FROM t1 ORDER BY a; +} {1 2 3 2 3 4 4 5 6} + +# Arrange the table rows in a different order and repeat. +# +do_execsql_test conflict-5.1 { + DROP TABLE t1; + CREATE TABLE t1( + b UNIQUE ON CONFLICT IGNORE, + a INT PRIMARY KEY ON CONFLICT REPLACE, + c UNIQUE ON CONFLICT FAIL + ); + INSERT INTO t1(a,b,c) VALUES(1,2,3), (2,3,4); + SELECT a,b,c FROM t1 ORDER BY a; +} {1 2 3 2 3 4} + +# Insert a row that conflicts on column B. The insert should be ignored. +# +do_execsql_test conflict-5.2 { + INSERT INTO t1(a,b,c) VALUES(3,2,5); + SELECT a,b,c FROM t1 ORDER BY a; +} {1 2 3 2 3 4} + +# Insert two rows where the second conflicts on C. The first row show go +# and and then there should be a constraint error. +# +do_test conflict-5.3 { + catchsql {INSERT INTO t1(a,b,c) VALUES(4,5,6), (5,6,4);} +} {1 {UNIQUE constraint failed: t1.c}} +do_execsql_test conflict-5.4 { + SELECT a,b,c FROM t1 ORDER BY a; +} {1 2 3 2 3 4 4 5 6} + +# Arrange the table rows in a different order and repeat. +# +do_execsql_test conflict-6.1 { + DROP TABLE t1; + CREATE TABLE t1( + c UNIQUE ON CONFLICT FAIL, + a INT PRIMARY KEY ON CONFLICT REPLACE, + b UNIQUE ON CONFLICT IGNORE + ); + INSERT INTO t1(a,b,c) VALUES(1,2,3), (2,3,4); + SELECT a,b,c FROM t1 ORDER BY a; +} {1 2 3 2 3 4} + +# Insert a row that conflicts on column B. The insert should be ignored. +# +do_execsql_test conflict-6.2 { + INSERT INTO t1(a,b,c) VALUES(3,2,5); + SELECT a,b,c FROM t1 ORDER BY a; +} {1 2 3 2 3 4} + +# Insert two rows where the second conflicts on C. The first row show go +# and and then there should be a constraint error. +# +do_test conflict-6.3 { + catchsql {INSERT INTO t1(a,b,c) VALUES(4,5,6), (5,6,4);} +} {1 {UNIQUE constraint failed: t1.c}} +do_execsql_test conflict-6.4 { + SELECT a,b,c FROM t1 ORDER BY a; +} {1 2 3 2 3 4 4 5 6} + +# Change which column is the PRIMARY KEY +# +do_execsql_test conflict-7.1 { + DROP TABLE t1; + CREATE TABLE t1( + a UNIQUE ON CONFLICT REPLACE, + b INTEGER PRIMARY KEY ON CONFLICT IGNORE, + c UNIQUE ON CONFLICT FAIL + ); + INSERT INTO t1(a,b,c) VALUES(1,2,3), (2,3,4); + SELECT a,b,c FROM t1 ORDER BY a; +} {1 2 3 2 3 4} + +# Insert a row that conflicts on column B. The insert should be ignored. +# +do_execsql_test conflict-7.2 { + INSERT INTO t1(a,b,c) VALUES(3,2,5); + SELECT a,b,c FROM t1 ORDER BY a; +} {1 2 3 2 3 4} + +# Insert two rows where the second conflicts on C. The first row show go +# and and then there should be a constraint error. +# +do_test conflict-7.3 { + catchsql {INSERT INTO t1(a,b,c) VALUES(4,5,6), (5,6,4);} +} {1 {UNIQUE constraint failed: t1.c}} +do_execsql_test conflict-7.4 { + SELECT a,b,c FROM t1 ORDER BY a; +} {1 2 3 2 3 4 4 5 6} + +# Change which column is the PRIMARY KEY +# +do_execsql_test conflict-8.1 { + DROP TABLE t1; + CREATE TABLE t1( + a UNIQUE ON CONFLICT REPLACE, + b INT PRIMARY KEY ON CONFLICT IGNORE, + c UNIQUE ON CONFLICT FAIL + ); + INSERT INTO t1(a,b,c) VALUES(1,2,3), (2,3,4); + SELECT a,b,c FROM t1 ORDER BY a; +} {1 2 3 2 3 4} + +# Insert a row that conflicts on column B. The insert should be ignored. +# +do_execsql_test conflict-8.2 { + INSERT INTO t1(a,b,c) VALUES(3,2,5); + SELECT a,b,c FROM t1 ORDER BY a; +} {1 2 3 2 3 4} + +# Insert two rows where the second conflicts on C. The first row show go +# and and then there should be a constraint error. +# +do_test conflict-8.3 { + catchsql {INSERT INTO t1(a,b,c) VALUES(4,5,6), (5,6,4);} +} {1 {UNIQUE constraint failed: t1.c}} +do_execsql_test conflict-8.4 { + SELECT a,b,c FROM t1 ORDER BY a; +} {1 2 3 2 3 4 4 5 6} + +# Change which column is the PRIMARY KEY +# +do_execsql_test conflict-9.1 { + DROP TABLE t1; + CREATE TABLE t1( + a UNIQUE ON CONFLICT REPLACE, + b INT PRIMARY KEY ON CONFLICT IGNORE, + c UNIQUE ON CONFLICT FAIL + ) WITHOUT ROWID; + INSERT INTO t1(a,b,c) VALUES(1,2,3), (2,3,4); + SELECT a,b,c FROM t1 ORDER BY a; +} {1 2 3 2 3 4} + +# Insert a row that conflicts on column B. The insert should be ignored. +# +do_execsql_test conflict-9.2 { + INSERT INTO t1(a,b,c) VALUES(3,2,5); + SELECT a,b,c FROM t1 ORDER BY a; +} {1 2 3 2 3 4} + +# Insert two rows where the second conflicts on C. The first row show go +# and and then there should be a constraint error. +# +do_test conflict-9.3 { + catchsql {INSERT INTO t1(a,b,c) VALUES(4,5,6), (5,6,4);} +} {1 {UNIQUE constraint failed: t1.c}} +do_execsql_test conflict-9.4 { + SELECT a,b,c FROM t1 ORDER BY a; +} {1 2 3 2 3 4 4 5 6} + +# Change which column is the PRIMARY KEY +# +do_execsql_test conflict-10.1 { + DROP TABLE t1; + CREATE TABLE t1( + a UNIQUE ON CONFLICT REPLACE, + b UNIQUE ON CONFLICT IGNORE, + c INTEGER PRIMARY KEY ON CONFLICT FAIL + ); + INSERT INTO t1(a,b,c) VALUES(1,2,3), (2,3,4); + SELECT a,b,c FROM t1 ORDER BY a; +} {1 2 3 2 3 4} + +# Insert a row that conflicts on column B. The insert should be ignored. +# +do_execsql_test conflict-10.2 { + INSERT INTO t1(a,b,c) VALUES(3,2,5); + SELECT a,b,c FROM t1 ORDER BY a; +} {1 2 3 2 3 4} + +# Insert two rows where the second conflicts on C. The first row show go +# and and then there should be a constraint error. +# +do_test conflict-10.3 { + catchsql {INSERT INTO t1(a,b,c) VALUES(4,5,6), (5,6,4);} +} {1 {UNIQUE constraint failed: t1.c}} +do_execsql_test conflict-10.4 { + SELECT a,b,c FROM t1 ORDER BY a; +} {1 2 3 2 3 4 4 5 6} + +# Change which column is the PRIMARY KEY +# +do_execsql_test conflict-11.1 { + DROP TABLE t1; + CREATE TABLE t1( + a UNIQUE ON CONFLICT REPLACE, + b UNIQUE ON CONFLICT IGNORE, + c PRIMARY KEY ON CONFLICT FAIL + ) WITHOUT ROWID; + INSERT INTO t1(a,b,c) VALUES(1,2,3), (2,3,4); + SELECT a,b,c FROM t1 ORDER BY a; +} {1 2 3 2 3 4} + +# Insert a row that conflicts on column B. The insert should be ignored. +# +do_execsql_test conflict-11.2 { + INSERT INTO t1(a,b,c) VALUES(3,2,5); + SELECT a,b,c FROM t1 ORDER BY a; +} {1 2 3 2 3 4} + +# Insert two rows where the second conflicts on C. The first row show go +# and and then there should be a constraint error. +# +do_test conflict-11.3 { + catchsql {INSERT INTO t1(a,b,c) VALUES(4,5,6), (5,6,4);} +} {1 {UNIQUE constraint failed: t1.c}} +do_execsql_test conflict-11.4 { + SELECT a,b,c FROM t1 ORDER BY a; +} {1 2 3 2 3 4 4 5 6} + + +finish_test diff --git a/test/crash8.test b/test/crash8.test index 8bc258651a..930834a962 100644 --- a/test/crash8.test +++ b/test/crash8.test @@ -341,62 +341,68 @@ ifcapable pragma { } {jkl} } -for {set i 1} {$i < 10} {incr i} { - catch { db close } - forcedelete test.db test.db-journal - sqlite3 db test.db - do_test crash8-5.$i.1 { - execsql { - CREATE TABLE t1(x PRIMARY KEY); - INSERT INTO t1 VALUES(randomblob(900)); - INSERT INTO t1 SELECT randomblob(900) FROM t1; - INSERT INTO t1 SELECT randomblob(900) FROM t1; - INSERT INTO t1 SELECT randomblob(900) FROM t1; - INSERT INTO t1 SELECT randomblob(900) FROM t1; - INSERT INTO t1 SELECT randomblob(900) FROM t1; - INSERT INTO t1 SELECT randomblob(900) FROM t1; /* 64 rows */ - } - crashsql -file test.db -delay [expr ($::i%2) + 1] { - PRAGMA cache_size = 10; - BEGIN; - UPDATE t1 SET x = randomblob(900); - ROLLBACK; - INSERT INTO t1 VALUES(randomblob(900)); - } - execsql { PRAGMA integrity_check } - } {ok} +# +# Since the following tests (crash8-5.*) rely upon being able +# to copy a file while open, they will not work on Windows. +# +if {$::tcl_platform(platform)=="unix"} { + for {set i 1} {$i < 10} {incr i} { + catch { db close } + forcedelete test.db test.db-journal + sqlite3 db test.db + do_test crash8-5.$i.1 { + execsql { + CREATE TABLE t1(x PRIMARY KEY); + INSERT INTO t1 VALUES(randomblob(900)); + INSERT INTO t1 SELECT randomblob(900) FROM t1; + INSERT INTO t1 SELECT randomblob(900) FROM t1; + INSERT INTO t1 SELECT randomblob(900) FROM t1; + INSERT INTO t1 SELECT randomblob(900) FROM t1; + INSERT INTO t1 SELECT randomblob(900) FROM t1; + INSERT INTO t1 SELECT randomblob(900) FROM t1; /* 64 rows */ + } + crashsql -file test.db -delay [expr ($::i%2) + 1] { + PRAGMA cache_size = 10; + BEGIN; + UPDATE t1 SET x = randomblob(900); + ROLLBACK; + INSERT INTO t1 VALUES(randomblob(900)); + } + execsql { PRAGMA integrity_check } + } {ok} - catch { db close } - forcedelete test.db test.db-journal - sqlite3 db test.db - do_test crash8-5.$i.2 { - execsql { - PRAGMA cache_size = 10; - CREATE TABLE t1(x PRIMARY KEY); - INSERT INTO t1 VALUES(randomblob(900)); - INSERT INTO t1 SELECT randomblob(900) FROM t1; - INSERT INTO t1 SELECT randomblob(900) FROM t1; - INSERT INTO t1 SELECT randomblob(900) FROM t1; - INSERT INTO t1 SELECT randomblob(900) FROM t1; - INSERT INTO t1 SELECT randomblob(900) FROM t1; - INSERT INTO t1 SELECT randomblob(900) FROM t1; /* 64 rows */ - BEGIN; - UPDATE t1 SET x = randomblob(900); - } - forcedelete testX.db testX.db-journal testX.db-wal - forcecopy test.db testX.db - forcecopy test.db-journal testX.db-journal - db close + catch { db close } + forcedelete test.db test.db-journal + sqlite3 db test.db + do_test crash8-5.$i.2 { + execsql { + PRAGMA cache_size = 10; + CREATE TABLE t1(x PRIMARY KEY); + INSERT INTO t1 VALUES(randomblob(900)); + INSERT INTO t1 SELECT randomblob(900) FROM t1; + INSERT INTO t1 SELECT randomblob(900) FROM t1; + INSERT INTO t1 SELECT randomblob(900) FROM t1; + INSERT INTO t1 SELECT randomblob(900) FROM t1; + INSERT INTO t1 SELECT randomblob(900) FROM t1; + INSERT INTO t1 SELECT randomblob(900) FROM t1; /* 64 rows */ + BEGIN; + UPDATE t1 SET x = randomblob(900); + } + forcedelete testX.db testX.db-journal testX.db-wal + forcecopy test.db testX.db + forcecopy test.db-journal testX.db-journal + db close - crashsql -file test.db -delay [expr ($::i%2) + 1] { - SELECT * FROM sqlite_master; - INSERT INTO t1 VALUES(randomblob(900)); - } + crashsql -file test.db -delay [expr ($::i%2) + 1] { + SELECT * FROM sqlite_master; + INSERT INTO t1 VALUES(randomblob(900)); + } - sqlite3 db2 testX.db - execsql { PRAGMA integrity_check } db2 - } {ok} + sqlite3 db2 testX.db + execsql { PRAGMA integrity_check } db2 + } {ok} + } + catch {db2 close} } -catch {db2 close} finish_test diff --git a/test/dbstatus.test b/test/dbstatus.test index c22fe15d43..368c6b28e5 100644 --- a/test/dbstatus.test +++ b/test/dbstatus.test @@ -134,7 +134,7 @@ foreach ::lookaside_buffer_size {0 64 120} { CREATE TABLE t2(c, d); CREATE VIEW v1 AS SELECT * FROM t1 UNION SELECT * FROM t2; } - 6y { + 6k { CREATE TABLE t1(a, b); CREATE INDEX i1 ON t1(a); CREATE INDEX i2 ON t1(a,b); @@ -204,6 +204,11 @@ foreach ::lookaside_buffer_size {0 64 120} { set nSchema4 [lindex [sqlite3_db_status db SQLITE_DBSTATUS_SCHEMA_USED 0] 1] set nFree [expr {$nAlloc1-$nAlloc2}] + # Tests for which the test name ends in an "k" report slightly less + # memory than is actually freed when all schema items are finalized. + # This is because memory allocated by KeyInfo objects is no longer + # counted as "schema memory". + # # Tests for which the test name ends in an "x" report slightly less # memory than is actually freed when all schema items are finalized. # This is because memory allocated by virtual table implementations @@ -220,7 +225,8 @@ foreach ::lookaside_buffer_size {0 64 120} { # Finally, on osx the estimate of memory used by the schema may be # slightly low. # - if {[string match *x $tn] || $AUTOVACUUM + if {[string match *k $tn] + || [string match *x $tn] || $AUTOVACUUM || ([string match *y $tn] && $STAT3) || ($::tcl_platform(os) == "Darwin") } { @@ -246,7 +252,7 @@ foreach ::lookaside_buffer_size {0 64 120} { # lookaside memory allocated by SQLite, and the memory allocated # for the prepared statements according to sqlite3_db_status(). # - # 3. Finalize all prepared statements Measure the total memory + # 3. Finalize all prepared statements. Measure the total memory # and the prepared statement memory again. # # 4. Repeat step 2. diff --git a/test/e_createtable.test b/test/e_createtable.test index b231cee804..8b57c73971 100644 --- a/test/e_createtable.test +++ b/test/e_createtable.test @@ -1103,8 +1103,8 @@ do_catchsql_test e_createtable-3.11.5 { # EVIDENCE-OF: R-52382-54248 Each table in SQLite may have at most one # PRIMARY KEY. # -# EVIDENCE-OF: R-18080-47271 If there is more than one PRIMARY KEY -# clause in a single CREATE TABLE statement, it is an error. +# EVIDENCE-OF: R-62315-57691 An error is rasied if more than one PRIMARY +# KEY clause appears in a CREATE TABLE statement. # # To test the two above, show that zero primary keys is Ok, one primary # key is Ok, and two or more primary keys is an error. @@ -1127,6 +1127,17 @@ do_createtable_tests 4.1.2 -error { 6 "CREATE TABLE t5(a INTEGER PRIMARY KEY, b, c, PRIMARY KEY(a))" {} } +# EVIDENCE-OF: R-54755-39291 The PRIMARY KEY is optional for ordinary +# tables but is required for WITHOUT ROWID tables. +# +do_catchsql_test 4.1.3 { + CREATE TABLE t6(a, b); --ok +} {0 {}} +do_catchsql_test 4.1.4 { + CREATE TABLE t7(a, b) WITHOUT ROWID; --Error, no PRIMARY KEY +} {1 {PRIMARY KEY missing on table t7}} + + proc table_pk {tbl} { set pk [list] db eval "pragma table_info($tbl)" a { @@ -1160,8 +1171,8 @@ do_createtable_tests 4.2 -repair { 2.3 "CREATE TABLE t5(a, b INTEGER PRIMARY KEY, c)" {b} } -# EVIDENCE-OF: R-33986-09410 Each row in a table with a primary key must -# feature a unique combination of values in its primary key columns. +# EVIDENCE-OF: R-59124-61339 Each row in a table with a primary key must +# have a unique combination of values in its primary key columns. # # EVIDENCE-OF: R-39102-06737 If an INSERT or UPDATE statement attempts # to modify the table content so that two or more rows feature identical @@ -1182,13 +1193,14 @@ do_execsql_test 4.3.0 { INSERT INTO t2 VALUES(X'ABCDEF', 'three'); } {} -do_createtable_tests 4.3.1 -error { %s not unique } { +do_createtable_tests 4.3.1 -error {UNIQUE constraint failed: t1.x} { 1 "INSERT INTO t1 VALUES(0, 0)" {"column x is"} 2 "INSERT INTO t1 VALUES(45.5, 'abc')" {"column x is"} 3 "INSERT INTO t1 VALUES(0.0, 'abc')" {"column x is"} 4 "INSERT INTO t1 VALUES('brambles', 'abc')" {"column x is"} 5 "INSERT INTO t1 VALUES(X'ABCDEF', 'abc')" {"column x is"} - +} +do_createtable_tests 4.3.1 -error {UNIQUE constraint failed: t2.x, t2.y} { 6 "INSERT INTO t2 VALUES(0, 'zero')" {"columns x, y are"} 7 "INSERT INTO t2 VALUES(45.5, 'one')" {"columns x, y are"} 8 "INSERT INTO t2 VALUES(0.0, 'zero')" {"columns x, y are"} @@ -1208,13 +1220,14 @@ do_createtable_tests 4.3.2 { 9 "INSERT INTO t2 VALUES('brambles', 'abc')" {} 10 "INSERT INTO t2 VALUES(X'ABCDEF', 'abc')" {} } -do_createtable_tests 4.3.3 -error { %s not unique } { +do_createtable_tests 4.3.3 -error {UNIQUE constraint failed: t1.x} { 1 "UPDATE t1 SET x=0 WHERE y='two'" {"column x is"} 2 "UPDATE t1 SET x='brambles' WHERE y='three'" {"column x is"} 3 "UPDATE t1 SET x=45.5 WHERE y='zero'" {"column x is"} 4 "UPDATE t1 SET x=X'ABCDEF' WHERE y='one'" {"column x is"} 5 "UPDATE t1 SET x=0.0 WHERE y='three'" {"column x is"} - +} +do_createtable_tests 4.3.3 -error {UNIQUE constraint failed: t2.x, t2.y} { 6 "UPDATE t2 SET x=0, y='zero' WHERE y='two'" {"columns x, y are"} 7 "UPDATE t2 SET x='brambles', y='two' WHERE y='three'" {"columns x, y are"} @@ -1250,8 +1263,9 @@ do_createtable_tests 4.4 { 14 "INSERT INTO t2 VALUES(NULL, NULL)" {} } -# EVIDENCE-OF: R-61866-38053 Unless the column is an INTEGER PRIMARY KEY -# SQLite allows NULL values in a PRIMARY KEY column. +# EVIDENCE-OF: R-35113-43214 Unless the column is an INTEGER PRIMARY KEY +# or the table is a WITHOUT ROWID table or the column is declared NOT +# NULL, SQLite allows NULL values in a PRIMARY KEY column. # # If the column is an integer primary key, attempting to insert a NULL # into the column triggers the auto-increment behavior. Attempting @@ -1273,6 +1287,14 @@ do_catchsql_test 4.5.3 { INSERT INTO t3 VALUES(2, 5, 3); UPDATE t3 SET u = NULL WHERE s = 2; } {1 {datatype mismatch}} +do_catchsql_test 4.5.4 { + CREATE TABLE t4(s, u INT PRIMARY KEY, v) WITHOUT ROWID; + INSERT INTO t4 VALUES(1, NULL, 2); +} {1 {NOT NULL constraint failed: t4.u}} +do_catchsql_test 4.5.5 { + CREATE TABLE t5(s, u INT PRIMARY KEY NOT NULL, v); + INSERT INTO t5 VALUES(1, NULL, 2); +} {1 {NOT NULL constraint failed: t5.u}} # EVIDENCE-OF: R-00227-21080 A UNIQUE constraint is similar to a PRIMARY # KEY constraint, except that a single table may have any number of @@ -1286,14 +1308,12 @@ do_createtable_tests 4.6 { 4 "CREATE TABLE t4(a, b, c, UNIQUE(a, b, c))" {} } -# EVIDENCE-OF: R-55240-58877 For each UNIQUE constraint on the table, -# each row must feature a unique combination of values in the columns +# EVIDENCE-OF: R-30981-64168 For each UNIQUE constraint on the table, +# each row must contain a unique combination of values in the columns # identified by the UNIQUE constraint. # -# EVIDENCE-OF: R-47733-51480 If an INSERT or UPDATE statement attempts -# to modify the table content so that two or more rows feature identical -# values in a set of columns that are subject to a UNIQUE constraint, it -# is a constraint violation. +# EVIDENCE-OF: R-59124-61339 Each row in a table with a primary key must +# have a unique combination of values in its primary key columns. # do_execsql_test 4.7.0 { INSERT INTO t1 VALUES(1, 2); @@ -1305,29 +1325,29 @@ do_execsql_test 4.7.0 { INSERT INTO t4 VALUES('xyx', 2, 1); INSERT INTO t4 VALUES('uvw', 1, 1); } -do_createtable_tests 4.7.1 -error { %s not unique } { - 1 "INSERT INTO t1 VALUES(1, 'one')" {{column a is}} - 2 "INSERT INTO t1 VALUES(4.3, 'two')" {{column a is}} - 3 "INSERT INTO t1 VALUES('reveal', 'three')" {{column a is}} - 4 "INSERT INTO t1 VALUES(X'123456', 'four')" {{column a is}} +do_createtable_tests 4.7.1 -error {UNIQUE constraint failed: %s} { + 1 "INSERT INTO t1 VALUES(1, 'one')" {{t1.a}} + 2 "INSERT INTO t1 VALUES(4.3, 'two')" {{t1.a}} + 3 "INSERT INTO t1 VALUES('reveal', 'three')" {{t1.a}} + 4 "INSERT INTO t1 VALUES(X'123456', 'four')" {{t1.a}} - 5 "UPDATE t1 SET a = 1 WHERE rowid=2" {{column a is}} - 6 "UPDATE t1 SET a = 4.3 WHERE rowid=3" {{column a is}} - 7 "UPDATE t1 SET a = 'reveal' WHERE rowid=4" {{column a is}} - 8 "UPDATE t1 SET a = X'123456' WHERE rowid=1" {{column a is}} + 5 "UPDATE t1 SET a = 1 WHERE rowid=2" {{t1.a}} + 6 "UPDATE t1 SET a = 4.3 WHERE rowid=3" {{t1.a}} + 7 "UPDATE t1 SET a = 'reveal' WHERE rowid=4" {{t1.a}} + 8 "UPDATE t1 SET a = X'123456' WHERE rowid=1" {{t1.a}} - 9 "INSERT INTO t4 VALUES('xyx', 1, 1)" {{columns a, b, c are}} - 10 "INSERT INTO t4 VALUES('xyx', 2, 1)" {{columns a, b, c are}} - 11 "INSERT INTO t4 VALUES('uvw', 1, 1)" {{columns a, b, c are}} + 9 "INSERT INTO t4 VALUES('xyx', 1, 1)" {{t4.a, t4.b, t4.c}} + 10 "INSERT INTO t4 VALUES('xyx', 2, 1)" {{t4.a, t4.b, t4.c}} + 11 "INSERT INTO t4 VALUES('uvw', 1, 1)" {{t4.a, t4.b, t4.c}} - 12 "UPDATE t4 SET a='xyx' WHERE rowid=3" {{columns a, b, c are}} - 13 "UPDATE t4 SET b=1 WHERE rowid=2" {{columns a, b, c are}} - 14 "UPDATE t4 SET a=0, b=0, c=0" {{columns a, b, c are}} + 12 "UPDATE t4 SET a='xyx' WHERE rowid=3" {{t4.a, t4.b, t4.c}} + 13 "UPDATE t4 SET b=1 WHERE rowid=2" {{t4.a, t4.b, t4.c}} + 14 "UPDATE t4 SET a=0, b=0, c=0" {{t4.a, t4.b, t4.c}} } -# EVIDENCE-OF: R-21289-11559 As with PRIMARY KEY constraints, for the -# purposes of UNIQUE constraints NULL values are considered distinct -# from all other values (including other NULLs). +# EVIDENCE-OF: R-00404-17670 For the purposes of UNIQUE constraints, +# NULL values are considered distinct from all other values, including +# other NULLs. # do_createtable_tests 4.8 { 1 "INSERT INTO t1 VALUES(NULL, NULL)" {} @@ -1342,10 +1362,9 @@ do_createtable_tests 4.8 { 9 "UPDATE t4 SET c = NULL" {} } -# EVIDENCE-OF: R-26983-26377 INTEGER PRIMARY KEY columns aside, both -# UNIQUE and PRIMARY KEY constraints are implemented by creating an -# index in the database (in the same way as a "CREATE UNIQUE INDEX" -# statement would). +# EVIDENCE-OF: R-55820-29984 In most cases, UNIQUE and PRIMARY KEY +# constraints are implemented by creating a unique index in the +# database. do_createtable_tests 4.9 -repair drop_all_tables -query { SELECT count(*) FROM sqlite_master WHERE type='index' } { @@ -1356,7 +1375,7 @@ do_createtable_tests 4.9 -repair drop_all_tables -query { 5 "CREATE TABLE t1(a PRIMARY KEY, b, c, UNIQUE(c, b))" 2 } -# EVIDENCE-OF: R-02252-33116 Such an index is used like any other index +# Obsolete: R-02252-33116 Such an index is used like any other index # in the database to optimize queries. # do_execsql_test 4.10.0 { @@ -1404,21 +1423,21 @@ do_execsql_test 4.11 { INSERT INTO t2 SELECT * FROM x2; } -do_createtable_tests 4.11 -error {constraint failed} { - 1a "INSERT INTO x1 VALUES('one', 0)" {} - 1b "INSERT INTO t1 VALUES('one', -4.0)" {} +do_createtable_tests 4.11 -error {CHECK constraint failed: %s} { + 1a "INSERT INTO x1 VALUES('one', 0)" {x1} + 1b "INSERT INTO t1 VALUES('one', -4.0)" {t1} - 2a "INSERT INTO x2 VALUES('abc', 1)" {} - 2b "INSERT INTO t2 VALUES('abc', 1)" {} + 2a "INSERT INTO x2 VALUES('abc', 1)" {x2} + 2b "INSERT INTO t2 VALUES('abc', 1)" {t2} - 3a "INSERT INTO x2 VALUES(0, 'abc')" {} - 3b "INSERT INTO t2 VALUES(0, 'abc')" {} + 3a "INSERT INTO x2 VALUES(0, 'abc')" {x2} + 3b "INSERT INTO t2 VALUES(0, 'abc')" {t2} - 4a "UPDATE t1 SET b=-1 WHERE rowid=1" {} - 4b "UPDATE x1 SET b=-1 WHERE rowid=1" {} + 4a "UPDATE t1 SET b=-1 WHERE rowid=1" {t1} + 4b "UPDATE x1 SET b=-1 WHERE rowid=1" {x1} - 4a "UPDATE x2 SET a='' WHERE rowid=1" {} - 4b "UPDATE t2 SET a='' WHERE rowid=1" {} + 4a "UPDATE x2 SET a='' WHERE rowid=1" {x2} + 4b "UPDATE t2 SET a='' WHERE rowid=1" {t2} } # EVIDENCE-OF: R-34109-39108 If the CHECK expression evaluates to NULL, @@ -1469,9 +1488,7 @@ do_execsql_test 4.14.0 { INSERT INTO t3 VALUES('x', 'y', 'z'); INSERT INTO t3 VALUES(1, 2, 3); } -do_createtable_tests 4.14 -error { - %s may not be NULL -} { +do_createtable_tests 4.14 -error {NOT NULL constraint failed: %s} { 1 "INSERT INTO t1 VALUES(NULL, 'a')" {t1.a} 2 "INSERT INTO t2 VALUES(NULL, 'b')" {t2.a} 3 "INSERT INTO t3 VALUES('c', 'd', NULL)" {t3.c} @@ -1537,12 +1554,12 @@ do_execsql_test 4.15.0 { } foreach {tn tbl res ac data} { - 1 t1_ab {1 {column a is not unique}} 0 {1 one 2 two 3 three} - 2 t1_ro {1 {column a is not unique}} 1 {1 one 2 two} - 3 t1_fa {1 {column a is not unique}} 0 {1 one 2 two 3 three 4 string} + 1 t1_ab {1 {UNIQUE constraint failed: t1_ab.a}} 0 {1 one 2 two 3 three} + 2 t1_ro {1 {UNIQUE constraint failed: t1_ro.a}} 1 {1 one 2 two} + 3 t1_fa {1 {UNIQUE constraint failed: t1_fa.a}} 0 {1 one 2 two 3 three 4 string} 4 t1_ig {0 {}} 0 {1 one 2 two 3 three 4 string 6 string} 5 t1_re {0 {}} 0 {1 one 2 two 4 string 3 string 6 string} - 6 t1_xx {1 {column a is not unique}} 0 {1 one 2 two 3 three} + 6 t1_xx {1 {UNIQUE constraint failed: t1_xx.a}} 0 {1 one 2 two 3 three} } { catchsql COMMIT do_execsql_test 4.15.$tn.1 "BEGIN; INSERT INTO $tbl VALUES(3, 'three')" @@ -1555,12 +1572,12 @@ foreach {tn tbl res ac data} { do_execsql_test 4.15.$tn.4 "SELECT * FROM $tbl" $data } foreach {tn tbl res ac data} { - 1 t2_ab {1 {t2_ab.b may not be NULL}} 0 {1 one 2 two 3 three} - 2 t2_ro {1 {t2_ro.b may not be NULL}} 1 {1 one 2 two} - 3 t2_fa {1 {t2_fa.b may not be NULL}} 0 {1 one 2 two 3 three 4 xx} + 1 t2_ab {1 {NOT NULL constraint failed: t2_ab.b}} 0 {1 one 2 two 3 three} + 2 t2_ro {1 {NOT NULL constraint failed: t2_ro.b}} 1 {1 one 2 two} + 3 t2_fa {1 {NOT NULL constraint failed: t2_fa.b}} 0 {1 one 2 two 3 three 4 xx} 4 t2_ig {0 {}} 0 {1 one 2 two 3 three 4 xx 6 xx} - 5 t2_re {1 {t2_re.b may not be NULL}} 0 {1 one 2 two 3 three} - 6 t2_xx {1 {t2_xx.b may not be NULL}} 0 {1 one 2 two 3 three} + 5 t2_re {1 {NOT NULL constraint failed: t2_re.b}} 0 {1 one 2 two 3 three} + 6 t2_xx {1 {NOT NULL constraint failed: t2_xx.b}} 0 {1 one 2 two 3 three} } { catchsql COMMIT do_execsql_test 4.16.$tn.1 "BEGIN; INSERT INTO $tbl VALUES(3, 'three')" @@ -1573,12 +1590,16 @@ foreach {tn tbl res ac data} { do_execsql_test 4.16.$tn.4 "SELECT * FROM $tbl" $data } foreach {tn tbl res ac data} { - 1 t3_ab {1 {columns a, b are not unique}} 0 {1 one 2 two 3 three} - 2 t3_ro {1 {columns a, b are not unique}} 1 {1 one 2 two} - 3 t3_fa {1 {columns a, b are not unique}} 0 {1 one 2 two 3 three 4 three} + 1 t3_ab {1 {UNIQUE constraint failed: t3_ab.a, t3_ab.b}} + 0 {1 one 2 two 3 three} + 2 t3_ro {1 {UNIQUE constraint failed: t3_ro.a, t3_ro.b}} + 1 {1 one 2 two} + 3 t3_fa {1 {UNIQUE constraint failed: t3_fa.a, t3_fa.b}} + 0 {1 one 2 two 3 three 4 three} 4 t3_ig {0 {}} 0 {1 one 2 two 3 three 4 three 6 three} 5 t3_re {0 {}} 0 {1 one 2 two 4 three 3 three 6 three} - 6 t3_xx {1 {columns a, b are not unique}} 0 {1 one 2 two 3 three} + 6 t3_xx {1 {UNIQUE constraint failed: t3_xx.a, t3_xx.b}} + 0 {1 one 2 two 3 three} } { catchsql COMMIT do_execsql_test 4.17.$tn.1 "BEGIN; INSERT INTO $tbl VALUES(3, 'three')" @@ -1609,7 +1630,7 @@ do_execsql_test 4.18.1 { do_execsql_test 4.18.2 { BEGIN; INSERT INTO t4 VALUES(5, 6) } do_catchsql_test 4.18.3 { INSERT INTO t4 SELECT a+4, b+4 FROM t4 -} {1 {constraint failed}} +} {1 {CHECK constraint failed: t4}} do_test e_createtable-4.18.4 { sqlite3_get_autocommit db } 0 do_execsql_test 4.18.5 { SELECT * FROM t4 } {1 2 3 4 5 6} @@ -1622,7 +1643,7 @@ do_execsql_test 4.19.0 { do_catchsql_test 4.19.1 { INSERT INTO t5 VALUES(NULL, 'not null') } {0 {}} do_execsql_test 4.19.2 { SELECT * FROM t5 } {} do_catchsql_test 4.19.3 { INSERT INTO t5 VALUES('not null', NULL) } \ - {1 {t5.b may not be NULL}} + {1 {NOT NULL constraint failed: t5.b}} do_execsql_test 4.19.4 { SELECT * FROM t5 } {} #------------------------------------------------------------------------ @@ -1691,10 +1712,10 @@ proc is_integer_primary_key {tbl col} { }]] 0 } -# EVIDENCE-OF: R-53738-31673 With one exception, if a table has a -# primary key that consists of a single column, and the declared type of -# that column is "INTEGER" in any mixture of upper and lower case, then -# the column becomes an alias for the rowid. +# EVIDENCE-OF: R-47901-33947 With one exception noted below, if a rowid +# table has a primary key that consists of a single column and the +# declared type of that column is "INTEGER" in any mixture of upper and +# lower case, then the column becomes an alias for the rowid. # # EVIDENCE-OF: R-45951-08347 if the declaration of a column with # declared type "INTEGER" includes an "PRIMARY KEY DESC" clause, it does @@ -1747,16 +1768,16 @@ do_execsql_test 5.4.3 { do_catchsql_test 5.4.4.1 { INSERT INTO t6 VALUES(2) -} {1 {column pk is not unique}} +} {1 {UNIQUE constraint failed: t6.pk}} do_catchsql_test 5.4.4.2 { INSERT INTO t7 VALUES(2) -} {1 {column pk is not unique}} +} {1 {UNIQUE constraint failed: t7.pk}} do_catchsql_test 5.4.4.3 { INSERT INTO t8 VALUES(2) -} {1 {column pk is not unique}} +} {1 {UNIQUE constraint failed: t8.pk}} do_catchsql_test 5.4.4.4 { INSERT INTO t9 VALUES(2) -} {1 {column pk is not unique}} +} {1 {UNIQUE constraint failed: t9.pk}} # EVIDENCE-OF: R-56094-57830 the following three table declarations all # cause the column "x" to be an alias for the rowid (an integer primary diff --git a/test/e_fkey.test b/test/e_fkey.test index 976ed16325..022611695d 100644 --- a/test/e_fkey.test +++ b/test/e_fkey.test @@ -211,7 +211,7 @@ do_test e_fkey-6.1 { catchsql { DELETE FROM t1 } -} {1 {foreign key constraint failed}} +} {1 {FOREIGN KEY constraint failed}} do_test e_fkey-6.2 { execsql { PRAGMA foreign_keys } } {1} @@ -265,11 +265,11 @@ do_test e_fkey-7.1 { # do_test e_fkey-8.1 { catchsql { INSERT INTO track VALUES(1, 'track 1', 1) } -} {1 {foreign key constraint failed}} +} {1 {FOREIGN KEY constraint failed}} do_test e_fkey-8.2 { execsql { INSERT INTO artist VALUES(2, 'artist 1') } catchsql { INSERT INTO track VALUES(1, 'track 1', 1) } -} {1 {foreign key constraint failed}} +} {1 {FOREIGN KEY constraint failed}} do_test e_fkey-8.2 { execsql { INSERT INTO track VALUES(1, 'track 1', 2) } } {} @@ -283,7 +283,7 @@ do_test e_fkey-8.2 { # do_test e_fkey-9.1 { catchsql { DELETE FROM artist WHERE artistid = 2 } -} {1 {foreign key constraint failed}} +} {1 {FOREIGN KEY constraint failed}} do_test e_fkey-9.2 { execsql { DELETE FROM track WHERE trackartist = 2; @@ -311,14 +311,14 @@ do_test e_fkey-10.2 { do_test e_fkey-10.3 { # Setting the trackid to a non-NULL value fails, of course. catchsql { UPDATE track SET trackartist = 5 WHERE trackid = 1 } -} {1 {foreign key constraint failed}} +} {1 {FOREIGN KEY constraint failed}} do_test e_fkey-10.4 { execsql { INSERT INTO artist VALUES(5, 'artist 5'); UPDATE track SET trackartist = 5 WHERE trackid = 1; } catchsql { DELETE FROM artist WHERE artistid = 5} -} {1 {foreign key constraint failed}} +} {1 {FOREIGN KEY constraint failed}} do_test e_fkey-10.5 { execsql { UPDATE track SET trackartist = NULL WHERE trackid = 1; @@ -344,8 +344,8 @@ proc test_r52486_21352 {tn sql} { set res [catchsql $sql] set results { {0 {}} - {1 {PRIMARY KEY must be unique}} - {1 {foreign key constraint failed}} + {1 {UNIQUE constraint failed: artist.artistid}} + {1 {FOREIGN KEY constraint failed}} } if {[lsearch $results $res]<0} { error $res @@ -409,7 +409,7 @@ do_test e_fkey-12.1 { } {} do_test e_fkey-12.2 { catchsql { INSERT INTO track VALUES(14, 'Mr. Bojangles', NULL) } -} {1 {track.trackartist may not be NULL}} +} {1 {NOT NULL constraint failed: track.trackartist}} #------------------------------------------------------------------------- # EVIDENCE-OF: R-16127-35442 @@ -438,7 +438,7 @@ do_test e_fkey-13.1 { } {} do_test e_fkey-13.2 { catchsql { INSERT INTO track VALUES(14, 'Mr. Bojangles', 3) } -} {1 {foreign key constraint failed}} +} {1 {FOREIGN KEY constraint failed}} do_test e_fkey-13.3 { execsql { INSERT INTO track VALUES(14, 'Mr. Bojangles', NULL) } } {} @@ -446,7 +446,7 @@ do_test e_fkey-13.4 { catchsql { UPDATE track SET trackartist = 3 WHERE trackname = 'Mr. Bojangles'; } -} {1 {foreign key constraint failed}} +} {1 {FOREIGN KEY constraint failed}} do_test e_fkey-13.5 { execsql { INSERT INTO artist VALUES(3, 'Sammy Davis Jr.'); @@ -464,7 +464,7 @@ do_test e_fkey-14.1 { catchsql { DELETE FROM artist WHERE artistname = 'Frank Sinatra'; } -} {1 {foreign key constraint failed}} +} {1 {FOREIGN KEY constraint failed}} do_test e_fkey-14.2 { execsql { DELETE FROM track WHERE trackname = 'My Way'; @@ -475,7 +475,7 @@ do_test e_fkey-14.3 { catchsql { UPDATE artist SET artistid=4 WHERE artistname = 'Dean Martin'; } -} {1 {foreign key constraint failed}} +} {1 {FOREIGN KEY constraint failed}} do_test e_fkey-14.4 { execsql { DELETE FROM track WHERE trackname IN('That''s Amore', 'Christmas Blues'); @@ -513,7 +513,7 @@ do_test e_fkey-15.1 { proc test_efkey_45 {tn isError sql} { do_test e_fkey-15.$tn.1 " catchsql {$sql} - " [lindex {{0 {}} {1 {foreign key constraint failed}}} $isError] + " [lindex {{0 {}} {1 {FOREIGN KEY constraint failed}}} $isError] do_test e_fkey-15.$tn.2 { execsql { @@ -557,10 +557,10 @@ do_test e_fkey-16.2 { } {} do_test e_fkey-16.3 { catchsql { UPDATE t2 SET b = 'two' WHERE rowid = 1 } -} {1 {foreign key constraint failed}} +} {1 {FOREIGN KEY constraint failed}} do_test e_fkey-16.4 { catchsql { DELETE FROM t1 WHERE rowid = 1 } -} {1 {foreign key constraint failed}} +} {1 {FOREIGN KEY constraint failed}} #------------------------------------------------------------------------- # Specifically, test that when comparing child and parent key values the @@ -592,7 +592,7 @@ do_test e_fkey-17.3 { } {integer integer text} do_test e_fkey-17.4 { catchsql { DELETE FROM t1 WHERE rowid = 2 } -} {1 {foreign key constraint failed}} +} {1 {FOREIGN KEY constraint failed}} ########################################################################### ### SECTION 3: Required and Suggested Database Indexes @@ -896,7 +896,7 @@ do_test e_fkey-23.1 { proc test_efkey_60 {tn isError sql} { do_test e_fkey-23.$tn " catchsql {$sql} - " [lindex {{0 {}} {1 {foreign key constraint failed}}} $isError] + " [lindex {{0 {}} {1 {FOREIGN KEY constraint failed}}} $isError] } test_efkey_60 2 1 "INSERT INTO c1 VALUES(239, 231)" @@ -933,7 +933,7 @@ do_test e_fkey-24.1 { proc test_efkey_61 {tn isError sql} { do_test e_fkey-24.$tn " catchsql {$sql} - " [lindex {{0 {}} {1 {foreign key constraint failed}}} $isError] + " [lindex {{0 {}} {1 {FOREIGN KEY constraint failed}}} $isError] } foreach {tn c} [list 2 c1 3 c2 4 c3] { test_efkey_61 $tn.1 1 "INSERT INTO $c VALUES(1, 2)" @@ -998,7 +998,7 @@ do_test e_fkey-25.5 { concat \ [execsql { SELECT rowid FROM track WHERE trackartist = 5 }] \ [catchsql { DELETE FROM artist WHERE artistid = 5 }] -} {1 1 {foreign key constraint failed}} +} {1 1 {FOREIGN KEY constraint failed}} do_test e_fkey-25.6 { concat \ @@ -1010,7 +1010,7 @@ do_test e_fkey-25.7 { concat \ [execsql { SELECT rowid FROM track WHERE trackartist = 6 }] \ [catchsql { DELETE FROM artist WHERE artistid = 6 }] -} {2 1 {foreign key constraint failed}} +} {2 1 {FOREIGN KEY constraint failed}} #------------------------------------------------------------------------- # EVIDENCE-OF: R-47936-10044 Or, more generally: @@ -1199,7 +1199,7 @@ do_test e_fkey-29.3 { catchsql { INSERT INTO song VALUES(2, 'Elvis Presley', 'Elvis Is Back!', 'Fever'); } -} {1 {foreign key constraint failed}} +} {1 {FOREIGN KEY constraint failed}} #------------------------------------------------------------------------- @@ -1240,7 +1240,7 @@ do_test e_fkey-31.1 { do_test e_fkey-31.2 { # Execute a statement that violates the immediate FK constraint. catchsql { INSERT INTO prince VALUES(1, 2) } -} {1 {foreign key constraint failed}} +} {1 {FOREIGN KEY constraint failed}} do_test e_fkey-31.3 { # This time, use a trigger to fix the constraint violation before the @@ -1265,7 +1265,7 @@ do_test e_fkey-31.4 { DROP TRIGGER kt; } catchsql { INSERT INTO prince VALUES(3, 4) } -} {1 {foreign key constraint failed}} +} {1 {FOREIGN KEY constraint failed}} do_test e_fkey-31.5 { execsql { COMMIT; @@ -1296,7 +1296,7 @@ do_test e_fkey-31.5 { proc test_efkey_34 {tn isError sql} { do_test e_fkey-32.$tn " catchsql {$sql} - " [lindex {{0 {}} {1 {foreign key constraint failed}}} $isError] + " [lindex {{0 {}} {1 {FOREIGN KEY constraint failed}}} $isError] } drop_all_tables @@ -1327,7 +1327,7 @@ drop_all_tables proc test_efkey_35 {tn isError sql} { do_test e_fkey-33.$tn " catchsql {$sql} - " [lindex {{0 {}} {1 {foreign key constraint failed}}} $isError] + " [lindex {{0 {}} {1 {FOREIGN KEY constraint failed}}} $isError] } do_test e_fkey-33.1 { execsql { @@ -1417,7 +1417,7 @@ do_test e_fkey-34.1 { proc test_efkey_29 {tn sql isError} { do_test e_fkey-34.$tn "catchsql {$sql}" [ - lindex {{0 {}} {1 {foreign key constraint failed}}} $isError + lindex {{0 {}} {1 {FOREIGN KEY constraint failed}}} $isError ] } test_efkey_29 2 "BEGIN" 0 @@ -1491,7 +1491,7 @@ do_test e_fkey-35.2 { INSERT INTO track VALUES(1, 'White Christmas', 5); } catchsql COMMIT -} {1 {foreign key constraint failed}} +} {1 {FOREIGN KEY constraint failed}} do_test e_fkey-35.3 { execsql { INSERT INTO artist VALUES(5, 'Bing Crosby'); @@ -1528,7 +1528,7 @@ do_test e_fkey-36.2 { } {} do_test e_fkey-36.3 { catchsql COMMIT -} {1 {foreign key constraint failed}} +} {1 {FOREIGN KEY constraint failed}} do_test e_fkey-36.4 { execsql { UPDATE t1 SET a = 5 WHERE a = 4; @@ -1558,7 +1558,7 @@ do_test e_fkey-37.1 { } {} do_test e_fkey-37.2 { catchsql {RELEASE one} -} {1 {foreign key constraint failed}} +} {1 {FOREIGN KEY constraint failed}} do_test e_fkey-37.3 { execsql { UPDATE t1 SET a = 7 WHERE a = 6; @@ -1575,7 +1575,7 @@ do_test e_fkey-37.4 { } {} do_test e_fkey-37.5 { catchsql {RELEASE one} -} {1 {foreign key constraint failed}} +} {1 {FOREIGN KEY constraint failed}} do_test e_fkey-37.6 { execsql {ROLLBACK TO one ; RELEASE one} } {} @@ -1606,7 +1606,7 @@ do_test e_fkey-38.2 { } {1 1 2 2 3 3 4 4 5 6} do_test e_fkey-38.3 { catchsql COMMIT -} {1 {foreign key constraint failed}} +} {1 {FOREIGN KEY constraint failed}} do_test e_fkey-38.4 { execsql { ROLLBACK TO one; @@ -1627,11 +1627,11 @@ do_test e_fkey-38.5 { } {} do_test e_fkey-38.6 { catchsql {RELEASE a} -} {1 {foreign key constraint failed}} +} {1 {FOREIGN KEY constraint failed}} do_test e_fkey-38.7 { execsql {ROLLBACK TO c} catchsql {RELEASE a} -} {1 {foreign key constraint failed}} +} {1 {FOREIGN KEY constraint failed}} do_test e_fkey-38.8 { execsql { ROLLBACK TO b; @@ -1782,7 +1782,7 @@ do_test e_fkey-41.2 { } {j k l m} do_test e_fkey-41.3 { catchsql COMMIT -} {1 {foreign key constraint failed}} +} {1 {FOREIGN KEY constraint failed}} do_test e_fkey-41.4 { execsql ROLLBACK } {} @@ -1820,10 +1820,10 @@ do_test e_fkey-41.2 { } {} do_test e_fkey-41.3 { catchsql { DELETE FROM parent WHERE p1 = 'a' } -} {1 {foreign key constraint failed}} +} {1 {FOREIGN KEY constraint failed}} do_test e_fkey-41.4 { catchsql { UPDATE parent SET p2 = 'e' WHERE p1 = 'c' } -} {1 {foreign key constraint failed}} +} {1 {FOREIGN KEY constraint failed}} #------------------------------------------------------------------------- # Test that RESTRICT is slightly different from NO ACTION for IMMEDIATE @@ -1857,7 +1857,7 @@ do_test e_fkey-42.1 { } {} do_test e_fkey-42.2 { catchsql { UPDATE parent SET x = 'key one' WHERE x = 'key1' } -} {1 {foreign key constraint failed}} +} {1 {FOREIGN KEY constraint failed}} do_test e_fkey-42.3 { execsql { UPDATE parent SET x = 'key two' WHERE x = 'key2'; @@ -1885,7 +1885,7 @@ do_test e_fkey-42.4 { } {} do_test e_fkey-42.5 { catchsql { DELETE FROM parent WHERE x = 'key1' } -} {1 {foreign key constraint failed}} +} {1 {FOREIGN KEY constraint failed}} do_test e_fkey-42.6 { execsql { DELETE FROM parent WHERE x = 'key2'; @@ -1908,7 +1908,7 @@ do_test e_fkey-42.7 { } {} do_test e_fkey-42.8 { catchsql { REPLACE INTO parent VALUES('key1') } -} {1 {foreign key constraint failed}} +} {1 {FOREIGN KEY constraint failed}} do_test e_fkey-42.9 { execsql { REPLACE INTO parent VALUES('key2'); @@ -1944,13 +1944,13 @@ do_test e_fkey-43.1 { } {} do_test e_fkey-43.2 { catchsql { UPDATE parent SET x = 'key one' WHERE x = 'key1' } -} {1 {foreign key constraint failed}} +} {1 {FOREIGN KEY constraint failed}} do_test e_fkey-43.3 { execsql { UPDATE parent SET x = 'key two' WHERE x = 'key2' } } {} do_test e_fkey-43.4 { catchsql COMMIT -} {1 {foreign key constraint failed}} +} {1 {FOREIGN KEY constraint failed}} do_test e_fkey-43.5 { execsql { UPDATE child2 SET c = 'key two'; @@ -1978,13 +1978,13 @@ do_test e_fkey-43.6 { } {} do_test e_fkey-43.7 { catchsql { DELETE FROM parent WHERE x = 'key1' } -} {1 {foreign key constraint failed}} +} {1 {FOREIGN KEY constraint failed}} do_test e_fkey-43.8 { execsql { DELETE FROM parent WHERE x = 'key2' } } {} do_test e_fkey-43.9 { catchsql COMMIT -} {1 {foreign key constraint failed}} +} {1 {FOREIGN KEY constraint failed}} do_test e_fkey-43.10 { execsql { UPDATE child2 SET c = NULL; @@ -2240,7 +2240,7 @@ do_test e_fkey-49.3 { } {ONE two three} do_test e_fkey-49.4 { catchsql { UPDATE parent SET a = '' WHERE a = 'oNe' } -} {1 {foreign key constraint failed}} +} {1 {FOREIGN KEY constraint failed}} #------------------------------------------------------------------------- @@ -2275,7 +2275,7 @@ do_test e_fkey-50.1 { } {} do_test e_fkey-50.2 { catchsql { DELETE FROM artist WHERE artistname = 'Sammy Davis Jr.' } -} {1 {foreign key constraint failed}} +} {1 {FOREIGN KEY constraint failed}} do_test e_fkey-50.3 { execsql { INSERT INTO artist VALUES(0, 'Unknown Artist'); @@ -2639,7 +2639,7 @@ do_test e_fkey-58.1 { } execsql { INSERT INTO c5 VALUES('a', 'b') } catchsql { DROP TABLE p } -} {1 {foreign key constraint failed}} +} {1 {FOREIGN KEY constraint failed}} do_test e_fkey-58.2 { execsql { SELECT * FROM p } } {a b} @@ -2648,7 +2648,7 @@ do_test e_fkey-58.3 { BEGIN; DROP TABLE p; } -} {1 {foreign key constraint failed}} +} {1 {FOREIGN KEY constraint failed}} do_test e_fkey-58.4 { execsql { SELECT * FROM p; @@ -2682,11 +2682,11 @@ do_test e_fkey-59.2 { } {} do_test e_fkey-59.3 { catchsql COMMIT -} {1 {foreign key constraint failed}} +} {1 {FOREIGN KEY constraint failed}} do_test e_fkey-59.4 { execsql { CREATE TABLE p(a, b, PRIMARY KEY(a, b)) } catchsql COMMIT -} {1 {foreign key constraint failed}} +} {1 {FOREIGN KEY constraint failed}} do_test e_fkey-59.5 { execsql { INSERT INTO p VALUES('a', 'b') } execsql COMMIT @@ -2849,7 +2849,7 @@ foreach zMatch [list SIMPLE PARTIAL FULL Simple parTIAL FuLL ] { # Check that the FK is enforced properly if there are no NULL values # in the child key columns. catchsql { INSERT INTO c VALUES('a', 2, 4) } - } {1 {foreign key constraint failed}} + } {1 {FOREIGN KEY constraint failed}} } #------------------------------------------------------------------------- @@ -2879,13 +2879,13 @@ do_test e_fkey-62.3 { } {} do_test e_fkey-62.4 { catchsql { INSERT INTO ci VALUES('x', 'y') } -} {1 {foreign key constraint failed}} +} {1 {FOREIGN KEY constraint failed}} do_test e_fkey-62.5 { catchsql { INSERT INTO cd VALUES('x', 'y') } } {0 {}} do_test e_fkey-62.6 { catchsql { COMMIT } -} {1 {foreign key constraint failed}} +} {1 {FOREIGN KEY constraint failed}} do_test e_fkey-62.7 { execsql { DELETE FROM cd; diff --git a/test/e_insert.test b/test/e_insert.test index d95273e93b..adda996b5a 100644 --- a/test/e_insert.test +++ b/test/e_insert.test @@ -371,22 +371,22 @@ do_execsql_test e_insert-4.1.0 { INSERT INTO a4 VALUES(3, 'a'); } {} foreach {tn sql error ac data } { - 1.1 "INSERT INTO a4 VALUES(2,'b')" {column c is not unique} 1 {1 a 2 a 3 a} + 1.1 "INSERT INTO a4 VALUES(2,'b')" {UNIQUE constraint failed: a4.c} 1 {1 a 2 a 3 a} 1.2 "INSERT OR REPLACE INTO a4 VALUES(2, 'b')" {} 1 {1 a 3 a 2 b} 1.3 "INSERT OR IGNORE INTO a4 VALUES(3, 'c')" {} 1 {1 a 3 a 2 b} 1.4 "BEGIN" {} 0 {1 a 3 a 2 b} - 1.5 "INSERT INTO a4 VALUES(1, 'd')" {column c is not unique} 0 {1 a 3 a 2 b} + 1.5 "INSERT INTO a4 VALUES(1, 'd')" {UNIQUE constraint failed: a4.c} 0 {1 a 3 a 2 b} 1.6 "INSERT OR ABORT INTO a4 VALUES(1, 'd')" - {column c is not unique} 0 {1 a 3 a 2 b} + {UNIQUE constraint failed: a4.c} 0 {1 a 3 a 2 b} 1.7 "INSERT OR ROLLBACK INTO a4 VALUES(1, 'd')" - {column c is not unique} 1 {1 a 3 a 2 b} + {UNIQUE constraint failed: a4.c} 1 {1 a 3 a 2 b} 1.8 "INSERT INTO a4 SELECT 4, 'e' UNION ALL SELECT 3, 'e'" - {column c is not unique} 1 {1 a 3 a 2 b} + {UNIQUE constraint failed: a4.c} 1 {1 a 3 a 2 b} 1.9 "INSERT OR FAIL INTO a4 SELECT 4, 'e' UNION ALL SELECT 3, 'e'" - {column c is not unique} 1 {1 a 3 a 2 b 4 e} + {UNIQUE constraint failed: a4.c} 1 {1 a 3 a 2 b 4 e} 2.1 "INSERT INTO a4 VALUES(2,'f')" - {column c is not unique} 1 {1 a 3 a 2 b 4 e} + {UNIQUE constraint failed: a4.c} 1 {1 a 3 a 2 b 4 e} 2.2 "REPLACE INTO a4 VALUES(2, 'f')" {} 1 {1 a 3 a 4 e 2 f} } { do_catchsql_test e_insert-4.1.$tn.1 $sql [list [expr {$error!=""}] $error] diff --git a/test/e_reindex.test b/test/e_reindex.test index c1eae0646c..4b86787a05 100644 --- a/test/e_reindex.test +++ b/test/e_reindex.test @@ -67,10 +67,10 @@ sqlite3 db test.db do_execsql_test e_reindex-1.3 { PRAGMA integrity_check; } [list \ - {rowid 4 missing from index i2} \ - {rowid 4 missing from index i1} \ - {rowid 5 missing from index i2} \ - {rowid 5 missing from index i1} \ + {row 3 missing from index i2} \ + {row 3 missing from index i1} \ + {row 4 missing from index i2} \ + {row 4 missing from index i1} \ {wrong # of entries in index i2} \ {wrong # of entries in index i1} ] diff --git a/test/e_update.test b/test/e_update.test index 159e0676f5..e9c6b26809 100644 --- a/test/e_update.test +++ b/test/e_update.test @@ -278,30 +278,30 @@ do_execsql_test e_update-1.8.0 { } {} foreach {tn sql error ac data } { 1 "UPDATE t3 SET b='one' WHERE a=3" - {column b is not unique} 1 {1 one 2 two 3 three 4 four} + {UNIQUE constraint failed: t3.b} 1 {1 one 2 two 3 three 4 four} 2 "UPDATE OR REPLACE t3 SET b='one' WHERE a=3" {} 1 {2 two 3 one 4 four} 3 "UPDATE OR FAIL t3 SET b='three'" - {column b is not unique} 1 {2 three 3 one 4 four} + {UNIQUE constraint failed: t3.b} 1 {2 three 3 one 4 four} 4 "UPDATE OR IGNORE t3 SET b='three' WHERE a=3" {} 1 {2 three 3 one 4 four} 5 "UPDATE OR ABORT t3 SET b='three' WHERE a=3" - {column b is not unique} 1 {2 three 3 one 4 four} + {UNIQUE constraint failed: t3.b} 1 {2 three 3 one 4 four} 6 "BEGIN" {} 0 {2 three 3 one 4 four} 7 "UPDATE t3 SET b='three' WHERE a=3" - {column b is not unique} 0 {2 three 3 one 4 four} + {UNIQUE constraint failed: t3.b} 0 {2 three 3 one 4 four} 8 "UPDATE OR ABORT t3 SET b='three' WHERE a=3" - {column b is not unique} 0 {2 three 3 one 4 four} + {UNIQUE constraint failed: t3.b} 0 {2 three 3 one 4 four} 9 "UPDATE OR FAIL t3 SET b='two'" - {column b is not unique} 0 {2 two 3 one 4 four} + {UNIQUE constraint failed: t3.b} 0 {2 two 3 one 4 four} 10 "UPDATE OR IGNORE t3 SET b='four' WHERE a=3" {} 0 {2 two 3 one 4 four} @@ -310,7 +310,7 @@ foreach {tn sql error ac data } { {} 0 {2 two 3 four} 12 "UPDATE OR ROLLBACK t3 SET b='four'" - {column b is not unique} 1 {2 three 3 one 4 four} + {UNIQUE constraint failed: t3.b} 1 {2 three 3 one 4 four} } { do_catchsql_test e_update-1.8.$tn.1 $sql [list [expr {$error!=""}] $error] do_execsql_test e_update-1.8.$tn.2 {SELECT * FROM t3} [list {*}$data] diff --git a/test/errmsg.test b/test/errmsg.test index 6b3f3b7db6..8df8a704f4 100644 --- a/test/errmsg.test +++ b/test/errmsg.test @@ -78,14 +78,14 @@ do_test 2.2 { error_messages "INSERT INTO t1 VALUES('ghi', 'def')" } [list {*}{ SQLITE_ERROR {SQL logic error or missing database} - SQLITE_CONSTRAINT {column b is not unique} + SQLITE_CONSTRAINT {UNIQUE constraint failed: t1.b} }] verify_ex_errcode 2.2b SQLITE_CONSTRAINT_UNIQUE do_test 2.3 { error_messages_v2 "INSERT INTO t1 VALUES('ghi', 'def')" } [list {*}{ - SQLITE_CONSTRAINT {column b is not unique} - SQLITE_CONSTRAINT {column b is not unique} + SQLITE_CONSTRAINT {UNIQUE constraint failed: t1.b} + SQLITE_CONSTRAINT {UNIQUE constraint failed: t1.b} }] verify_ex_errcode 2.3b SQLITE_CONSTRAINT_UNIQUE diff --git a/test/fkey2.test b/test/fkey2.test index 3e5b27c1e6..4c8daa0b02 100644 --- a/test/fkey2.test +++ b/test/fkey2.test @@ -104,38 +104,38 @@ set FkeySimpleSchema { set FkeySimpleTests { - 1.1 "INSERT INTO t2 VALUES(1, 3)" {1 {foreign key constraint failed}} + 1.1 "INSERT INTO t2 VALUES(1, 3)" {1 {FOREIGN KEY constraint failed}} 1.2 "INSERT INTO t1 VALUES(1, 2)" {0 {}} 1.3 "INSERT INTO t2 VALUES(1, 3)" {0 {}} - 1.4 "INSERT INTO t2 VALUES(2, 4)" {1 {foreign key constraint failed}} + 1.4 "INSERT INTO t2 VALUES(2, 4)" {1 {FOREIGN KEY constraint failed}} 1.5 "INSERT INTO t2 VALUES(NULL, 4)" {0 {}} - 1.6 "UPDATE t2 SET c=2 WHERE d=4" {1 {foreign key constraint failed}} + 1.6 "UPDATE t2 SET c=2 WHERE d=4" {1 {FOREIGN KEY constraint failed}} 1.7 "UPDATE t2 SET c=1 WHERE d=4" {0 {}} 1.9 "UPDATE t2 SET c=1 WHERE d=4" {0 {}} 1.10 "UPDATE t2 SET c=NULL WHERE d=4" {0 {}} - 1.11 "DELETE FROM t1 WHERE a=1" {1 {foreign key constraint failed}} - 1.12 "UPDATE t1 SET a = 2" {1 {foreign key constraint failed}} + 1.11 "DELETE FROM t1 WHERE a=1" {1 {FOREIGN KEY constraint failed}} + 1.12 "UPDATE t1 SET a = 2" {1 {FOREIGN KEY constraint failed}} 1.13 "UPDATE t1 SET a = 1" {0 {}} - 2.1 "INSERT INTO t4 VALUES(1, 3)" {1 {foreign key constraint failed}} + 2.1 "INSERT INTO t4 VALUES(1, 3)" {1 {FOREIGN KEY constraint failed}} 2.2 "INSERT INTO t3 VALUES(1, 2)" {0 {}} 2.3 "INSERT INTO t4 VALUES(1, 3)" {0 {}} - 4.1 "INSERT INTO t8 VALUES(1, 3)" {1 {foreign key constraint failed}} + 4.1 "INSERT INTO t8 VALUES(1, 3)" {1 {FOREIGN KEY constraint failed}} 4.2 "INSERT INTO t7 VALUES(2, 1)" {0 {}} 4.3 "INSERT INTO t8 VALUES(1, 3)" {0 {}} - 4.4 "INSERT INTO t8 VALUES(2, 4)" {1 {foreign key constraint failed}} + 4.4 "INSERT INTO t8 VALUES(2, 4)" {1 {FOREIGN KEY constraint failed}} 4.5 "INSERT INTO t8 VALUES(NULL, 4)" {0 {}} - 4.6 "UPDATE t8 SET c=2 WHERE d=4" {1 {foreign key constraint failed}} + 4.6 "UPDATE t8 SET c=2 WHERE d=4" {1 {FOREIGN KEY constraint failed}} 4.7 "UPDATE t8 SET c=1 WHERE d=4" {0 {}} 4.9 "UPDATE t8 SET c=1 WHERE d=4" {0 {}} 4.10 "UPDATE t8 SET c=NULL WHERE d=4" {0 {}} - 4.11 "DELETE FROM t7 WHERE b=1" {1 {foreign key constraint failed}} - 4.12 "UPDATE t7 SET b = 2" {1 {foreign key constraint failed}} + 4.11 "DELETE FROM t7 WHERE b=1" {1 {FOREIGN KEY constraint failed}} + 4.12 "UPDATE t7 SET b = 2" {1 {FOREIGN KEY constraint failed}} 4.13 "UPDATE t7 SET b = 1" {0 {}} - 4.14 "INSERT INTO t8 VALUES('a', 'b')" {1 {foreign key constraint failed}} - 4.15 "UPDATE t7 SET b = 5" {1 {foreign key constraint failed}} - 4.16 "UPDATE t7 SET rowid = 5" {1 {foreign key constraint failed}} + 4.14 "INSERT INTO t8 VALUES('a', 'b')" {1 {FOREIGN KEY constraint failed}} + 4.15 "UPDATE t7 SET b = 5" {1 {FOREIGN KEY constraint failed}} + 4.16 "UPDATE t7 SET rowid = 5" {1 {FOREIGN KEY constraint failed}} 4.17 "UPDATE t7 SET a = 10" {0 {}} 5.1 "INSERT INTO t9 VALUES(1, 3)" {1 {no such table: main.nosuchtable}} @@ -215,7 +215,7 @@ do_test fkey2-1.5.1 { } {35.0 text} do_test fkey2-1.5.2 { catchsql { DELETE FROM i } -} {1 {foreign key constraint failed}} +} {1 {FOREIGN KEY constraint failed}} # Same test using a regular primary key with integer affinity. drop_all_tables @@ -231,7 +231,7 @@ do_test fkey2-1.6.1 { } {35.0 text 35 integer} do_test fkey2-1.6.2 { catchsql { DELETE FROM i } -} {1 {foreign key constraint failed}} +} {1 {FOREIGN KEY constraint failed}} # Use a collation sequence on the parent key. drop_all_tables @@ -243,7 +243,7 @@ do_test fkey2-1.7.1 { INSERT INTO j VALUES('sqlite'); } catchsql { DELETE FROM i } -} {1 {foreign key constraint failed}} +} {1 {FOREIGN KEY constraint failed}} # Use the parent key collation even if it is default and the child key # has an explicit value. @@ -255,7 +255,7 @@ do_test fkey2-1.7.2 { INSERT INTO i VALUES('SQLite'); } catchsql { INSERT INTO j VALUES('sqlite') } -} {1 {foreign key constraint failed}} +} {1 {FOREIGN KEY constraint failed}} do_test fkey2-1.7.3 { execsql { INSERT INTO i VALUES('sqlite'); @@ -263,7 +263,7 @@ do_test fkey2-1.7.3 { DELETE FROM i WHERE i = 'SQLite'; } catchsql { DELETE FROM i WHERE i = 'sqlite' } -} {1 {foreign key constraint failed}} +} {1 {FOREIGN KEY constraint failed}} #------------------------------------------------------------------------- # This section (test cases fkey2-2.*) contains tests to check that the @@ -271,7 +271,7 @@ do_test fkey2-1.7.3 { # proc fkey2-2-test {tn nocommit sql {res {}}} { if {$res eq "FKV"} { - set expected {1 {foreign key constraint failed}} + set expected {1 {FOREIGN KEY constraint failed}} } else { set expected [list 0 $res] } @@ -279,7 +279,7 @@ proc fkey2-2-test {tn nocommit sql {res {}}} { if {$nocommit} { do_test fkey2-2.${tn}c { catchsql COMMIT - } {1 {foreign key constraint failed}} + } {1 {FOREIGN KEY constraint failed}} } } @@ -375,7 +375,7 @@ fkey2-2-test 65 1 "INSERT INTO leaf VALUES('b', 2)" fkey2-2-test 66 1 "INSERT INTO leaf VALUES('c', 1)" do_test fkey2-2-test-67 { catchsql "INSERT INTO node SELECT parent, 3 FROM leaf" -} {1 {column nodeid is not unique}} +} {1 {UNIQUE constraint failed: node.nodeid}} fkey2-2-test 68 0 "COMMIT" FKV fkey2-2-test 69 1 "INSERT INTO node VALUES(1, NULL)" fkey2-2-test 70 0 "INSERT INTO node VALUES(2, NULL)" @@ -417,14 +417,14 @@ do_test fkey2-3.1.2 { } {} do_test fkey2-3.1.3 { catchsql { UPDATE ab SET a = 5 } -} {1 {constraint failed}} +} {1 {CHECK constraint failed: ef}} do_test fkey2-3.1.4 { execsql { SELECT * FROM ab } } {1 b} do_test fkey2-3.1.4 { execsql BEGIN; catchsql { UPDATE ab SET a = 5 } -} {1 {constraint failed}} +} {1 {CHECK constraint failed: ef}} do_test fkey2-3.1.5 { execsql COMMIT; execsql { SELECT * FROM ab; SELECT * FROM cd; SELECT * FROM ef } @@ -433,7 +433,7 @@ do_test fkey2-3.1.5 { do_test fkey2-3.2.1 { execsql BEGIN; catchsql { DELETE FROM ab } -} {1 {foreign key constraint failed}} +} {1 {FOREIGN KEY constraint failed}} do_test fkey2-3.2.2 { execsql COMMIT execsql { SELECT * FROM ab; SELECT * FROM cd; SELECT * FROM ef } @@ -555,7 +555,7 @@ do_test fkey2-7.1 { } {} do_test fkey2-7.2 { catchsql { INSERT INTO t2 VALUES(1, 'A'); } -} {1 {foreign key constraint failed}} +} {1 {FOREIGN KEY constraint failed}} do_test fkey2-7.3 { execsql { INSERT INTO t1 VALUES(1, 2); @@ -568,19 +568,19 @@ do_test fkey2-7.4 { } {} do_test fkey2-7.5 { catchsql { UPDATE t2 SET c = 3 } -} {1 {foreign key constraint failed}} +} {1 {FOREIGN KEY constraint failed}} do_test fkey2-7.6 { catchsql { DELETE FROM t1 WHERE a = 2 } -} {1 {foreign key constraint failed}} +} {1 {FOREIGN KEY constraint failed}} do_test fkey2-7.7 { execsql { DELETE FROM t1 WHERE a = 1 } } {} do_test fkey2-7.8 { catchsql { UPDATE t1 SET a = 3 } -} {1 {foreign key constraint failed}} +} {1 {FOREIGN KEY constraint failed}} do_test fkey2-7.9 { catchsql { UPDATE t2 SET rowid = 3 } -} {1 {foreign key constraint failed}} +} {1 {FOREIGN KEY constraint failed}} #------------------------------------------------------------------------- # Test that it is not possible to enable/disable FK support while a @@ -645,7 +645,7 @@ do_test fkey2-9.1.4 { } {2 two} do_test fkey2-9.1.5 { catchsql { DELETE FROM t1 } -} {1 {foreign key constraint failed}} +} {1 {FOREIGN KEY constraint failed}} do_test fkey2-9.2.1 { execsql { @@ -780,13 +780,13 @@ do_test fkey2-12.1.3 { } {} do_test fkey2-12.1.4 { catchsql "UPDATE t1 SET b = 'five' WHERE b = 'two'" -} {1 {foreign key constraint failed}} +} {1 {FOREIGN KEY constraint failed}} do_test fkey2-12.1.5 { execsql "DELETE FROM t1 WHERE b = 'two'" } {} do_test fkey2-12.1.6 { catchsql "COMMIT" -} {1 {foreign key constraint failed}} +} {1 {FOREIGN KEY constraint failed}} do_test fkey2-12.1.7 { execsql { INSERT INTO t1 VALUES(2, 'two'); @@ -828,7 +828,7 @@ do_test fkey2-12.2.3 { INSERT INTO t2 VALUES('b'); } catchsql { DELETE FROM t1 } -} {1 {foreign key constraint failed}} +} {1 {FOREIGN KEY constraint failed}} do_test fkey2-12.2.4 { execsql { SELECT * FROM t1; @@ -866,14 +866,14 @@ do_test fkey2-12.3.2 { } {no possibly} do_test fkey2-12.3.3 { catchsql { INSERT INTO down(c39, c38) VALUES('yes', 'no') } -} {1 {foreign key constraint failed}} +} {1 {FOREIGN KEY constraint failed}} do_test fkey2-12.3.4 { execsql { INSERT INTO up(c34, c35) VALUES('yes', 'no'); INSERT INTO down(c39, c38) VALUES('yes', 'no'); } catchsql { DELETE FROM up WHERE c34 = 'yes' } -} {1 {foreign key constraint failed}} +} {1 {FOREIGN KEY constraint failed}} do_test fkey2-12.3.5 { execsql { DELETE FROM up WHERE c34 = 'possibly'; @@ -901,7 +901,7 @@ foreach {tn stmt} { } { do_test fkey2-13.1.$tn.1 { catchsql $stmt - } {1 {foreign key constraint failed}} + } {1 {FOREIGN KEY constraint failed}} do_test fkey2-13.1.$tn.2 { execsql { SELECT * FROM pp; @@ -911,7 +911,7 @@ foreach {tn stmt} { do_test fkey2-13.1.$tn.3 { execsql BEGIN; catchsql $stmt - } {1 {foreign key constraint failed}} + } {1 {FOREIGN KEY constraint failed}} do_test fkey2-13.1.$tn.4 { execsql { COMMIT; @@ -1015,13 +1015,13 @@ ifcapable altertable { ] do_test fkey2-14.2.2.3 { catchsql { INSERT INTO t3 VALUES(1, 2, 3) } - } {1 {foreign key constraint failed}} + } {1 {FOREIGN KEY constraint failed}} do_test fkey2-14.2.2.4 { execsql { INSERT INTO t4 VALUES(1, NULL) } } {} do_test fkey2-14.2.2.5 { catchsql { UPDATE t4 SET b = 5 } - } {1 {foreign key constraint failed}} + } {1 {FOREIGN KEY constraint failed}} do_test fkey2-14.2.2.6 { catchsql { UPDATE t4 SET b = 1 } } {0 {}} @@ -1096,13 +1096,13 @@ ifcapable altertable { ] do_test fkey2-14.2tmp.2.3 { catchsql { INSERT INTO t3 VALUES(1, 2, 3) } - } {1 {foreign key constraint failed}} + } {1 {FOREIGN KEY constraint failed}} do_test fkey2-14.2tmp.2.4 { execsql { INSERT INTO t4 VALUES(1, NULL) } } {} do_test fkey2-14.2tmp.2.5 { catchsql { UPDATE t4 SET b = 5 } - } {1 {foreign key constraint failed}} + } {1 {FOREIGN KEY constraint failed}} do_test fkey2-14.2tmp.2.6 { catchsql { UPDATE t4 SET b = 1 } } {0 {}} @@ -1178,13 +1178,13 @@ ifcapable altertable { ] do_test fkey2-14.2aux.2.3 { catchsql { INSERT INTO t3 VALUES(1, 2, 3) } - } {1 {foreign key constraint failed}} + } {1 {FOREIGN KEY constraint failed}} do_test fkey2-14.2aux.2.4 { execsql { INSERT INTO t4 VALUES(1, NULL) } } {} do_test fkey2-14.2aux.2.5 { catchsql { UPDATE t4 SET b = 5 } - } {1 {foreign key constraint failed}} + } {1 {FOREIGN KEY constraint failed}} do_test fkey2-14.2aux.2.6 { catchsql { UPDATE t4 SET b = 1 } } {0 {}} @@ -1210,7 +1210,7 @@ do_test fkey-2.14.3.2 { } {} do_test fkey-2.14.3.3 { catchsql { DROP TABLE t1 } -} {1 {foreign key constraint failed}} +} {1 {FOREIGN KEY constraint failed}} do_test fkey-2.14.3.4 { execsql { DELETE FROM t2; @@ -1229,7 +1229,7 @@ do_test fkey-2.14.3.5 { } {} do_test fkey-2.14.3.6 { catchsql { DROP TABLE t1 } -} {1 {foreign key constraint failed}} +} {1 {FOREIGN KEY constraint failed}} do_test fkey-2.14.3.7 { execsql { DROP TABLE t2; @@ -1387,15 +1387,15 @@ foreach {tn zSchema} { do_test fkey2-16.1.$tn.3 { catchsql { UPDATE self SET b = 15 } - } {1 {foreign key constraint failed}} + } {1 {FOREIGN KEY constraint failed}} do_test fkey2-16.1.$tn.4 { catchsql { UPDATE self SET a = 15 } - } {1 {foreign key constraint failed}} + } {1 {FOREIGN KEY constraint failed}} do_test fkey2-16.1.$tn.5 { catchsql { UPDATE self SET a = 15, b = 16 } - } {1 {foreign key constraint failed}} + } {1 {FOREIGN KEY constraint failed}} do_test fkey2-16.1.$tn.6 { catchsql { UPDATE self SET a = 17, b = 17 } @@ -1406,7 +1406,7 @@ foreach {tn zSchema} { } {} do_test fkey2-16.1.$tn.8 { catchsql { INSERT INTO self VALUES(20, 21) } - } {1 {foreign key constraint failed}} + } {1 {FOREIGN KEY constraint failed}} } #------------------------------------------------------------------------- @@ -1463,7 +1463,7 @@ do_test fkey2-17.1.6 { INSERT INTO one VALUES(0, 0, 0); UPDATE two SET e=e+1, f=f+1; } -} {1 {foreign key constraint failed}} +} {1 {FOREIGN KEY constraint failed}} do_test fkey2-17.1.7 { execsql { SELECT * FROM one } } {1 2 3 2 3 4 3 4 5 0 0 0} @@ -1619,7 +1619,7 @@ ifcapable auth { } do_test fkey2-18.8 { catchsql { INSERT INTO short VALUES(1, 3, 2) } - } {1 {foreign key constraint failed}} + } {1 {FOREIGN KEY constraint failed}} do_test fkey2-18.9 { execsql { INSERT INTO short VALUES(1, 3, NULL) } } {} @@ -1628,7 +1628,7 @@ ifcapable auth { } {1 3 2 1 3 {}} do_test fkey2-18.11 { catchsql { UPDATE short SET f = 2 WHERE f IS NULL } - } {1 {foreign key constraint failed}} + } {1 {FOREIGN KEY constraint failed}} db auth {} unset authargs @@ -1680,7 +1680,7 @@ foreach {tn insert} { } { do_test fkey2-20.2.$tn.1 { catchsql "$insert INTO cc VALUES(1, 2)" - } {1 {foreign key constraint failed}} + } {1 {FOREIGN KEY constraint failed}} do_test fkey2-20.2.$tn.2 { execsql { SELECT * FROM cc } } {} @@ -1691,7 +1691,7 @@ foreach {tn insert} { INSERT INTO cc VALUES(1, 2); } catchsql "$insert INTO cc VALUES(3, 4)" - } {1 {foreign key constraint failed}} + } {1 {FOREIGN KEY constraint failed}} do_test fkey2-20.2.$tn.4 { execsql { COMMIT ; SELECT * FROM cc } } {1 2} @@ -1716,13 +1716,13 @@ foreach {tn update} { } {} do_test fkey2-20.3.$tn.2 { catchsql "$update pp SET a = 1" - } {1 {foreign key constraint failed}} + } {1 {FOREIGN KEY constraint failed}} do_test fkey2-20.3.$tn.3 { execsql { SELECT * FROM pp } } {2 two} do_test fkey2-20.3.$tn.4 { catchsql "$update cc SET d = 1" - } {1 {foreign key constraint failed}} + } {1 {FOREIGN KEY constraint failed}} do_test fkey2-20.3.$tn.5 { execsql { SELECT * FROM cc } } {1 2} @@ -1732,7 +1732,7 @@ foreach {tn update} { INSERT INTO pp VALUES(3, 'three'); } catchsql "$update pp SET a = 1 WHERE a = 2" - } {1 {foreign key constraint failed}} + } {1 {FOREIGN KEY constraint failed}} do_test fkey2-20.3.$tn.7 { execsql { COMMIT ; SELECT * FROM pp } } {2 two 3 three} @@ -1742,7 +1742,7 @@ foreach {tn update} { INSERT INTO cc VALUES(2, 2); } catchsql "$update cc SET d = 1 WHERE c = 1" - } {1 {foreign key constraint failed}} + } {1 {FOREIGN KEY constraint failed}} do_test fkey2-20.3.$tn.9 { execsql { COMMIT ; SELECT * FROM cc } } {1 2 2 2} @@ -1768,7 +1768,7 @@ do_test fkey2-genfkey.1.1 { } {} do_test fkey2-genfkey.1.2 { catchsql { INSERT INTO t2 VALUES(1, 2) } -} {1 {foreign key constraint failed}} +} {1 {FOREIGN KEY constraint failed}} do_test fkey2-genfkey.1.3 { execsql { INSERT INTO t1 VALUES(1, 2, 3); @@ -1780,7 +1780,7 @@ do_test fkey2-genfkey.1.4 { } {} do_test fkey2-genfkey.1.5 { catchsql { UPDATE t2 SET e = 5 WHERE e IS NULL } -} {1 {foreign key constraint failed}} +} {1 {FOREIGN KEY constraint failed}} do_test fkey2-genfkey.1.6 { execsql { UPDATE t2 SET e = 1 WHERE e IS NULL } } {} @@ -1789,13 +1789,13 @@ do_test fkey2-genfkey.1.7 { } {} do_test fkey2-genfkey.1.8 { catchsql { UPDATE t1 SET a = 10 } -} {1 {foreign key constraint failed}} +} {1 {FOREIGN KEY constraint failed}} do_test fkey2-genfkey.1.9 { catchsql { UPDATE t1 SET a = NULL } } {1 {datatype mismatch}} do_test fkey2-genfkey.1.10 { catchsql { DELETE FROM t1 } -} {1 {foreign key constraint failed}} +} {1 {FOREIGN KEY constraint failed}} do_test fkey2-genfkey.1.11 { execsql { UPDATE t2 SET e = NULL } } {} @@ -1815,7 +1815,7 @@ do_test fkey2-genfkey.1.13 { } {} do_test fkey2-genfkey.1.14 { catchsql { INSERT INTO t3 VALUES(3, 1, 4) } -} {1 {foreign key constraint failed}} +} {1 {FOREIGN KEY constraint failed}} do_test fkey2-genfkey.1.15 { execsql { INSERT INTO t1 VALUES(1, 1, 4); @@ -1824,16 +1824,16 @@ do_test fkey2-genfkey.1.15 { } {} do_test fkey2-genfkey.1.16 { catchsql { DELETE FROM t1 } -} {1 {foreign key constraint failed}} +} {1 {FOREIGN KEY constraint failed}} do_test fkey2-genfkey.1.17 { catchsql { UPDATE t1 SET b = 10} -} {1 {foreign key constraint failed}} +} {1 {FOREIGN KEY constraint failed}} do_test fkey2-genfkey.1.18 { execsql { UPDATE t1 SET a = 10} } {} do_test fkey2-genfkey.1.19 { catchsql { UPDATE t3 SET h = 'hello' WHERE i = 3} -} {1 {foreign key constraint failed}} +} {1 {FOREIGN KEY constraint failed}} drop_all_tables do_test fkey2-genfkey.2.1 { @@ -1946,7 +1946,7 @@ do_test fkey2-dd08e5.1.2 { catchsql { DELETE FROM tdd08; } -} {1 {foreign key constraint failed}} +} {1 {FOREIGN KEY constraint failed}} do_test fkey2-dd08e5.1.3 { execsql { SELECT * FROM tdd08; @@ -1956,17 +1956,17 @@ do_test fkey2-dd08e5.1.4 { catchsql { INSERT INTO tdd08_b VALUES(400,500,300); } -} {1 {foreign key constraint failed}} +} {1 {FOREIGN KEY constraint failed}} do_test fkey2-dd08e5.1.5 { catchsql { UPDATE tdd08_b SET x=x+1; } -} {1 {foreign key constraint failed}} +} {1 {FOREIGN KEY constraint failed}} do_test fkey2-dd08e5.1.6 { catchsql { UPDATE tdd08 SET a=a+1; } -} {1 {foreign key constraint failed}} +} {1 {FOREIGN KEY constraint failed}} #------------------------------------------------------------------------- # Verify that ticket ce7c133ea6cc9ccdc1a60d80441f80b6180f5eba @@ -1987,12 +1987,12 @@ do_test fkey2-ce7c13.1.2 { catchsql { UPDATE tce71 set b = 201 where a = 100; } -} {1 {foreign key constraint failed}} +} {1 {FOREIGN KEY constraint failed}} do_test fkey2-ce7c13.1.3 { catchsql { UPDATE tce71 set a = 101 where a = 100; } -} {1 {foreign key constraint failed}} +} {1 {FOREIGN KEY constraint failed}} do_test fkey2-ce7c13.1.4 { execsql { CREATE TABLE tce73(a INTEGER PRIMARY KEY, b, UNIQUE(a,b)); @@ -2007,11 +2007,11 @@ do_test fkey2-ce7c13.1.5 { catchsql { UPDATE tce73 set b = 201 where a = 100; } -} {1 {foreign key constraint failed}} +} {1 {FOREIGN KEY constraint failed}} do_test fkey2-ce7c13.1.6 { catchsql { UPDATE tce73 set a = 101 where a = 100; } -} {1 {foreign key constraint failed}} +} {1 {FOREIGN KEY constraint failed}} finish_test diff --git a/test/fkey3.test b/test/fkey3.test index 6a11f8883e..a8d0382020 100644 --- a/test/fkey3.test +++ b/test/fkey3.test @@ -43,13 +43,13 @@ do_test fkey3-1.2 { catchsql { DELETE FROM t1 WHERE x=100; } -} {1 {foreign key constraint failed}} +} {1 {FOREIGN KEY constraint failed}} do_test fkey3-1.3 { catchsql { DROP TABLE t1; } -} {1 {foreign key constraint failed}} +} {1 {FOREIGN KEY constraint failed}} do_test fkey3-1.4 { execsql { @@ -95,17 +95,17 @@ do_execsql_test 3.1.1 { } {} do_catchsql_test 3.1.2 { INSERT INTO t3 VALUES(NULL, 2, 5, 2); -} {1 {foreign key constraint failed}} +} {1 {FOREIGN KEY constraint failed}} do_catchsql_test 3.1.3 { INSERT INTO t3 VALUES(NULL, 3, 5, 2); -} {1 {foreign key constraint failed}} +} {1 {FOREIGN KEY constraint failed}} do_execsql_test 3.2.1 { CREATE TABLE t4(a UNIQUE, b REFERENCES t4(a)); } do_catchsql_test 3.2.2 { INSERT INTO t4 VALUES(NULL, 1); -} {1 {foreign key constraint failed}} +} {1 {FOREIGN KEY constraint failed}} do_execsql_test 3.3.1 { CREATE TABLE t5(a INTEGER PRIMARY KEY, b REFERENCES t5(a)); @@ -113,7 +113,7 @@ do_execsql_test 3.3.1 { } {} do_catchsql_test 3.3.2 { INSERT INTO t5 VALUES(NULL, 3); -} {1 {foreign key constraint failed}} +} {1 {FOREIGN KEY constraint failed}} do_execsql_test 3.4.1 { CREATE TABLE t6(a INTEGER PRIMARY KEY, b, c, d, @@ -127,7 +127,7 @@ do_execsql_test 3.4.4 { INSERT INTO t6 VALUES(NULL, 'a', 1, 'a'); } {} do_execsql_test 3.4.5 { INSERT INTO t6 VALUES(5, 'a', 2, 'a'); } {} do_catchsql_test 3.4.6 { INSERT INTO t6 VALUES(NULL, 'a', 65, 'a'); -} {1 {foreign key constraint failed}} +} {1 {FOREIGN KEY constraint failed}} do_execsql_test 3.4.7 { INSERT INTO t6 VALUES(100, 'one', 100, 'one'); @@ -149,10 +149,10 @@ do_execsql_test 3.5.2 { INSERT INTO t7 VALUES('x', 1, 'x', NULL) } {} do_execsql_test 3.5.3 { INSERT INTO t7 VALUES('x', 2, 'x', 2) } {} do_catchsql_test 3.5.4 { INSERT INTO t7 VALUES('x', 450, 'x', NULL); -} {1 {foreign key constraint failed}} +} {1 {FOREIGN KEY constraint failed}} do_catchsql_test 3.5.5 { INSERT INTO t7 VALUES('x', 450, 'x', 451); -} {1 {foreign key constraint failed}} +} {1 {FOREIGN KEY constraint failed}} do_execsql_test 3.6.1 { @@ -163,7 +163,7 @@ do_execsql_test 3.6.1 { } do_catchsql_test 3.6.2 { UPDATE t8 SET d = 2; -} {1 {foreign key constraint failed}} +} {1 {FOREIGN KEY constraint failed}} do_execsql_test 3.6.3 { UPDATE t8 SET d = 1; } do_execsql_test 3.6.4 { UPDATE t8 SET e = 2; } @@ -181,6 +181,6 @@ do_catchsql_test 3.6.5 { INSERT INTO TestTable VALUES (1, 'parent', 1, null); INSERT INTO TestTable VALUES (2, 'child', 1, 1); UPDATE TestTable SET parent_id=1000 where id=2; -} {1 {foreign key constraint failed}} +} {1 {FOREIGN KEY constraint failed}} finish_test diff --git a/test/fkey6.test b/test/fkey6.test index f14e15d2d8..7c24704e03 100644 --- a/test/fkey6.test +++ b/test/fkey6.test @@ -47,7 +47,7 @@ do_execsql_test fkey6-1.1 { } {} do_test fkey6-1.2 { catchsql {DELETE FROM t1 WHERE x=2;} -} {1 {foreign key constraint failed}} +} {1 {FOREIGN KEY constraint failed}} do_test fkey6-1.3 { sqlite3_db_status db DBSTATUS_DEFERRED_FKS 0 } {0 0 0} @@ -99,7 +99,7 @@ do_execsql_test fkey6-1.10.1 { } {1 0 1 0} do_test fkey6-1.10.2 { catchsql {DELETE FROM t1 WHERE x=3} -} {1 {foreign key constraint failed}} +} {1 {FOREIGN KEY constraint failed}} db eval {ROLLBACK} do_test fkey6-1.20 { @@ -173,4 +173,3 @@ do_execsql_test fkey6-2.6 { finish_test - diff --git a/test/fts3expr.test b/test/fts3expr.test index e7c4f65598..192219f142 100644 --- a/test/fts3expr.test +++ b/test/fts3expr.test @@ -28,6 +28,7 @@ set sqlite_fts3_enable_parentheses 1 proc test_fts3expr {expr} { db one {SELECT fts3_exprtest('simple', $expr, 'a', 'b', 'c')} } + do_test fts3expr-1.0 { test_fts3expr "abcd" } {PHRASE 3 0 abcd} @@ -495,5 +496,17 @@ do_test fts3expr-7.1 { } {} +do_test fts3expr-8.0 { test_fts3expr "(blah)" } {PHRASE 3 0 blah} +do_test fts3expr-8.1 { test_fts3expr "(blah.)" } {PHRASE 3 0 blah} +do_test fts3expr-8.2 { test_fts3expr "(blah,)" } {PHRASE 3 0 blah} +do_test fts3expr-8.3 { test_fts3expr "(blah!)" } {PHRASE 3 0 blah} +do_test fts3expr-8.4 { test_fts3expr "(blah-)" } {PHRASE 3 0 blah} + +do_test fts3expr-8.5 { test_fts3expr "((blah.))" } {PHRASE 3 0 blah} +do_test fts3expr-8.6 { test_fts3expr "(((blah,)))" } {PHRASE 3 0 blah} +do_test fts3expr-8.7 { test_fts3expr "((((blah!))))" } {PHRASE 3 0 blah} + +do_test fts3expr-8.8 { test_fts3expr "(,(blah-),)" } {PHRASE 3 0 blah} + set sqlite_fts3_enable_parentheses 0 finish_test diff --git a/test/func4.test b/test/func4.test index 34a8be8840..e94f8c3418 100644 --- a/test/func4.test +++ b/test/func4.test @@ -381,32 +381,32 @@ ifcapable check { catchsql { INSERT INTO t1 (x) VALUES (NULL); } - } {1 {constraint failed}} + } {1 {CHECK constraint failed: t1}} do_test func4-3.3 { catchsql { INSERT INTO t1 (x) VALUES (NULL); } - } {1 {constraint failed}} + } {1 {CHECK constraint failed: t1}} do_test func4-3.4 { catchsql { INSERT INTO t1 (x) VALUES (''); } - } {1 {constraint failed}} + } {1 {CHECK constraint failed: t1}} do_test func4-3.5 { catchsql { INSERT INTO t1 (x) VALUES ('bad'); } - } {1 {constraint failed}} + } {1 {CHECK constraint failed: t1}} do_test func4-3.6 { catchsql { INSERT INTO t1 (x) VALUES ('1234bad'); } - } {1 {constraint failed}} + } {1 {CHECK constraint failed: t1}} do_test func4-3.7 { catchsql { INSERT INTO t1 (x) VALUES ('1234.56bad'); } - } {1 {constraint failed}} + } {1 {CHECK constraint failed: t1}} do_test func4-3.8 { catchsql { INSERT INTO t1 (x) VALUES (1234); @@ -416,7 +416,7 @@ ifcapable check { catchsql { INSERT INTO t1 (x) VALUES (1234.56); } - } {1 {constraint failed}} + } {1 {CHECK constraint failed: t1}} do_test func4-3.10 { catchsql { INSERT INTO t1 (x) VALUES ('1234'); @@ -426,32 +426,32 @@ ifcapable check { catchsql { INSERT INTO t1 (x) VALUES ('1234.56'); } - } {1 {constraint failed}} + } {1 {CHECK constraint failed: t1}} do_test func4-3.12 { catchsql { INSERT INTO t1 (x) VALUES (ZEROBLOB(4)); } - } {1 {constraint failed}} + } {1 {CHECK constraint failed: t1}} do_test func4-3.13 { catchsql { INSERT INTO t1 (x) VALUES (X''); } - } {1 {constraint failed}} + } {1 {CHECK constraint failed: t1}} do_test func4-3.14 { catchsql { INSERT INTO t1 (x) VALUES (X'1234'); } - } {1 {constraint failed}} + } {1 {CHECK constraint failed: t1}} do_test func4-3.15 { catchsql { INSERT INTO t1 (x) VALUES (X'12345678'); } - } {1 {constraint failed}} + } {1 {CHECK constraint failed: t1}} do_test func4-3.16 { catchsql { INSERT INTO t1 (x) VALUES ('1234.00'); } - } {1 {constraint failed}} + } {1 {CHECK constraint failed: t1}} do_test func4-3.17 { catchsql { INSERT INTO t1 (x) VALUES (1234.00); @@ -461,13 +461,13 @@ ifcapable check { catchsql { INSERT INTO t1 (x) VALUES ('-9223372036854775809'); } - } {1 {constraint failed}} + } {1 {CHECK constraint failed: t1}} if {$highPrecision(1)} { do_test func4-3.19 { catchsql { INSERT INTO t1 (x) VALUES (9223372036854775808); } - } {1 {constraint failed}} + } {1 {CHECK constraint failed: t1}} } do_execsql_test func4-3.20 { SELECT x FROM t1 ORDER BY x; @@ -483,32 +483,32 @@ ifcapable check { catchsql { INSERT INTO t2 (x) VALUES (NULL); } - } {1 {constraint failed}} + } {1 {CHECK constraint failed: t2}} do_test func4-4.3 { catchsql { INSERT INTO t2 (x) VALUES (NULL); } - } {1 {constraint failed}} + } {1 {CHECK constraint failed: t2}} do_test func4-4.4 { catchsql { INSERT INTO t2 (x) VALUES (''); } - } {1 {constraint failed}} + } {1 {CHECK constraint failed: t2}} do_test func4-4.5 { catchsql { INSERT INTO t2 (x) VALUES ('bad'); } - } {1 {constraint failed}} + } {1 {CHECK constraint failed: t2}} do_test func4-4.6 { catchsql { INSERT INTO t2 (x) VALUES ('1234bad'); } - } {1 {constraint failed}} + } {1 {CHECK constraint failed: t2}} do_test func4-4.7 { catchsql { INSERT INTO t2 (x) VALUES ('1234.56bad'); } - } {1 {constraint failed}} + } {1 {CHECK constraint failed: t2}} do_test func4-4.8 { catchsql { INSERT INTO t2 (x) VALUES (1234); @@ -533,22 +533,22 @@ ifcapable check { catchsql { INSERT INTO t2 (x) VALUES (ZEROBLOB(4)); } - } {1 {constraint failed}} + } {1 {CHECK constraint failed: t2}} do_test func4-4.13 { catchsql { INSERT INTO t2 (x) VALUES (X''); } - } {1 {constraint failed}} + } {1 {CHECK constraint failed: t2}} do_test func4-4.14 { catchsql { INSERT INTO t2 (x) VALUES (X'1234'); } - } {1 {constraint failed}} + } {1 {CHECK constraint failed: t2}} do_test func4-4.15 { catchsql { INSERT INTO t2 (x) VALUES (X'12345678'); } - } {1 {constraint failed}} + } {1 {CHECK constraint failed: t2}} do_execsql_test func4-4.16 { SELECT x FROM t2 ORDER BY x; } {1234.0 1234.0 1234.56 1234.56} diff --git a/test/in.test b/test/in.test index 3b23f04bbf..515e598c12 100644 --- a/test/in.test +++ b/test/in.test @@ -332,7 +332,7 @@ do_test in-10.2 { catchsql { INSERT INTO t5 VALUES(4); } -} {1 {constraint failed}} +} {1 {CHECK constraint failed: t5}} # Ticket #1821 # diff --git a/test/incrblob2.test b/test/incrblob2.test index 9046de2781..a8f40f09dc 100644 --- a/test/incrblob2.test +++ b/test/incrblob2.test @@ -397,16 +397,16 @@ do_test incrblob2-8.4 { } {cccccccccccccccccccc} do_test incrblob2-8.5 { catchsql {UPDATE t3 SET a = 6 WHERE a > 3} -} {1 {column a is not unique}} +} {1 {UNIQUE constraint failed: t3.a}} do_test incrblob2-8.6 { catchsql {UPDATE t3 SET a = 6 WHERE a > 3} -} {1 {column a is not unique}} +} {1 {UNIQUE constraint failed: t3.a}} do_test incrblob2-8.7 { sqlite3_blob_read $h 0 20 } {cccccccccccccccccccc} do_test incrblob2-8.8 { catchsql {UPDATE t3 SET a = 6 WHERE a = 3 OR a = 5} -} {1 {column a is not unique}} +} {1 {UNIQUE constraint failed: t3.a}} do_test incrblob2-8.9 { set rc [catch {sqlite3_blob_read $h 0 20} msg] list $rc $msg diff --git a/test/index.test b/test/index.test index 2b95bad830..59c0ea6f90 100644 --- a/test/index.test +++ b/test/index.test @@ -666,7 +666,7 @@ ifcapable conflict { BEGIN; INSERT INTO t7 VALUES(1); } - } {1 {column a is not unique}} + } {1 {UNIQUE constraint failed: t7.a}} do_test index-19.3 { catchsql { BEGIN; @@ -676,7 +676,7 @@ ifcapable conflict { catchsql { INSERT INTO t8 VALUES(1); } - } {1 {column a is not unique}} + } {1 {UNIQUE constraint failed: t8.a}} do_test index-19.5 { catchsql { BEGIN; diff --git a/test/index3.test b/test/index3.test index 161ddecc01..a9f9b7ae6f 100644 --- a/test/index3.test +++ b/test/index3.test @@ -34,7 +34,7 @@ do_test index3-1.2 { BEGIN; CREATE UNIQUE INDEX i1 ON t1(a); } -} {1 {indexed columns are not unique}} +} {1 {UNIQUE constraint failed: t1.a}} do_test index3-1.3 { catchsql COMMIT; } {0 {}} diff --git a/test/index4.test b/test/index4.test index 018ed744a1..4fbfa5291b 100644 --- a/test/index4.test +++ b/test/index4.test @@ -120,7 +120,7 @@ do_execsql_test 2.1 { } do_catchsql_test 2.2 { CREATE UNIQUE INDEX i3 ON t2(x); -} {1 {indexed columns are not unique}} +} {1 {UNIQUE constraint failed: t2.x}} finish_test diff --git a/test/index6.test b/test/index6.test index c427dc3df3..48706be3cc 100644 --- a/test/index6.test +++ b/test/index6.test @@ -220,7 +220,7 @@ do_test index6-3.2 { catchsql { INSERT INTO t3(a,b) VALUES(150, 'test1'); } -} {1 {column a is not unique}} +} {1 {UNIQUE constraint failed: t3.a}} do_test index6-3.3 { # can insert multiple rows with a==999 because such rows are not # part of the unique index. diff --git a/test/index7.test b/test/index7.test new file mode 100644 index 0000000000..1c81f6024b --- /dev/null +++ b/test/index7.test @@ -0,0 +1,251 @@ +# 2013-11-04 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# Test cases for partial indices in WITHOUT ROWID tables +# + + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +ifcapable !vtab { + finish_test + return +} + +load_static_extension db wholenumber; +do_test index7-1.1 { + # Able to parse and manage partial indices + execsql { + CREATE TABLE t1(a,b,c PRIMARY KEY) WITHOUT rowid; + CREATE INDEX t1a ON t1(a) WHERE a IS NOT NULL; + CREATE INDEX t1b ON t1(b) WHERE b>10; + CREATE VIRTUAL TABLE nums USING wholenumber; + INSERT INTO t1(a,b,c) + SELECT CASE WHEN value%3!=0 THEN value END, value, value + FROM nums WHERE value<=20; + SELECT count(a), count(b) FROM t1; + PRAGMA integrity_check; + } +} {14 20 ok} + +# Make sure the count(*) optimization works correctly with +# partial indices. Ticket [a5c8ed66cae16243be6] 2013-10-03. +# +do_execsql_test index7-1.1.1 { + SELECT count(*) FROM t1; +} {20} + +# Error conditions during parsing... +# +do_test index7-1.2 { + catchsql { + CREATE INDEX bad1 ON t1(a,b) WHERE x IS NOT NULL; + } +} {1 {no such column: x}} +do_test index7-1.3 { + catchsql { + CREATE INDEX bad1 ON t1(a,b) WHERE EXISTS(SELECT * FROM t1); + } +} {1 {subqueries prohibited in partial index WHERE clauses}} +do_test index7-1.4 { + catchsql { + CREATE INDEX bad1 ON t1(a,b) WHERE a!=?1; + } +} {1 {parameters prohibited in partial index WHERE clauses}} +do_test index7-1.5 { + catchsql { + CREATE INDEX bad1 ON t1(a,b) WHERE a!=random(); + } +} {1 {functions prohibited in partial index WHERE clauses}} +do_test index7-1.6 { + catchsql { + CREATE INDEX bad1 ON t1(a,b) WHERE a NOT LIKE 'abc%'; + } +} {1 {functions prohibited in partial index WHERE clauses}} + +do_test index7-1.10 { + execsql { + ANALYZE; + SELECT idx, stat FROM sqlite_stat1 ORDER BY idx; + PRAGMA integrity_check; + } +} {t1 {20 1} t1a {14 1} t1b {10 1} ok} + +# STAT1 shows the partial indices have a reduced number of +# rows. +# +do_test index7-1.11 { + execsql { + UPDATE t1 SET a=b; + ANALYZE; + SELECT idx, stat FROM sqlite_stat1 ORDER BY idx; + PRAGMA integrity_check; + } +} {t1 {20 1} t1a {20 1} t1b {10 1} ok} + +do_test index7-1.11b { + execsql { + UPDATE t1 SET a=NULL WHERE b%3!=0; + UPDATE t1 SET b=b+100; + ANALYZE; + SELECT idx, stat FROM sqlite_stat1 ORDER BY idx; + PRAGMA integrity_check; + } +} {t1 {20 1} t1a {6 1} t1b {20 1} ok} + +do_test index7-1.12 { + execsql { + UPDATE t1 SET a=CASE WHEN b%3!=0 THEN b END; + UPDATE t1 SET b=b-100; + ANALYZE; + SELECT idx, stat FROM sqlite_stat1 ORDER BY idx; + PRAGMA integrity_check; + } +} {t1 {20 1} t1a {13 1} t1b {10 1} ok} + +do_test index7-1.13 { + execsql { + DELETE FROM t1 WHERE b BETWEEN 8 AND 12; + ANALYZE; + SELECT idx, stat FROM sqlite_stat1 ORDER BY idx; + PRAGMA integrity_check; + } +} {t1 {15 1} t1a {10 1} t1b {8 1} ok} + +do_test index7-1.14 { + execsql { + REINDEX; + ANALYZE; + SELECT idx, stat FROM sqlite_stat1 ORDER BY idx; + PRAGMA integrity_check; + } +} {t1 {15 1} t1a {10 1} t1b {8 1} ok} + +do_test index7-1.15 { + execsql { + CREATE INDEX t1c ON t1(c); + ANALYZE; + SELECT idx, stat FROM sqlite_stat1 ORDER BY idx; + PRAGMA integrity_check; + } +} {t1 {15 1} t1a {10 1} t1b {8 1} t1c {15 1} ok} + +# Queries use partial indices as appropriate times. +# +do_test index7-2.1 { + execsql { + CREATE TABLE t2(a,b PRIMARY KEY) without rowid; + INSERT INTO t2(a,b) SELECT value, value FROM nums WHERE value<1000; + UPDATE t2 SET a=NULL WHERE b%5==0; + CREATE INDEX t2a1 ON t2(a) WHERE a IS NOT NULL; + SELECT count(*) FROM t2 WHERE a IS NOT NULL; + } +} {800} +do_test index7-2.2 { + execsql { + EXPLAIN QUERY PLAN + SELECT * FROM t2 WHERE a=5; + } +} {/.* TABLE t2 USING COVERING INDEX t2a1 .*/} +ifcapable stat4||stat3 { + do_test index7-2.3stat4 { + execsql { + EXPLAIN QUERY PLAN + SELECT * FROM t2 WHERE a IS NOT NULL; + } + } {/.* TABLE t2 USING COVERING INDEX t2a1 .*/} +} else { + do_test index7-2.3stat4 { + execsql { + EXPLAIN QUERY PLAN + SELECT * FROM t2 WHERE a IS NOT NULL AND a>0; + } + } {/.* TABLE t2 USING COVERING INDEX t2a1 .*/} +} +do_test index7-2.4 { + execsql { + EXPLAIN QUERY PLAN + SELECT * FROM t2 WHERE a IS NULL; + } +} {~/.*INDEX t2a1.*/} + +do_execsql_test index7-2.101 { + DROP INDEX t2a1; + UPDATE t2 SET a=b, b=b+10000; + SELECT b FROM t2 WHERE a=15; +} {10015} +do_execsql_test index7-2.102 { + CREATE INDEX t2a2 ON t2(a) WHERE a<100 OR a>200; + SELECT b FROM t2 WHERE a=15; + PRAGMA integrity_check; +} {10015 ok} +do_execsql_test index7-2.102eqp { + EXPLAIN QUERY PLAN + SELECT b FROM t2 WHERE a=15; +} {~/.*INDEX t2a2.*/} +do_execsql_test index7-2.103 { + SELECT b FROM t2 WHERE a=15 AND a<100; +} {10015} +do_execsql_test index7-2.103eqp { + EXPLAIN QUERY PLAN + SELECT b FROM t2 WHERE a=15 AND a<100; +} {/.*INDEX t2a2.*/} +do_execsql_test index7-2.104 { + SELECT b FROM t2 WHERE a=515 AND a>200; +} {10515} +do_execsql_test index7-2.104eqp { + EXPLAIN QUERY PLAN + SELECT b FROM t2 WHERE a=515 AND a>200; +} {/.*INDEX t2a2.*/} + +# Partial UNIQUE indices +# +do_execsql_test index7-3.1 { + CREATE TABLE t3(a,b PRIMARY KEY) without rowid; + INSERT INTO t3 SELECT value, value FROM nums WHERE value<200; + UPDATE t3 SET a=999 WHERE b%5!=0; + CREATE UNIQUE INDEX t3a ON t3(a) WHERE a<>999; +} {} +do_test index7-3.2 { + # unable to insert a duplicate row a-value that is not 999. + catchsql { + INSERT INTO t3(a,b) VALUES(150, 'test1'); + } +} {1 {UNIQUE constraint failed: t3.a}} +do_test index7-3.3 { + # can insert multiple rows with a==999 because such rows are not + # part of the unique index. + catchsql { + INSERT INTO t3(a,b) VALUES(999, 'test1'), (999, 'test2'); + } +} {0 {}} +do_execsql_test index7-3.4 { + SELECT count(*) FROM t3 WHERE a=999; +} {162} +integrity_check index7-3.5 + +do_execsql_test index7-4.0 { + VACUUM; + PRAGMA integrity_check; +} {ok} + +# Silently ignore database name qualifiers in partial indices. +# +do_execsql_test index7-5.0 { + CREATE INDEX t3b ON t3(b) WHERE xyzzy.t3.b BETWEEN 5 AND 10; + /* ^^^^^-- ignored */ + ANALYZE; + SELECT count(*) FROM t3 WHERE t3.b BETWEEN 5 AND 10; + SELECT stat+0 FROM sqlite_stat1 WHERE idx='t3b'; +} {6 6} + +finish_test diff --git a/test/insert4.test b/test/insert4.test index f4a45c182c..343a08af81 100644 --- a/test/insert4.test +++ b/test/insert4.test @@ -54,7 +54,7 @@ do_test insert4-1.1 { catchsql { INSERT INTO t1 SELECT * FROM t2; } -} {1 {constraint failed}} +} {1 {CHECK constraint failed: t1}} xferopt_test insert4-1.2 0 do_test insert4-1.3 { execsql { @@ -101,7 +101,7 @@ do_test insert4-2.3.3 { INSERT INTO t1 SELECT * FROM t2 LIMIT 1; SELECT * FROM t1; } -} {1 {constraint failed}} +} {1 {CHECK constraint failed: t1}} xferopt_test insert4-2.3.4 0 # Do not run the transfer optimization if there is a DISTINCT @@ -119,7 +119,7 @@ do_test insert4-2.4.3 { DELETE FROM t1; INSERT INTO t1 SELECT DISTINCT * FROM t2; } -} {1 {constraint failed}} +} {1 {CHECK constraint failed: t1}} xferopt_test insert4-2.4.4 0 # The following procedure constructs two tables then tries to transfer @@ -315,7 +315,7 @@ do_test insert4-6.6 { catchsql { INSERT INTO t6b SELECT * FROM t6a; } -} {1 {constraint failed}} +} {1 {CHECK constraint failed: t6b}} do_test insert4-6.7 { execsql { DROP TABLE t6b; @@ -324,7 +324,7 @@ do_test insert4-6.7 { catchsql { INSERT INTO t6b SELECT * FROM t6a; } -} {1 {constraint failed}} +} {1 {CHECK constraint failed: t6b}} # Ticket [6284df89debdfa61db8073e062908af0c9b6118e] # Disable the xfer optimization if the destination table contains @@ -353,7 +353,7 @@ ifcapable foreignkey { catchsql { INSERT INTO t7b SELECT * FROM t7c; } - } {1 {foreign key constraint failed}} + } {1 {FOREIGN KEY constraint failed}} do_test insert4-7.4 { execsql {SELECT * FROM t7b} } {} @@ -452,7 +452,7 @@ do_test insert4-8.5 { catchsql { INSERT INTO t1 SELECT * FROM t2; } -} {1 {PRIMARY KEY must be unique}} +} {1 {UNIQUE constraint failed: t1.a}} do_test insert4-8.6 { execsql { SELECT * FROM t1; @@ -472,7 +472,7 @@ do_test insert4-8.7 { catchsql { INSERT INTO t1 SELECT * FROM t2; } -} {1 {PRIMARY KEY must be unique}} +} {1 {UNIQUE constraint failed: t1.a}} do_test insert4-8.8 { execsql { SELECT * FROM t1; @@ -494,7 +494,7 @@ do_test insert4-8.9 { INSERT INTO t1 VALUES(2,3); INSERT INTO t1 SELECT * FROM t2; } -} {1 {PRIMARY KEY must be unique}} +} {1 {UNIQUE constraint failed: t1.a}} do_test insert4-8.10 { catchsql {COMMIT} } {1 {cannot commit - no transaction is active}} diff --git a/test/intpkey.test b/test/intpkey.test index 7ed25e4a13..41858e5d46 100644 --- a/test/intpkey.test +++ b/test/intpkey.test @@ -76,7 +76,7 @@ do_test intpkey-1.6 { INSERT INTO t1 VALUES(5,'second','entry'); }} msg] lappend r $msg -} {1 {PRIMARY KEY must be unique}} +} {1 {UNIQUE constraint failed: t1.a}} do_test intpkey-1.7 { execsql { SELECT rowid, * FROM t1; diff --git a/test/memdb.test b/test/memdb.test index 802fb1a5c4..a2efc0369b 100644 --- a/test/memdb.test +++ b/test/memdb.test @@ -240,7 +240,7 @@ foreach {i conf1 conf2 cmd t0 t1 t2} { if {$i>1} break } - if {$t0} {set t1 {column a is not unique}} + if {$t0} {set t1 {UNIQUE constraint failed: t1.a}} do_test memdb-5.$i { if {$conf1!=""} {set conf1 "ON CONFLICT $conf1"} if {$conf2!=""} {set conf2 "ON CONFLICT $conf2"} diff --git a/test/misc1.test b/test/misc1.test index 188a2837ba..8573d349b3 100644 --- a/test/misc1.test +++ b/test/misc1.test @@ -235,7 +235,7 @@ do_test misc1-7.4 { catchsql { INSERT INTO t5 VALUES(1,2,4); } -} {1 {columns a, b are not unique}} +} {1 {UNIQUE constraint failed: t5.a, t5.b}} do_test misc1-7.5 { catchsql { INSERT INTO t5 VALUES(0,2,4); diff --git a/test/misc3.test b/test/misc3.test index 81a8266b9c..bc1f0ff911 100644 --- a/test/misc3.test +++ b/test/misc3.test @@ -283,7 +283,7 @@ ifcapable {explain} { }] set y [regexp { 123456789012 } $x] lappend y [regexp { 4.5678 } $x] - lappend y [regexp {,-BINARY} $x] + lappend y [regexp {,-B} $x] } {1 1 1} } else { do_test misc3-6.11-utf8 { @@ -293,7 +293,7 @@ ifcapable {explain} { set y [regexp { 123456789012 } $x] lappend y [regexp { 4.5678 } $x] lappend y [regexp { hello } $x] - lappend y [regexp {,-BINARY} $x] + lappend y [regexp {,-B} $x] } {1 1 1 1} } } diff --git a/test/notnull.test b/test/notnull.test index 01738a4551..23fd33d4ba 100644 --- a/test/notnull.test +++ b/test/notnull.test @@ -47,7 +47,7 @@ do_test notnull-1.2 { INSERT INTO t1(b,c,d,e) VALUES(2,3,4,5); SELECT * FROM t1 order by a; } -} {1 {t1.a may not be NULL}} +} {1 {NOT NULL constraint failed: t1.a}} verify_ex_errcode notnull-1.2b SQLITE_CONSTRAINT_NOTNULL do_test notnull-1.3 { catchsql { @@ -62,7 +62,7 @@ do_test notnull-1.4 { INSERT OR REPLACE INTO t1(b,c,d,e) VALUES(2,3,4,5); SELECT * FROM t1 order by a; } -} {1 {t1.a may not be NULL}} +} {1 {NOT NULL constraint failed: t1.a}} verify_ex_errcode notnull-1.4b SQLITE_CONSTRAINT_NOTNULL do_test notnull-1.5 { catchsql { @@ -70,7 +70,7 @@ do_test notnull-1.5 { INSERT OR ABORT INTO t1(b,c,d,e) VALUES(2,3,4,5); SELECT * FROM t1 order by a; } -} {1 {t1.a may not be NULL}} +} {1 {NOT NULL constraint failed: t1.a}} verify_ex_errcode notnull-1.5b SQLITE_CONSTRAINT_NOTNULL do_test notnull-1.6 { catchsql { @@ -106,7 +106,7 @@ do_test notnull-1.10 { INSERT INTO t1(a,b,c,d,e) VALUES(1,null,3,4,5); SELECT * FROM t1 order by a; } -} {1 {t1.b may not be NULL}} +} {1 {NOT NULL constraint failed: t1.b}} verify_ex_errcode notnull-1.10b SQLITE_CONSTRAINT_NOTNULL do_test notnull-1.11 { catchsql { @@ -149,7 +149,7 @@ do_test notnull-1.16 { INSERT OR ABORT INTO t1(a,b,c,d,e) VALUES(1,2,null,4,5); SELECT * FROM t1 order by a; } -} {1 {t1.c may not be NULL}} +} {1 {NOT NULL constraint failed: t1.c}} verify_ex_errcode notnull-1.16b SQLITE_CONSTRAINT_NOTNULL do_test notnull-1.17 { catchsql { @@ -157,7 +157,7 @@ do_test notnull-1.17 { INSERT OR ABORT INTO t1(a,b,c,d,e) VALUES(1,2,3,null,5); SELECT * FROM t1 order by a; } -} {1 {t1.d may not be NULL}} +} {1 {NOT NULL constraint failed: t1.d}} verify_ex_errcode notnull-1.17b SQLITE_CONSTRAINT_NOTNULL do_test notnull-1.18 { catchsql { @@ -179,7 +179,7 @@ do_test notnull-1.20 { INSERT INTO t1(a,b,c,d,e) VALUES(1,2,3,4,null); SELECT * FROM t1 order by a; } -} {1 {t1.e may not be NULL}} +} {1 {NOT NULL constraint failed: t1.e}} verify_ex_errcode notnull-1.20b SQLITE_CONSTRAINT_NOTNULL do_test notnull-1.21 { catchsql { @@ -196,7 +196,7 @@ do_test notnull-2.1 { UPDATE t1 SET a=null; SELECT * FROM t1 ORDER BY a; } -} {1 {t1.a may not be NULL}} +} {1 {NOT NULL constraint failed: t1.a}} verify_ex_errcode notnull-2.1b SQLITE_CONSTRAINT_NOTNULL do_test notnull-2.2 { catchsql { @@ -205,7 +205,7 @@ do_test notnull-2.2 { UPDATE OR REPLACE t1 SET a=null; SELECT * FROM t1 ORDER BY a; } -} {1 {t1.a may not be NULL}} +} {1 {NOT NULL constraint failed: t1.a}} verify_ex_errcode notnull-2.2b SQLITE_CONSTRAINT_NOTNULL do_test notnull-2.3 { catchsql { @@ -222,7 +222,7 @@ do_test notnull-2.4 { UPDATE OR ABORT t1 SET a=null; SELECT * FROM t1 ORDER BY a; } -} {1 {t1.a may not be NULL}} +} {1 {NOT NULL constraint failed: t1.a}} verify_ex_errcode notnull-2.4b SQLITE_CONSTRAINT_NOTNULL do_test notnull-2.5 { catchsql { @@ -231,7 +231,7 @@ do_test notnull-2.5 { UPDATE t1 SET b=null; SELECT * FROM t1 ORDER BY a; } -} {1 {t1.b may not be NULL}} +} {1 {NOT NULL constraint failed: t1.b}} verify_ex_errcode notnull-2.6b SQLITE_CONSTRAINT_NOTNULL do_test notnull-2.6 { catchsql { @@ -272,7 +272,7 @@ do_test notnull-2.10 { UPDATE t1 SET e=null, a=b, b=a; SELECT * FROM t1 ORDER BY a; } -} {1 {t1.e may not be NULL}} +} {1 {NOT NULL constraint failed: t1.e}} verify_ex_errcode notnull-2.10b SQLITE_CONSTRAINT_NOTNULL do_test notnull-3.0 { @@ -298,7 +298,7 @@ do_test notnull-3.2 { INSERT INTO t1(b,c,d,e) VALUES(2,3,4,5); SELECT * FROM t1 order by a; } -} {1 {t1.a may not be NULL}} +} {1 {NOT NULL constraint failed: t1.a}} verify_ex_errcode notnull-3.2b SQLITE_CONSTRAINT_NOTNULL do_test notnull-3.3 { catchsql { @@ -313,7 +313,7 @@ do_test notnull-3.4 { INSERT OR REPLACE INTO t1(b,c,d,e) VALUES(2,3,4,5); SELECT * FROM t1 order by a; } -} {1 {t1.a may not be NULL}} +} {1 {NOT NULL constraint failed: t1.a}} verify_ex_errcode notnull-3.4b SQLITE_CONSTRAINT_NOTNULL do_test notnull-3.5 { catchsql { @@ -321,7 +321,7 @@ do_test notnull-3.5 { INSERT OR ABORT INTO t1(b,c,d,e) VALUES(2,3,4,5); SELECT * FROM t1 order by a; } -} {1 {t1.a may not be NULL}} +} {1 {NOT NULL constraint failed: t1.a}} verify_ex_errcode notnull-3.5b SQLITE_CONSTRAINT_NOTNULL do_test notnull-3.6 { catchsql { @@ -357,7 +357,7 @@ do_test notnull-3.10 { INSERT INTO t1(a,b,c,d,e) VALUES(1,null,3,4,5); SELECT * FROM t1 order by a; } -} {1 {t1.b may not be NULL}} +} {1 {NOT NULL constraint failed: t1.b}} verify_ex_errcode notnull-3.10b SQLITE_CONSTRAINT_NOTNULL do_test notnull-3.11 { catchsql { @@ -400,7 +400,7 @@ do_test notnull-3.16 { INSERT OR ABORT INTO t1(a,b,c,d,e) VALUES(1,2,null,4,5); SELECT * FROM t1 order by a; } -} {1 {t1.c may not be NULL}} +} {1 {NOT NULL constraint failed: t1.c}} verify_ex_errcode notnull-3.16b SQLITE_CONSTRAINT_NOTNULL do_test notnull-3.17 { catchsql { @@ -408,7 +408,7 @@ do_test notnull-3.17 { INSERT OR ABORT INTO t1(a,b,c,d,e) VALUES(1,2,3,null,5); SELECT * FROM t1 order by a; } -} {1 {t1.d may not be NULL}} +} {1 {NOT NULL constraint failed: t1.d}} verify_ex_errcode notnull-3.17b SQLITE_CONSTRAINT_NOTNULL do_test notnull-3.18 { catchsql { @@ -430,7 +430,7 @@ do_test notnull-3.20 { INSERT INTO t1(a,b,c,d,e) VALUES(1,2,3,4,null); SELECT * FROM t1 order by a; } -} {1 {t1.e may not be NULL}} +} {1 {NOT NULL constraint failed: t1.e}} verify_ex_errcode notnull-3.20b SQLITE_CONSTRAINT_NOTNULL do_test notnull-3.21 { catchsql { @@ -447,7 +447,7 @@ do_test notnull-4.1 { UPDATE t1 SET a=null; SELECT * FROM t1 ORDER BY a; } -} {1 {t1.a may not be NULL}} +} {1 {NOT NULL constraint failed: t1.a}} verify_ex_errcode notnull-4.1b SQLITE_CONSTRAINT_NOTNULL do_test notnull-4.2 { catchsql { @@ -456,7 +456,7 @@ do_test notnull-4.2 { UPDATE OR REPLACE t1 SET a=null; SELECT * FROM t1 ORDER BY a; } -} {1 {t1.a may not be NULL}} +} {1 {NOT NULL constraint failed: t1.a}} verify_ex_errcode notnull-4.2b SQLITE_CONSTRAINT_NOTNULL do_test notnull-4.3 { catchsql { @@ -473,7 +473,7 @@ do_test notnull-4.4 { UPDATE OR ABORT t1 SET a=null; SELECT * FROM t1 ORDER BY a; } -} {1 {t1.a may not be NULL}} +} {1 {NOT NULL constraint failed: t1.a}} verify_ex_errcode notnull-4.4b SQLITE_CONSTRAINT_NOTNULL do_test notnull-4.5 { catchsql { @@ -482,7 +482,7 @@ do_test notnull-4.5 { UPDATE t1 SET b=null; SELECT * FROM t1 ORDER BY a; } -} {1 {t1.b may not be NULL}} +} {1 {NOT NULL constraint failed: t1.b}} verify_ex_errcode notnull-4.5b SQLITE_CONSTRAINT_NOTNULL do_test notnull-4.6 { catchsql { @@ -523,7 +523,7 @@ do_test notnull-4.10 { UPDATE t1 SET e=null, a=b, b=a; SELECT * FROM t1 ORDER BY a; } -} {1 {t1.e may not be NULL}} +} {1 {NOT NULL constraint failed: t1.e}} verify_ex_errcode notnull-4.10b SQLITE_CONSTRAINT_NOTNULL # Test that bug 29ab7be99f is fixed. @@ -542,7 +542,7 @@ do_test notnull-5.2 { INSERT INTO t1 VALUES(1, 2); INSERT INTO t1 SELECT * FROM t2; } -} {1 {t1.b may not be NULL}} +} {1 {NOT NULL constraint failed: t1.b}} verify_ex_errcode notnull-5.2b SQLITE_CONSTRAINT_NOTNULL do_test notnull-5.3 { execsql { SELECT * FROM t1 } @@ -555,7 +555,7 @@ do_test notnull-5.4 { INSERT INTO t1 SELECT * FROM t2; COMMIT; } -} {1 {t1.b may not be NULL}} +} {1 {NOT NULL constraint failed: t1.b}} verify_ex_errcode notnull-5.4b SQLITE_CONSTRAINT_NOTNULL do_test notnull-5.5 { execsql { SELECT * FROM t1 } diff --git a/test/orderby5.test b/test/orderby5.test index 5bae5db717..6da0dd4e76 100644 --- a/test/orderby5.test +++ b/test/orderby5.test @@ -94,4 +94,19 @@ do_execsql_test 2.7 { } {/B-TREE/} +do_execsql_test 3.0 { + CREATE TABLE t3(a INTEGER PRIMARY KEY, b, c, d, e, f); + CREATE INDEX t3bcde ON t3(b, c, d, e); + EXPLAIN QUERY PLAN + SELECT a FROM t3 WHERE b=2 AND c=3 ORDER BY d DESC, e DESC, b, c, a DESC; +} {~/B-TREE/} +do_execsql_test 3.1 { + DROP TABLE t3; + CREATE TABLE t3(a INTEGER PRIMARY KEY, b, c, d, e, f) WITHOUT rowid; + CREATE INDEX t3bcde ON t3(b, c, d, e); + EXPLAIN QUERY PLAN + SELECT a FROM t3 WHERE b=2 AND c=3 ORDER BY d DESC, e DESC, b, c, a DESC; +} {~/B-TREE/} + + finish_test diff --git a/test/pager1.test b/test/pager1.test index 4a3b6fa2d8..005b356080 100644 --- a/test/pager1.test +++ b/test/pager1.test @@ -271,7 +271,7 @@ do_execsql_test pager1-3.1.2 { } {3 0} do_catchsql_test pager1-3.1.3 { INSERT INTO t1 SELECT a+3, randomblob(1500) FROM t1 -} {1 {constraint failed}} +} {1 {CHECK constraint failed: counter}} do_execsql_test pager1-3.4 { SELECT * FROM counter } {3 0} do_execsql_test pager1-3.5 { SELECT a FROM t1 } {1 2 3} do_execsql_test pager1-3.6 { COMMIT } {} @@ -1703,7 +1703,7 @@ do_catchsql_test pager1-14.1.4 { BEGIN; INSERT INTO t1(rowid, a, b) SELECT a+3, b, b FROM t1; INSERT INTO t1(rowid, a, b) SELECT a+3, b, b FROM t1; -} {1 {PRIMARY KEY must be unique}} +} {1 {UNIQUE constraint failed: t1.rowid}} do_execsql_test pager1-14.1.5 { COMMIT; SELECT * FROM t1; diff --git a/test/pragma.test b/test/pragma.test index a6d198eb69..1043170378 100644 --- a/test/pragma.test +++ b/test/pragma.test @@ -285,31 +285,31 @@ ifcapable attach { db close sqlite3 db test.db execsql {PRAGMA integrity_check} - } {{rowid 1 missing from index i2} {rowid 2 missing from index i2} {wrong # of entries in index i2}} + } {{row 1 missing from index i2} {row 2 missing from index i2} {wrong # of entries in index i2}} do_test pragma-3.3 { execsql {PRAGMA integrity_check=1} - } {{rowid 1 missing from index i2}} + } {{row 1 missing from index i2}} do_test pragma-3.4 { execsql { ATTACH DATABASE 'test.db' AS t2; PRAGMA integrity_check } - } {{rowid 1 missing from index i2} {rowid 2 missing from index i2} {wrong # of entries in index i2} {rowid 1 missing from index i2} {rowid 2 missing from index i2} {wrong # of entries in index i2}} + } {{row 1 missing from index i2} {row 2 missing from index i2} {wrong # of entries in index i2} {row 1 missing from index i2} {row 2 missing from index i2} {wrong # of entries in index i2}} do_test pragma-3.5 { execsql { PRAGMA integrity_check=4 } - } {{rowid 1 missing from index i2} {rowid 2 missing from index i2} {wrong # of entries in index i2} {rowid 1 missing from index i2}} + } {{row 1 missing from index i2} {row 2 missing from index i2} {wrong # of entries in index i2} {row 1 missing from index i2}} do_test pragma-3.6 { execsql { PRAGMA integrity_check=xyz } - } {{rowid 1 missing from index i2} {rowid 2 missing from index i2} {wrong # of entries in index i2} {rowid 1 missing from index i2} {rowid 2 missing from index i2} {wrong # of entries in index i2}} + } {{row 1 missing from index i2} {row 2 missing from index i2} {wrong # of entries in index i2} {row 1 missing from index i2} {row 2 missing from index i2} {wrong # of entries in index i2}} do_test pragma-3.7 { execsql { PRAGMA integrity_check=0 } - } {{rowid 1 missing from index i2} {rowid 2 missing from index i2} {wrong # of entries in index i2} {rowid 1 missing from index i2} {rowid 2 missing from index i2} {wrong # of entries in index i2}} + } {{row 1 missing from index i2} {row 2 missing from index i2} {wrong # of entries in index i2} {row 1 missing from index i2} {row 2 missing from index i2} {wrong # of entries in index i2}} # Add additional corruption by appending unused pages to the end of # the database file testerr.db @@ -344,7 +344,7 @@ ifcapable attach { } {{*** in database t2 *** Page 4 is never used Page 5 is never used -Page 6 is never used} {rowid 1 missing from index i2} {rowid 2 missing from index i2} {wrong # of entries in index i2}} +Page 6 is never used} {row 1 missing from index i2} {row 2 missing from index i2} {wrong # of entries in index i2}} do_test pragma-3.10 { execsql { PRAGMA integrity_check=1 @@ -358,7 +358,7 @@ Page 4 is never used}} } {{*** in database t2 *** Page 4 is never used Page 5 is never used -Page 6 is never used} {rowid 1 missing from index i2} {rowid 2 missing from index i2}} +Page 6 is never used} {row 1 missing from index i2} {row 2 missing from index i2}} do_test pragma-3.12 { execsql { PRAGMA integrity_check=4 @@ -366,7 +366,7 @@ Page 6 is never used} {rowid 1 missing from index i2} {rowid 2 missing from inde } {{*** in database t2 *** Page 4 is never used Page 5 is never used -Page 6 is never used} {rowid 1 missing from index i2}} +Page 6 is never used} {row 1 missing from index i2}} do_test pragma-3.13 { execsql { PRAGMA integrity_check=3 @@ -390,10 +390,10 @@ Page 5 is never used}} } {{*** in database t2 *** Page 4 is never used Page 5 is never used -Page 6 is never used} {rowid 1 missing from index i2} {rowid 2 missing from index i2} {wrong # of entries in index i2} {*** in database t3 *** +Page 6 is never used} {row 1 missing from index i2} {row 2 missing from index i2} {wrong # of entries in index i2} {*** in database t3 *** Page 4 is never used Page 5 is never used -Page 6 is never used} {rowid 1 missing from index i2} {rowid 2 missing from index i2} {wrong # of entries in index i2}} +Page 6 is never used} {row 1 missing from index i2} {row 2 missing from index i2} {wrong # of entries in index i2}} do_test pragma-3.16 { execsql { PRAGMA integrity_check(10) @@ -401,10 +401,10 @@ Page 6 is never used} {rowid 1 missing from index i2} {rowid 2 missing from inde } {{*** in database t2 *** Page 4 is never used Page 5 is never used -Page 6 is never used} {rowid 1 missing from index i2} {rowid 2 missing from index i2} {wrong # of entries in index i2} {*** in database t3 *** +Page 6 is never used} {row 1 missing from index i2} {row 2 missing from index i2} {wrong # of entries in index i2} {*** in database t3 *** Page 4 is never used Page 5 is never used -Page 6 is never used} {rowid 1 missing from index i2}} +Page 6 is never used} {row 1 missing from index i2}} do_test pragma-3.17 { execsql { PRAGMA integrity_check=8 @@ -412,7 +412,7 @@ Page 6 is never used} {rowid 1 missing from index i2}} } {{*** in database t2 *** Page 4 is never used Page 5 is never used -Page 6 is never used} {rowid 1 missing from index i2} {rowid 2 missing from index i2} {wrong # of entries in index i2} {*** in database t3 *** +Page 6 is never used} {row 1 missing from index i2} {row 2 missing from index i2} {wrong # of entries in index i2} {*** in database t3 *** Page 4 is never used Page 5 is never used}} do_test pragma-3.18 { @@ -422,7 +422,7 @@ Page 5 is never used}} } {{*** in database t2 *** Page 4 is never used Page 5 is never used -Page 6 is never used} {rowid 1 missing from index i2}} +Page 6 is never used} {row 1 missing from index i2}} } do_test pragma-3.19 { catch {db close} diff --git a/test/rollback.test b/test/rollback.test index fc123ab938..c339c5d7d6 100644 --- a/test/rollback.test +++ b/test/rollback.test @@ -54,7 +54,7 @@ ifcapable conflict { catchsql { INSERT INTO t3 SELECT a FROM t1; } - } {1 {column a is not unique}} + } {1 {UNIQUE constraint failed: t3.a}} # Try to continue with the SELECT statement # diff --git a/test/savepoint.test b/test/savepoint.test index 015d97fe1a..9f4571abef 100644 --- a/test/savepoint.test +++ b/test/savepoint.test @@ -858,7 +858,7 @@ do_test savepoint-12.2 { SAVEPOINT sp2; INSERT OR ROLLBACK INTO t4 VALUES(1, 'one'); } -} {1 {column a is not unique}} +} {1 {UNIQUE constraint failed: t4.a}} do_test savepoint-12.3 { sqlite3_get_autocommit db } {1} diff --git a/test/schema5.test b/test/schema5.test index 6dea5e8f5f..29df3f16f5 100644 --- a/test/schema5.test +++ b/test/schema5.test @@ -30,7 +30,7 @@ do_test schema5-1.1 { } {1 2 3} do_test schema5-1.2 { catchsql {INSERT INTO t1 VALUES(1,3,4);} -} {1 {column a is not unique}} +} {1 {UNIQUE constraint failed: t1.a}} do_test schema5-1.3 { db eval { DROP TABLE t1; @@ -44,7 +44,7 @@ do_test schema5-1.3 { } {1 2 3} do_test schema5-1.4 { catchsql {INSERT INTO t1 VALUES(10,11,12);} -} {1 {constraint two failed}} +} {1 {CHECK constraint failed: two}} do_test schema5-1.5 { db eval { DROP TABLE t1; @@ -57,10 +57,10 @@ do_test schema5-1.5 { } {} do_test schema5-1.6 { catchsql {INSERT INTO t1 VALUES(1,3,4)} -} {1 {column a is not unique}} +} {1 {UNIQUE constraint failed: t1.a}} do_test schema5-1.7 { catchsql {INSERT INTO t1 VALUES(10,2,3)} -} {1 {columns b, c are not unique}} +} {1 {UNIQUE constraint failed: t1.b, t1.c}} diff --git a/test/stat.test b/test/stat.test index ac88f7acb3..f8d3877e36 100644 --- a/test/stat.test +++ b/test/stat.test @@ -112,7 +112,17 @@ do_execsql_test stat-2.1 { t3 /00e/ 22 leaf 2 730 276 366 \ t3 /00f/ 23 leaf 2 738 268 370 \ ] -do_execsql_test stat-2.2 { DROP TABLE t3 } {} + +# With every index entry overflowing, make sure no pages are missed +# (other than the locking page which is 64 in this test build.) +# +do_execsql_test stat-2.2 { + UPDATE t3 SET a=a||hex(randomblob(700)); + VACUUM; + SELECT pageno FROM stat EXCEPT SELECT pageno-1 FROM stat; +} {64 136} + +do_execsql_test stat-2.3 { DROP TABLE t3; VACUUM; } {} do_execsql_test stat-3.1 { CREATE TABLE t4(x); @@ -122,22 +132,22 @@ do_execsql_test stat-3.1 { FROM stat WHERE name != 'sqlite_master'; } [list \ i4 / 3 leaf 1 103 905 7782 \ - i4 /000+000000 9 overflow 0 1020 0 0 \ - i4 /000+000001 10 overflow 0 1020 0 0 \ - i4 /000+000002 11 overflow 0 1020 0 0 \ - i4 /000+000003 12 overflow 0 1020 0 0 \ - i4 /000+000004 13 overflow 0 1020 0 0 \ - i4 /000+000005 14 overflow 0 1020 0 0 \ - i4 /000+000006 15 overflow 0 1020 0 0 \ - i4 /000+000007 16 overflow 0 539 481 0 \ + i4 /000+000000 4 overflow 0 1020 0 0 \ + i4 /000+000001 5 overflow 0 1020 0 0 \ + i4 /000+000002 6 overflow 0 1020 0 0 \ + i4 /000+000003 7 overflow 0 1020 0 0 \ + i4 /000+000004 8 overflow 0 1020 0 0 \ + i4 /000+000005 9 overflow 0 1020 0 0 \ + i4 /000+000006 10 overflow 0 1020 0 0 \ + i4 /000+000007 11 overflow 0 539 481 0 \ t4 / 2 leaf 1 640 367 7780 \ - t4 /000+000000 22 overflow 0 1020 0 0 \ - t4 /000+000001 23 overflow 0 1020 0 0 \ - t4 /000+000002 21 overflow 0 1020 0 0 \ - t4 /000+000003 20 overflow 0 1020 0 0 \ - t4 /000+000004 19 overflow 0 1020 0 0 \ - t4 /000+000005 18 overflow 0 1020 0 0 \ - t4 /000+000006 17 overflow 0 1020 0 0 \ + t4 /000+000000 12 overflow 0 1020 0 0 \ + t4 /000+000001 13 overflow 0 1020 0 0 \ + t4 /000+000002 14 overflow 0 1020 0 0 \ + t4 /000+000003 15 overflow 0 1020 0 0 \ + t4 /000+000004 16 overflow 0 1020 0 0 \ + t4 /000+000005 17 overflow 0 1020 0 0 \ + t4 /000+000006 18 overflow 0 1020 0 0 \ ] do_execsql_test stat-4.1 { @@ -146,8 +156,8 @@ do_execsql_test stat-4.1 { SELECT name, path, pageno, pagetype, ncell, payload, unused, mx_payload FROM stat WHERE name = 't5' OR name = 'i5'; } [list \ - i5 / 5 leaf 0 0 1016 0 \ - t5 / 4 leaf 0 0 1016 0 \ + i5 / 20 leaf 0 0 1016 0 \ + t5 / 19 leaf 0 0 1016 0 \ ] db close diff --git a/test/table.test b/test/table.test index e186450a2f..ed9efc02cd 100644 --- a/test/table.test +++ b/test/table.test @@ -464,7 +464,7 @@ do_test table-10.1 { CREATE TABLE t6(a REFERENCES t4(a) NOT NULL); INSERT INTO t6 VALUES(NULL); } -} {1 {t6.a may not be NULL}} +} {1 {NOT NULL constraint failed: t6.a}} do_test table-10.2 { catchsql { DROP TABLE t6; diff --git a/test/tableopts.test b/test/tableopts.test new file mode 100644 index 0000000000..0b2457ec4c --- /dev/null +++ b/test/tableopts.test @@ -0,0 +1,76 @@ +# 2013-10-19 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# Test the operation of table-options in the WITH clause of the +# CREATE TABLE statement. +# + + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +do_test tableopt-1.1 { + catchsql { + CREATE TABLE t1(a,b) WITHOUT rowid; + } +} {1 {PRIMARY KEY missing on table t1}} +do_test tableopt-1.1b { + catchsql { + CREATE TABLE t1(a INTEGER PRIMARY KEY AUTOINCREMENT,b) WITHOUT rowid; + } +} {1 {AUTOINCREMENT not allowed on WITHOUT ROWID tables}} +do_test tableopt-1.2 { + catchsql { + CREATE TABLE t1(a,b) WITHOUT unknown2; + } +} {1 {unknown table option: unknown2}} + +do_execsql_test tableopt-2.1 { + CREATE TABLE t1(a, b, c, PRIMARY KEY(a,b)) WITHOUT rowid; + INSERT INTO t1 VALUES(1,2,3),(2,3,4); + SELECT c FROM t1 WHERE a IN (1,2) ORDER BY b; +} {3 4} +do_test tableopt-2.1.1 { + catchsql { + SELECT rowid, * FROM t1; + } +} {1 {no such column: rowid}} +do_test tableopt-2.1.2 { + catchsql { + SELECT _rowid_, * FROM t1; + } +} {1 {no such column: _rowid_}} +do_test tableopt-2.1.3 { + catchsql { + SELECT oid, * FROM t1; + } +} {1 {no such column: oid}} +do_execsql_test tableopt-2.2 { + VACUUM; + SELECT c FROM t1 WHERE a IN (1,2) ORDER BY b; +} {3 4} +do_test tableopt-2.3 { + sqlite3 db2 test.db + db2 eval {SELECT c FROM t1 WHERE a IN (1,2) ORDER BY b;} +} {3 4} +db2 close + +# Make sure the "without" keyword is still usable as a table or +# column name. +# +do_execsql_test tableopt-3.1 { + CREATE TABLE without(x INTEGER PRIMARY KEY, without TEXT); + INSERT INTO without VALUES(1, 'xyzzy'), (2, 'fizzle'); + SELECT * FROM without WHERE without='xyzzy'; +} {1 xyzzy} + + +finish_test diff --git a/test/tester.tcl b/test/tester.tcl index a62300e183..1e69fde110 100644 --- a/test/tester.tcl +++ b/test/tester.tcl @@ -1029,6 +1029,78 @@ proc explain {sql {db db}} { } } +proc explain_i {sql {db db}} { + puts "" + puts "addr opcode p1 p2 p3 p4 p5 #" + puts "---- ------------ ------ ------ ------ ---------------- -- -" + + + # Set up colors for the different opcodes. Scheme is as follows: + # + # Red: Opcodes that write to a b-tree. + # Blue: Opcodes that reposition or seek a cursor. + # Green: The ResultRow opcode. + # + set R "\033\[31;1m" ;# Red fg + set G "\033\[32;1m" ;# Green fg + set B "\033\[34;1m" ;# Red fg + set D "\033\[39;0m" ;# Default fg + foreach opcode { + Seek SeekGe SeekGt SeekLe SeekLt NotFound Last Rewind + NoConflict Next Prev + } { + set color($opcode) $B + } + foreach opcode {ResultRow} { + set color($opcode) $G + } + foreach opcode {IdxInsert Insert Delete IdxDelete} { + set color($opcode) $R + } + + set bSeenGoto 0 + $db eval "explain $sql" {} { + set x($addr) 0 + set op($addr) $opcode + + if {$opcode == "Goto" && ($bSeenGoto==0 || ($p2 > $addr+10))} { + set linebreak($p2) 1 + set bSeenGoto 1 + } + + if {$opcode == "Next" || $opcode=="Prev"} { + for {set i $p2} {$i<$addr} {incr i} { + incr x($i) 2 + } + } + + if {$opcode == "Goto" && $p2<$addr && $op($p2)=="Yield"} { + for {set i [expr $p2+1]} {$i<$addr} {incr i} { + incr x($i) 2 + } + } + + if {$opcode == "Halt" && $comment == "End of coroutine"} { + set linebreak([expr $addr+1]) 1 + } + } + + $db eval "explain $sql" {} { + if {[info exists linebreak($addr)]} { + puts "" + } + set I [string repeat " " $x($addr)] + + set col "" + catch { set col $color($opcode) } + + puts [format {%-4d %s%s%-12.12s%s %-6d %-6d %-6d % -17s %s %s} \ + $addr $I $col $opcode $D $p1 $p2 $p3 $p4 $p5 $comment + ] + } + puts "---- ------------ ------ ------ ------ ---------------- -- -" +} + # Show the VDBE program for an SQL statement but omit the Trace # opcode at the beginning. This procedure can be used to prove # that different SQL statements generate exactly the same VDBE code. diff --git a/test/tkt-4a03edc4c8.test b/test/tkt-4a03edc4c8.test index 649f27d22b..1908bcdf2c 100644 --- a/test/tkt-4a03edc4c8.test +++ b/test/tkt-4a03edc4c8.test @@ -31,7 +31,7 @@ do_test tkt-4a03ed-1.1 { INSERT INTO t1 VALUES(1, 2); COMMIT; } -} {1 {column b is not unique}} +} {1 {UNIQUE constraint failed: t1.b}} do_test tkt-4a03ed-1.2 { db eval { PRAGMA integrity_check; diff --git a/test/tkt-78e04e52ea.test b/test/tkt-78e04e52ea.test index dde6502a9d..975e5b3d1c 100644 --- a/test/tkt-78e04e52ea.test +++ b/test/tkt-78e04e52ea.test @@ -29,7 +29,7 @@ do_test tkt-78e04-1.1 { catchsql { INSERT INTO ""("") VALUES(1); } -} {1 {column is not unique}} +} {1 {UNIQUE constraint failed: .}} do_test tkt-78e04-1.2 { execsql { PRAGMA table_info(""); diff --git a/test/tkt-b1d3a2e531.test b/test/tkt-b1d3a2e531.test index 54534b6cbe..745bbe8664 100644 --- a/test/tkt-b1d3a2e531.test +++ b/test/tkt-b1d3a2e531.test @@ -98,7 +98,7 @@ do_catchsql_test 3.2 { DROP TABLE pp1; DROP TABLE cc1; COMMIT; -} {1 {foreign key constraint failed}} +} {1 {FOREIGN KEY constraint failed}} do_catchsql_test 3.3 { DROP TABLE cc2; COMMIT; diff --git a/test/tkt1567.test b/test/tkt1567.test index 6c4548a314..cb1a6be506 100644 --- a/test/tkt1567.test +++ b/test/tkt1567.test @@ -40,7 +40,7 @@ do_test tkt1567-1.4 { catchsql { UPDATE t1 SET a = CASE WHEN rowid<90 THEN substr(a,1,10) ELSE '9999' END; } -} {1 {column a is not unique}} +} {1 {UNIQUE constraint failed: t1.a}} do_test tkt1567-1.5 { execsql { COMMIT; @@ -48,4 +48,35 @@ do_test tkt1567-1.5 { } {} integrity_check tkt1567-1.6 +do_test tkt1567-2.1 { + execsql { + CREATE TABLE t2(a TEXT PRIMARY KEY, rowid INT) WITHOUT rowid; + } + set bigstr abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ + for {set i 0} {$i<100} {incr i} { + set x [format %5d [expr $i*2]] + set sql "INSERT INTO t2 VALUES('$x-$bigstr', $i+1)" + execsql $sql + } +} {} +integrity_check tkt1567-2.2 + +do_test tkt1567-2.3 { + execsql { + BEGIN; + UPDATE t2 SET a = a||'x' WHERE rowid%2==0; + } +} {} +do_test tkt1567-2.4 { + catchsql { + UPDATE t2 SET a = CASE WHEN rowid<90 THEN substr(a,1,10) ELSE '9999' END; + } +} {1 {UNIQUE constraint failed: t2.a}} +do_test tkt1567-2.5 { + execsql { + COMMIT; + } +} {} +integrity_check tkt1567-2.6 + finish_test diff --git a/test/tkt35xx.test b/test/tkt35xx.test index f9d10c3033..3b911c1247 100644 --- a/test/tkt35xx.test +++ b/test/tkt35xx.test @@ -74,7 +74,7 @@ do_test tkt35xx-1.2.2 { DROP TABLE t5; INSERT INTO t3(a, b) SELECT c, d FROM t4; } -} {1 {PRIMARY KEY must be unique}} +} {1 {UNIQUE constraint failed: t3.a}} do_test tkt35xx-1.2.3 { # Show that the transaction has not been rolled back. catchsql BEGIN diff --git a/test/trigger2.test b/test/trigger2.test index b4b922a5ee..7b939bdab7 100644 --- a/test/trigger2.test +++ b/test/trigger2.test @@ -497,7 +497,7 @@ ifcapable conflict { catchsql { INSERT OR ABORT INTO tbl values (2, 2, 3); } - } {1 {column a is not unique}} + } {1 {UNIQUE constraint failed: tbl.a}} do_test trigger2-6.1c { execsql { SELECT * from tbl; @@ -507,7 +507,7 @@ ifcapable conflict { catchsql { INSERT OR FAIL INTO tbl values (2, 2, 3); } - } {1 {column a is not unique}} + } {1 {UNIQUE constraint failed: tbl.a}} do_test trigger2-6.1e { execsql { SELECT * from tbl; @@ -523,7 +523,7 @@ ifcapable conflict { catchsql { INSERT OR ROLLBACK INTO tbl values (3, 2, 3); } - } {1 {column a is not unique}} + } {1 {UNIQUE constraint failed: tbl.a}} do_test trigger2-6.1h { execsql { SELECT * from tbl; @@ -551,7 +551,7 @@ ifcapable conflict { catchsql { UPDATE OR ABORT tbl SET a = 4 WHERE a = 1; } - } {1 {column a is not unique}} + } {1 {UNIQUE constraint failed: tbl.a}} do_test trigger2-6.2c { execsql { SELECT * from tbl; @@ -561,7 +561,7 @@ ifcapable conflict { catchsql { UPDATE OR FAIL tbl SET a = 4 WHERE a = 1; } - } {1 {column a is not unique}} + } {1 {UNIQUE constraint failed: tbl.a}} do_test trigger2-6.2e { execsql { SELECT * from tbl; @@ -583,7 +583,7 @@ ifcapable conflict { catchsql { UPDATE OR ROLLBACK tbl SET a = 4 WHERE a = 1; } - } {1 {column a is not unique}} + } {1 {UNIQUE constraint failed: tbl.a}} do_test trigger2-6.2h { execsql { SELECT * from tbl; diff --git a/test/triggerC.test b/test/triggerC.test index 8d9848794a..14cc0f01dd 100644 --- a/test/triggerC.test +++ b/test/triggerC.test @@ -157,7 +157,7 @@ do_test triggerC-1.14 { } {} do_test triggerC-1.15 { catchsql { UPDATE OR ROLLBACK t1 SET a=100 } -} {1 {PRIMARY KEY must be unique}} +} {1 {UNIQUE constraint failed: t1.a}} #------------------------------------------------------------------------- diff --git a/test/unique.test b/test/unique.test index eac19b59e0..04581c231b 100644 --- a/test/unique.test +++ b/test/unique.test @@ -47,8 +47,8 @@ do_test unique-1.3 { catchsql { INSERT INTO t1(a,b,c) VALUES(1,3,4) } -} {1 {column a is not unique}} -verify_ex_errcode unique-1.3b SQLITE_CONSTRAINT_UNIQUE +} {1 {UNIQUE constraint failed: t1.a}} +verify_ex_errcode unique-1.3b SQLITE_CONSTRAINT_PRIMARYKEY do_test unique-1.4 { execsql { SELECT * FROM t1 ORDER BY a; @@ -58,7 +58,7 @@ do_test unique-1.5 { catchsql { INSERT INTO t1(a,b,c) VALUES(3,2,4) } -} {1 {column b is not unique}} +} {1 {UNIQUE constraint failed: t1.b}} verify_ex_errcode unique-1.5b SQLITE_CONSTRAINT_UNIQUE do_test unique-1.6 { execsql { @@ -100,7 +100,7 @@ do_test unique-2.3 { catchsql { INSERT INTO t2 VALUES(1,5); } -} {1 {column a is not unique}} +} {1 {UNIQUE constraint failed: t2.a}} verify_ex_errcode unique-2.3b SQLITE_CONSTRAINT_UNIQUE do_test unique-2.4 { catchsql { @@ -127,7 +127,7 @@ do_test unique-2.8 { catchsql { CREATE UNIQUE INDEX i2 ON t2(a); } -} {1 {indexed columns are not unique}} +} {1 {UNIQUE constraint failed: t2.a}} verify_ex_errcode unique-2.8b SQLITE_CONSTRAINT_UNIQUE do_test unique-2.9 { catchsql { @@ -166,7 +166,7 @@ do_test unique-3.4 { INSERT INTO t3(a,b,c,d) VALUES(1,4,3,5); SELECT * FROM t3 ORDER BY a,b,c,d; } -} {1 {columns a, c, d are not unique}} +} {1 {UNIQUE constraint failed: t3.a, t3.c, t3.d}} verify_ex_errcode unique-3.4b SQLITE_CONSTRAINT_UNIQUE integrity_check unique-3.5 @@ -221,7 +221,7 @@ do_test unique-4.9 { } {0 {}} do_test unique-4.10 { catchsql {CREATE UNIQUE INDEX i4c ON t4(b)} -} {1 {indexed columns are not unique}} +} {1 {UNIQUE constraint failed: t4.b}} verify_ex_errcode unique-4.10b SQLITE_CONSTRAINT_UNIQUE integrity_check unique-4.99 @@ -254,7 +254,7 @@ do_test unique-5.2 { catchsql { INSERT INTO t5 VALUES(1,2,3,4,5,6); } -} {1 {columns first_column_with_long_name, second_column_with_long_name, third_column_with_long_name, fourth_column_with_long_name, fifth_column_with_long_name, sixth_column_with_long_name are not unique}} +} {1 {UNIQUE constraint failed: t5.first_column_with_long_name, t5.second_column_with_long_name, t5.third_column_with_long_name, t5.fourth_column_with_long_name, t5.fifth_column_with_long_name, t5.sixth_column_with_long_name}} verify_ex_errcode unique-5.2b SQLITE_CONSTRAINT_UNIQUE diff --git a/test/update.test b/test/update.test index a6fef7d9af..e67b0efddc 100644 --- a/test/update.test +++ b/test/update.test @@ -452,7 +452,7 @@ do_test update-10.3 { UPDATE t1 SET a=1, e=10 WHERE f=7; SELECT * FROM t1; } -} {1 {PRIMARY KEY must be unique}} +} {1 {UNIQUE constraint failed: t1.a}} do_test update-10.4 { catchsql { SELECT * FROM t1; @@ -469,7 +469,7 @@ do_test update-10.6 { UPDATE t1 SET b=2, e=12 WHERE f=7; SELECT * FROM t1; } -} {1 {column b is not unique}} +} {1 {UNIQUE constraint failed: t1.b}} do_test update-10.7 { catchsql { SELECT * FROM t1; @@ -486,7 +486,7 @@ do_test update-10.9 { UPDATE t1 SET c=3, d=4, e=14 WHERE f=7; SELECT * FROM t1; } -} {1 {columns c, d are not unique}} +} {1 {UNIQUE constraint failed: t1.c, t1.d}} do_test update-10.10 { catchsql { SELECT * FROM t1; diff --git a/test/vtab1.test b/test/vtab1.test index dfcec5ba90..3eb37357d9 100644 --- a/test/vtab1.test +++ b/test/vtab1.test @@ -1040,10 +1040,10 @@ do_test vtab1.12-1 { # First test outside of a transaction. do_test vtab1.12-2 { catchsql { INSERT INTO echo_c SELECT * FROM b; } -} {1 {echo-vtab-error: column a is not unique}} +} {1 {echo-vtab-error: UNIQUE constraint failed: c.a}} do_test vtab1.12-2.1 { sqlite3_errmsg db -} {echo-vtab-error: column a is not unique} +} {echo-vtab-error: UNIQUE constraint failed: c.a} do_test vtab1.12-3 { execsql { SELECT * FROM c } } {3 G H} @@ -1052,7 +1052,7 @@ do_test vtab1.12-3 { do_test vtab1.12-4 { execsql {BEGIN} catchsql { INSERT INTO echo_c SELECT * FROM b; } -} {1 {echo-vtab-error: column a is not unique}} +} {1 {echo-vtab-error: UNIQUE constraint failed: c.a}} do_test vtab1.12-5 { execsql { SELECT * FROM c } } {3 G H} diff --git a/test/wal.test b/test/wal.test index c8078a1b95..7435538678 100644 --- a/test/wal.test +++ b/test/wal.test @@ -322,7 +322,7 @@ do_test wal-5.4 { INSERT INTO t3 VALUES('abc'); } catchsql { INSERT INTO t3 VALUES('abc') } -} {1 {column x is not unique}} +} {1 {UNIQUE constraint failed: t3.x}} do_test wal-5.5 { execsql { COMMIT; diff --git a/test/where8.test b/test/where8.test index 9127179292..a1ef1d796c 100644 --- a/test/where8.test +++ b/test/where8.test @@ -12,7 +12,6 @@ # is testing of where.c. More specifically, the focus is the optimization # of WHERE clauses that feature the OR operator. # -# $Id: where8.test,v 1.9 2009/07/31 06:14:52 danielk1977 Exp $ set testdir [file dirname $argv0] source $testdir/tester.tcl @@ -749,4 +748,13 @@ do_test where8-5.3 { } } {1 {}} +# The OR optimization and WITHOUT ROWID +# +do_execsql_test where8-6.1 { + CREATE TABLE t600(a PRIMARY KEY, b) WITHOUT rowid; + CREATE INDEX t600b ON t600(b); + INSERT INTO t600 VALUES('state','screen'),('exact','dolphin'),('green','mercury'); + SELECT a, b, '|' FROM t600 WHERE a=='state' OR b='mercury' ORDER BY +a; +} {green mercury | state screen |} + finish_test diff --git a/test/without_rowid1.test b/test/without_rowid1.test new file mode 100644 index 0000000000..1a53d26e66 --- /dev/null +++ b/test/without_rowid1.test @@ -0,0 +1,203 @@ +# 2013-10-30 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# This file implements regression tests for SQLite library. The +# focus of this file is testing WITHOUT ROWID tables. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +set testprefix without_rowid1 + +# Create and query a WITHOUT ROWID table. +# +do_execsql_test without_rowid1-1.0 { + CREATE TABLE t1(a,b,c,d, PRIMARY KEY(c,a)) WITHOUT ROWID; + CREATE INDEX t1bd ON t1(b, d); + INSERT INTO t1 VALUES('journal','sherman','ammonia','helena'); + INSERT INTO t1 VALUES('dynamic','juliet','flipper','command'); + INSERT INTO t1 VALUES('journal','sherman','gamma','patriot'); + INSERT INTO t1 VALUES('arctic','sleep','ammonia','helena'); + SELECT *, '|' FROM t1 ORDER BY c, a; +} {arctic sleep ammonia helena | journal sherman ammonia helena | dynamic juliet flipper command | journal sherman gamma patriot |} + +integrity_check without_rowid1-1.0ic + +do_execsql_test without_rowid1-1.1 { + SELECT *, '|' FROM t1 ORDER BY +c, a; +} {arctic sleep ammonia helena | journal sherman ammonia helena | dynamic juliet flipper command | journal sherman gamma patriot |} + +do_execsql_test without_rowid1-1.2 { + SELECT *, '|' FROM t1 ORDER BY c DESC, a DESC; +} {journal sherman gamma patriot | dynamic juliet flipper command | journal sherman ammonia helena | arctic sleep ammonia helena |} + +do_execsql_test without_rowid1-1.11 { + SELECT *, '|' FROM t1 ORDER BY b, d; +} {dynamic juliet flipper command | journal sherman ammonia helena | journal sherman gamma patriot | arctic sleep ammonia helena |} + +do_execsql_test without_rowid1-1.12 { + SELECT *, '|' FROM t1 ORDER BY +b, d; +} {dynamic juliet flipper command | journal sherman ammonia helena | journal sherman gamma patriot | arctic sleep ammonia helena |} + +# Trying to insert a duplicate PRIMARY KEY fails. +# +do_test without_rowid1-1.21 { + catchsql { + INSERT INTO t1 VALUES('dynamic','phone','flipper','harvard'); + } +} {1 {UNIQUE constraint failed: t1.c, t1.a}} + +# REPLACE INTO works, however. +# +do_execsql_test without_rowid1-1.22 { + REPLACE INTO t1 VALUES('dynamic','phone','flipper','harvard'); + SELECT *, '|' FROM t1 ORDER BY c, a; +} {arctic sleep ammonia helena | journal sherman ammonia helena | dynamic phone flipper harvard | journal sherman gamma patriot |} + +do_execsql_test without_rowid1-1.23 { + SELECT *, '|' FROM t1 ORDER BY b, d; +} {dynamic phone flipper harvard | journal sherman ammonia helena | journal sherman gamma patriot | arctic sleep ammonia helena |} + +# UPDATE statements. +# +do_execsql_test without_rowid1-1.31 { + UPDATE t1 SET d=3.1415926 WHERE a='journal'; + SELECT *, '|' FROM t1 ORDER BY c, a; +} {arctic sleep ammonia helena | journal sherman ammonia 3.1415926 | dynamic phone flipper harvard | journal sherman gamma 3.1415926 |} +do_execsql_test without_rowid1-1.32 { + SELECT *, '|' FROM t1 ORDER BY b, d; +} {dynamic phone flipper harvard | journal sherman ammonia 3.1415926 | journal sherman gamma 3.1415926 | arctic sleep ammonia helena |} + +do_execsql_test without_rowid1-1.35 { + UPDATE t1 SET a=1250 WHERE b='phone'; + SELECT *, '|' FROM t1 ORDER BY c, a; +} {arctic sleep ammonia helena | journal sherman ammonia 3.1415926 | 1250 phone flipper harvard | journal sherman gamma 3.1415926 |} +integrity_check without_rowid1-1.36 + +do_execsql_test without_rowid1-1.37 { + SELECT *, '|' FROM t1 ORDER BY b, d; +} {1250 phone flipper harvard | journal sherman ammonia 3.1415926 | journal sherman gamma 3.1415926 | arctic sleep ammonia helena |} + +do_execsql_test without_rowid1-1.40 { + VACUUM; + SELECT *, '|' FROM t1 ORDER BY b, d; +} {1250 phone flipper harvard | journal sherman ammonia 3.1415926 | journal sherman gamma 3.1415926 | arctic sleep ammonia helena |} +integrity_check without_rowid1-1.41 + +# Verify that ANALYZE works +# +do_execsql_test without_rowid1-1.50 { + ANALYZE; + SELECT * FROM sqlite_stat1 ORDER BY idx; +} {t1 t1 {4 2 1} t1 t1bd {4 2 2}} +ifcapable stat3 { + do_execsql_test without_rowid1-1.51 { + SELECT DISTINCT tbl, idx FROM sqlite_stat3 ORDER BY idx; + } {t1 t1 t1 t1bd} +} +ifcapable stat4 { + do_execsql_test without_rowid1-1.52 { + SELECT DISTINCT tbl, idx FROM sqlite_stat4 ORDER BY idx; + } {t1 t1 t1 t1bd} +} + +#---------- + +do_execsql_test 2.1.1 { + CREATE TABLE t4 (a COLLATE nocase PRIMARY KEY, b) WITHOUT ROWID; + INSERT INTO t4 VALUES('abc', 'def'); + SELECT * FROM t4; +} {abc def} +do_execsql_test 2.1.2 { + UPDATE t4 SET a = 'ABC'; + SELECT * FROM t4; +} {ABC def} + +do_execsql_test 2.2.1 { + DROP TABLE t4; + CREATE TABLE t4 (b, a COLLATE nocase PRIMARY KEY) WITHOUT ROWID; + INSERT INTO t4(a, b) VALUES('abc', 'def'); + SELECT * FROM t4; +} {def abc} + +do_execsql_test 2.2.2 { + UPDATE t4 SET a = 'ABC', b = 'xyz'; + SELECT * FROM t4; +} {xyz ABC} + +do_execsql_test 2.3.1 { + CREATE TABLE t5 (a, b, PRIMARY KEY(b, a)) WITHOUT ROWID; + INSERT INTO t5(a, b) VALUES('abc', 'def'); + UPDATE t5 SET a='abc', b='def'; +} {} + +do_execsql_test 2.4.1 { + CREATE TABLE t6 ( + a COLLATE nocase, b, c UNIQUE, PRIMARY KEY(b, a) + ) WITHOUT ROWID; + + INSERT INTO t6(a, b, c) VALUES('abc', 'def', 'ghi'); + UPDATE t6 SET a='ABC', c='ghi'; +} {} + +do_execsql_test 2.4.2 { + SELECT * FROM t6 ORDER BY b, a; + SELECT * FROM t6 ORDER BY c; +} {ABC def ghi ABC def ghi} + +#------------------------------------------------------------------------- +# Unless the destination table is completely empty, the xfer optimization +# is disabled for WITHOUT ROWID tables. The following tests check for +# some problems that might occur if this were not the case. +# +reset_db +do_execsql_test 3.1.1 { + CREATE TABLE t1(a, b, PRIMARY KEY(a)) WITHOUT ROWID; + CREATE UNIQUE INDEX i1 ON t1(b); + + CREATE TABLE t2(a, b, PRIMARY KEY(a)) WITHOUT ROWID; + CREATE UNIQUE INDEX i2 ON t2(b); + + INSERT INTO t1 VALUES('one', 'two'); + INSERT INTO t2 VALUES('three', 'two'); +} + +do_execsql_test 3.1.2 { + INSERT OR REPLACE INTO t1 SELECT * FROM t2; + SELECT * FROM t1; +} {three two} + +do_execsql_test 3.1.3 { + DELETE FROM t1; + INSERT INTO t1 SELECT * FROM t2; + SELECT * FROM t1; +} {three two} + +do_catchsql_test 3.1.4 { + INSERT INTO t2 VALUES('four', 'four'); + INSERT INTO t2 VALUES('six', 'two'); + INSERT INTO t1 SELECT * FROM t2; +} {1 {UNIQUE constraint failed: t2.b}} + +do_execsql_test 3.1.5 { + CREATE TABLE t3(a PRIMARY KEY); + CREATE TABLE t4(a PRIMARY KEY); + + INSERT INTO t4 VALUES('i'); + INSERT INTO t4 VALUES('ii'); + INSERT INTO t4 VALUES('iii'); + + INSERT INTO t3 SELECT * FROM t4; + SELECT * FROM t3; +} {i ii iii} + +finish_test + diff --git a/test/without_rowid2.test b/test/without_rowid2.test new file mode 100644 index 0000000000..5ba1a23bef --- /dev/null +++ b/test/without_rowid2.test @@ -0,0 +1,125 @@ +# 2013-11-02 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# This file implements regression tests for SQLite library. The +# focus of this file is testing WITHOUT ROWID tables, and especially +# FOREIGN KEY constraints. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +ifcapable {!foreignkey} { + finish_test + return +} + +# Create a table and some data to work with. +# +do_test without_rowid2-1.0 { + execsql { + CREATE TABLE t1( + a INT PRIMARY KEY, + b INT + REFERENCES t1 ON DELETE CASCADE + REFERENCES t2, + c TEXT, + FOREIGN KEY (b,c) REFERENCES t2(x,y) ON UPDATE CASCADE + ) WITHOUT rowid; + } +} {} +do_test without_rowid2-1.1 { + execsql { + CREATE TABLE t2( + x INT PRIMARY KEY, + y TEXT + ) WITHOUT rowid; + } +} {} +do_test without_rowid2-1.2 { + execsql { + CREATE TABLE t3( + a INT REFERENCES t2, + b INT REFERENCES t1, + FOREIGN KEY (a,b) REFERENCES t2(x,y) + ); + } +} {} + +do_test without_rowid2-2.1 { + execsql { + CREATE TABLE t4(a int primary key) WITHOUT rowid; + CREATE TABLE t5(x references t4); + CREATE TABLE t6(x references t4); + CREATE TABLE t7(x references t4); + CREATE TABLE t8(x references t4); + CREATE TABLE t9(x references t4); + CREATE TABLE t10(x references t4); + DROP TABLE t7; + DROP TABLE t9; + DROP TABLE t5; + DROP TABLE t8; + DROP TABLE t6; + DROP TABLE t10; + } +} {} + +do_test without_rowid2-3.1 { + execsql { + CREATE TABLE t5(a PRIMARY KEY, b, c) WITHOUT rowid; + CREATE TABLE t6( + d REFERENCES t5, + e REFERENCES t5(c) + ); + PRAGMA foreign_key_list(t6); + } +} [concat \ + {0 0 t5 e c {NO ACTION} {NO ACTION} NONE} \ + {1 0 t5 d {} {NO ACTION} {NO ACTION} NONE} \ +] +do_test without_rowid2-3.2 { + execsql { + CREATE TABLE t7(d, e, f, + FOREIGN KEY (d, e) REFERENCES t5(a, b) + ); + PRAGMA foreign_key_list(t7); + } +} [concat \ + {0 0 t5 d a {NO ACTION} {NO ACTION} NONE} \ + {0 1 t5 e b {NO ACTION} {NO ACTION} NONE} \ +] +do_test without_rowid2-3.3 { + execsql { + CREATE TABLE t8(d, e, f, + FOREIGN KEY (d, e) REFERENCES t5 ON DELETE CASCADE ON UPDATE SET NULL + ); + PRAGMA foreign_key_list(t8); + } +} [concat \ + {0 0 t5 d {} {SET NULL} CASCADE NONE} \ + {0 1 t5 e {} {SET NULL} CASCADE NONE} \ +] +do_test without_rowid2-3.4 { + execsql { + CREATE TABLE t9(d, e, f, + FOREIGN KEY (d, e) REFERENCES t5 ON DELETE CASCADE ON UPDATE SET DEFAULT + ); + PRAGMA foreign_key_list(t9); + } +} [concat \ + {0 0 t5 d {} {SET DEFAULT} CASCADE NONE} \ + {0 1 t5 e {} {SET DEFAULT} CASCADE NONE} \ +] +do_test without_rowid2-3.5 { + sqlite3_db_status db DBSTATUS_DEFERRED_FKS 0 +} {0 0 0} + +finish_test diff --git a/test/without_rowid3.test b/test/without_rowid3.test new file mode 100644 index 0000000000..c4c2d6f483 --- /dev/null +++ b/test/without_rowid3.test @@ -0,0 +1,2084 @@ +# 2013-11-02 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# +# This file implements tests for foreign keys on WITHOUT ROWID +# tables. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +ifcapable {!foreignkey||!trigger} { + finish_test + return +} + +#------------------------------------------------------------------------- +# Test structure: +# +# without_rowid3-1.*: Simple tests to check that immediate and deferred foreign key +# constraints work when not inside a transaction. +# +# without_rowid3-2.*: Tests to verify that deferred foreign keys work inside +# explicit transactions (i.e that processing really is deferred). +# +# without_rowid3-3.*: Tests that a statement transaction is rolled back if an +# immediate foreign key constraint is violated. +# +# without_rowid3-4.*: Test that FK actions may recurse even when recursive triggers +# are disabled. +# +# without_rowid3-5.*: Check that if foreign-keys are enabled, it is not possible +# to write to an FK column using the incremental blob API. +# +# without_rowid3-6.*: Test that FK processing is automatically disabled when +# running VACUUM. +# +# without_rowid3-7.*: Test using an IPK as the key in the child (referencing) table. +# +# without_rowid3-8.*: Test that enabling/disabling foreign key support while a +# transaction is active is not possible. +# +# without_rowid3-9.*: Test SET DEFAULT actions. +# +# without_rowid3-10.*: Test errors. +# +# without_rowid3-11.*: Test CASCADE actions. +# +# without_rowid3-12.*: Test RESTRICT actions. +# +# without_rowid3-13.*: Test that FK processing is performed when a row is REPLACED by +# an UPDATE or INSERT statement. +# +# without_rowid3-14.*: Test the ALTER TABLE and DROP TABLE commands. +# +# without_rowid3-15.*: Test that if there are no (known) outstanding foreign key +# constraint violations in the database, inserting into a parent +# table or deleting from a child table does not cause SQLite +# to check if this has repaired an outstanding violation. +# +# without_rowid3-16.*: Test that rows that refer to themselves may be inserted, +# updated and deleted. +# +# without_rowid3-17.*: Test that the "count_changes" pragma does not interfere with +# FK constraint processing. +# +# without_rowid3-18.*: Test that the authorization callback is invoked when processing +# FK constraints. +# +# without_rowid3-20.*: Test that ON CONFLICT clauses specified as part of statements +# do not affect the operation of FK constraints. +# +# without_rowid3-genfkey.*: Tests that were used with the shell tool .genfkey +# command. Recycled to test the built-in implementation. +# +# without_rowid3-dd08e5.*: Tests to verify that ticket dd08e5a988d00decc4a543daa8d +# has been fixed. +# + + +execsql { PRAGMA foreign_keys = on } + +set FkeySimpleSchema { + PRAGMA foreign_keys = on; + CREATE TABLE t1(a PRIMARY KEY, b) WITHOUT rowid; + CREATE TABLE t2(c REFERENCES t1(a) /D/ , d); + + CREATE TABLE t3(a PRIMARY KEY, b) WITHOUT rowid; + CREATE TABLE t4(c REFERENCES t3 /D/, d); + + CREATE TABLE t7(a, b INT PRIMARY KEY) WITHOUT rowid; + CREATE TABLE t8(c REFERENCES t7 /D/, d); + + CREATE TABLE t9(a REFERENCES nosuchtable, b); + CREATE TABLE t10(a REFERENCES t9(c) /D/, b); +} + + +set FkeySimpleTests { + 1.1 "INSERT INTO t2 VALUES(1, 3)" {1 {FOREIGN KEY constraint failed}} + 1.2 "INSERT INTO t1 VALUES(1, 2)" {0 {}} + 1.3 "INSERT INTO t2 VALUES(1, 3)" {0 {}} + 1.4 "INSERT INTO t2 VALUES(2, 4)" {1 {FOREIGN KEY constraint failed}} + 1.5 "INSERT INTO t2 VALUES(NULL, 4)" {0 {}} + 1.6 "UPDATE t2 SET c=2 WHERE d=4" {1 {FOREIGN KEY constraint failed}} + 1.7 "UPDATE t2 SET c=1 WHERE d=4" {0 {}} + 1.9 "UPDATE t2 SET c=1 WHERE d=4" {0 {}} + 1.10 "UPDATE t2 SET c=NULL WHERE d=4" {0 {}} + 1.11 "DELETE FROM t1 WHERE a=1" {1 {FOREIGN KEY constraint failed}} + 1.12 "UPDATE t1 SET a = 2" {1 {FOREIGN KEY constraint failed}} + 1.13 "UPDATE t1 SET a = 1" {0 {}} + + 2.1 "INSERT INTO t4 VALUES(1, 3)" {1 {FOREIGN KEY constraint failed}} + 2.2 "INSERT INTO t3 VALUES(1, 2)" {0 {}} + 2.3 "INSERT INTO t4 VALUES(1, 3)" {0 {}} + + 4.1 "INSERT INTO t8 VALUES(1, 3)" {1 {FOREIGN KEY constraint failed}} + 4.2 "INSERT INTO t7 VALUES(2, 1)" {0 {}} + 4.3 "INSERT INTO t8 VALUES(1, 3)" {0 {}} + 4.4 "INSERT INTO t8 VALUES(2, 4)" {1 {FOREIGN KEY constraint failed}} + 4.5 "INSERT INTO t8 VALUES(NULL, 4)" {0 {}} + 4.6 "UPDATE t8 SET c=2 WHERE d=4" {1 {FOREIGN KEY constraint failed}} + 4.7 "UPDATE t8 SET c=1 WHERE d=4" {0 {}} + 4.9 "UPDATE t8 SET c=1 WHERE d=4" {0 {}} + 4.10 "UPDATE t8 SET c=NULL WHERE d=4" {0 {}} + 4.11 "DELETE FROM t7 WHERE b=1" {1 {FOREIGN KEY constraint failed}} + 4.12 "UPDATE t7 SET b = 2" {1 {FOREIGN KEY constraint failed}} + 4.13 "UPDATE t7 SET b = 1" {0 {}} + 4.14 "INSERT INTO t8 VALUES('a', 'b')" {1 {FOREIGN KEY constraint failed}} + 4.15 "UPDATE t7 SET b = 5" {1 {FOREIGN KEY constraint failed}} + 4.17 "UPDATE t7 SET a = 10" {0 {}} + + 5.1 "INSERT INTO t9 VALUES(1, 3)" {1 {no such table: main.nosuchtable}} + 5.2 "INSERT INTO t10 VALUES(1, 3)" + {1 {foreign key mismatch - "t10" referencing "t9"}} +} + +do_test without_rowid3-1.1.0 { + execsql [string map {/D/ {}} $FkeySimpleSchema] +} {} +foreach {tn zSql res} $FkeySimpleTests { + do_test without_rowid3-1.1.$tn.1 { catchsql $zSql } $res + do_test without_rowid3-1.1.$tn.2 { execsql {PRAGMA foreign_key_check(t1)} } {} + do_test without_rowid3-1.1.$tn.3 { execsql {PRAGMA foreign_key_check(t2)} } {} + do_test without_rowid3-1.1.$tn.4 { execsql {PRAGMA foreign_key_check(t3)} } {} + do_test without_rowid3-1.1.$tn.5 { execsql {PRAGMA foreign_key_check(t4)} } {} + do_test without_rowid3-1.1.$tn.6 { execsql {PRAGMA foreign_key_check(t7)} } {} + do_test without_rowid3-1.1.$tn.7 { execsql {PRAGMA foreign_key_check(t8)} } {} +} +drop_all_tables + +do_test without_rowid3-1.2.0 { + execsql [string map {/D/ {DEFERRABLE INITIALLY DEFERRED}} $FkeySimpleSchema] +} {} +foreach {tn zSql res} $FkeySimpleTests { + do_test without_rowid3-1.2.$tn { catchsql $zSql } $res + do_test without_rowid3-1.2.$tn.2 { execsql {PRAGMA foreign_key_check(t1)} } {} + do_test without_rowid3-1.2.$tn.3 { execsql {PRAGMA foreign_key_check(t2)} } {} + do_test without_rowid3-1.2.$tn.4 { execsql {PRAGMA foreign_key_check(t3)} } {} + do_test without_rowid3-1.2.$tn.5 { execsql {PRAGMA foreign_key_check(t4)} } {} + do_test without_rowid3-1.2.$tn.6 { execsql {PRAGMA foreign_key_check(t7)} } {} + do_test without_rowid3-1.2.$tn.7 { execsql {PRAGMA foreign_key_check(t8)} } {} +} +drop_all_tables + +do_test without_rowid3-1.3.0 { + execsql [string map {/D/ {}} $FkeySimpleSchema] + execsql { PRAGMA count_changes = 1 } +} {} +foreach {tn zSql res} $FkeySimpleTests { + if {$res == "0 {}"} { set res {0 1} } + do_test without_rowid3-1.3.$tn { catchsql $zSql } $res + do_test without_rowid3-1.3.$tn.2 { execsql {PRAGMA foreign_key_check(t1)} } {} + do_test without_rowid3-1.3.$tn.3 { execsql {PRAGMA foreign_key_check(t2)} } {} + do_test without_rowid3-1.3.$tn.4 { execsql {PRAGMA foreign_key_check(t3)} } {} + do_test without_rowid3-1.3.$tn.5 { execsql {PRAGMA foreign_key_check(t4)} } {} + do_test without_rowid3-1.3.$tn.6 { execsql {PRAGMA foreign_key_check(t7)} } {} + do_test without_rowid3-1.3.$tn.7 { execsql {PRAGMA foreign_key_check(t8)} } {} +} +execsql { PRAGMA count_changes = 0 } +drop_all_tables + +do_test without_rowid3-1.4.0 { + execsql [string map {/D/ {}} $FkeySimpleSchema] + execsql { PRAGMA count_changes = 1 } +} {} +foreach {tn zSql res} $FkeySimpleTests { + if {$res == "0 {}"} { set res {0 1} } + execsql BEGIN + do_test without_rowid3-1.4.$tn { catchsql $zSql } $res + execsql COMMIT +} +execsql { PRAGMA count_changes = 0 } +drop_all_tables + +# Special test: When the parent key is an IPK, make sure the affinity of +# the IPK is not applied to the child key value before it is inserted +# into the child table. +do_test without_rowid3-1.5.1 { + execsql { + CREATE TABLE i(i INT PRIMARY KEY) WITHOUT rowid; + CREATE TABLE j(j REFERENCES i); + INSERT INTO i VALUES(35); + INSERT INTO j VALUES('35.0'); + SELECT j, typeof(j) FROM j; + } +} {35.0 text} +do_test without_rowid3-1.5.2 { + catchsql { DELETE FROM i } +} {1 {FOREIGN KEY constraint failed}} + +# Same test using a regular primary key with integer affinity. +drop_all_tables +do_test without_rowid3-1.6.1 { + execsql { + CREATE TABLE i(i INT UNIQUE); + CREATE TABLE j(j REFERENCES i(i)); + INSERT INTO i VALUES('35.0'); + INSERT INTO j VALUES('35.0'); + SELECT j, typeof(j) FROM j; + SELECT i, typeof(i) FROM i; + } +} {35.0 text 35 integer} +do_test without_rowid3-1.6.2 { + catchsql { DELETE FROM i } +} {1 {FOREIGN KEY constraint failed}} + +# Use a collation sequence on the parent key. +drop_all_tables +do_test without_rowid3-1.7.1 { + execsql { + CREATE TABLE i(i TEXT COLLATE nocase PRIMARY KEY) WITHOUT rowid; + CREATE TABLE j(j TEXT COLLATE binary REFERENCES i(i)); + INSERT INTO i VALUES('SQLite'); + INSERT INTO j VALUES('sqlite'); + } + catchsql { DELETE FROM i } +} {1 {FOREIGN KEY constraint failed}} + +# Use the parent key collation even if it is default and the child key +# has an explicit value. +drop_all_tables +do_test without_rowid3-1.7.2 { + execsql { + CREATE TABLE i(i TEXT PRIMARY KEY) WITHOUT rowid; -- Colseq is "BINARY" + CREATE TABLE j(j TEXT COLLATE nocase REFERENCES i(i)); + INSERT INTO i VALUES('SQLite'); + } + catchsql { INSERT INTO j VALUES('sqlite') } +} {1 {FOREIGN KEY constraint failed}} +do_test without_rowid3-1.7.3 { + execsql { + INSERT INTO i VALUES('sqlite'); + INSERT INTO j VALUES('sqlite'); + DELETE FROM i WHERE i = 'SQLite'; + } + catchsql { DELETE FROM i WHERE i = 'sqlite' } +} {1 {FOREIGN KEY constraint failed}} + +#------------------------------------------------------------------------- +# This section (test cases without_rowid3-2.*) contains tests to check that the +# deferred foreign key constraint logic works. +# +proc without_rowid3-2-test {tn nocommit sql {res {}}} { + if {$res eq "FKV"} { + set expected {1 {FOREIGN KEY constraint failed}} + } else { + set expected [list 0 $res] + } + do_test without_rowid3-2.$tn [list catchsql $sql] $expected + if {$nocommit} { + do_test without_rowid3-2.${tn}c { + catchsql COMMIT + } {1 {FOREIGN KEY constraint failed}} + } +} + +without_rowid3-2-test 1 0 { + CREATE TABLE node( + nodeid PRIMARY KEY, + parent REFERENCES node DEFERRABLE INITIALLY DEFERRED + ) WITHOUT rowid; + CREATE TABLE leaf( + cellid PRIMARY KEY, + parent REFERENCES node DEFERRABLE INITIALLY DEFERRED + ) WITHOUT rowid; +} + +without_rowid3-2-test 1 0 "INSERT INTO node VALUES(1, 0)" FKV +without_rowid3-2-test 2 0 "BEGIN" +without_rowid3-2-test 3 1 "INSERT INTO node VALUES(1, 0)" +without_rowid3-2-test 4 0 "UPDATE node SET parent = NULL" +without_rowid3-2-test 5 0 "COMMIT" +without_rowid3-2-test 6 0 "SELECT * FROM node" {1 {}} + +without_rowid3-2-test 7 0 "BEGIN" +without_rowid3-2-test 8 1 "INSERT INTO leaf VALUES('a', 2)" +without_rowid3-2-test 9 1 "INSERT INTO node VALUES(2, 0)" +without_rowid3-2-test 10 0 "UPDATE node SET parent = 1 WHERE nodeid = 2" +without_rowid3-2-test 11 0 "COMMIT" +without_rowid3-2-test 12 0 "SELECT * FROM node" {1 {} 2 1} +without_rowid3-2-test 13 0 "SELECT * FROM leaf" {a 2} + +without_rowid3-2-test 14 0 "BEGIN" +without_rowid3-2-test 15 1 "DELETE FROM node WHERE nodeid = 2" +without_rowid3-2-test 16 0 "INSERT INTO node VALUES(2, NULL)" +without_rowid3-2-test 17 0 "COMMIT" +without_rowid3-2-test 18 0 "SELECT * FROM node" {1 {} 2 {}} +without_rowid3-2-test 19 0 "SELECT * FROM leaf" {a 2} + +without_rowid3-2-test 20 0 "BEGIN" +without_rowid3-2-test 21 0 "INSERT INTO leaf VALUES('b', 1)" +without_rowid3-2-test 22 0 "SAVEPOINT save" +without_rowid3-2-test 23 0 "DELETE FROM node WHERE nodeid = 1" +without_rowid3-2-test 24 0 "ROLLBACK TO save" +without_rowid3-2-test 25 0 "COMMIT" +without_rowid3-2-test 26 0 "SELECT * FROM node" {1 {} 2 {}} +without_rowid3-2-test 27 0 "SELECT * FROM leaf" {a 2 b 1} + +without_rowid3-2-test 28 0 "BEGIN" +without_rowid3-2-test 29 0 "INSERT INTO leaf VALUES('c', 1)" +without_rowid3-2-test 30 0 "SAVEPOINT save" +without_rowid3-2-test 31 0 "DELETE FROM node WHERE nodeid = 1" +without_rowid3-2-test 32 1 "RELEASE save" +without_rowid3-2-test 33 1 "DELETE FROM leaf WHERE cellid = 'b'" +without_rowid3-2-test 34 0 "DELETE FROM leaf WHERE cellid = 'c'" +without_rowid3-2-test 35 0 "COMMIT" +without_rowid3-2-test 36 0 "SELECT * FROM node" {2 {}} +without_rowid3-2-test 37 0 "SELECT * FROM leaf" {a 2} + +without_rowid3-2-test 38 0 "SAVEPOINT outer" +without_rowid3-2-test 39 1 "INSERT INTO leaf VALUES('d', 3)" +without_rowid3-2-test 40 1 "RELEASE outer" FKV +without_rowid3-2-test 41 1 "INSERT INTO leaf VALUES('e', 3)" +without_rowid3-2-test 42 0 "INSERT INTO node VALUES(3, 2)" +without_rowid3-2-test 43 0 "RELEASE outer" + +without_rowid3-2-test 44 0 "SAVEPOINT outer" +without_rowid3-2-test 45 1 "DELETE FROM node WHERE nodeid=3" +without_rowid3-2-test 47 0 "INSERT INTO node VALUES(3, 2)" +without_rowid3-2-test 48 0 "ROLLBACK TO outer" +without_rowid3-2-test 49 0 "RELEASE outer" + +without_rowid3-2-test 50 0 "SAVEPOINT outer" +without_rowid3-2-test 51 1 "INSERT INTO leaf VALUES('f', 4)" +without_rowid3-2-test 52 1 "SAVEPOINT inner" +without_rowid3-2-test 53 1 "INSERT INTO leaf VALUES('g', 4)" +without_rowid3-2-test 54 1 "RELEASE outer" FKV +without_rowid3-2-test 55 1 "ROLLBACK TO inner" +without_rowid3-2-test 56 0 "COMMIT" FKV +without_rowid3-2-test 57 0 "INSERT INTO node VALUES(4, NULL)" +without_rowid3-2-test 58 0 "RELEASE outer" +without_rowid3-2-test 59 0 "SELECT * FROM node" {2 {} 3 2 4 {}} +without_rowid3-2-test 60 0 "SELECT * FROM leaf" {a 2 d 3 e 3 f 4} + +# The following set of tests check that if a statement that affects +# multiple rows violates some foreign key constraints, then strikes a +# constraint that causes the statement-transaction to be rolled back, +# the deferred constraint counter is correctly reset to the value it +# had before the statement-transaction was opened. +# +without_rowid3-2-test 61 0 "BEGIN" +without_rowid3-2-test 62 0 "DELETE FROM leaf" +without_rowid3-2-test 63 0 "DELETE FROM node" +without_rowid3-2-test 64 1 "INSERT INTO leaf VALUES('a', 1)" +without_rowid3-2-test 65 1 "INSERT INTO leaf VALUES('b', 2)" +without_rowid3-2-test 66 1 "INSERT INTO leaf VALUES('c', 1)" +do_test without_rowid3-2-test-67 { + catchsql "INSERT INTO node SELECT parent, 3 FROM leaf" +} {1 {UNIQUE constraint failed: node.nodeid}} +without_rowid3-2-test 68 0 "COMMIT" FKV +without_rowid3-2-test 69 1 "INSERT INTO node VALUES(1, NULL)" +without_rowid3-2-test 70 0 "INSERT INTO node VALUES(2, NULL)" +without_rowid3-2-test 71 0 "COMMIT" + +without_rowid3-2-test 72 0 "BEGIN" +without_rowid3-2-test 73 1 "DELETE FROM node" +without_rowid3-2-test 74 0 "INSERT INTO node(nodeid) SELECT DISTINCT parent FROM leaf" +without_rowid3-2-test 75 0 "COMMIT" + +#------------------------------------------------------------------------- +# Test cases without_rowid3-3.* test that a program that executes foreign key +# actions (CASCADE, SET DEFAULT, SET NULL etc.) or tests FK constraints +# opens a statement transaction if required. +# +# without_rowid3-3.1.*: Test UPDATE statements. +# without_rowid3-3.2.*: Test DELETE statements. +# +drop_all_tables +do_test without_rowid3-3.1.1 { + execsql { + CREATE TABLE ab(a PRIMARY KEY, b) WITHOUT rowid; + CREATE TABLE cd( + c PRIMARY KEY REFERENCES ab ON UPDATE CASCADE ON DELETE CASCADE, + d + ) WITHOUT rowid; + CREATE TABLE ef( + e REFERENCES cd ON UPDATE CASCADE, + f, CHECK (e!=5) + ); + } +} {} +do_test without_rowid3-3.1.2 { + execsql { + INSERT INTO ab VALUES(1, 'b'); + INSERT INTO cd VALUES(1, 'd'); + INSERT INTO ef VALUES(1, 'e'); + } +} {} +do_test without_rowid3-3.1.3 { + catchsql { UPDATE ab SET a = 5 } +} {1 {CHECK constraint failed: ef}} +do_test without_rowid3-3.1.4 { + execsql { SELECT * FROM ab } +} {1 b} +do_test without_rowid3-3.1.4 { + execsql BEGIN; + catchsql { UPDATE ab SET a = 5 } +} {1 {CHECK constraint failed: ef}} +do_test without_rowid3-3.1.5 { + execsql COMMIT; + execsql { SELECT * FROM ab; SELECT * FROM cd; SELECT * FROM ef } +} {1 b 1 d 1 e} + +do_test without_rowid3-3.2.1 { + execsql BEGIN; + catchsql { DELETE FROM ab } +} {1 {FOREIGN KEY constraint failed}} +do_test without_rowid3-3.2.2 { + execsql COMMIT + execsql { SELECT * FROM ab; SELECT * FROM cd; SELECT * FROM ef } +} {1 b 1 d 1 e} + +#------------------------------------------------------------------------- +# Test cases without_rowid3-4.* test that recursive foreign key actions +# (i.e. CASCADE) are allowed even if recursive triggers are disabled. +# +drop_all_tables +do_test without_rowid3-4.1 { + execsql { + CREATE TABLE t1( + node PRIMARY KEY, + parent REFERENCES t1 ON DELETE CASCADE + ) WITHOUT rowid; + CREATE TABLE t2(node PRIMARY KEY, parent) WITHOUT rowid; + CREATE TRIGGER t2t AFTER DELETE ON t2 BEGIN + DELETE FROM t2 WHERE parent = old.node; + END; + INSERT INTO t1 VALUES(1, NULL); + INSERT INTO t1 VALUES(2, 1); + INSERT INTO t1 VALUES(3, 1); + INSERT INTO t1 VALUES(4, 2); + INSERT INTO t1 VALUES(5, 2); + INSERT INTO t1 VALUES(6, 3); + INSERT INTO t1 VALUES(7, 3); + INSERT INTO t2 SELECT * FROM t1; + } +} {} +do_test without_rowid3-4.2 { + execsql { PRAGMA recursive_triggers = off } + execsql { + BEGIN; + DELETE FROM t1 WHERE node = 1; + SELECT node FROM t1; + } +} {} +do_test without_rowid3-4.3 { + execsql { + DELETE FROM t2 WHERE node = 1; + SELECT node FROM t2; + ROLLBACK; + } +} {4 5 6 7} +do_test without_rowid3-4.4 { + execsql { PRAGMA recursive_triggers = on } + execsql { + BEGIN; + DELETE FROM t1 WHERE node = 1; + SELECT node FROM t1; + } +} {} +do_test without_rowid3-4.3 { + execsql { + DELETE FROM t2 WHERE node = 1; + SELECT node FROM t2; + ROLLBACK; + } +} {} + +#------------------------------------------------------------------------- +# Test cases without_rowid3-5.* verify that the incremental blob API may not +# write to a foreign key column while foreign-keys are enabled. +# +drop_all_tables +ifcapable incrblob { + do_test without_rowid3-5.1 { + execsql { + CREATE TABLE t1(a PRIMARY KEY, b) WITHOUT rowid; + CREATE TABLE t2(a PRIMARY KEY, b REFERENCES t1(a)) WITHOUT rowid; + INSERT INTO t1 VALUES('hello', 'world'); + INSERT INTO t2 VALUES('key', 'hello'); + } + } {} + do_test without_rowid3-5.2 { + set rc [catch { set fd [db incrblob t2 b 1] } msg] + list $rc $msg + } {1 {cannot open table without rowid: t2}} + do_test without_rowid3-5.5 { + execsql { PRAGMA foreign_keys = on } + } {} +} + +drop_all_tables +ifcapable vacuum { + do_test without_rowid3-6.1 { + execsql { + CREATE TABLE t1(a REFERENCES t2(c), b); + CREATE TABLE t2(c UNIQUE, b); + INSERT INTO t2 VALUES(1, 2); + INSERT INTO t1 VALUES(1, 2); + VACUUM; + } + } {} +} + +#------------------------------------------------------------------------- +# Test that it is possible to use an INT PRIMARY KEY as the child key +# of a foreign constraint. +# +drop_all_tables +do_test without_rowid3-7.1 { + execsql { + CREATE TABLE t1(a PRIMARY KEY, b) WITHOUT rowid; + CREATE TABLE t2(c INT PRIMARY KEY REFERENCES t1, b) WITHOUT rowid; + } +} {} +do_test without_rowid3-7.2 { + catchsql { INSERT INTO t2 VALUES(1, 'A'); } +} {1 {FOREIGN KEY constraint failed}} +do_test without_rowid3-7.3 { + execsql { + INSERT INTO t1 VALUES(1, 2); + INSERT INTO t1 VALUES(2, 3); + INSERT INTO t2 VALUES(1, 'A'); + } +} {} +do_test without_rowid3-7.4 { + execsql { UPDATE t2 SET c = 2 } +} {} +do_test without_rowid3-7.5 { + catchsql { UPDATE t2 SET c = 3 } +} {1 {FOREIGN KEY constraint failed}} +do_test without_rowid3-7.6 { + catchsql { DELETE FROM t1 WHERE a = 2 } +} {1 {FOREIGN KEY constraint failed}} +do_test without_rowid3-7.7 { + execsql { DELETE FROM t1 WHERE a = 1 } +} {} +do_test without_rowid3-7.8 { + catchsql { UPDATE t1 SET a = 3 } +} {1 {FOREIGN KEY constraint failed}} + +#------------------------------------------------------------------------- +# Test that it is not possible to enable/disable FK support while a +# transaction is open. +# +drop_all_tables +proc without_rowid3-8-test {tn zSql value} { + do_test without_rowid3-2.8.$tn.1 [list execsql $zSql] {} + do_test without_rowid3-2.8.$tn.2 { execsql "PRAGMA foreign_keys" } $value +} +without_rowid3-8-test 1 { PRAGMA foreign_keys = 0 } 0 +without_rowid3-8-test 2 { PRAGMA foreign_keys = 1 } 1 +without_rowid3-8-test 3 { BEGIN } 1 +without_rowid3-8-test 4 { PRAGMA foreign_keys = 0 } 1 +without_rowid3-8-test 5 { COMMIT } 1 +without_rowid3-8-test 6 { PRAGMA foreign_keys = 0 } 0 +without_rowid3-8-test 7 { BEGIN } 0 +without_rowid3-8-test 8 { PRAGMA foreign_keys = 1 } 0 +without_rowid3-8-test 9 { COMMIT } 0 +without_rowid3-8-test 10 { PRAGMA foreign_keys = 1 } 1 +without_rowid3-8-test 11 { PRAGMA foreign_keys = off } 0 +without_rowid3-8-test 12 { PRAGMA foreign_keys = on } 1 +without_rowid3-8-test 13 { PRAGMA foreign_keys = no } 0 +without_rowid3-8-test 14 { PRAGMA foreign_keys = yes } 1 +without_rowid3-8-test 15 { PRAGMA foreign_keys = false } 0 +without_rowid3-8-test 16 { PRAGMA foreign_keys = true } 1 + +#------------------------------------------------------------------------- +# The following tests, without_rowid3-9.*, test SET DEFAULT actions. +# +drop_all_tables +do_test without_rowid3-9.1.1 { + execsql { + CREATE TABLE t1(a INT PRIMARY KEY, b) WITHOUT rowid; + CREATE TABLE t2( + c INT PRIMARY KEY, + d INTEGER DEFAULT 1 REFERENCES t1 ON DELETE SET DEFAULT + ) WITHOUT rowid; + DELETE FROM t1; + } +} {} +do_test without_rowid3-9.1.2 { + execsql { + INSERT INTO t1 VALUES(1, 'one'); + INSERT INTO t1 VALUES(2, 'two'); + INSERT INTO t2 VALUES(1, 2); + SELECT * FROM t2; + DELETE FROM t1 WHERE a = 2; + SELECT * FROM t2; + } +} {1 2 1 1} +do_test without_rowid3-9.1.3 { + execsql { + INSERT INTO t1 VALUES(2, 'two'); + UPDATE t2 SET d = 2; + DELETE FROM t1 WHERE a = 1; + SELECT * FROM t2; + } +} {1 2} +do_test without_rowid3-9.1.4 { + execsql { SELECT * FROM t1 } +} {2 two} +do_test without_rowid3-9.1.5 { + catchsql { DELETE FROM t1 } +} {1 {FOREIGN KEY constraint failed}} + +do_test without_rowid3-9.2.1 { + execsql { + CREATE TABLE pp(a, b, c, PRIMARY KEY(b, c)) WITHOUT rowid; + CREATE TABLE cc(d DEFAULT 3, e DEFAULT 1, f DEFAULT 2, + FOREIGN KEY(f, d) REFERENCES pp + ON UPDATE SET DEFAULT + ON DELETE SET NULL + ); + INSERT INTO pp VALUES(1, 2, 3); + INSERT INTO pp VALUES(4, 5, 6); + INSERT INTO pp VALUES(7, 8, 9); + } +} {} +do_test without_rowid3-9.2.2 { + execsql { + INSERT INTO cc VALUES(6, 'A', 5); + INSERT INTO cc VALUES(6, 'B', 5); + INSERT INTO cc VALUES(9, 'A', 8); + INSERT INTO cc VALUES(9, 'B', 8); + UPDATE pp SET b = 1 WHERE a = 7; + SELECT * FROM cc; + } +} {6 A 5 6 B 5 3 A 2 3 B 2} +do_test without_rowid3-9.2.3 { + execsql { + DELETE FROM pp WHERE a = 4; + SELECT * FROM cc; + } +} {{} A {} {} B {} 3 A 2 3 B 2} + +#------------------------------------------------------------------------- +# The following tests, without_rowid3-10.*, test "foreign key mismatch" and +# other errors. +# +set tn 0 +foreach zSql [list { + CREATE TABLE p(a PRIMARY KEY, b) WITHOUT rowid; + CREATE TABLE c(x REFERENCES p(c)); +} { + CREATE TABLE c(x REFERENCES v(y)); + CREATE VIEW v AS SELECT x AS y FROM c; +} { + CREATE TABLE p(a, b, PRIMARY KEY(a, b)) WITHOUT rowid; + CREATE TABLE c(x REFERENCES p); +} { + CREATE TABLE p(a COLLATE binary, b); + CREATE UNIQUE INDEX i ON p(a COLLATE nocase); + CREATE TABLE c(x REFERENCES p(a)); +}] { + drop_all_tables + do_test without_rowid3-10.1.[incr tn] { + execsql $zSql + catchsql { INSERT INTO c DEFAULT VALUES } + } {/1 {foreign key mismatch - "c" referencing "."}/} +} + +# "rowid" cannot be used as part of a child or parent key definition +# unless it happens to be the name of an explicitly declared column. +# +do_test without_rowid3-10.2.1 { + drop_all_tables + catchsql { + CREATE TABLE t1(a PRIMARY KEY, b) WITHOUT rowid; + CREATE TABLE t2(c, d, FOREIGN KEY(rowid) REFERENCES t1(a)); + } +} {1 {unknown column "rowid" in foreign key definition}} +do_test without_rowid3-10.2.2 { + drop_all_tables + catchsql { + CREATE TABLE t1(a PRIMARY KEY, b) WITHOUT rowid; + CREATE TABLE t2(rowid, d, FOREIGN KEY(rowid) REFERENCES t1(a)); + } +} {0 {}} +do_test without_rowid3-10.2.1 { + drop_all_tables + catchsql { + CREATE TABLE t1(a, b); + CREATE TABLE t2(c, d, FOREIGN KEY(c) REFERENCES t1(rowid)); + INSERT INTO t1(rowid, a, b) VALUES(1, 1, 1); + INSERT INTO t2 VALUES(1, 1); + } +} {1 {foreign key mismatch - "t2" referencing "t1"}} +do_test without_rowid3-10.2.2 { + drop_all_tables + catchsql { + CREATE TABLE t1(rowid PRIMARY KEY, b) WITHOUT rowid; + CREATE TABLE t2(c, d, FOREIGN KEY(c) REFERENCES t1(rowid)); + INSERT INTO t1(rowid, b) VALUES(1, 1); + INSERT INTO t2 VALUES(1, 1); + } +} {0 {}} + + +#------------------------------------------------------------------------- +# The following tests, without_rowid3-11.*, test CASCADE actions. +# +drop_all_tables +do_test without_rowid3-11.1.1 { + execsql { + CREATE TABLE t1(a INT PRIMARY KEY, b) WITHOUT rowid; + CREATE TABLE t2(c, d, FOREIGN KEY(c) REFERENCES t1(a) ON UPDATE CASCADE); + + INSERT INTO t1 VALUES(10, 100); + INSERT INTO t2 VALUES(10, 100); + UPDATE t1 SET a = 15; + SELECT * FROM t2; + } +} {15 100} + +#------------------------------------------------------------------------- +# The following tests, without_rowid3-12.*, test RESTRICT actions. +# +drop_all_tables +do_test without_rowid3-12.1.1 { + execsql { + CREATE TABLE t1(a, b PRIMARY KEY) WITHOUT rowid; + CREATE TABLE t2( + x REFERENCES t1 ON UPDATE RESTRICT DEFERRABLE INITIALLY DEFERRED + ); + INSERT INTO t1 VALUES(1, 'one'); + INSERT INTO t1 VALUES(2, 'two'); + INSERT INTO t1 VALUES(3, 'three'); + } +} {} +do_test without_rowid3-12.1.2 { + execsql "BEGIN" + execsql "INSERT INTO t2 VALUES('two')" +} {} +do_test without_rowid3-12.1.3 { + execsql "UPDATE t1 SET b = 'four' WHERE b = 'one'" +} {} +do_test without_rowid3-12.1.4 { + catchsql "UPDATE t1 SET b = 'five' WHERE b = 'two'" +} {1 {FOREIGN KEY constraint failed}} +do_test without_rowid3-12.1.5 { + execsql "DELETE FROM t1 WHERE b = 'two'" +} {} +do_test without_rowid3-12.1.6 { + catchsql "COMMIT" +} {1 {FOREIGN KEY constraint failed}} +do_test without_rowid3-12.1.7 { + execsql { + INSERT INTO t1 VALUES(2, 'two'); + COMMIT; + } +} {} + +drop_all_tables +do_test without_rowid3-12.2.1 { + execsql { + CREATE TABLE t1(x COLLATE NOCASE PRIMARY KEY) WITHOUT rowid; + CREATE TRIGGER tt1 AFTER DELETE ON t1 + WHEN EXISTS ( SELECT 1 FROM t2 WHERE old.x = y ) + BEGIN + INSERT INTO t1 VALUES(old.x); + END; + CREATE TABLE t2(y REFERENCES t1); + INSERT INTO t1 VALUES('A'); + INSERT INTO t1 VALUES('B'); + INSERT INTO t2 VALUES('a'); + INSERT INTO t2 VALUES('b'); + + SELECT * FROM t1; + SELECT * FROM t2; + } +} {A B a b} +do_test without_rowid3-12.2.2 { + execsql { DELETE FROM t1 } + execsql { + SELECT * FROM t1; + SELECT * FROM t2; + } +} {A B a b} +do_test without_rowid3-12.2.3 { + execsql { + DROP TABLE t2; + CREATE TABLE t2(y REFERENCES t1 ON DELETE RESTRICT); + INSERT INTO t2 VALUES('a'); + INSERT INTO t2 VALUES('b'); + } + catchsql { DELETE FROM t1 } +} {1 {FOREIGN KEY constraint failed}} +do_test without_rowid3-12.2.4 { + execsql { + SELECT * FROM t1; + SELECT * FROM t2; + } +} {A B a b} + +drop_all_tables +do_test without_rowid3-12.3.1 { + execsql { + CREATE TABLE up( + c00, c01, c02, c03, c04, c05, c06, c07, c08, c09, + c10, c11, c12, c13, c14, c15, c16, c17, c18, c19, + c20, c21, c22, c23, c24, c25, c26, c27, c28, c29, + c30, c31, c32, c33, c34, c35, c36, c37, c38, c39, + PRIMARY KEY(c34, c35) + ) WITHOUT rowid; + CREATE TABLE down( + c00, c01, c02, c03, c04, c05, c06, c07, c08, c09, + c10, c11, c12, c13, c14, c15, c16, c17, c18, c19, + c20, c21, c22, c23, c24, c25, c26, c27, c28, c29, + c30, c31, c32, c33, c34, c35, c36, c37, c38, c39, + FOREIGN KEY(c39, c38) REFERENCES up ON UPDATE CASCADE + ); + } +} {} +do_test without_rowid3-12.3.2 { + execsql { + INSERT INTO up(c34, c35) VALUES('yes', 'no'); + INSERT INTO down(c39, c38) VALUES('yes', 'no'); + UPDATE up SET c34 = 'possibly'; + SELECT c38, c39 FROM down; + DELETE FROM down; + } +} {no possibly} +do_test without_rowid3-12.3.3 { + catchsql { INSERT INTO down(c39, c38) VALUES('yes', 'no') } +} {1 {FOREIGN KEY constraint failed}} +do_test without_rowid3-12.3.4 { + execsql { + INSERT INTO up(c34, c35) VALUES('yes', 'no'); + INSERT INTO down(c39, c38) VALUES('yes', 'no'); + } + catchsql { DELETE FROM up WHERE c34 = 'yes' } +} {1 {FOREIGN KEY constraint failed}} +do_test without_rowid3-12.3.5 { + execsql { + DELETE FROM up WHERE c34 = 'possibly'; + SELECT c34, c35 FROM up; + SELECT c39, c38 FROM down; + } +} {yes no yes no} + +#------------------------------------------------------------------------- +# The following tests, without_rowid3-13.*, test that FK processing is performed +# when rows are REPLACEd. +# +drop_all_tables +do_test without_rowid3-13.1.1 { + execsql { + CREATE TABLE pp(a UNIQUE, b, c, PRIMARY KEY(b, c)) WITHOUT rowid; + CREATE TABLE cc(d, e, f UNIQUE, FOREIGN KEY(d, e) REFERENCES pp); + INSERT INTO pp VALUES(1, 2, 3); + INSERT INTO cc VALUES(2, 3, 1); + } +} {} +foreach {tn stmt} { + 1 "REPLACE INTO pp VALUES(1, 4, 5)" +} { + do_test without_rowid3-13.1.$tn.1 { + catchsql $stmt + } {1 {FOREIGN KEY constraint failed}} + do_test without_rowid3-13.1.$tn.2 { + execsql { + SELECT * FROM pp; + SELECT * FROM cc; + } + } {1 2 3 2 3 1} + do_test without_rowid3-13.1.$tn.3 { + execsql BEGIN; + catchsql $stmt + } {1 {FOREIGN KEY constraint failed}} + do_test without_rowid3-13.1.$tn.4 { + execsql { + COMMIT; + SELECT * FROM pp; + SELECT * FROM cc; + } + } {1 2 3 2 3 1} +} + +#------------------------------------------------------------------------- +# The following tests, without_rowid3-14.*, test that the "DROP TABLE" and "ALTER +# TABLE" commands work as expected wrt foreign key constraints. +# +# without_rowid3-14.1*: ALTER TABLE ADD COLUMN +# without_rowid3-14.2*: ALTER TABLE RENAME TABLE +# without_rowid3-14.3*: DROP TABLE +# +drop_all_tables +ifcapable altertable { + do_test without_rowid3-14.1.1 { + # Adding a column with a REFERENCES clause is not supported. + execsql { + CREATE TABLE t1(a PRIMARY KEY) WITHOUT rowid; + CREATE TABLE t2(a, b); + } + catchsql { ALTER TABLE t2 ADD COLUMN c REFERENCES t1 } + } {0 {}} + do_test without_rowid3-14.1.2 { + catchsql { ALTER TABLE t2 ADD COLUMN d DEFAULT NULL REFERENCES t1 } + } {0 {}} + do_test without_rowid3-14.1.3 { + catchsql { ALTER TABLE t2 ADD COLUMN e REFERENCES t1 DEFAULT NULL} + } {0 {}} + do_test without_rowid3-14.1.4 { + catchsql { ALTER TABLE t2 ADD COLUMN f REFERENCES t1 DEFAULT 'text'} + } {1 {Cannot add a REFERENCES column with non-NULL default value}} + do_test without_rowid3-14.1.5 { + catchsql { ALTER TABLE t2 ADD COLUMN g DEFAULT CURRENT_TIME REFERENCES t1 } + } {1 {Cannot add a REFERENCES column with non-NULL default value}} + do_test without_rowid3-14.1.6 { + execsql { + PRAGMA foreign_keys = off; + ALTER TABLE t2 ADD COLUMN h DEFAULT 'text' REFERENCES t1; + PRAGMA foreign_keys = on; + SELECT sql FROM sqlite_master WHERE name='t2'; + } + } {{CREATE TABLE t2(a, b, c REFERENCES t1, d DEFAULT NULL REFERENCES t1, e REFERENCES t1 DEFAULT NULL, h DEFAULT 'text' REFERENCES t1)}} + + + # Test the sqlite_rename_parent() function directly. + # + proc test_rename_parent {zCreate zOld zNew} { + db eval {SELECT sqlite_rename_parent($zCreate, $zOld, $zNew)} + } + do_test without_rowid3-14.2.1.1 { + test_rename_parent {CREATE TABLE t1(a REFERENCES t2)} t2 t3 + } {{CREATE TABLE t1(a REFERENCES "t3")}} + do_test without_rowid3-14.2.1.2 { + test_rename_parent {CREATE TABLE t1(a REFERENCES t2)} t4 t3 + } {{CREATE TABLE t1(a REFERENCES t2)}} + do_test without_rowid3-14.2.1.3 { + test_rename_parent {CREATE TABLE t1(a REFERENCES "t2")} t2 t3 + } {{CREATE TABLE t1(a REFERENCES "t3")}} + + # Test ALTER TABLE RENAME TABLE a bit. + # + do_test without_rowid3-14.2.2.1 { + drop_all_tables + execsql { + CREATE TABLE t1(a PRIMARY KEY, b REFERENCES t1) WITHOUT rowid; + CREATE TABLE t2(a PRIMARY KEY, b REFERENCES t1, c REFERENCES t2) + WITHOUT rowid; + CREATE TABLE t3(a REFERENCES t1, b REFERENCES t2, c REFERENCES t1); + } + execsql { SELECT sql FROM sqlite_master WHERE type = 'table'} + } [list \ + {CREATE TABLE t1(a PRIMARY KEY, b REFERENCES t1) WITHOUT rowid} \ + {CREATE TABLE t2(a PRIMARY KEY, b REFERENCES t1, c REFERENCES t2) + WITHOUT rowid} \ + {CREATE TABLE t3(a REFERENCES t1, b REFERENCES t2, c REFERENCES t1)} \ + ] + do_test without_rowid3-14.2.2.2 { + execsql { ALTER TABLE t1 RENAME TO t4 } + execsql { SELECT sql FROM sqlite_master WHERE type = 'table'} + } [list \ + {CREATE TABLE "t4"(a PRIMARY KEY, b REFERENCES "t4") WITHOUT rowid} \ + {CREATE TABLE t2(a PRIMARY KEY, b REFERENCES "t4", c REFERENCES t2) + WITHOUT rowid} \ + {CREATE TABLE t3(a REFERENCES "t4", b REFERENCES t2, c REFERENCES "t4")} \ + ] + do_test without_rowid3-14.2.2.3 { + catchsql { INSERT INTO t3 VALUES(1, 2, 3) } + } {1 {FOREIGN KEY constraint failed}} + do_test without_rowid3-14.2.2.4 { + execsql { INSERT INTO t4 VALUES(1, NULL) } + } {} + do_test without_rowid3-14.2.2.5 { + catchsql { UPDATE t4 SET b = 5 } + } {1 {FOREIGN KEY constraint failed}} + do_test without_rowid3-14.2.2.6 { + catchsql { UPDATE t4 SET b = 1 } + } {0 {}} + do_test without_rowid3-14.2.2.7 { + execsql { INSERT INTO t3 VALUES(1, NULL, 1) } + } {} + + # Repeat for TEMP tables + # + drop_all_tables + do_test without_rowid3-14.1tmp.1 { + # Adding a column with a REFERENCES clause is not supported. + execsql { + CREATE TEMP TABLE t1(a PRIMARY KEY) WITHOUT rowid; + CREATE TEMP TABLE t2(a, b); + } + catchsql { ALTER TABLE t2 ADD COLUMN c REFERENCES t1 } + } {0 {}} + do_test without_rowid3-14.1tmp.2 { + catchsql { ALTER TABLE t2 ADD COLUMN d DEFAULT NULL REFERENCES t1 } + } {0 {}} + do_test without_rowid3-14.1tmp.3 { + catchsql { ALTER TABLE t2 ADD COLUMN e REFERENCES t1 DEFAULT NULL} + } {0 {}} + do_test without_rowid3-14.1tmp.4 { + catchsql { ALTER TABLE t2 ADD COLUMN f REFERENCES t1 DEFAULT 'text'} + } {1 {Cannot add a REFERENCES column with non-NULL default value}} + do_test without_rowid3-14.1tmp.5 { + catchsql { ALTER TABLE t2 ADD COLUMN g DEFAULT CURRENT_TIME REFERENCES t1 } + } {1 {Cannot add a REFERENCES column with non-NULL default value}} + do_test without_rowid3-14.1tmp.6 { + execsql { + PRAGMA foreign_keys = off; + ALTER TABLE t2 ADD COLUMN h DEFAULT 'text' REFERENCES t1; + PRAGMA foreign_keys = on; + SELECT sql FROM sqlite_temp_master WHERE name='t2'; + } + } {{CREATE TABLE t2(a, b, c REFERENCES t1, d DEFAULT NULL REFERENCES t1, e REFERENCES t1 DEFAULT NULL, h DEFAULT 'text' REFERENCES t1)}} + + do_test without_rowid3-14.2tmp.1.1 { + test_rename_parent {CREATE TABLE t1(a REFERENCES t2)} t2 t3 + } {{CREATE TABLE t1(a REFERENCES "t3")}} + do_test without_rowid3-14.2tmp.1.2 { + test_rename_parent {CREATE TABLE t1(a REFERENCES t2)} t4 t3 + } {{CREATE TABLE t1(a REFERENCES t2)}} + do_test without_rowid3-14.2tmp.1.3 { + test_rename_parent {CREATE TABLE t1(a REFERENCES "t2")} t2 t3 + } {{CREATE TABLE t1(a REFERENCES "t3")}} + + # Test ALTER TABLE RENAME TABLE a bit. + # + do_test without_rowid3-14.2tmp.2.1 { + drop_all_tables + execsql { + CREATE TEMP TABLE t1(a PRIMARY KEY, b REFERENCES t1) WITHOUT rowid; + CREATE TEMP TABLE t2(a PRIMARY KEY, b REFERENCES t1, c REFERENCES t2) + WITHOUT rowid; + CREATE TEMP TABLE t3(a REFERENCES t1, b REFERENCES t2, c REFERENCES t1); + } + execsql { SELECT sql FROM sqlite_temp_master WHERE type = 'table'} + } [list \ + {CREATE TABLE t1(a PRIMARY KEY, b REFERENCES t1) WITHOUT rowid} \ + {CREATE TABLE t2(a PRIMARY KEY, b REFERENCES t1, c REFERENCES t2) + WITHOUT rowid} \ + {CREATE TABLE t3(a REFERENCES t1, b REFERENCES t2, c REFERENCES t1)} \ + ] + do_test without_rowid3-14.2tmp.2.2 { + execsql { ALTER TABLE t1 RENAME TO t4 } + execsql { SELECT sql FROM sqlite_temp_master WHERE type = 'table'} + } [list \ + {CREATE TABLE "t4"(a PRIMARY KEY, b REFERENCES "t4") WITHOUT rowid} \ + {CREATE TABLE t2(a PRIMARY KEY, b REFERENCES "t4", c REFERENCES t2) + WITHOUT rowid} \ + {CREATE TABLE t3(a REFERENCES "t4", b REFERENCES t2, c REFERENCES "t4")} \ + ] + do_test without_rowid3-14.2tmp.2.3 { + catchsql { INSERT INTO t3 VALUES(1, 2, 3) } + } {1 {FOREIGN KEY constraint failed}} + do_test without_rowid3-14.2tmp.2.4 { + execsql { INSERT INTO t4 VALUES(1, NULL) } + } {} + do_test without_rowid3-14.2tmp.2.5 { + catchsql { UPDATE t4 SET b = 5 } + } {1 {FOREIGN KEY constraint failed}} + do_test without_rowid3-14.2tmp.2.6 { + catchsql { UPDATE t4 SET b = 1 } + } {0 {}} + do_test without_rowid3-14.2tmp.2.7 { + execsql { INSERT INTO t3 VALUES(1, NULL, 1) } + } {} + + # Repeat for ATTACH-ed tables + # + drop_all_tables + do_test without_rowid3-14.1aux.1 { + # Adding a column with a REFERENCES clause is not supported. + execsql { + ATTACH ':memory:' AS aux; + CREATE TABLE aux.t1(a PRIMARY KEY) WITHOUT rowid; + CREATE TABLE aux.t2(a, b); + } + catchsql { ALTER TABLE t2 ADD COLUMN c REFERENCES t1 } + } {0 {}} + do_test without_rowid3-14.1aux.2 { + catchsql { ALTER TABLE t2 ADD COLUMN d DEFAULT NULL REFERENCES t1 } + } {0 {}} + do_test without_rowid3-14.1aux.3 { + catchsql { ALTER TABLE t2 ADD COLUMN e REFERENCES t1 DEFAULT NULL} + } {0 {}} + do_test without_rowid3-14.1aux.4 { + catchsql { ALTER TABLE t2 ADD COLUMN f REFERENCES t1 DEFAULT 'text'} + } {1 {Cannot add a REFERENCES column with non-NULL default value}} + do_test without_rowid3-14.1aux.5 { + catchsql { ALTER TABLE t2 ADD COLUMN g DEFAULT CURRENT_TIME REFERENCES t1 } + } {1 {Cannot add a REFERENCES column with non-NULL default value}} + do_test without_rowid3-14.1aux.6 { + execsql { + PRAGMA foreign_keys = off; + ALTER TABLE t2 ADD COLUMN h DEFAULT 'text' REFERENCES t1; + PRAGMA foreign_keys = on; + SELECT sql FROM aux.sqlite_master WHERE name='t2'; + } + } {{CREATE TABLE t2(a, b, c REFERENCES t1, d DEFAULT NULL REFERENCES t1, e REFERENCES t1 DEFAULT NULL, h DEFAULT 'text' REFERENCES t1)}} + + do_test without_rowid3-14.2aux.1.1 { + test_rename_parent {CREATE TABLE t1(a REFERENCES t2)} t2 t3 + } {{CREATE TABLE t1(a REFERENCES "t3")}} + do_test without_rowid3-14.2aux.1.2 { + test_rename_parent {CREATE TABLE t1(a REFERENCES t2)} t4 t3 + } {{CREATE TABLE t1(a REFERENCES t2)}} + do_test without_rowid3-14.2aux.1.3 { + test_rename_parent {CREATE TABLE t1(a REFERENCES "t2")} t2 t3 + } {{CREATE TABLE t1(a REFERENCES "t3")}} + + # Test ALTER TABLE RENAME TABLE a bit. + # + do_test without_rowid3-14.2aux.2.1 { + drop_all_tables + execsql { + CREATE TABLE aux.t1(a PRIMARY KEY, b REFERENCES t1) WITHOUT rowid; + CREATE TABLE aux.t2(a PRIMARY KEY, b REFERENCES t1, c REFERENCES t2) + WITHOUT rowid; + CREATE TABLE aux.t3(a REFERENCES t1, b REFERENCES t2, c REFERENCES t1); + } + execsql { SELECT sql FROM aux.sqlite_master WHERE type = 'table'} + } [list \ + {CREATE TABLE t1(a PRIMARY KEY, b REFERENCES t1) WITHOUT rowid} \ + {CREATE TABLE t2(a PRIMARY KEY, b REFERENCES t1, c REFERENCES t2) + WITHOUT rowid} \ + {CREATE TABLE t3(a REFERENCES t1, b REFERENCES t2, c REFERENCES t1)} \ + ] + do_test without_rowid3-14.2aux.2.2 { + execsql { ALTER TABLE t1 RENAME TO t4 } + execsql { SELECT sql FROM aux.sqlite_master WHERE type = 'table'} + } [list \ + {CREATE TABLE "t4"(a PRIMARY KEY, b REFERENCES "t4") WITHOUT rowid} \ + {CREATE TABLE t2(a PRIMARY KEY, b REFERENCES "t4", c REFERENCES t2) + WITHOUT rowid} \ + {CREATE TABLE t3(a REFERENCES "t4", b REFERENCES t2, c REFERENCES "t4")} \ + ] + do_test without_rowid3-14.2aux.2.3 { + catchsql { INSERT INTO t3 VALUES(1, 2, 3) } + } {1 {FOREIGN KEY constraint failed}} + do_test without_rowid3-14.2aux.2.4 { + execsql { INSERT INTO t4 VALUES(1, NULL) } + } {} + do_test without_rowid3-14.2aux.2.5 { + catchsql { UPDATE t4 SET b = 5 } + } {1 {FOREIGN KEY constraint failed}} + do_test without_rowid3-14.2aux.2.6 { + catchsql { UPDATE t4 SET b = 1 } + } {0 {}} + do_test without_rowid3-14.2aux.2.7 { + execsql { INSERT INTO t3 VALUES(1, NULL, 1) } + } {} +} + +do_test without_rowid3-2.14.3.1 { + drop_all_tables + execsql { + CREATE TABLE t1(a, b REFERENCES nosuchtable); + DROP TABLE t1; + } +} {} +do_test without_rowid3-2.14.3.2 { + execsql { + CREATE TABLE t1(a PRIMARY KEY, b) WITHOUT rowid; + INSERT INTO t1 VALUES('a', 1); + CREATE TABLE t2(x REFERENCES t1); + INSERT INTO t2 VALUES('a'); + } +} {} +do_test without_rowid3-2.14.3.3 { + catchsql { DROP TABLE t1 } +} {1 {FOREIGN KEY constraint failed}} +do_test without_rowid3-2.14.3.4 { + execsql { + DELETE FROM t2; + DROP TABLE t1; + } +} {} +do_test without_rowid3-2.14.3.4 { + catchsql { INSERT INTO t2 VALUES('x') } +} {1 {no such table: main.t1}} +do_test without_rowid3-2.14.3.5 { + execsql { + CREATE TABLE t1(x PRIMARY KEY) WITHOUT rowid; + INSERT INTO t1 VALUES('x'); + } + execsql { INSERT INTO t2 VALUES('x') } +} {} +do_test without_rowid3-2.14.3.6 { + catchsql { DROP TABLE t1 } +} {1 {FOREIGN KEY constraint failed}} +do_test without_rowid3-2.14.3.7 { + execsql { + DROP TABLE t2; + DROP TABLE t1; + } +} {} +do_test without_rowid3-2.14.3.8 { + execsql { + CREATE TABLE pp(x, y, PRIMARY KEY(x, y)) WITHOUT ROWID; + CREATE TABLE cc(a, b, FOREIGN KEY(a, b) REFERENCES pp(x, z)); + } + catchsql { INSERT INTO cc VALUES(1, 2) } +} {1 {foreign key mismatch - "cc" referencing "pp"}} +do_test without_rowid3-2.14.3.9 { + execsql { DROP TABLE cc } +} {} +do_test without_rowid3-2.14.3.10 { + execsql { + CREATE TABLE cc(a, b, + FOREIGN KEY(a, b) REFERENCES pp DEFERRABLE INITIALLY DEFERRED + ); + } + execsql { + INSERT INTO pp VALUES('a', 'b'); + INSERT INTO cc VALUES('a', 'b'); + BEGIN; + DROP TABLE pp; + CREATE TABLE pp(a, b, c, PRIMARY KEY(b, c)) WITHOUT rowid; + INSERT INTO pp VALUES(1, 'a', 'b'); + COMMIT; + } +} {} +do_test without_rowid3-2.14.3.11 { + execsql { + BEGIN; + DROP TABLE cc; + DROP TABLE pp; + COMMIT; + } +} {} +do_test without_rowid3-2.14.3.12 { + execsql { + CREATE TABLE b1(a, b); + CREATE TABLE b2(a, b REFERENCES b1); + DROP TABLE b1; + } +} {} +do_test without_rowid3-2.14.3.13 { + execsql { + CREATE TABLE b3(a, b REFERENCES b2 DEFERRABLE INITIALLY DEFERRED); + DROP TABLE b2; + } +} {} + +# Test that nothing goes wrong when dropping a table that refers to a view. +# Or dropping a view that an existing FK (incorrectly) refers to. Or either +# of the above scenarios with a virtual table. +drop_all_tables +do_test without_rowid3-2.14.4.1 { + execsql { + CREATE TABLE t1(x REFERENCES v); + CREATE VIEW v AS SELECT * FROM t1; + } +} {} +do_test without_rowid3-2.14.4.2 { + execsql { + DROP VIEW v; + } +} {} +ifcapable vtab { + register_echo_module db + do_test without_rowid3-2.14.4.3 { + execsql { CREATE VIRTUAL TABLE v USING echo(t1) } + } {} + do_test without_rowid3-2.14.4.2 { + execsql { + DROP TABLE v; + } + } {} +} + +#------------------------------------------------------------------------- +# The following tests, without_rowid3-15.*, test that unnecessary FK related scans +# and lookups are avoided when the constraint counters are zero. +# +drop_all_tables +proc execsqlS {zSql} { + set ::sqlite_search_count 0 + set ::sqlite_found_count 0 + set res [uplevel [list execsql $zSql]] + concat [expr $::sqlite_found_count + $::sqlite_search_count] $res +} +do_test without_rowid3-15.1.1 { + execsql { + CREATE TABLE pp(a PRIMARY KEY, b) WITHOUT rowid; + CREATE TABLE cc(x, y REFERENCES pp DEFERRABLE INITIALLY DEFERRED); + INSERT INTO pp VALUES(1, 'one'); + INSERT INTO pp VALUES(2, 'two'); + INSERT INTO cc VALUES('neung', 1); + INSERT INTO cc VALUES('song', 2); + } +} {} +do_test without_rowid3-15.1.2 { + execsqlS { INSERT INTO pp VALUES(3, 'three') } +} {0} +do_test without_rowid3-15.1.3 { + execsql { + BEGIN; + INSERT INTO cc VALUES('see', 4); -- Violates deferred constraint + } + execsqlS { INSERT INTO pp VALUES(5, 'five') } +} {2} +do_test without_rowid3-15.1.4 { + execsql { DELETE FROM cc WHERE x = 'see' } + execsqlS { INSERT INTO pp VALUES(6, 'six') } +} {0} +do_test without_rowid3-15.1.5 { + execsql COMMIT +} {} +do_test without_rowid3-15.1.6 { + execsql BEGIN + execsqlS { + DELETE FROM cc WHERE x = 'neung'; + ROLLBACK; + } +} {1} +do_test without_rowid3-15.1.7 { + execsql { + BEGIN; + DELETE FROM pp WHERE a = 2; + } + execsqlS { + DELETE FROM cc WHERE x = 'neung'; + ROLLBACK; + } +} {2} + +#------------------------------------------------------------------------- +# This next block of tests, without_rowid3-16.*, test that rows that refer to +# themselves may be inserted and deleted. +# +foreach {tn zSchema} { + 1 { CREATE TABLE self(a INTEGER PRIMARY KEY, b REFERENCES self(a)) + WITHOUT rowid } + 2 { CREATE TABLE self(a PRIMARY KEY, b REFERENCES self(a)) WITHOUT rowid } + 3 { CREATE TABLE self(a UNIQUE, b INT PRIMARY KEY REFERENCES self(a)) + WITHOUT rowid } +} { + drop_all_tables + do_test without_rowid3-16.1.$tn.1 { + execsql $zSchema + execsql { INSERT INTO self VALUES(13, 13) } + } {} + do_test without_rowid3-16.1.$tn.2 { + execsql { UPDATE self SET a = 14, b = 14 } + } {} + + do_test without_rowid3-16.1.$tn.3 { + catchsql { UPDATE self SET b = 15 } + } {1 {FOREIGN KEY constraint failed}} + + do_test without_rowid3-16.1.$tn.4 { + catchsql { UPDATE self SET a = 15 } + } {1 {FOREIGN KEY constraint failed}} + + do_test without_rowid3-16.1.$tn.5 { + catchsql { UPDATE self SET a = 15, b = 16 } + } {1 {FOREIGN KEY constraint failed}} + + do_test without_rowid3-16.1.$tn.6 { + catchsql { UPDATE self SET a = 17, b = 17 } + } {0 {}} + + do_test without_rowid3-16.1.$tn.7 { + execsql { DELETE FROM self } + } {} + do_test without_rowid3-16.1.$tn.8 { + catchsql { INSERT INTO self VALUES(20, 21) } + } {1 {FOREIGN KEY constraint failed}} +} + +# Additional tests cases using multi-column self-referential +# FOREIGN KEY constraints. +# +drop_all_tables +do_execsql_test without_rowid3-16.4.1.1 { + PRAGMA foreign_keys=ON; + CREATE TABLE t1(a,b,c,d,e,f, + UNIQUE (a,b), + PRIMARY KEY (e,c), + FOREIGN KEY (d,f) REFERENCES t1(e,c) + ) WITHOUT rowid; + INSERT INTO t1 VALUES(1,2,3,5,5,3); + INSERT INTO t1 VALUES(2,3,4,6,6,4); + INSERT INTO t1 VALUES('x','y',1.5,'fizzle','fizzle',1.5); + SELECT *, '|' FROM t1 ORDER BY a, b; +} {1 2 3 5 5 3 | 2 3 4 6 6 4 | x y 1.5 fizzle fizzle 1.5 |} + +do_execsql_test without_rowid3-16.4.1.2 { + UPDATE t1 SET c=99, f=99 WHERE a=1; + SELECT *, '|' FROM t1 ORDER BY a, b; +} {1 2 99 5 5 99 | 2 3 4 6 6 4 | x y 1.5 fizzle fizzle 1.5 |} + +do_execsql_test without_rowid3-16.4.1.3 { + UPDATE t1 SET e=876, d=876 WHERE a=2; + SELECT *, '|' FROM t1 ORDER BY a, b; +} {1 2 99 5 5 99 | 2 3 4 876 876 4 | x y 1.5 fizzle fizzle 1.5 |} + +do_test without_rowid3-16.4.1.4 { + catchsql { + UPDATE t1 SET c=11, e=22 WHERE a=1; + } +} {1 {FOREIGN KEY constraint failed}} + +do_test without_rowid3-16.4.1.5 { + catchsql { + UPDATE t1 SET d=11, f=22 WHERE a=1; + } +} {1 {FOREIGN KEY constraint failed}} + +do_execsql_test without_rowid3-16.4.1.6 { + DELETE FROM t1 WHERE a=1; + SELECT *, '|' FROM t1 ORDER BY a, b; +} {2 3 4 876 876 4 | x y 1.5 fizzle fizzle 1.5 |} + +do_execsql_test without_rowid3-16.4.2.1 { + DROP TABLE t1; + CREATE TABLE t1(a,b,c,d,e,f, + PRIMARY KEY (a,b), + UNIQUE (e,c), + FOREIGN KEY (d,f) REFERENCES t1(e,c) + ) WITHOUT rowid; + INSERT INTO t1 VALUES(1,2,3,5,5,3); + INSERT INTO t1 VALUES(2,3,4,6,6,4); + INSERT INTO t1 VALUES('x','y',1.5,'fizzle','fizzle',1.5); + SELECT *, '|' FROM t1 ORDER BY a, b; +} {1 2 3 5 5 3 | 2 3 4 6 6 4 | x y 1.5 fizzle fizzle 1.5 |} + +do_execsql_test without_rowid3-16.4.2.2 { + UPDATE t1 SET c=99, f=99 WHERE a=1; + SELECT *, '|' FROM t1 ORDER BY a, b; +} {1 2 99 5 5 99 | 2 3 4 6 6 4 | x y 1.5 fizzle fizzle 1.5 |} + +do_execsql_test without_rowid3-16.4.2.3 { + UPDATE t1 SET e=876, d=876 WHERE a=2; + SELECT *, '|' FROM t1 ORDER BY a, b; +} {1 2 99 5 5 99 | 2 3 4 876 876 4 | x y 1.5 fizzle fizzle 1.5 |} + +do_test without_rowid3-16.4.2.4 { + catchsql { + UPDATE t1 SET c=11, e=22 WHERE a=1; + } +} {1 {FOREIGN KEY constraint failed}} + +do_test without_rowid3-16.4.2.5 { + catchsql { + UPDATE t1 SET d=11, f=22 WHERE a=1; + } +} {1 {FOREIGN KEY constraint failed}} + +do_execsql_test without_rowid3-16.4.2.6 { + DELETE FROM t1 WHERE a=1; + SELECT *, '|' FROM t1 ORDER BY a, b; +} {2 3 4 876 876 4 | x y 1.5 fizzle fizzle 1.5 |} + + +#------------------------------------------------------------------------- +# This next block of tests, without_rowid3-17.*, tests that if "PRAGMA count_changes" +# is turned on statements that violate immediate FK constraints return +# SQLITE_CONSTRAINT immediately, not after returning a number of rows. +# Whereas statements that violate deferred FK constraints return the number +# of rows before failing. +# +# Also test that rows modified by FK actions are not counted in either the +# returned row count or the values returned by sqlite3_changes(). Like +# trigger related changes, they are included in sqlite3_total_changes() though. +# +drop_all_tables +do_test without_rowid3-17.1.1 { + execsql { PRAGMA count_changes = 1 } + execsql { + CREATE TABLE one(a, b, c, UNIQUE(b, c)); + CREATE TABLE two(d, e, f, FOREIGN KEY(e, f) REFERENCES one(b, c)); + INSERT INTO one VALUES(1, 2, 3); + } +} {1} +do_test without_rowid3-17.1.2 { + set STMT [sqlite3_prepare_v2 db "INSERT INTO two VALUES(4, 5, 6)" -1 dummy] + sqlite3_step $STMT +} {SQLITE_CONSTRAINT} +verify_ex_errcode without_rowid3-17.1.2b SQLITE_CONSTRAINT_FOREIGNKEY +ifcapable autoreset { + do_test without_rowid3-17.1.3 { + sqlite3_step $STMT + } {SQLITE_CONSTRAINT} + verify_ex_errcode without_rowid3-17.1.3b SQLITE_CONSTRAINT_FOREIGNKEY +} else { + do_test without_rowid3-17.1.3 { + sqlite3_step $STMT + } {SQLITE_MISUSE} +} +do_test without_rowid3-17.1.4 { + sqlite3_finalize $STMT +} {SQLITE_CONSTRAINT} +verify_ex_errcode without_rowid3-17.1.4b SQLITE_CONSTRAINT_FOREIGNKEY +do_test without_rowid3-17.1.5 { + execsql { + INSERT INTO one VALUES(2, 3, 4); + INSERT INTO one VALUES(3, 4, 5); + INSERT INTO two VALUES(1, 2, 3); + INSERT INTO two VALUES(2, 3, 4); + INSERT INTO two VALUES(3, 4, 5); + } +} {1 1 1 1 1} +do_test without_rowid3-17.1.6 { + catchsql { + BEGIN; + INSERT INTO one VALUES(0, 0, 0); + UPDATE two SET e=e+1, f=f+1; + } +} {1 {FOREIGN KEY constraint failed}} +do_test without_rowid3-17.1.7 { + execsql { SELECT * FROM one } +} {1 2 3 2 3 4 3 4 5 0 0 0} +do_test without_rowid3-17.1.8 { + execsql { SELECT * FROM two } +} {1 2 3 2 3 4 3 4 5} +do_test without_rowid3-17.1.9 { + execsql COMMIT +} {} +do_test without_rowid3-17.1.10 { + execsql { + CREATE TABLE three( + g, h, i, + FOREIGN KEY(h, i) REFERENCES one(b, c) DEFERRABLE INITIALLY DEFERRED + ); + } +} {} +do_test without_rowid3-17.1.11 { + set STMT [sqlite3_prepare_v2 db "INSERT INTO three VALUES(7, 8, 9)" -1 dummy] + sqlite3_step $STMT +} {SQLITE_ROW} +do_test without_rowid3-17.1.12 { + sqlite3_column_text $STMT 0 +} {1} +do_test without_rowid3-17.1.13 { + sqlite3_step $STMT +} {SQLITE_CONSTRAINT} +verify_ex_errcode without_rowid3-17.1.13b SQLITE_CONSTRAINT_FOREIGNKEY +do_test without_rowid3-17.1.14 { + sqlite3_finalize $STMT +} {SQLITE_CONSTRAINT} +verify_ex_errcode without_rowid3-17.1.14b SQLITE_CONSTRAINT_FOREIGNKEY + +drop_all_tables +do_test without_rowid3-17.2.1 { + execsql { + CREATE TABLE high("a'b!" PRIMARY KEY, b) WITHOUT rowid; + CREATE TABLE low( + c, + "d&6" REFERENCES high ON UPDATE CASCADE ON DELETE CASCADE + ); + } +} {} +do_test without_rowid3-17.2.2 { + execsql { + INSERT INTO high VALUES('a', 'b'); + INSERT INTO low VALUES('b', 'a'); + } + db changes +} {1} +set nTotal [db total_changes] +do_test without_rowid3-17.2.3 { + execsql { UPDATE high SET "a'b!" = 'c' } +} {1} +do_test without_rowid3-17.2.4 { + db changes +} {1} +do_test without_rowid3-17.2.5 { + expr [db total_changes] - $nTotal +} {2} +do_test without_rowid3-17.2.6 { + execsql { SELECT * FROM high ; SELECT * FROM low } +} {c b b c} +do_test without_rowid3-17.2.7 { + execsql { DELETE FROM high } +} {1} +do_test without_rowid3-17.2.8 { + db changes +} {1} +do_test without_rowid3-17.2.9 { + expr [db total_changes] - $nTotal +} {4} +do_test without_rowid3-17.2.10 { + execsql { SELECT * FROM high ; SELECT * FROM low } +} {} +execsql { PRAGMA count_changes = 0 } + +#------------------------------------------------------------------------- +# Test that the authorization callback works. +# + +ifcapable auth { + do_test without_rowid3-18.1 { + execsql { + CREATE TABLE long(a, b PRIMARY KEY, c) WITHOUT rowid; + CREATE TABLE short(d, e, f REFERENCES long); + CREATE TABLE mid(g, h, i REFERENCES long DEFERRABLE INITIALLY DEFERRED); + } + } {} + + proc auth {args} {eval lappend ::authargs $args ; return SQLITE_OK} + db auth auth + + # An insert on the parent table must read the child key of any deferred + # foreign key constraints. But not the child key of immediate constraints. + set authargs {} + do_test without_rowid3-18.2 { + execsql { INSERT INTO long VALUES(1, 2, 3) } + set authargs + } {SQLITE_INSERT long {} main {} SQLITE_READ mid i main {}} + + # An insert on the child table of an immediate constraint must read the + # parent key columns (to see if it is a violation or not). + set authargs {} + do_test without_rowid3-18.3 { + execsql { INSERT INTO short VALUES(1, 3, 2) } + set authargs + } {SQLITE_INSERT short {} main {} SQLITE_READ long b main {}} + + # As must an insert on the child table of a deferred constraint. + set authargs {} + do_test without_rowid3-18.4 { + execsql { INSERT INTO mid VALUES(1, 3, 2) } + set authargs + } {SQLITE_INSERT mid {} main {} SQLITE_READ long b main {}} + + do_test without_rowid3-18.5 { + execsql { + CREATE TABLE nought(a, b PRIMARY KEY, c) WITHOUT rowid; + CREATE TABLE cross(d, e, f, + FOREIGN KEY(e) REFERENCES nought(b) ON UPDATE CASCADE + ); + } + execsql { INSERT INTO nought VALUES(2, 1, 2) } + execsql { INSERT INTO cross VALUES(0, 1, 0) } + set authargs [list] + execsql { UPDATE nought SET b = 5 } + set authargs + } {SQLITE_UPDATE nought b main {} SQLITE_READ cross e main {} SQLITE_READ cross e main {} SQLITE_READ nought b main {} SQLITE_READ nought b main {} SQLITE_READ nought b main {} SQLITE_UPDATE cross e main {} SQLITE_READ nought b main {} SQLITE_READ cross e main {} SQLITE_READ nought b main {} SQLITE_READ nought b main {}} + + do_test without_rowid3-18.6 { + execsql {SELECT * FROM cross} + } {0 5 0} + + do_test without_rowid3-18.7 { + execsql { + CREATE TABLE one(a INT PRIMARY KEY, b) WITHOUT rowid; + CREATE TABLE two(b, c REFERENCES one); + INSERT INTO one VALUES(101, 102); + } + set authargs [list] + execsql { INSERT INTO two VALUES(100, 101); } + set authargs + } {SQLITE_INSERT two {} main {} SQLITE_READ one a main {}} + + # Return SQLITE_IGNORE to requests to read from the parent table. This + # causes inserts of non-NULL keys into the child table to fail. + # + rename auth {} + proc auth {args} { + if {[lindex $args 1] == "long"} {return SQLITE_IGNORE} + return SQLITE_OK + } + do_test without_rowid3-18.8 { + catchsql { INSERT INTO short VALUES(1, 3, 2) } + } {1 {FOREIGN KEY constraint failed}} + do_test without_rowid3-18.9 { + execsql { INSERT INTO short VALUES(1, 3, NULL) } + } {} + do_test without_rowid3-18.10 { + execsql { SELECT * FROM short } + } {1 3 2 1 3 {}} + do_test without_rowid3-18.11 { + catchsql { UPDATE short SET f = 2 WHERE f IS NULL } + } {1 {FOREIGN KEY constraint failed}} + + db auth {} + unset authargs +} + + +do_test without_rowid3-19.1 { + execsql { + CREATE TABLE main(id INT PRIMARY KEY) WITHOUT rowid; + CREATE TABLE sub(id INT REFERENCES main(id)); + INSERT INTO main VALUES(1); + INSERT INTO main VALUES(2); + INSERT INTO sub VALUES(2); + } +} {} +do_test without_rowid3-19.2 { + set S [sqlite3_prepare_v2 db "DELETE FROM main WHERE id = ?" -1 dummy] + sqlite3_bind_int $S 1 2 + sqlite3_step $S +} {SQLITE_CONSTRAINT} +verify_ex_errcode without_rowid3-19.2b SQLITE_CONSTRAINT_FOREIGNKEY +do_test without_rowid3-19.3 { + sqlite3_reset $S +} {SQLITE_CONSTRAINT} +verify_ex_errcode without_rowid3-19.3b SQLITE_CONSTRAINT_FOREIGNKEY +do_test without_rowid3-19.4 { + sqlite3_bind_int $S 1 1 + sqlite3_step $S +} {SQLITE_DONE} +do_test without_rowid3-19.4 { + sqlite3_finalize $S +} {SQLITE_OK} + +drop_all_tables +do_test without_rowid3-20.1 { + execsql { + CREATE TABLE pp(a PRIMARY KEY, b) WITHOUT rowid; + CREATE TABLE cc(c PRIMARY KEY, d REFERENCES pp) WITHOUT rowid; + } +} {} + +foreach {tn insert} { + 1 "INSERT" + 2 "INSERT OR IGNORE" + 3 "INSERT OR ABORT" + 4 "INSERT OR ROLLBACK" + 5 "INSERT OR REPLACE" + 6 "INSERT OR FAIL" +} { + do_test without_rowid3-20.2.$tn.1 { + catchsql "$insert INTO cc VALUES(1, 2)" + } {1 {FOREIGN KEY constraint failed}} + do_test without_rowid3-20.2.$tn.2 { + execsql { SELECT * FROM cc } + } {} + do_test without_rowid3-20.2.$tn.3 { + execsql { + BEGIN; + INSERT INTO pp VALUES(2, 'two'); + INSERT INTO cc VALUES(1, 2); + } + catchsql "$insert INTO cc VALUES(3, 4)" + } {1 {FOREIGN KEY constraint failed}} + do_test without_rowid3-20.2.$tn.4 { + execsql { COMMIT ; SELECT * FROM cc } + } {1 2} + do_test without_rowid3-20.2.$tn.5 { + execsql { DELETE FROM cc ; DELETE FROM pp } + } {} +} + +foreach {tn update} { + 1 "UPDATE" + 2 "UPDATE OR IGNORE" + 3 "UPDATE OR ABORT" + 4 "UPDATE OR ROLLBACK" + 5 "UPDATE OR REPLACE" + 6 "UPDATE OR FAIL" +} { + do_test without_rowid3-20.3.$tn.1 { + execsql { + INSERT INTO pp VALUES(2, 'two'); + INSERT INTO cc VALUES(1, 2); + } + } {} + do_test without_rowid3-20.3.$tn.2 { + catchsql "$update pp SET a = 1" + } {1 {FOREIGN KEY constraint failed}} + do_test without_rowid3-20.3.$tn.3 { + execsql { SELECT * FROM pp } + } {2 two} + do_test without_rowid3-20.3.$tn.4 { + catchsql "$update cc SET d = 1" + } {1 {FOREIGN KEY constraint failed}} + do_test without_rowid3-20.3.$tn.5 { + execsql { SELECT * FROM cc } + } {1 2} + do_test without_rowid3-20.3.$tn.6 { + execsql { + BEGIN; + INSERT INTO pp VALUES(3, 'three'); + } + catchsql "$update pp SET a = 1 WHERE a = 2" + } {1 {FOREIGN KEY constraint failed}} + do_test without_rowid3-20.3.$tn.7 { + execsql { COMMIT ; SELECT * FROM pp } + } {2 two 3 three} + do_test without_rowid3-20.3.$tn.8 { + execsql { + BEGIN; + INSERT INTO cc VALUES(2, 2); + } + catchsql "$update cc SET d = 1 WHERE c = 1" + } {1 {FOREIGN KEY constraint failed}} + do_test without_rowid3-20.3.$tn.9 { + execsql { COMMIT ; SELECT * FROM cc } + } {1 2 2 2} + do_test without_rowid3-20.3.$tn.10 { + execsql { DELETE FROM cc ; DELETE FROM pp } + } {} +} + +#------------------------------------------------------------------------- +# The following block of tests, those prefixed with "without_rowid3-genfkey.", +# are the same tests that were used to test the ".genfkey" command provided +# by the shell tool. So these tests show that the built-in foreign key +# implementation is more or less compatible with the triggers generated +# by genfkey. +# +drop_all_tables +do_test without_rowid3-genfkey.1.1 { + execsql { + CREATE TABLE t1(a INT PRIMARY KEY, b, c, UNIQUE(b, c)) WITHOUT rowid; + CREATE TABLE t2(e REFERENCES t1, f); + CREATE TABLE t3(g, h, i, FOREIGN KEY (h, i) REFERENCES t1(b, c)); + } +} {} +do_test without_rowid3-genfkey.1.2 { + catchsql { INSERT INTO t2 VALUES(1, 2) } +} {1 {FOREIGN KEY constraint failed}} +do_test without_rowid3-genfkey.1.3 { + execsql { + INSERT INTO t1 VALUES(1, 2, 3); + INSERT INTO t2 VALUES(1, 2); + } +} {} +do_test without_rowid3-genfkey.1.4 { + execsql { INSERT INTO t2 VALUES(NULL, 3) } +} {} +do_test without_rowid3-genfkey.1.5 { + catchsql { UPDATE t2 SET e = 5 WHERE e IS NULL } +} {1 {FOREIGN KEY constraint failed}} +do_test without_rowid3-genfkey.1.6 { + execsql { UPDATE t2 SET e = 1 WHERE e IS NULL } +} {} +do_test without_rowid3-genfkey.1.7 { + execsql { UPDATE t2 SET e = NULL WHERE f = 3 } +} {} +do_test without_rowid3-genfkey.1.8 { + catchsql { UPDATE t1 SET a = 10 } +} {1 {FOREIGN KEY constraint failed}} +do_test without_rowid3-genfkey.1.9 { + catchsql { UPDATE t1 SET a = NULL } +} {1 {NOT NULL constraint failed: t1.a}} +do_test without_rowid3-genfkey.1.10 { + catchsql { DELETE FROM t1 } +} {1 {FOREIGN KEY constraint failed}} +do_test without_rowid3-genfkey.1.11 { + execsql { UPDATE t2 SET e = NULL } +} {} +do_test without_rowid3-genfkey.1.12 { + execsql { + UPDATE t1 SET a = 10; + DELETE FROM t1; + DELETE FROM t2; + } +} {} +do_test without_rowid3-genfkey.1.13 { + execsql { + INSERT INTO t3 VALUES(1, NULL, NULL); + INSERT INTO t3 VALUES(1, 2, NULL); + INSERT INTO t3 VALUES(1, NULL, 3); + } +} {} +do_test without_rowid3-genfkey.1.14 { + catchsql { INSERT INTO t3 VALUES(3, 1, 4) } +} {1 {FOREIGN KEY constraint failed}} +do_test without_rowid3-genfkey.1.15 { + execsql { + INSERT INTO t1 VALUES(1, 1, 4); + INSERT INTO t3 VALUES(3, 1, 4); + } +} {} +do_test without_rowid3-genfkey.1.16 { + catchsql { DELETE FROM t1 } +} {1 {FOREIGN KEY constraint failed}} +do_test without_rowid3-genfkey.1.17 { + catchsql { UPDATE t1 SET b = 10} +} {1 {FOREIGN KEY constraint failed}} +do_test without_rowid3-genfkey.1.18 { + execsql { UPDATE t1 SET a = 10} +} {} +do_test without_rowid3-genfkey.1.19 { + catchsql { UPDATE t3 SET h = 'hello' WHERE i = 3} +} {1 {FOREIGN KEY constraint failed}} + +drop_all_tables +do_test without_rowid3-genfkey.2.1 { + execsql { + CREATE TABLE t1(a INT PRIMARY KEY, b, c, UNIQUE(b, c)) WITHOUT rowid; + CREATE TABLE t2(e REFERENCES t1 ON UPDATE CASCADE ON DELETE CASCADE, f); + CREATE TABLE t3(g, h, i, + FOREIGN KEY (h, i) + REFERENCES t1(b, c) ON UPDATE CASCADE ON DELETE CASCADE + ); + } +} {} +do_test without_rowid3-genfkey.2.2 { + execsql { + INSERT INTO t1 VALUES(1, 2, 3); + INSERT INTO t1 VALUES(4, 5, 6); + INSERT INTO t2 VALUES(1, 'one'); + INSERT INTO t2 VALUES(4, 'four'); + } +} {} +do_test without_rowid3-genfkey.2.3 { + execsql { + UPDATE t1 SET a = 2 WHERE a = 1; + SELECT * FROM t2; + } +} {2 one 4 four} +do_test without_rowid3-genfkey.2.4 { + execsql { + DELETE FROM t1 WHERE a = 4; + SELECT * FROM t2; + } +} {2 one} + +do_test without_rowid3-genfkey.2.5 { + execsql { + INSERT INTO t3 VALUES('hello', 2, 3); + UPDATE t1 SET c = 2; + SELECT * FROM t3; + } +} {hello 2 2} +do_test without_rowid3-genfkey.2.6 { + execsql { + DELETE FROM t1; + SELECT * FROM t3; + } +} {} + +drop_all_tables +do_test without_rowid3-genfkey.3.1 { + execsql { + CREATE TABLE t1(a INTEGER PRIMARY KEY, b, c, UNIQUE(c, b)) WITHOUT rowid; + CREATE TABLE t2(e REFERENCES t1 ON UPDATE SET NULL ON DELETE SET NULL, f); + CREATE TABLE t3(g, h, i, + FOREIGN KEY (h, i) + REFERENCES t1(b, c) ON UPDATE SET NULL ON DELETE SET NULL + ); + } +} {} +do_test without_rowid3-genfkey.3.2 { + execsql { + INSERT INTO t1 VALUES(1, 2, 3); + INSERT INTO t1 VALUES(4, 5, 6); + INSERT INTO t2 VALUES(1, 'one'); + INSERT INTO t2 VALUES(4, 'four'); + } +} {} +do_test without_rowid3-genfkey.3.3 { + execsql { + UPDATE t1 SET a = 2 WHERE a = 1; + SELECT * FROM t2; + } +} {{} one 4 four} +do_test without_rowid3-genfkey.3.4 { + execsql { + DELETE FROM t1 WHERE a = 4; + SELECT * FROM t2; + } +} {{} one {} four} +do_test without_rowid3-genfkey.3.5 { + execsql { + INSERT INTO t3 VALUES('hello', 2, 3); + UPDATE t1 SET c = 2; + SELECT * FROM t3; + } +} {hello {} {}} +do_test without_rowid3-genfkey.3.6 { + execsql { + UPDATE t3 SET h = 2, i = 2; + DELETE FROM t1; + SELECT * FROM t3; + } +} {hello {} {}} + +#------------------------------------------------------------------------- +# Verify that ticket dd08e5a988d00decc4a543daa8dbbfab9c577ad8 has been +# fixed. +# +do_test without_rowid3-dd08e5.1.1 { + execsql { + PRAGMA foreign_keys=ON; + CREATE TABLE tdd08(a INTEGER PRIMARY KEY, b) WITHOUT rowid; + CREATE UNIQUE INDEX idd08 ON tdd08(a,b); + INSERT INTO tdd08 VALUES(200,300); + + CREATE TABLE tdd08_b(w,x,y, FOREIGN KEY(x,y) REFERENCES tdd08(a,b)); + INSERT INTO tdd08_b VALUES(100,200,300); + } +} {} +do_test without_rowid3-dd08e5.1.2 { + catchsql { + DELETE FROM tdd08; + } +} {1 {FOREIGN KEY constraint failed}} +do_test without_rowid3-dd08e5.1.3 { + execsql { + SELECT * FROM tdd08; + } +} {200 300} +do_test without_rowid3-dd08e5.1.4 { + catchsql { + INSERT INTO tdd08_b VALUES(400,500,300); + } +} {1 {FOREIGN KEY constraint failed}} +do_test without_rowid3-dd08e5.1.5 { + catchsql { + UPDATE tdd08_b SET x=x+1; + } +} {1 {FOREIGN KEY constraint failed}} +do_test without_rowid3-dd08e5.1.6 { + catchsql { + UPDATE tdd08 SET a=a+1; + } +} {1 {FOREIGN KEY constraint failed}} + +#------------------------------------------------------------------------- +# Verify that ticket ce7c133ea6cc9ccdc1a60d80441f80b6180f5eba +# fixed. +# +do_test without_rowid3-ce7c13.1.1 { + execsql { + CREATE TABLE tce71(a INTEGER PRIMARY KEY, b) WITHOUT rowid; + CREATE UNIQUE INDEX ice71 ON tce71(a,b); + INSERT INTO tce71 VALUES(100,200); + CREATE TABLE tce72(w, x, y, FOREIGN KEY(x,y) REFERENCES tce71(a,b)); + INSERT INTO tce72 VALUES(300,100,200); + UPDATE tce71 set b = 200 where a = 100; + SELECT * FROM tce71, tce72; + } +} {100 200 300 100 200} +do_test without_rowid3-ce7c13.1.2 { + catchsql { + UPDATE tce71 set b = 201 where a = 100; + } +} {1 {FOREIGN KEY constraint failed}} +do_test without_rowid3-ce7c13.1.3 { + catchsql { + UPDATE tce71 set a = 101 where a = 100; + } +} {1 {FOREIGN KEY constraint failed}} +do_test without_rowid3-ce7c13.1.4 { + execsql { + CREATE TABLE tce73(a INTEGER PRIMARY KEY, b, UNIQUE(a,b)) WITHOUT rowid; + INSERT INTO tce73 VALUES(100,200); + CREATE TABLE tce74(w, x, y, FOREIGN KEY(x,y) REFERENCES tce73(a,b)); + INSERT INTO tce74 VALUES(300,100,200); + UPDATE tce73 set b = 200 where a = 100; + SELECT * FROM tce73, tce74; + } +} {100 200 300 100 200} +do_test without_rowid3-ce7c13.1.5 { + catchsql { + UPDATE tce73 set b = 201 where a = 100; + } +} {1 {FOREIGN KEY constraint failed}} +do_test without_rowid3-ce7c13.1.6 { + catchsql { + UPDATE tce73 set a = 101 where a = 100; + } +} {1 {FOREIGN KEY constraint failed}} + +finish_test diff --git a/test/without_rowid4.test b/test/without_rowid4.test new file mode 100644 index 0000000000..d8c2d69fe9 --- /dev/null +++ b/test/without_rowid4.test @@ -0,0 +1,764 @@ +# 2013-11-04 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# Regression testing of FOR EACH ROW table triggers on WITHOUT ROWID +# tables. +# +# 1. Trigger execution order tests. +# These tests ensure that BEFORE and AFTER triggers are fired at the correct +# times relative to each other and the triggering statement. +# +# without_rowid4-1.1.*: ON UPDATE trigger execution model. +# without_rowid4-1.2.*: DELETE trigger execution model. +# without_rowid4-1.3.*: INSERT trigger execution model. +# +# 2. Trigger program execution tests. +# These tests ensure that trigger programs execute correctly (ie. that a +# trigger program can correctly execute INSERT, UPDATE, DELETE * SELECT +# statements, and combinations thereof). +# +# 3. Selective trigger execution +# This tests that conditional triggers (ie. UPDATE OF triggers and triggers +# with WHEN clauses) are fired only fired when they are supposed to be. +# +# without_rowid4-3.1: UPDATE OF triggers +# without_rowid4-3.2: WHEN clause +# +# 4. Cascaded trigger execution +# Tests that trigger-programs may cause other triggers to fire. Also that a +# trigger-program is never executed recursively. +# +# without_rowid4-4.1: Trivial cascading trigger +# without_rowid4-4.2: Trivial recursive trigger handling +# +# 5. Count changes behaviour. +# Verify that rows altered by triggers are not included in the return value +# of the "count changes" interface. +# +# 6. ON CONFLICT clause handling +# without_rowid4-6.1[a-f]: INSERT statements +# without_rowid4-6.2[a-f]: UPDATE statements +# +# 7. & 8. Triggers on views fire correctly. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +ifcapable {!trigger} { + finish_test + return +} + +# The tests in this file were written before SQLite supported recursive +# trigger invocation, and some tests depend on that to pass. So disable +# recursive triggers for this file. +catchsql { pragma recursive_triggers = off } + +# 1. +ifcapable subquery { + set ii 0 + set tbl_definitions [list \ + {CREATE TABLE tbl (a INTEGER PRIMARY KEY, b) WITHOUT rowid;} \ + {CREATE TABLE tbl (a, b PRIMARY KEY) WITHOUT rowid;} \ + {CREATE TABLE tbl (a PRIMARY KEY, b) WITHOUT rowid; + CREATE INDEX tbl_idx ON tbl(b);} \ + ] + ifcapable tempdb { + lappend tbl_definitions \ + {CREATE TEMP TABLE tbl (a PRIMARY KEY, b) WITHOUT rowid; + CREATE INDEX tbl_idx ON tbl(b);} + lappend tbl_definitions \ + {CREATE TEMP TABLE tbl (a PRIMARY KEY, b) WITHOUT rowid} + lappend tbl_definitions \ + {CREATE TEMPORARY TABLE tbl (a INTEGER PRIMARY KEY, b) WITHOUT rowid;} + } + foreach tbl_defn $tbl_definitions { + incr ii + catchsql { DROP INDEX tbl_idx; } + catchsql { + DROP TABLE rlog; + DROP TABLE clog; + DROP TABLE tbl; + DROP TABLE other_tbl; + } + + execsql $tbl_defn + + execsql { + INSERT INTO tbl VALUES(1, 2); + INSERT INTO tbl VALUES(3, 4); + + CREATE TABLE rlog (idx, old_a, old_b, db_sum_a, db_sum_b, new_a, new_b); + CREATE TABLE clog (idx, old_a, old_b, db_sum_a, db_sum_b, new_a, new_b); + + CREATE TRIGGER before_update_row BEFORE UPDATE ON tbl FOR EACH ROW + BEGIN + INSERT INTO rlog VALUES ( (SELECT coalesce(max(idx),0) + 1 FROM rlog), + old.a, old.b, + (SELECT coalesce(sum(a),0) FROM tbl), + (SELECT coalesce(sum(b),0) FROM tbl), + new.a, new.b); + END; + + CREATE TRIGGER after_update_row AFTER UPDATE ON tbl FOR EACH ROW + BEGIN + INSERT INTO rlog VALUES ( (SELECT coalesce(max(idx),0) + 1 FROM rlog), + old.a, old.b, + (SELECT coalesce(sum(a),0) FROM tbl), + (SELECT coalesce(sum(b),0) FROM tbl), + new.a, new.b); + END; + + CREATE TRIGGER conditional_update_row AFTER UPDATE ON tbl FOR EACH ROW + WHEN old.a = 1 + BEGIN + INSERT INTO clog VALUES ( (SELECT coalesce(max(idx),0) + 1 FROM clog), + old.a, old.b, + (SELECT coalesce(sum(a),0) FROM tbl), + (SELECT coalesce(sum(b),0) FROM tbl), + new.a, new.b); + END; + } + + do_test without_rowid4-1.$ii.1 { + set r {} + foreach v [execsql { + UPDATE tbl SET a = a * 10, b = b * 10; + SELECT * FROM rlog ORDER BY idx; + SELECT * FROM clog ORDER BY idx; + }] { + lappend r [expr {int($v)}] + } + set r + } [list 1 1 2 4 6 10 20 \ + 2 1 2 13 24 10 20 \ + 3 3 4 13 24 30 40 \ + 4 3 4 40 60 30 40 \ + 1 1 2 13 24 10 20 ] + + execsql { + DELETE FROM rlog; + DELETE FROM tbl; + INSERT INTO tbl VALUES (100, 100); + INSERT INTO tbl VALUES (300, 200); + CREATE TRIGGER delete_before_row BEFORE DELETE ON tbl FOR EACH ROW + BEGIN + INSERT INTO rlog VALUES ( (SELECT coalesce(max(idx),0) + 1 FROM rlog), + old.a, old.b, + (SELECT coalesce(sum(a),0) FROM tbl), + (SELECT coalesce(sum(b),0) FROM tbl), + 0, 0); + END; + + CREATE TRIGGER delete_after_row AFTER DELETE ON tbl FOR EACH ROW + BEGIN + INSERT INTO rlog VALUES ( (SELECT coalesce(max(idx),0) + 1 FROM rlog), + old.a, old.b, + (SELECT coalesce(sum(a),0) FROM tbl), + (SELECT coalesce(sum(b),0) FROM tbl), + 0, 0); + END; + } + do_test without_rowid4-1.$ii.2 { + set r {} + foreach v [execsql { + DELETE FROM tbl; + SELECT * FROM rlog; + }] { + lappend r [expr {int($v)}] + } + set r + } [list 1 100 100 400 300 0 0 \ + 2 100 100 300 200 0 0 \ + 3 300 200 300 200 0 0 \ + 4 300 200 0 0 0 0 ] + + execsql { + DELETE FROM rlog; + CREATE TRIGGER insert_before_row BEFORE INSERT ON tbl FOR EACH ROW + BEGIN + INSERT INTO rlog VALUES ( (SELECT coalesce(max(idx),0) + 1 FROM rlog), + 0, 0, + (SELECT coalesce(sum(a),0) FROM tbl), + (SELECT coalesce(sum(b),0) FROM tbl), + new.a, new.b); + END; + + CREATE TRIGGER insert_after_row AFTER INSERT ON tbl FOR EACH ROW + BEGIN + INSERT INTO rlog VALUES ( (SELECT coalesce(max(idx),0) + 1 FROM rlog), + 0, 0, + (SELECT coalesce(sum(a),0) FROM tbl), + (SELECT coalesce(sum(b),0) FROM tbl), + new.a, new.b); + END; + } + do_test without_rowid4-1.$ii.3 { + execsql { + + CREATE TABLE other_tbl(a, b); + INSERT INTO other_tbl VALUES(1, 2); + INSERT INTO other_tbl VALUES(3, 4); + -- INSERT INTO tbl SELECT * FROM other_tbl; + INSERT INTO tbl VALUES(5, 6); + DROP TABLE other_tbl; + + SELECT * FROM rlog; + } + } [list 1 0 0 0 0 5 6 \ + 2 0 0 5 6 5 6 ] + + integrity_check without_rowid4-1.$ii.4 + } + catchsql { + DROP TABLE rlog; + DROP TABLE clog; + DROP TABLE tbl; + DROP TABLE other_tbl; + } +} + +# 2. +set ii 0 +foreach tr_program { + {UPDATE tbl SET b = old.b;} + {INSERT INTO log VALUES(new.c, 2, 3);} + {DELETE FROM log WHERE a = 1;} + {INSERT INTO tbl VALUES(500, new.b * 10, 700); + UPDATE tbl SET c = old.c; + DELETE FROM log;} + {INSERT INTO log select * from tbl;} +} { + foreach test_varset [ list \ + { + set statement {UPDATE tbl SET c = 10 WHERE a = 1;} + set prep {INSERT INTO tbl VALUES(1, 2, 3);} + set newC 10 + set newB 2 + set newA 1 + set oldA 1 + set oldB 2 + set oldC 3 + } \ + { + set statement {DELETE FROM tbl WHERE a = 1;} + set prep {INSERT INTO tbl VALUES(1, 2, 3);} + set oldA 1 + set oldB 2 + set oldC 3 + } \ + { + set statement {INSERT INTO tbl VALUES(1, 2, 3);} + set newA 1 + set newB 2 + set newC 3 + } + ] \ + { + set statement {} + set prep {} + set newA {''} + set newB {''} + set newC {''} + set oldA {''} + set oldB {''} + set oldC {''} + + incr ii + + eval $test_varset + + set statement_type [string range $statement 0 5] + set tr_program_fixed $tr_program + if {$statement_type == "DELETE"} { + regsub -all new\.a $tr_program_fixed {''} tr_program_fixed + regsub -all new\.b $tr_program_fixed {''} tr_program_fixed + regsub -all new\.c $tr_program_fixed {''} tr_program_fixed + } + if {$statement_type == "INSERT"} { + regsub -all old\.a $tr_program_fixed {''} tr_program_fixed + regsub -all old\.b $tr_program_fixed {''} tr_program_fixed + regsub -all old\.c $tr_program_fixed {''} tr_program_fixed + } + + + set tr_program_cooked $tr_program + regsub -all new\.a $tr_program_cooked $newA tr_program_cooked + regsub -all new\.b $tr_program_cooked $newB tr_program_cooked + regsub -all new\.c $tr_program_cooked $newC tr_program_cooked + regsub -all old\.a $tr_program_cooked $oldA tr_program_cooked + regsub -all old\.b $tr_program_cooked $oldB tr_program_cooked + regsub -all old\.c $tr_program_cooked $oldC tr_program_cooked + + catchsql { + DROP TABLE tbl; + DROP TABLE log; + } + + execsql { + CREATE TABLE tbl(a PRIMARY KEY, b, c) WITHOUT rowid; + CREATE TABLE log(a, b, c); + } + + set query {SELECT * FROM tbl; SELECT * FROM log;} + set prep "$prep; INSERT INTO log VALUES(1, 2, 3);\ + INSERT INTO log VALUES(10, 20, 30);" + +# Check execution of BEFORE programs: + + set before_data [ execsql "$prep $tr_program_cooked $statement $query" ] + + execsql "DELETE FROM tbl; DELETE FROM log; $prep"; + execsql "CREATE TRIGGER the_trigger BEFORE [string range $statement 0 6]\ + ON tbl BEGIN $tr_program_fixed END;" + + do_test without_rowid4-2.$ii-before "execsql {$statement $query}" $before_data + + execsql "DROP TRIGGER the_trigger;" + execsql "DELETE FROM tbl; DELETE FROM log;" + +# Check execution of AFTER programs + set after_data [ execsql "$prep $statement $tr_program_cooked $query" ] + + execsql "DELETE FROM tbl; DELETE FROM log; $prep"; + execsql "CREATE TRIGGER the_trigger AFTER [string range $statement 0 6]\ + ON tbl BEGIN $tr_program_fixed END;" + + do_test without_rowid4-2.$ii-after "execsql {$statement $query}" $after_data + execsql "DROP TRIGGER the_trigger;" + + integrity_check without_rowid4-2.$ii-integrity + } +} +catchsql { + DROP TABLE tbl; + DROP TABLE log; +} + +# 3. + +# without_rowid4-3.1: UPDATE OF triggers +execsql { + CREATE TABLE tbl (a, b, c, d, PRIMARY KEY(a,b,c,d)) WITHOUT rowid; + CREATE TABLE log (a); + INSERT INTO log VALUES (0); + INSERT INTO tbl VALUES (0, 0, 0, 0); + INSERT INTO tbl VALUES (1, 0, 0, 0); + CREATE TRIGGER tbl_after_update_cd BEFORE UPDATE OF c, d ON tbl + BEGIN + UPDATE log SET a = a + 1; + END; +} +do_test without_rowid4-3.1 { + execsql { + UPDATE tbl SET b = 1, c = 10; -- 2 + UPDATE tbl SET b = 10; -- 0 + UPDATE tbl SET d = 4 WHERE a = 0; --1 + UPDATE tbl SET a = 4, b = 10; --0 + SELECT * FROM log; + } +} {3} +execsql { + DROP TABLE tbl; + DROP TABLE log; +} + +# without_rowid4-3.2: WHEN clause +set when_triggers [list {t1 BEFORE INSERT ON tbl WHEN new.a > 20}] +ifcapable subquery { + lappend when_triggers \ + {t2 BEFORE INSERT ON tbl WHEN (SELECT count(*) FROM tbl) = 0} +} + +execsql { + CREATE TABLE tbl (a, b, c, d); + CREATE TABLE log (a); + INSERT INTO log VALUES (0); +} + +foreach trig $when_triggers { + execsql "CREATE TRIGGER $trig BEGIN UPDATE log set a = a + 1; END;" +} + +ifcapable subquery { + set t232 {1 0 1} +} else { + set t232 {0 0 1} +} +do_test without_rowid4-3.2 { + execsql { + + INSERT INTO tbl VALUES(0, 0, 0, 0); -- 1 (ifcapable subquery) + SELECT * FROM log; + UPDATE log SET a = 0; + + INSERT INTO tbl VALUES(0, 0, 0, 0); -- 0 + SELECT * FROM log; + UPDATE log SET a = 0; + + INSERT INTO tbl VALUES(200, 0, 0, 0); -- 1 + SELECT * FROM log; + UPDATE log SET a = 0; + } +} $t232 +execsql { + DROP TABLE tbl; + DROP TABLE log; +} +integrity_check without_rowid4-3.3 + +# Simple cascaded trigger +execsql { + CREATE TABLE tblA(a, b, PRIMARY KEY(a,b)) WITHOUT rowid; + CREATE TABLE tblB(a, b, PRIMARY KEY(a,b)) WITHOUT rowid; + CREATE TABLE tblC(a, b, PRIMARY KEY(a,b)) WITHOUT rowid; + + CREATE TRIGGER tr1 BEFORE INSERT ON tblA BEGIN + INSERT INTO tblB values(new.a, new.b); + END; + + CREATE TRIGGER tr2 BEFORE INSERT ON tblB BEGIN + INSERT INTO tblC values(new.a, new.b); + END; +} +do_test without_rowid4-4.1 { + execsql { + INSERT INTO tblA values(1, 2); + SELECT * FROM tblA; + SELECT * FROM tblB; + SELECT * FROM tblC; + } +} {1 2 1 2 1 2} +execsql { + DROP TABLE tblA; + DROP TABLE tblB; + DROP TABLE tblC; +} + +# Simple recursive trigger +execsql { + CREATE TABLE tbl(a, b, c, PRIMARY KEY(c,a,b)) WITHOUT rowid; + CREATE TRIGGER tbl_trig BEFORE INSERT ON tbl + BEGIN + INSERT INTO tbl VALUES (new.a, new.b, new.c+1); + END; +} +do_test without_rowid4-4.2 { + execsql { + INSERT INTO tbl VALUES (1, 2, 3); + select * from tbl; + } +} {1 2 3 1 2 4} +execsql { + DROP TABLE tbl; +} + +# 5. +execsql { + CREATE TABLE tbl(a, b, c, PRIMARY KEY(c,a,b)) WITHOUT rowid; + CREATE TRIGGER tbl_trig BEFORE INSERT ON tbl + BEGIN + INSERT INTO tbl VALUES (1, 2, 3); + INSERT INTO tbl VALUES (2, 2, 3); + UPDATE tbl set b = 10 WHERE a = 1; + DELETE FROM tbl WHERE a = 1; + DELETE FROM tbl; + END; +} +do_test without_rowid4-5 { + execsql { + INSERT INTO tbl VALUES(100, 200, 300); + } + db changes +} {1} +execsql { + DROP TABLE tbl; +} + +ifcapable conflict { + # Handling of ON CONFLICT by INSERT statements inside triggers + execsql { + CREATE TABLE tbl (a PRIMARY KEY, b, c) WITHOUT rowid; + CREATE TRIGGER ai_tbl AFTER INSERT ON tbl BEGIN + INSERT OR IGNORE INTO tbl values (new.a, 0, 0); + END; + } + do_test without_rowid4-6.1a { + execsql { + BEGIN; + INSERT INTO tbl values (1, 2, 3); + SELECT * from tbl; + } + } {1 2 3} + do_test without_rowid4-6.1b { + catchsql { + INSERT OR ABORT INTO tbl values (2, 2, 3); + } + } {1 {UNIQUE constraint failed: tbl.a}} + do_test without_rowid4-6.1c { + execsql { + SELECT * from tbl; + } + } {1 2 3} + do_test without_rowid4-6.1d { + catchsql { + INSERT OR FAIL INTO tbl values (2, 2, 3); + } + } {1 {UNIQUE constraint failed: tbl.a}} + do_test without_rowid4-6.1e { + execsql { + SELECT * from tbl; + } + } {1 2 3 2 2 3} + do_test without_rowid4-6.1f { + execsql { + INSERT OR REPLACE INTO tbl values (2, 2, 3); + SELECT * from tbl; + } + } {1 2 3 2 0 0} + do_test without_rowid4-6.1g { + catchsql { + INSERT OR ROLLBACK INTO tbl values (3, 2, 3); + } + } {1 {UNIQUE constraint failed: tbl.a}} + do_test without_rowid4-6.1h { + execsql { + SELECT * from tbl; + } + } {} + execsql {DELETE FROM tbl} + + + # Handling of ON CONFLICT by UPDATE statements inside triggers + execsql { + INSERT INTO tbl values (4, 2, 3); + INSERT INTO tbl values (6, 3, 4); + CREATE TRIGGER au_tbl AFTER UPDATE ON tbl BEGIN + UPDATE OR IGNORE tbl SET a = new.a, c = 10; + END; + } + do_test without_rowid4-6.2a { + execsql { + BEGIN; + UPDATE tbl SET a = 1 WHERE a = 4; + SELECT * from tbl; + } + } {1 2 10 6 3 4} + do_test without_rowid4-6.2b { + catchsql { + UPDATE OR ABORT tbl SET a = 4 WHERE a = 1; + } + } {1 {UNIQUE constraint failed: tbl.a}} + do_test without_rowid4-6.2c { + execsql { + SELECT * from tbl; + } + } {1 2 10 6 3 4} + do_test without_rowid4-6.2d { + catchsql { + UPDATE OR FAIL tbl SET a = 4 WHERE a = 1; + } + } {1 {UNIQUE constraint failed: tbl.a}} + do_test without_rowid4-6.2e { + execsql { + SELECT * from tbl; + } + } {4 2 10 6 3 4} + do_test without_rowid4-6.2f.1 { + execsql { + UPDATE OR REPLACE tbl SET a = 1 WHERE a = 4; + SELECT * from tbl; + } + } {1 3 10} + do_test without_rowid4-6.2f.2 { + execsql { + INSERT INTO tbl VALUES (2, 3, 4); + SELECT * FROM tbl; + } + } {1 3 10 2 3 4} + do_test without_rowid4-6.2g { + catchsql { + UPDATE OR ROLLBACK tbl SET a = 4 WHERE a = 1; + } + } {1 {UNIQUE constraint failed: tbl.a}} + do_test without_rowid4-6.2h { + execsql { + SELECT * from tbl; + } + } {4 2 3 6 3 4} + execsql { + DROP TABLE tbl; + } +} ; # ifcapable conflict + +# 7. Triggers on views +ifcapable view { + +do_test without_rowid4-7.1 { + execsql { + CREATE TABLE ab(a, b, PRIMARY KEY(a,b)) WITHOUT rowid; + CREATE TABLE cd(c, d, PRIMARY KEY(c,d)) WITHOUT rowid; + INSERT INTO ab VALUES (1, 2); + INSERT INTO ab VALUES (0, 0); + INSERT INTO cd VALUES (3, 4); + + CREATE TABLE tlog(ii INTEGER PRIMARY KEY, + olda, oldb, oldc, oldd, newa, newb, newc, newd); + + CREATE VIEW abcd AS SELECT a, b, c, d FROM ab, cd; + + CREATE TRIGGER before_update INSTEAD OF UPDATE ON abcd BEGIN + INSERT INTO tlog VALUES(NULL, + old.a, old.b, old.c, old.d, new.a, new.b, new.c, new.d); + END; + CREATE TRIGGER after_update INSTEAD OF UPDATE ON abcd BEGIN + INSERT INTO tlog VALUES(NULL, + old.a, old.b, old.c, old.d, new.a, new.b, new.c, new.d); + END; + + CREATE TRIGGER before_delete INSTEAD OF DELETE ON abcd BEGIN + INSERT INTO tlog VALUES(NULL, + old.a, old.b, old.c, old.d, 0, 0, 0, 0); + END; + CREATE TRIGGER after_delete INSTEAD OF DELETE ON abcd BEGIN + INSERT INTO tlog VALUES(NULL, + old.a, old.b, old.c, old.d, 0, 0, 0, 0); + END; + + CREATE TRIGGER before_insert INSTEAD OF INSERT ON abcd BEGIN + INSERT INTO tlog VALUES(NULL, + 0, 0, 0, 0, new.a, new.b, new.c, new.d); + END; + CREATE TRIGGER after_insert INSTEAD OF INSERT ON abcd BEGIN + INSERT INTO tlog VALUES(NULL, + 0, 0, 0, 0, new.a, new.b, new.c, new.d); + END; + } +} {}; + +do_test without_rowid4-7.2 { + execsql { + UPDATE abcd SET a = 100, b = 5*5 WHERE a = 1; + DELETE FROM abcd WHERE a = 1; + INSERT INTO abcd VALUES(10, 20, 30, 40); + SELECT * FROM tlog; + } +} [ list 1 1 2 3 4 100 25 3 4 \ + 2 1 2 3 4 100 25 3 4 \ + 3 1 2 3 4 0 0 0 0 \ + 4 1 2 3 4 0 0 0 0 \ + 5 0 0 0 0 10 20 30 40 \ + 6 0 0 0 0 10 20 30 40 ] + +do_test without_rowid4-7.3 { + execsql { + DELETE FROM tlog; + INSERT INTO abcd VALUES(10, 20, 30, 40); + UPDATE abcd SET a = 100, b = 5*5 WHERE a = 1; + DELETE FROM abcd WHERE a = 1; + SELECT * FROM tlog; + } +} [ list \ + 1 0 0 0 0 10 20 30 40 \ + 2 0 0 0 0 10 20 30 40 \ + 3 1 2 3 4 100 25 3 4 \ + 4 1 2 3 4 100 25 3 4 \ + 5 1 2 3 4 0 0 0 0 \ + 6 1 2 3 4 0 0 0 0 \ +] +do_test without_rowid4-7.4 { + execsql { + DELETE FROM tlog; + DELETE FROM abcd WHERE a = 1; + INSERT INTO abcd VALUES(10, 20, 30, 40); + UPDATE abcd SET a = 100, b = 5*5 WHERE a = 1; + SELECT * FROM tlog; + } +} [ list \ + 1 1 2 3 4 0 0 0 0 \ + 2 1 2 3 4 0 0 0 0 \ + 3 0 0 0 0 10 20 30 40 \ + 4 0 0 0 0 10 20 30 40 \ + 5 1 2 3 4 100 25 3 4 \ + 6 1 2 3 4 100 25 3 4 \ +] + +do_test without_rowid4-8.1 { + execsql { + CREATE TABLE t1(a,b,c, PRIMARY KEY(a,b,c)) WITHOUT rowid; + INSERT INTO t1 VALUES(1,2,3); + CREATE VIEW v1 AS + SELECT a+b AS x, b+c AS y, a+c AS z FROM t1; + SELECT * FROM v1; + } +} {3 5 4} +do_test without_rowid4-8.2 { + execsql { + CREATE TABLE v1log(a,b,c,d,e,f); + CREATE TRIGGER r1 INSTEAD OF DELETE ON v1 BEGIN + INSERT INTO v1log VALUES(OLD.x,NULL,OLD.y,NULL,OLD.z,NULL); + END; + DELETE FROM v1 WHERE x=1; + SELECT * FROM v1log; + } +} {} +do_test without_rowid4-8.3 { + execsql { + DELETE FROM v1 WHERE x=3; + SELECT * FROM v1log; + } +} {3 {} 5 {} 4 {}} +do_test without_rowid4-8.4 { + execsql { + INSERT INTO t1 VALUES(4,5,6); + DELETE FROM v1log; + DELETE FROM v1 WHERE y=11; + SELECT * FROM v1log; + } +} {9 {} 11 {} 10 {}} +do_test without_rowid4-8.5 { + execsql { + CREATE TRIGGER r2 INSTEAD OF INSERT ON v1 BEGIN + INSERT INTO v1log VALUES(NULL,NEW.x,NULL,NEW.y,NULL,NEW.z); + END; + DELETE FROM v1log; + INSERT INTO v1 VALUES(1,2,3); + SELECT * FROM v1log; + } +} {{} 1 {} 2 {} 3} +do_test without_rowid4-8.6 { + execsql { + CREATE TRIGGER r3 INSTEAD OF UPDATE ON v1 BEGIN + INSERT INTO v1log VALUES(OLD.x,NEW.x,OLD.y,NEW.y,OLD.z,NEW.z); + END; + DELETE FROM v1log; + UPDATE v1 SET x=x+100, y=y+200, z=z+300; + SELECT * FROM v1log; + } +} {3 103 5 205 4 304 9 109 11 211 10 310} + +# At one point the following was causing a segfault. +do_test without_rowid4-9.1 { + execsql { + CREATE TABLE t3(a TEXT, b TEXT); + CREATE VIEW v3 AS SELECT t3.a FROM t3; + CREATE TRIGGER trig1 INSTEAD OF DELETE ON v3 BEGIN + SELECT 1; + END; + DELETE FROM v3 WHERE a = 1; + } +} {} + +} ;# ifcapable view + +integrity_check without_rowid4-9.9 + +finish_test diff --git a/test/wordcount.c b/test/wordcount.c new file mode 100644 index 0000000000..2161c07174 --- /dev/null +++ b/test/wordcount.c @@ -0,0 +1,483 @@ +/* +** This C program extracts all "words" from an input document and adds them +** to an SQLite database. A "word" is any contiguous sequence of alphabetic +** characters. All digits, punctuation, and whitespace characters are +** word separators. The database stores a single entry for each distinct +** word together with a count of the number of occurrences of that word. +** A fresh database is created automatically on each run. +** +** wordcount DATABASE INPUTFILE +** +** The INPUTFILE name can be omitted, in which case input it taken from +** standard input. +** +** Option: +** +** --without-rowid Use a WITHOUT ROWID table to store the words. +** --insert Use INSERT mode (the default) +** --replace Use REPLACE mode +** --select Use SELECT mode +** --update Use UPDATE mode +** --delete Use DELETE mode +** --nocase Add the NOCASE collating sequence to the words. +** --trace Enable sqlite3_trace() output. +** --summary Show summary information on the collected data. +** --stats Show sqlite3_status() results at the end. +** --pagesize NNN Use a page size of NNN +** --cachesize NNN Use a cache size of NNN +** --commit NNN Commit after every NNN operations +** --nosync Use PRAGMA synchronous=OFF +** --journal MMMM Use PRAGMA journal_mode=MMMM +** +** Modes: +** +** Insert mode means: +** (1) INSERT OR IGNORE INTO wordcount VALUES($new,1) +** (2) UPDATE wordcount SET cnt=cnt+1 WHERE word=$new -- if (1) is a noop +** +** Update mode means: +** (1) INSERT OR IGNORE INTO wordcount VALUES($new,0) +** (2) UPDATE wordcount SET cnt=cnt+1 WHERE word=$new +** +** Replace mode means: +** (1) REPLACE INTO wordcount +** VALUES($new,ifnull((SELECT cnt FROM wordcount WHERE word=$new),0)+1); +** +** Select mode means: +** (1) SELECT 1 FROM wordcount WHERE word=$new +** (2) INSERT INTO wordcount VALUES($new,1) -- if (1) returns nothing +** (3) UPDATE wordcount SET cnt=cnt+1 WHERE word=$new --if (1) return TRUE +** +** Delete mode means: +** (1) DELETE FROM wordcount WHERE word=$new +** +** Note that delete mode is only useful for preexisting databases. The +** wordcount table is created using IF NOT EXISTS so this utility can be +** run multiple times on the same database file. The --without-rowid, +** --nocase, and --pagesize parameters are only effective when creating +** a new database and are harmless no-ops on preexisting databases. +** +****************************************************************************** +** +** Compile as follows: +** +** gcc -I. wordcount.c sqlite3.c -ldl -lpthreads +** +** Or: +** +** gcc -I. -DSQLITE_THREADSAFE=0 -DSQLITE_OMIT_LOAD_EXTENSION \ +** wordcount.c sqlite3.c +*/ +#include +#include +#include +#include +#include +#include "sqlite3.h" + +/* Print an error message and exit */ +static void fatal_error(const char *zMsg, ...){ + va_list ap; + va_start(ap, zMsg); + vfprintf(stderr, zMsg, ap); + va_end(ap); + exit(1); +} + +/* The sqlite3_trace() callback function */ +static void traceCallback(void *NotUsed, const char *zSql){ + printf("%s;\n", zSql); +} + +/* An sqlite3_exec() callback that prints results on standard output, +** each column separated by a single space. */ +static int printResult(void *NotUsed, int nArg, char **azArg, char **azNm){ + int i; + printf("--"); + for(i=0; i0 && (nOp%commitInterval)==0 ){ + sqlite3_exec(db, "COMMIT; BEGIN IMMEDIATE", 0, 0, 0); + } + } + } + sqlite3_exec(db, "COMMIT", 0, 0, 0); + if( zFileToRead ) fclose(in); + sqlite3_finalize(pInsert); + sqlite3_finalize(pUpdate); + sqlite3_finalize(pSelect); + sqlite3_finalize(pDelete); + + if( showSummary ){ + sqlite3_create_function(db, "checksum", -1, SQLITE_UTF8, 0, + 0, checksumStep, checksumFinalize); + sqlite3_exec(db, + "SELECT 'count(*): ', count(*) FROM wordcount;\n" + "SELECT 'sum(cnt): ', sum(cnt) FROM wordcount;\n" + "SELECT 'max(cnt): ', max(cnt) FROM wordcount;\n" + "SELECT 'avg(cnt): ', avg(cnt) FROM wordcount;\n" + "SELECT 'sum(cnt=1):', sum(cnt=1) FROM wordcount;\n" + "SELECT 'top 10: ', group_concat(word, ', ') FROM " + "(SELECT word FROM wordcount ORDER BY cnt DESC LIMIT 10);\n" + "SELECT 'checksum: ', checksum(word, cnt) FROM " + "(SELECT word, cnt FROM wordcount ORDER BY word);\n" + "PRAGMA integrity_check;\n", + printResult, 0, 0); + } + + /* Database connection statistics printed after both prepared statements + ** have been finalized */ + if( showStats ){ + sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_USED, &iCur, &iHiwtr, 0); + printf("-- Lookaside Slots Used: %d (max %d)\n", iCur,iHiwtr); + sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_HIT, &iCur, &iHiwtr, 0); + printf("-- Successful lookasides: %d\n", iHiwtr); + sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE, &iCur,&iHiwtr,0); + printf("-- Lookaside size faults: %d\n", iHiwtr); + sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL, &iCur,&iHiwtr,0); + printf("-- Lookaside OOM faults: %d\n", iHiwtr); + sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_USED, &iCur, &iHiwtr, 0); + printf("-- Pager Heap Usage: %d bytes\n", iCur); + sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_HIT, &iCur, &iHiwtr, 1); + printf("-- Page cache hits: %d\n", iCur); + sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_MISS, &iCur, &iHiwtr, 1); + printf("-- Page cache misses: %d\n", iCur); + sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_WRITE, &iCur, &iHiwtr, 1); + printf("-- Page cache writes: %d\n", iCur); + sqlite3_db_status(db, SQLITE_DBSTATUS_SCHEMA_USED, &iCur, &iHiwtr, 0); + printf("-- Schema Heap Usage: %d bytes\n", iCur); + sqlite3_db_status(db, SQLITE_DBSTATUS_STMT_USED, &iCur, &iHiwtr, 0); + printf("-- Statement Heap Usage: %d bytes\n", iCur); + } + + sqlite3_close(db); + + /* Global memory usage statistics printed after the database connection + ** has closed. Memory usage should be zero at this point. */ + if( showStats ){ + sqlite3_status(SQLITE_STATUS_MEMORY_USED, &iCur, &iHiwtr, 0); + printf("-- Memory Used (bytes): %d (max %d)\n", iCur,iHiwtr); + sqlite3_status(SQLITE_STATUS_MALLOC_COUNT, &iCur, &iHiwtr, 0); + printf("-- Outstanding Allocations: %d (max %d)\n", iCur,iHiwtr); + sqlite3_status(SQLITE_STATUS_PAGECACHE_OVERFLOW, &iCur, &iHiwtr, 0); + printf("-- Pcache Overflow Bytes: %d (max %d)\n", iCur,iHiwtr); + sqlite3_status(SQLITE_STATUS_SCRATCH_OVERFLOW, &iCur, &iHiwtr, 0); + printf("-- Scratch Overflow Bytes: %d (max %d)\n", iCur,iHiwtr); + sqlite3_status(SQLITE_STATUS_MALLOC_SIZE, &iCur, &iHiwtr, 0); + printf("-- Largest Allocation: %d bytes\n",iHiwtr); + sqlite3_status(SQLITE_STATUS_PAGECACHE_SIZE, &iCur, &iHiwtr, 0); + printf("-- Largest Pcache Allocation: %d bytes\n",iHiwtr); + sqlite3_status(SQLITE_STATUS_SCRATCH_SIZE, &iCur, &iHiwtr, 0); + printf("-- Largest Scratch Allocation: %d bytes\n", iHiwtr); + } + return 0; +} diff --git a/tool/build-all-msvc.bat b/tool/build-all-msvc.bat index ed05f959fe..c730943f68 100755 --- a/tool/build-all-msvc.bat +++ b/tool/build-all-msvc.bat @@ -252,7 +252,7 @@ FOR %%P IN (%PLATFORMS%) DO ( CALL :fn_CopyVariable %%P_NAME PLATFORMNAME REM - REM NOTE: This is the inner loop. There should be exactly one iteration. + REM NOTE: This is the second loop. There should be exactly one iteration. REM This loop is necessary because the PlatformName environment REM variable was set above and that value is needed by some of the REM commands contained in the inner loop. If these commands were @@ -289,6 +289,10 @@ FOR %%P IN (%PLATFORMS%) DO ( REM SET PATH=%TOOLPATH%;%SystemRoot%\System32;%SystemRoot% + REM + REM NOTE: This is the inner loop. There are normally two iterations, one + REM for each supported build configuration, e.g. Debug or Retail. + REM FOR %%B IN (%CONFIGURATIONS%) DO ( REM REM NOTE: When preparing the debug build, set the DEBUG and MEMDEBUG @@ -318,6 +322,10 @@ FOR %%P IN (%PLATFORMS%) DO ( REM platform to the platform-specific directory beneath the REM binary directory. REM + REM 5. Unless prevented from doing so, copy the "sqlite3.pdb" + REM symbols file for this platform to the platform-specific + REM directory beneath the binary directory. + REM "%ComSpec%" /C ( REM REM NOTE: Attempt to setup the MSVC environment for this platform. @@ -345,21 +353,30 @@ FOR %%P IN (%PLATFORMS%) DO ( ) REM - REM NOTE: When using MSVC 2012, the native SDK path cannot simply use - REM the "lib" sub-directory beneath the location specified in the - REM WindowsSdkDir environment variable because that location does - REM not actually contain the necessary library files for x86. - REM This must be done for each iteration because it relies upon - REM the WindowsSdkDir environment variable being set by the batch - REM file used to setup the MSVC environment. + REM NOTE: When using MSVC 2012 and/or 2013, the native SDK path cannot + REM simply use the "lib" sub-directory beneath the location + REM specified in the WindowsSdkDir environment variable because + REM that location does not actually contain the necessary library + REM files for x86. This must be done for each iteration because + REM it relies upon the WindowsSdkDir environment variable being + REM set by the batch file used to setup the MSVC environment. REM IF DEFINED SET_NSDKLIBPATH ( + REM + REM NOTE: The Windows Phone SDK has a slightly different directory + REM structure and must be handled specially here. + REM IF DEFINED WindowsPhoneKitDir ( CALL :fn_CopyVariable WindowsPhoneKitDir NSDKLIBPATH CALL :fn_AppendVariable NSDKLIBPATH \lib\x86 ) ELSE IF DEFINED WindowsSdkDir ( CALL :fn_CopyVariable WindowsSdkDir NSDKLIBPATH + REM + REM NOTE: The Windows 8.1 SDK has a slightly different directory + REM naming convention. Currently, this tool assumes that + REM the Windows 8.1 SDK should only be used with MSVC 2013. + REM IF "%VisualStudioVersion%" == "12.0" ( CALL :fn_AppendVariable NSDKLIBPATH \lib\winv6.3\um\x86 ) ELSE ( diff --git a/tool/mkkeywordhash.c b/tool/mkkeywordhash.c index 4e5ba8f1a8..f3ef73f394 100644 --- a/tool/mkkeywordhash.c +++ b/tool/mkkeywordhash.c @@ -262,6 +262,7 @@ static Keyword aKeywordTable[] = { { "VALUES", "TK_VALUES", ALWAYS }, { "VIEW", "TK_VIEW", VIEW }, { "VIRTUAL", "TK_VIRTUAL", VTAB }, + { "WITHOUT", "TK_WITHOUT", ALWAYS }, { "WHEN", "TK_WHEN", ALWAYS }, { "WHERE", "TK_WHERE", ALWAYS }, }; diff --git a/tool/spaceanal.tcl b/tool/spaceanal.tcl index 9cb62983ef..a227b85243 100644 --- a/tool/spaceanal.tcl +++ b/tool/spaceanal.tcl @@ -571,7 +571,7 @@ subreport {All tables} {NOT is_index} 0 if {$nindex>0} { subreport {All indices} {is_index} 0 } -foreach tbl [mem eval {SELECT name FROM space_used WHERE NOT is_index +foreach tbl [mem eval {SELECT DISTINCT tblname name FROM space_used ORDER BY name}] { set qn [quote $tbl] set name [string toupper $tbl] @@ -766,7 +766,7 @@ mem eval {SELECT * FROM space_used} x { set sep ( foreach col $x(*) { set v $x($col) - if {$v=="" || ![string is double $v]} {set v [quote $v]} + if {$v=="" || ![string is double $v]} {set v '[quote $v]'} puts -nonewline $sep$v set sep , }