000001 /*
000002 ** 2001 September 15
000003 **
000004 ** The author disclaims copyright to this source code. In place of
000005 ** a legal notice, here is a blessing:
000006 **
000007 ** May you do good and not evil.
000008 ** May you find forgiveness for yourself and forgive others.
000009 ** May you share freely, never taking more than you give.
000010 **
000011 *************************************************************************
000012 ** This file contains C code routines that are called by the SQLite parser
000013 ** when syntax rules are reduced. The routines in this file handle the
000014 ** following kinds of SQL syntax:
000015 **
000016 ** CREATE TABLE
000017 ** DROP TABLE
000018 ** CREATE INDEX
000019 ** DROP INDEX
000020 ** creating ID lists
000021 ** BEGIN TRANSACTION
000022 ** COMMIT
000023 ** ROLLBACK
000024 */
000025 #include "sqliteInt.h"
000026
000027 #ifndef SQLITE_OMIT_SHARED_CACHE
000028 /*
000029 ** The TableLock structure is only used by the sqlite3TableLock() and
000030 ** codeTableLocks() functions.
000031 */
000032 struct TableLock {
000033 int iDb; /* The database containing the table to be locked */
000034 Pgno iTab; /* The root page of the table to be locked */
000035 u8 isWriteLock; /* True for write lock. False for a read lock */
000036 const char *zLockName; /* Name of the table */
000037 };
000038
000039 /*
000040 ** Record the fact that we want to lock a table at run-time.
000041 **
000042 ** The table to be locked has root page iTab and is found in database iDb.
000043 ** A read or a write lock can be taken depending on isWritelock.
000044 **
000045 ** This routine just records the fact that the lock is desired. The
000046 ** code to make the lock occur is generated by a later call to
000047 ** codeTableLocks() which occurs during sqlite3FinishCoding().
000048 */
000049 static SQLITE_NOINLINE void lockTable(
000050 Parse *pParse, /* Parsing context */
000051 int iDb, /* Index of the database containing the table to lock */
000052 Pgno iTab, /* Root page number of the table to be locked */
000053 u8 isWriteLock, /* True for a write lock */
000054 const char *zName /* Name of the table to be locked */
000055 ){
000056 Parse *pToplevel;
000057 int i;
000058 int nBytes;
000059 TableLock *p;
000060 assert( iDb>=0 );
000061
000062 pToplevel = sqlite3ParseToplevel(pParse);
000063 for(i=0; i<pToplevel->nTableLock; i++){
000064 p = &pToplevel->aTableLock[i];
000065 if( p->iDb==iDb && p->iTab==iTab ){
000066 p->isWriteLock = (p->isWriteLock || isWriteLock);
000067 return;
000068 }
000069 }
000070
000071 nBytes = sizeof(TableLock) * (pToplevel->nTableLock+1);
000072 pToplevel->aTableLock =
000073 sqlite3DbReallocOrFree(pToplevel->db, pToplevel->aTableLock, nBytes);
000074 if( pToplevel->aTableLock ){
000075 p = &pToplevel->aTableLock[pToplevel->nTableLock++];
000076 p->iDb = iDb;
000077 p->iTab = iTab;
000078 p->isWriteLock = isWriteLock;
000079 p->zLockName = zName;
000080 }else{
000081 pToplevel->nTableLock = 0;
000082 sqlite3OomFault(pToplevel->db);
000083 }
000084 }
000085 void sqlite3TableLock(
000086 Parse *pParse, /* Parsing context */
000087 int iDb, /* Index of the database containing the table to lock */
000088 Pgno iTab, /* Root page number of the table to be locked */
000089 u8 isWriteLock, /* True for a write lock */
000090 const char *zName /* Name of the table to be locked */
000091 ){
000092 if( iDb==1 ) return;
000093 if( !sqlite3BtreeSharable(pParse->db->aDb[iDb].pBt) ) return;
000094 lockTable(pParse, iDb, iTab, isWriteLock, zName);
000095 }
000096
000097 /*
000098 ** Code an OP_TableLock instruction for each table locked by the
000099 ** statement (configured by calls to sqlite3TableLock()).
000100 */
000101 static void codeTableLocks(Parse *pParse){
000102 int i;
000103 Vdbe *pVdbe = pParse->pVdbe;
000104 assert( pVdbe!=0 );
000105
000106 for(i=0; i<pParse->nTableLock; i++){
000107 TableLock *p = &pParse->aTableLock[i];
000108 int p1 = p->iDb;
000109 sqlite3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, p->isWriteLock,
000110 p->zLockName, P4_STATIC);
000111 }
000112 }
000113 #else
000114 #define codeTableLocks(x)
000115 #endif
000116
000117 /*
000118 ** Return TRUE if the given yDbMask object is empty - if it contains no
000119 ** 1 bits. This routine is used by the DbMaskAllZero() and DbMaskNotZero()
000120 ** macros when SQLITE_MAX_ATTACHED is greater than 30.
000121 */
000122 #if SQLITE_MAX_ATTACHED>30
000123 int sqlite3DbMaskAllZero(yDbMask m){
000124 int i;
000125 for(i=0; i<sizeof(yDbMask); i++) if( m[i] ) return 0;
000126 return 1;
000127 }
000128 #endif
000129
000130 /*
000131 ** This routine is called after a single SQL statement has been
000132 ** parsed and a VDBE program to execute that statement has been
000133 ** prepared. This routine puts the finishing touches on the
000134 ** VDBE program and resets the pParse structure for the next
000135 ** parse.
000136 **
000137 ** Note that if an error occurred, it might be the case that
000138 ** no VDBE code was generated.
000139 */
000140 void sqlite3FinishCoding(Parse *pParse){
000141 sqlite3 *db;
000142 Vdbe *v;
000143 int iDb, i;
000144
000145 assert( pParse->pToplevel==0 );
000146 db = pParse->db;
000147 assert( db->pParse==pParse );
000148 if( pParse->nested ) return;
000149 if( pParse->nErr ){
000150 if( db->mallocFailed ) pParse->rc = SQLITE_NOMEM;
000151 return;
000152 }
000153 assert( db->mallocFailed==0 );
000154
000155 /* Begin by generating some termination code at the end of the
000156 ** vdbe program
000157 */
000158 v = pParse->pVdbe;
000159 if( v==0 ){
000160 if( db->init.busy ){
000161 pParse->rc = SQLITE_DONE;
000162 return;
000163 }
000164 v = sqlite3GetVdbe(pParse);
000165 if( v==0 ) pParse->rc = SQLITE_ERROR;
000166 }
000167 assert( !pParse->isMultiWrite
000168 || sqlite3VdbeAssertMayAbort(v, pParse->mayAbort));
000169 if( v ){
000170 if( pParse->bReturning ){
000171 Returning *pReturning = pParse->u1.pReturning;
000172 int addrRewind;
000173 int reg;
000174
000175 if( pReturning->nRetCol ){
000176 sqlite3VdbeAddOp0(v, OP_FkCheck);
000177 addrRewind =
000178 sqlite3VdbeAddOp1(v, OP_Rewind, pReturning->iRetCur);
000179 VdbeCoverage(v);
000180 reg = pReturning->iRetReg;
000181 for(i=0; i<pReturning->nRetCol; i++){
000182 sqlite3VdbeAddOp3(v, OP_Column, pReturning->iRetCur, i, reg+i);
000183 }
000184 sqlite3VdbeAddOp2(v, OP_ResultRow, reg, i);
000185 sqlite3VdbeAddOp2(v, OP_Next, pReturning->iRetCur, addrRewind+1);
000186 VdbeCoverage(v);
000187 sqlite3VdbeJumpHere(v, addrRewind);
000188 }
000189 }
000190 sqlite3VdbeAddOp0(v, OP_Halt);
000191
000192 /* The cookie mask contains one bit for each database file open.
000193 ** (Bit 0 is for main, bit 1 is for temp, and so forth.) Bits are
000194 ** set for each database that is used. Generate code to start a
000195 ** transaction on each used database and to verify the schema cookie
000196 ** on each used database.
000197 */
000198 assert( pParse->nErr>0 || sqlite3VdbeGetOp(v, 0)->opcode==OP_Init );
000199 sqlite3VdbeJumpHere(v, 0);
000200 assert( db->nDb>0 );
000201 iDb = 0;
000202 do{
000203 Schema *pSchema;
000204 if( DbMaskTest(pParse->cookieMask, iDb)==0 ) continue;
000205 sqlite3VdbeUsesBtree(v, iDb);
000206 pSchema = db->aDb[iDb].pSchema;
000207 sqlite3VdbeAddOp4Int(v,
000208 OP_Transaction, /* Opcode */
000209 iDb, /* P1 */
000210 DbMaskTest(pParse->writeMask,iDb), /* P2 */
000211 pSchema->schema_cookie, /* P3 */
000212 pSchema->iGeneration /* P4 */
000213 );
000214 if( db->init.busy==0 ) sqlite3VdbeChangeP5(v, 1);
000215 VdbeComment((v,
000216 "usesStmtJournal=%d", pParse->mayAbort && pParse->isMultiWrite));
000217 }while( ++iDb<db->nDb );
000218 #ifndef SQLITE_OMIT_VIRTUALTABLE
000219 for(i=0; i<pParse->nVtabLock; i++){
000220 char *vtab = (char *)sqlite3GetVTable(db, pParse->apVtabLock[i]);
000221 sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB);
000222 }
000223 pParse->nVtabLock = 0;
000224 #endif
000225
000226 #ifndef SQLITE_OMIT_SHARED_CACHE
000227 /* Once all the cookies have been verified and transactions opened,
000228 ** obtain the required table-locks. This is a no-op unless the
000229 ** shared-cache feature is enabled.
000230 */
000231 if( pParse->nTableLock ) codeTableLocks(pParse);
000232 #endif
000233
000234 /* Initialize any AUTOINCREMENT data structures required.
000235 */
000236 if( pParse->pAinc ) sqlite3AutoincrementBegin(pParse);
000237
000238 /* Code constant expressions that were factored out of inner loops.
000239 */
000240 if( pParse->pConstExpr ){
000241 ExprList *pEL = pParse->pConstExpr;
000242 pParse->okConstFactor = 0;
000243 for(i=0; i<pEL->nExpr; i++){
000244 assert( pEL->a[i].u.iConstExprReg>0 );
000245 sqlite3ExprCode(pParse, pEL->a[i].pExpr, pEL->a[i].u.iConstExprReg);
000246 }
000247 }
000248
000249 if( pParse->bReturning ){
000250 Returning *pRet = pParse->u1.pReturning;
000251 if( pRet->nRetCol ){
000252 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pRet->iRetCur, pRet->nRetCol);
000253 }
000254 }
000255
000256 /* Finally, jump back to the beginning of the executable code. */
000257 sqlite3VdbeGoto(v, 1);
000258 }
000259
000260 /* Get the VDBE program ready for execution
000261 */
000262 assert( v!=0 || pParse->nErr );
000263 assert( db->mallocFailed==0 || pParse->nErr );
000264 if( pParse->nErr==0 ){
000265 /* A minimum of one cursor is required if autoincrement is used
000266 * See ticket [a696379c1f08866] */
000267 assert( pParse->pAinc==0 || pParse->nTab>0 );
000268 sqlite3VdbeMakeReady(v, pParse);
000269 pParse->rc = SQLITE_DONE;
000270 }else{
000271 pParse->rc = SQLITE_ERROR;
000272 }
000273 }
000274
000275 /*
000276 ** Run the parser and code generator recursively in order to generate
000277 ** code for the SQL statement given onto the end of the pParse context
000278 ** currently under construction. Notes:
000279 **
000280 ** * The final OP_Halt is not appended and other initialization
000281 ** and finalization steps are omitted because those are handling by the
000282 ** outermost parser.
000283 **
000284 ** * Built-in SQL functions always take precedence over application-defined
000285 ** SQL functions. In other words, it is not possible to override a
000286 ** built-in function.
000287 */
000288 void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
000289 va_list ap;
000290 char *zSql;
000291 sqlite3 *db = pParse->db;
000292 u32 savedDbFlags = db->mDbFlags;
000293 char saveBuf[PARSE_TAIL_SZ];
000294
000295 if( pParse->nErr ) return;
000296 if( pParse->eParseMode ) return;
000297 assert( pParse->nested<10 ); /* Nesting should only be of limited depth */
000298 va_start(ap, zFormat);
000299 zSql = sqlite3VMPrintf(db, zFormat, ap);
000300 va_end(ap);
000301 if( zSql==0 ){
000302 /* This can result either from an OOM or because the formatted string
000303 ** exceeds SQLITE_LIMIT_LENGTH. In the latter case, we need to set
000304 ** an error */
000305 if( !db->mallocFailed ) pParse->rc = SQLITE_TOOBIG;
000306 pParse->nErr++;
000307 return;
000308 }
000309 pParse->nested++;
000310 memcpy(saveBuf, PARSE_TAIL(pParse), PARSE_TAIL_SZ);
000311 memset(PARSE_TAIL(pParse), 0, PARSE_TAIL_SZ);
000312 db->mDbFlags |= DBFLAG_PreferBuiltin;
000313 sqlite3RunParser(pParse, zSql);
000314 db->mDbFlags = savedDbFlags;
000315 sqlite3DbFree(db, zSql);
000316 memcpy(PARSE_TAIL(pParse), saveBuf, PARSE_TAIL_SZ);
000317 pParse->nested--;
000318 }
000319
000320 /*
000321 ** Locate the in-memory structure that describes a particular database
000322 ** table given the name of that table and (optionally) the name of the
000323 ** database containing the table. Return NULL if not found.
000324 **
000325 ** If zDatabase is 0, all databases are searched for the table and the
000326 ** first matching table is returned. (No checking for duplicate table
000327 ** names is done.) The search order is TEMP first, then MAIN, then any
000328 ** auxiliary databases added using the ATTACH command.
000329 **
000330 ** See also sqlite3LocateTable().
000331 */
000332 Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
000333 Table *p = 0;
000334 int i;
000335
000336 /* All mutexes are required for schema access. Make sure we hold them. */
000337 assert( zDatabase!=0 || sqlite3BtreeHoldsAllMutexes(db) );
000338 if( zDatabase ){
000339 for(i=0; i<db->nDb; i++){
000340 if( sqlite3StrICmp(zDatabase, db->aDb[i].zDbSName)==0 ) break;
000341 }
000342 if( i>=db->nDb ){
000343 /* No match against the official names. But always match "main"
000344 ** to schema 0 as a legacy fallback. */
000345 if( sqlite3StrICmp(zDatabase,"main")==0 ){
000346 i = 0;
000347 }else{
000348 return 0;
000349 }
000350 }
000351 p = sqlite3HashFind(&db->aDb[i].pSchema->tblHash, zName);
000352 if( p==0 && sqlite3StrNICmp(zName, "sqlite_", 7)==0 ){
000353 if( i==1 ){
000354 if( sqlite3StrICmp(zName+7, &PREFERRED_TEMP_SCHEMA_TABLE[7])==0
000355 || sqlite3StrICmp(zName+7, &PREFERRED_SCHEMA_TABLE[7])==0
000356 || sqlite3StrICmp(zName+7, &LEGACY_SCHEMA_TABLE[7])==0
000357 ){
000358 p = sqlite3HashFind(&db->aDb[1].pSchema->tblHash,
000359 LEGACY_TEMP_SCHEMA_TABLE);
000360 }
000361 }else{
000362 if( sqlite3StrICmp(zName+7, &PREFERRED_SCHEMA_TABLE[7])==0 ){
000363 p = sqlite3HashFind(&db->aDb[i].pSchema->tblHash,
000364 LEGACY_SCHEMA_TABLE);
000365 }
000366 }
000367 }
000368 }else{
000369 /* Match against TEMP first */
000370 p = sqlite3HashFind(&db->aDb[1].pSchema->tblHash, zName);
000371 if( p ) return p;
000372 /* The main database is second */
000373 p = sqlite3HashFind(&db->aDb[0].pSchema->tblHash, zName);
000374 if( p ) return p;
000375 /* Attached databases are in order of attachment */
000376 for(i=2; i<db->nDb; i++){
000377 assert( sqlite3SchemaMutexHeld(db, i, 0) );
000378 p = sqlite3HashFind(&db->aDb[i].pSchema->tblHash, zName);
000379 if( p ) break;
000380 }
000381 if( p==0 && sqlite3StrNICmp(zName, "sqlite_", 7)==0 ){
000382 if( sqlite3StrICmp(zName+7, &PREFERRED_SCHEMA_TABLE[7])==0 ){
000383 p = sqlite3HashFind(&db->aDb[0].pSchema->tblHash, LEGACY_SCHEMA_TABLE);
000384 }else if( sqlite3StrICmp(zName+7, &PREFERRED_TEMP_SCHEMA_TABLE[7])==0 ){
000385 p = sqlite3HashFind(&db->aDb[1].pSchema->tblHash,
000386 LEGACY_TEMP_SCHEMA_TABLE);
000387 }
000388 }
000389 }
000390 return p;
000391 }
000392
000393 /*
000394 ** Locate the in-memory structure that describes a particular database
000395 ** table given the name of that table and (optionally) the name of the
000396 ** database containing the table. Return NULL if not found. Also leave an
000397 ** error message in pParse->zErrMsg.
000398 **
000399 ** The difference between this routine and sqlite3FindTable() is that this
000400 ** routine leaves an error message in pParse->zErrMsg where
000401 ** sqlite3FindTable() does not.
000402 */
000403 Table *sqlite3LocateTable(
000404 Parse *pParse, /* context in which to report errors */
000405 u32 flags, /* LOCATE_VIEW or LOCATE_NOERR */
000406 const char *zName, /* Name of the table we are looking for */
000407 const char *zDbase /* Name of the database. Might be NULL */
000408 ){
000409 Table *p;
000410 sqlite3 *db = pParse->db;
000411
000412 /* Read the database schema. If an error occurs, leave an error message
000413 ** and code in pParse and return NULL. */
000414 if( (db->mDbFlags & DBFLAG_SchemaKnownOk)==0
000415 && SQLITE_OK!=sqlite3ReadSchema(pParse)
000416 ){
000417 return 0;
000418 }
000419
000420 p = sqlite3FindTable(db, zName, zDbase);
000421 if( p==0 ){
000422 #ifndef SQLITE_OMIT_VIRTUALTABLE
000423 /* If zName is the not the name of a table in the schema created using
000424 ** CREATE, then check to see if it is the name of an virtual table that
000425 ** can be an eponymous virtual table. */
000426 if( (pParse->prepFlags & SQLITE_PREPARE_NO_VTAB)==0 && db->init.busy==0 ){
000427 Module *pMod = (Module*)sqlite3HashFind(&db->aModule, zName);
000428 if( pMod==0 && sqlite3_strnicmp(zName, "pragma_", 7)==0 ){
000429 pMod = sqlite3PragmaVtabRegister(db, zName);
000430 }
000431 if( pMod && sqlite3VtabEponymousTableInit(pParse, pMod) ){
000432 testcase( pMod->pEpoTab==0 );
000433 return pMod->pEpoTab;
000434 }
000435 }
000436 #endif
000437 if( flags & LOCATE_NOERR ) return 0;
000438 pParse->checkSchema = 1;
000439 }else if( IsVirtual(p) && (pParse->prepFlags & SQLITE_PREPARE_NO_VTAB)!=0 ){
000440 p = 0;
000441 }
000442
000443 if( p==0 ){
000444 const char *zMsg = flags & LOCATE_VIEW ? "no such view" : "no such table";
000445 if( zDbase ){
000446 sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName);
000447 }else{
000448 sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName);
000449 }
000450 }else{
000451 assert( HasRowid(p) || p->iPKey<0 );
000452 }
000453
000454 return p;
000455 }
000456
000457 /*
000458 ** Locate the table identified by *p.
000459 **
000460 ** This is a wrapper around sqlite3LocateTable(). The difference between
000461 ** sqlite3LocateTable() and this function is that this function restricts
000462 ** the search to schema (p->pSchema) if it is not NULL. p->pSchema may be
000463 ** non-NULL if it is part of a view or trigger program definition. See
000464 ** sqlite3FixSrcList() for details.
000465 */
000466 Table *sqlite3LocateTableItem(
000467 Parse *pParse,
000468 u32 flags,
000469 SrcItem *p
000470 ){
000471 const char *zDb;
000472 if( p->fg.fixedSchema ){
000473 int iDb = sqlite3SchemaToIndex(pParse->db, p->u4.pSchema);
000474 zDb = pParse->db->aDb[iDb].zDbSName;
000475 }else{
000476 assert( !p->fg.isSubquery );
000477 zDb = p->u4.zDatabase;
000478 }
000479 return sqlite3LocateTable(pParse, flags, p->zName, zDb);
000480 }
000481
000482 /*
000483 ** Return the preferred table name for system tables. Translate legacy
000484 ** names into the new preferred names, as appropriate.
000485 */
000486 const char *sqlite3PreferredTableName(const char *zName){
000487 if( sqlite3StrNICmp(zName, "sqlite_", 7)==0 ){
000488 if( sqlite3StrICmp(zName+7, &LEGACY_SCHEMA_TABLE[7])==0 ){
000489 return PREFERRED_SCHEMA_TABLE;
000490 }
000491 if( sqlite3StrICmp(zName+7, &LEGACY_TEMP_SCHEMA_TABLE[7])==0 ){
000492 return PREFERRED_TEMP_SCHEMA_TABLE;
000493 }
000494 }
000495 return zName;
000496 }
000497
000498 /*
000499 ** Locate the in-memory structure that describes
000500 ** a particular index given the name of that index
000501 ** and the name of the database that contains the index.
000502 ** Return NULL if not found.
000503 **
000504 ** If zDatabase is 0, all databases are searched for the
000505 ** table and the first matching index is returned. (No checking
000506 ** for duplicate index names is done.) The search order is
000507 ** TEMP first, then MAIN, then any auxiliary databases added
000508 ** using the ATTACH command.
000509 */
000510 Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
000511 Index *p = 0;
000512 int i;
000513 /* All mutexes are required for schema access. Make sure we hold them. */
000514 assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
000515 for(i=OMIT_TEMPDB; i<db->nDb; i++){
000516 int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
000517 Schema *pSchema = db->aDb[j].pSchema;
000518 assert( pSchema );
000519 if( zDb && sqlite3DbIsNamed(db, j, zDb)==0 ) continue;
000520 assert( sqlite3SchemaMutexHeld(db, j, 0) );
000521 p = sqlite3HashFind(&pSchema->idxHash, zName);
000522 if( p ) break;
000523 }
000524 return p;
000525 }
000526
000527 /*
000528 ** Reclaim the memory used by an index
000529 */
000530 void sqlite3FreeIndex(sqlite3 *db, Index *p){
000531 #ifndef SQLITE_OMIT_ANALYZE
000532 sqlite3DeleteIndexSamples(db, p);
000533 #endif
000534 sqlite3ExprDelete(db, p->pPartIdxWhere);
000535 sqlite3ExprListDelete(db, p->aColExpr);
000536 sqlite3DbFree(db, p->zColAff);
000537 if( p->isResized ) sqlite3DbFree(db, (void *)p->azColl);
000538 #ifdef SQLITE_ENABLE_STAT4
000539 sqlite3_free(p->aiRowEst);
000540 #endif
000541 sqlite3DbFree(db, p);
000542 }
000543
000544 /*
000545 ** For the index called zIdxName which is found in the database iDb,
000546 ** unlike that index from its Table then remove the index from
000547 ** the index hash table and free all memory structures associated
000548 ** with the index.
000549 */
000550 void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
000551 Index *pIndex;
000552 Hash *pHash;
000553
000554 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
000555 pHash = &db->aDb[iDb].pSchema->idxHash;
000556 pIndex = sqlite3HashInsert(pHash, zIdxName, 0);
000557 if( ALWAYS(pIndex) ){
000558 if( pIndex->pTable->pIndex==pIndex ){
000559 pIndex->pTable->pIndex = pIndex->pNext;
000560 }else{
000561 Index *p;
000562 /* Justification of ALWAYS(); The index must be on the list of
000563 ** indices. */
000564 p = pIndex->pTable->pIndex;
000565 while( ALWAYS(p) && p->pNext!=pIndex ){ p = p->pNext; }
000566 if( ALWAYS(p && p->pNext==pIndex) ){
000567 p->pNext = pIndex->pNext;
000568 }
000569 }
000570 sqlite3FreeIndex(db, pIndex);
000571 }
000572 db->mDbFlags |= DBFLAG_SchemaChange;
000573 }
000574
000575 /*
000576 ** Look through the list of open database files in db->aDb[] and if
000577 ** any have been closed, remove them from the list. Reallocate the
000578 ** db->aDb[] structure to a smaller size, if possible.
000579 **
000580 ** Entry 0 (the "main" database) and entry 1 (the "temp" database)
000581 ** are never candidates for being collapsed.
000582 */
000583 void sqlite3CollapseDatabaseArray(sqlite3 *db){
000584 int i, j;
000585 for(i=j=2; i<db->nDb; i++){
000586 struct Db *pDb = &db->aDb[i];
000587 if( pDb->pBt==0 ){
000588 sqlite3DbFree(db, pDb->zDbSName);
000589 pDb->zDbSName = 0;
000590 continue;
000591 }
000592 if( j<i ){
000593 db->aDb[j] = db->aDb[i];
000594 }
000595 j++;
000596 }
000597 db->nDb = j;
000598 if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
000599 memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
000600 sqlite3DbFree(db, db->aDb);
000601 db->aDb = db->aDbStatic;
000602 }
000603 }
000604
000605 /*
000606 ** Reset the schema for the database at index iDb. Also reset the
000607 ** TEMP schema. The reset is deferred if db->nSchemaLock is not zero.
000608 ** Deferred resets may be run by calling with iDb<0.
000609 */
000610 void sqlite3ResetOneSchema(sqlite3 *db, int iDb){
000611 int i;
000612 assert( iDb<db->nDb );
000613
000614 if( iDb>=0 ){
000615 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
000616 DbSetProperty(db, iDb, DB_ResetWanted);
000617 DbSetProperty(db, 1, DB_ResetWanted);
000618 db->mDbFlags &= ~DBFLAG_SchemaKnownOk;
000619 }
000620
000621 if( db->nSchemaLock==0 ){
000622 for(i=0; i<db->nDb; i++){
000623 if( DbHasProperty(db, i, DB_ResetWanted) ){
000624 sqlite3SchemaClear(db->aDb[i].pSchema);
000625 }
000626 }
000627 }
000628 }
000629
000630 /*
000631 ** Erase all schema information from all attached databases (including
000632 ** "main" and "temp") for a single database connection.
000633 */
000634 void sqlite3ResetAllSchemasOfConnection(sqlite3 *db){
000635 int i;
000636 sqlite3BtreeEnterAll(db);
000637 for(i=0; i<db->nDb; i++){
000638 Db *pDb = &db->aDb[i];
000639 if( pDb->pSchema ){
000640 if( db->nSchemaLock==0 ){
000641 sqlite3SchemaClear(pDb->pSchema);
000642 }else{
000643 DbSetProperty(db, i, DB_ResetWanted);
000644 }
000645 }
000646 }
000647 db->mDbFlags &= ~(DBFLAG_SchemaChange|DBFLAG_SchemaKnownOk);
000648 sqlite3VtabUnlockList(db);
000649 sqlite3BtreeLeaveAll(db);
000650 if( db->nSchemaLock==0 ){
000651 sqlite3CollapseDatabaseArray(db);
000652 }
000653 }
000654
000655 /*
000656 ** This routine is called when a commit occurs.
000657 */
000658 void sqlite3CommitInternalChanges(sqlite3 *db){
000659 db->mDbFlags &= ~DBFLAG_SchemaChange;
000660 }
000661
000662 /*
000663 ** Set the expression associated with a column. This is usually
000664 ** the DEFAULT value, but might also be the expression that computes
000665 ** the value for a generated column.
000666 */
000667 void sqlite3ColumnSetExpr(
000668 Parse *pParse, /* Parsing context */
000669 Table *pTab, /* The table containing the column */
000670 Column *pCol, /* The column to receive the new DEFAULT expression */
000671 Expr *pExpr /* The new default expression */
000672 ){
000673 ExprList *pList;
000674 assert( IsOrdinaryTable(pTab) );
000675 pList = pTab->u.tab.pDfltList;
000676 if( pCol->iDflt==0
000677 || NEVER(pList==0)
000678 || NEVER(pList->nExpr<pCol->iDflt)
000679 ){
000680 pCol->iDflt = pList==0 ? 1 : pList->nExpr+1;
000681 pTab->u.tab.pDfltList = sqlite3ExprListAppend(pParse, pList, pExpr);
000682 }else{
000683 sqlite3ExprDelete(pParse->db, pList->a[pCol->iDflt-1].pExpr);
000684 pList->a[pCol->iDflt-1].pExpr = pExpr;
000685 }
000686 }
000687
000688 /*
000689 ** Return the expression associated with a column. The expression might be
000690 ** the DEFAULT clause or the AS clause of a generated column.
000691 ** Return NULL if the column has no associated expression.
000692 */
000693 Expr *sqlite3ColumnExpr(Table *pTab, Column *pCol){
000694 if( pCol->iDflt==0 ) return 0;
000695 if( !IsOrdinaryTable(pTab) ) return 0;
000696 if( NEVER(pTab->u.tab.pDfltList==0) ) return 0;
000697 if( NEVER(pTab->u.tab.pDfltList->nExpr<pCol->iDflt) ) return 0;
000698 return pTab->u.tab.pDfltList->a[pCol->iDflt-1].pExpr;
000699 }
000700
000701 /*
000702 ** Set the collating sequence name for a column.
000703 */
000704 void sqlite3ColumnSetColl(
000705 sqlite3 *db,
000706 Column *pCol,
000707 const char *zColl
000708 ){
000709 i64 nColl;
000710 i64 n;
000711 char *zNew;
000712 assert( zColl!=0 );
000713 n = sqlite3Strlen30(pCol->zCnName) + 1;
000714 if( pCol->colFlags & COLFLAG_HASTYPE ){
000715 n += sqlite3Strlen30(pCol->zCnName+n) + 1;
000716 }
000717 nColl = sqlite3Strlen30(zColl) + 1;
000718 zNew = sqlite3DbRealloc(db, pCol->zCnName, nColl+n);
000719 if( zNew ){
000720 pCol->zCnName = zNew;
000721 memcpy(pCol->zCnName + n, zColl, nColl);
000722 pCol->colFlags |= COLFLAG_HASCOLL;
000723 }
000724 }
000725
000726 /*
000727 ** Return the collating sequence name for a column
000728 */
000729 const char *sqlite3ColumnColl(Column *pCol){
000730 const char *z;
000731 if( (pCol->colFlags & COLFLAG_HASCOLL)==0 ) return 0;
000732 z = pCol->zCnName;
000733 while( *z ){ z++; }
000734 if( pCol->colFlags & COLFLAG_HASTYPE ){
000735 do{ z++; }while( *z );
000736 }
000737 return z+1;
000738 }
000739
000740 /*
000741 ** Delete memory allocated for the column names of a table or view (the
000742 ** Table.aCol[] array).
000743 */
000744 void sqlite3DeleteColumnNames(sqlite3 *db, Table *pTable){
000745 int i;
000746 Column *pCol;
000747 assert( pTable!=0 );
000748 assert( db!=0 );
000749 if( (pCol = pTable->aCol)!=0 ){
000750 for(i=0; i<pTable->nCol; i++, pCol++){
000751 assert( pCol->zCnName==0 || pCol->hName==sqlite3StrIHash(pCol->zCnName) );
000752 sqlite3DbFree(db, pCol->zCnName);
000753 }
000754 sqlite3DbNNFreeNN(db, pTable->aCol);
000755 if( IsOrdinaryTable(pTable) ){
000756 sqlite3ExprListDelete(db, pTable->u.tab.pDfltList);
000757 }
000758 if( db->pnBytesFreed==0 ){
000759 pTable->aCol = 0;
000760 pTable->nCol = 0;
000761 if( IsOrdinaryTable(pTable) ){
000762 pTable->u.tab.pDfltList = 0;
000763 }
000764 }
000765 }
000766 }
000767
000768 /*
000769 ** Remove the memory data structures associated with the given
000770 ** Table. No changes are made to disk by this routine.
000771 **
000772 ** This routine just deletes the data structure. It does not unlink
000773 ** the table data structure from the hash table. But it does destroy
000774 ** memory structures of the indices and foreign keys associated with
000775 ** the table.
000776 **
000777 ** The db parameter is optional. It is needed if the Table object
000778 ** contains lookaside memory. (Table objects in the schema do not use
000779 ** lookaside memory, but some ephemeral Table objects do.) Or the
000780 ** db parameter can be used with db->pnBytesFreed to measure the memory
000781 ** used by the Table object.
000782 */
000783 static void SQLITE_NOINLINE deleteTable(sqlite3 *db, Table *pTable){
000784 Index *pIndex, *pNext;
000785
000786 #ifdef SQLITE_DEBUG
000787 /* Record the number of outstanding lookaside allocations in schema Tables
000788 ** prior to doing any free() operations. Since schema Tables do not use
000789 ** lookaside, this number should not change.
000790 **
000791 ** If malloc has already failed, it may be that it failed while allocating
000792 ** a Table object that was going to be marked ephemeral. So do not check
000793 ** that no lookaside memory is used in this case either. */
000794 int nLookaside = 0;
000795 assert( db!=0 );
000796 if( !db->mallocFailed && (pTable->tabFlags & TF_Ephemeral)==0 ){
000797 nLookaside = sqlite3LookasideUsed(db, 0);
000798 }
000799 #endif
000800
000801 /* Delete all indices associated with this table. */
000802 for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
000803 pNext = pIndex->pNext;
000804 assert( pIndex->pSchema==pTable->pSchema
000805 || (IsVirtual(pTable) && pIndex->idxType!=SQLITE_IDXTYPE_APPDEF) );
000806 if( db->pnBytesFreed==0 && !IsVirtual(pTable) ){
000807 char *zName = pIndex->zName;
000808 TESTONLY ( Index *pOld = ) sqlite3HashInsert(
000809 &pIndex->pSchema->idxHash, zName, 0
000810 );
000811 assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
000812 assert( pOld==pIndex || pOld==0 );
000813 }
000814 sqlite3FreeIndex(db, pIndex);
000815 }
000816
000817 if( IsOrdinaryTable(pTable) ){
000818 sqlite3FkDelete(db, pTable);
000819 }
000820 #ifndef SQLITE_OMIT_VIRTUALTABLE
000821 else if( IsVirtual(pTable) ){
000822 sqlite3VtabClear(db, pTable);
000823 }
000824 #endif
000825 else{
000826 assert( IsView(pTable) );
000827 sqlite3SelectDelete(db, pTable->u.view.pSelect);
000828 }
000829
000830 /* Delete the Table structure itself.
000831 */
000832 sqlite3DeleteColumnNames(db, pTable);
000833 sqlite3DbFree(db, pTable->zName);
000834 sqlite3DbFree(db, pTable->zColAff);
000835 sqlite3ExprListDelete(db, pTable->pCheck);
000836 sqlite3DbFree(db, pTable);
000837
000838 /* Verify that no lookaside memory was used by schema tables */
000839 assert( nLookaside==0 || nLookaside==sqlite3LookasideUsed(db,0) );
000840 }
000841 void sqlite3DeleteTable(sqlite3 *db, Table *pTable){
000842 /* Do not delete the table until the reference count reaches zero. */
000843 assert( db!=0 );
000844 if( !pTable ) return;
000845 if( db->pnBytesFreed==0 && (--pTable->nTabRef)>0 ) return;
000846 deleteTable(db, pTable);
000847 }
000848 void sqlite3DeleteTableGeneric(sqlite3 *db, void *pTable){
000849 sqlite3DeleteTable(db, (Table*)pTable);
000850 }
000851
000852
000853 /*
000854 ** Unlink the given table from the hash tables and the delete the
000855 ** table structure with all its indices and foreign keys.
000856 */
000857 void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
000858 Table *p;
000859 Db *pDb;
000860
000861 assert( db!=0 );
000862 assert( iDb>=0 && iDb<db->nDb );
000863 assert( zTabName );
000864 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
000865 testcase( zTabName[0]==0 ); /* Zero-length table names are allowed */
000866 pDb = &db->aDb[iDb];
000867 p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName, 0);
000868 sqlite3DeleteTable(db, p);
000869 db->mDbFlags |= DBFLAG_SchemaChange;
000870 }
000871
000872 /*
000873 ** Given a token, return a string that consists of the text of that
000874 ** token. Space to hold the returned string
000875 ** is obtained from sqliteMalloc() and must be freed by the calling
000876 ** function.
000877 **
000878 ** Any quotation marks (ex: "name", 'name', [name], or `name`) that
000879 ** surround the body of the token are removed.
000880 **
000881 ** Tokens are often just pointers into the original SQL text and so
000882 ** are not \000 terminated and are not persistent. The returned string
000883 ** is \000 terminated and is persistent.
000884 */
000885 char *sqlite3NameFromToken(sqlite3 *db, const Token *pName){
000886 char *zName;
000887 if( pName ){
000888 zName = sqlite3DbStrNDup(db, (const char*)pName->z, pName->n);
000889 sqlite3Dequote(zName);
000890 }else{
000891 zName = 0;
000892 }
000893 return zName;
000894 }
000895
000896 /*
000897 ** Open the sqlite_schema table stored in database number iDb for
000898 ** writing. The table is opened using cursor 0.
000899 */
000900 void sqlite3OpenSchemaTable(Parse *p, int iDb){
000901 Vdbe *v = sqlite3GetVdbe(p);
000902 sqlite3TableLock(p, iDb, SCHEMA_ROOT, 1, LEGACY_SCHEMA_TABLE);
000903 sqlite3VdbeAddOp4Int(v, OP_OpenWrite, 0, SCHEMA_ROOT, iDb, 5);
000904 if( p->nTab==0 ){
000905 p->nTab = 1;
000906 }
000907 }
000908
000909 /*
000910 ** Parameter zName points to a nul-terminated buffer containing the name
000911 ** of a database ("main", "temp" or the name of an attached db). This
000912 ** function returns the index of the named database in db->aDb[], or
000913 ** -1 if the named db cannot be found.
000914 */
000915 int sqlite3FindDbName(sqlite3 *db, const char *zName){
000916 int i = -1; /* Database number */
000917 if( zName ){
000918 Db *pDb;
000919 for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
000920 if( 0==sqlite3_stricmp(pDb->zDbSName, zName) ) break;
000921 /* "main" is always an acceptable alias for the primary database
000922 ** even if it has been renamed using SQLITE_DBCONFIG_MAINDBNAME. */
000923 if( i==0 && 0==sqlite3_stricmp("main", zName) ) break;
000924 }
000925 }
000926 return i;
000927 }
000928
000929 /*
000930 ** The token *pName contains the name of a database (either "main" or
000931 ** "temp" or the name of an attached db). This routine returns the
000932 ** index of the named database in db->aDb[], or -1 if the named db
000933 ** does not exist.
000934 */
000935 int sqlite3FindDb(sqlite3 *db, Token *pName){
000936 int i; /* Database number */
000937 char *zName; /* Name we are searching for */
000938 zName = sqlite3NameFromToken(db, pName);
000939 i = sqlite3FindDbName(db, zName);
000940 sqlite3DbFree(db, zName);
000941 return i;
000942 }
000943
000944 /* The table or view or trigger name is passed to this routine via tokens
000945 ** pName1 and pName2. If the table name was fully qualified, for example:
000946 **
000947 ** CREATE TABLE xxx.yyy (...);
000948 **
000949 ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
000950 ** the table name is not fully qualified, i.e.:
000951 **
000952 ** CREATE TABLE yyy(...);
000953 **
000954 ** Then pName1 is set to "yyy" and pName2 is "".
000955 **
000956 ** This routine sets the *ppUnqual pointer to point at the token (pName1 or
000957 ** pName2) that stores the unqualified table name. The index of the
000958 ** database "xxx" is returned.
000959 */
000960 int sqlite3TwoPartName(
000961 Parse *pParse, /* Parsing and code generating context */
000962 Token *pName1, /* The "xxx" in the name "xxx.yyy" or "xxx" */
000963 Token *pName2, /* The "yyy" in the name "xxx.yyy" */
000964 Token **pUnqual /* Write the unqualified object name here */
000965 ){
000966 int iDb; /* Database holding the object */
000967 sqlite3 *db = pParse->db;
000968
000969 assert( pName2!=0 );
000970 if( pName2->n>0 ){
000971 if( db->init.busy ) {
000972 sqlite3ErrorMsg(pParse, "corrupt database");
000973 return -1;
000974 }
000975 *pUnqual = pName2;
000976 iDb = sqlite3FindDb(db, pName1);
000977 if( iDb<0 ){
000978 sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
000979 return -1;
000980 }
000981 }else{
000982 assert( db->init.iDb==0 || db->init.busy || IN_SPECIAL_PARSE
000983 || (db->mDbFlags & DBFLAG_Vacuum)!=0);
000984 iDb = db->init.iDb;
000985 *pUnqual = pName1;
000986 }
000987 return iDb;
000988 }
000989
000990 /*
000991 ** True if PRAGMA writable_schema is ON
000992 */
000993 int sqlite3WritableSchema(sqlite3 *db){
000994 testcase( (db->flags&(SQLITE_WriteSchema|SQLITE_Defensive))==0 );
000995 testcase( (db->flags&(SQLITE_WriteSchema|SQLITE_Defensive))==
000996 SQLITE_WriteSchema );
000997 testcase( (db->flags&(SQLITE_WriteSchema|SQLITE_Defensive))==
000998 SQLITE_Defensive );
000999 testcase( (db->flags&(SQLITE_WriteSchema|SQLITE_Defensive))==
001000 (SQLITE_WriteSchema|SQLITE_Defensive) );
001001 return (db->flags&(SQLITE_WriteSchema|SQLITE_Defensive))==SQLITE_WriteSchema;
001002 }
001003
001004 /*
001005 ** This routine is used to check if the UTF-8 string zName is a legal
001006 ** unqualified name for a new schema object (table, index, view or
001007 ** trigger). All names are legal except those that begin with the string
001008 ** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
001009 ** is reserved for internal use.
001010 **
001011 ** When parsing the sqlite_schema table, this routine also checks to
001012 ** make sure the "type", "name", and "tbl_name" columns are consistent
001013 ** with the SQL.
001014 */
001015 int sqlite3CheckObjectName(
001016 Parse *pParse, /* Parsing context */
001017 const char *zName, /* Name of the object to check */
001018 const char *zType, /* Type of this object */
001019 const char *zTblName /* Parent table name for triggers and indexes */
001020 ){
001021 sqlite3 *db = pParse->db;
001022 if( sqlite3WritableSchema(db)
001023 || db->init.imposterTable
001024 || !sqlite3Config.bExtraSchemaChecks
001025 ){
001026 /* Skip these error checks for writable_schema=ON */
001027 return SQLITE_OK;
001028 }
001029 if( db->init.busy ){
001030 if( sqlite3_stricmp(zType, db->init.azInit[0])
001031 || sqlite3_stricmp(zName, db->init.azInit[1])
001032 || sqlite3_stricmp(zTblName, db->init.azInit[2])
001033 ){
001034 sqlite3ErrorMsg(pParse, ""); /* corruptSchema() will supply the error */
001035 return SQLITE_ERROR;
001036 }
001037 }else{
001038 if( (pParse->nested==0 && 0==sqlite3StrNICmp(zName, "sqlite_", 7))
001039 || (sqlite3ReadOnlyShadowTables(db) && sqlite3ShadowTableName(db, zName))
001040 ){
001041 sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s",
001042 zName);
001043 return SQLITE_ERROR;
001044 }
001045
001046 }
001047 return SQLITE_OK;
001048 }
001049
001050 /*
001051 ** Return the PRIMARY KEY index of a table
001052 */
001053 Index *sqlite3PrimaryKeyIndex(Table *pTab){
001054 Index *p;
001055 for(p=pTab->pIndex; p && !IsPrimaryKeyIndex(p); p=p->pNext){}
001056 return p;
001057 }
001058
001059 /*
001060 ** Convert an table column number into a index column number. That is,
001061 ** for the column iCol in the table (as defined by the CREATE TABLE statement)
001062 ** find the (first) offset of that column in index pIdx. Or return -1
001063 ** if column iCol is not used in index pIdx.
001064 */
001065 i16 sqlite3TableColumnToIndex(Index *pIdx, i16 iCol){
001066 int i;
001067 for(i=0; i<pIdx->nColumn; i++){
001068 if( iCol==pIdx->aiColumn[i] ) return i;
001069 }
001070 return -1;
001071 }
001072
001073 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
001074 /* Convert a storage column number into a table column number.
001075 **
001076 ** The storage column number (0,1,2,....) is the index of the value
001077 ** as it appears in the record on disk. The true column number
001078 ** is the index (0,1,2,...) of the column in the CREATE TABLE statement.
001079 **
001080 ** The storage column number is less than the table column number if
001081 ** and only there are VIRTUAL columns to the left.
001082 **
001083 ** If SQLITE_OMIT_GENERATED_COLUMNS, this routine is a no-op macro.
001084 */
001085 i16 sqlite3StorageColumnToTable(Table *pTab, i16 iCol){
001086 if( pTab->tabFlags & TF_HasVirtual ){
001087 int i;
001088 for(i=0; i<=iCol; i++){
001089 if( pTab->aCol[i].colFlags & COLFLAG_VIRTUAL ) iCol++;
001090 }
001091 }
001092 return iCol;
001093 }
001094 #endif
001095
001096 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
001097 /* Convert a table column number into a storage column number.
001098 **
001099 ** The storage column number (0,1,2,....) is the index of the value
001100 ** as it appears in the record on disk. Or, if the input column is
001101 ** the N-th virtual column (zero-based) then the storage number is
001102 ** the number of non-virtual columns in the table plus N.
001103 **
001104 ** The true column number is the index (0,1,2,...) of the column in
001105 ** the CREATE TABLE statement.
001106 **
001107 ** If the input column is a VIRTUAL column, then it should not appear
001108 ** in storage. But the value sometimes is cached in registers that
001109 ** follow the range of registers used to construct storage. This
001110 ** avoids computing the same VIRTUAL column multiple times, and provides
001111 ** values for use by OP_Param opcodes in triggers. Hence, if the
001112 ** input column is a VIRTUAL table, put it after all the other columns.
001113 **
001114 ** In the following, N means "normal column", S means STORED, and
001115 ** V means VIRTUAL. Suppose the CREATE TABLE has columns like this:
001116 **
001117 ** CREATE TABLE ex(N,S,V,N,S,V,N,S,V);
001118 ** -- 0 1 2 3 4 5 6 7 8
001119 **
001120 ** Then the mapping from this function is as follows:
001121 **
001122 ** INPUTS: 0 1 2 3 4 5 6 7 8
001123 ** OUTPUTS: 0 1 6 2 3 7 4 5 8
001124 **
001125 ** So, in other words, this routine shifts all the virtual columns to
001126 ** the end.
001127 **
001128 ** If SQLITE_OMIT_GENERATED_COLUMNS then there are no virtual columns and
001129 ** this routine is a no-op macro. If the pTab does not have any virtual
001130 ** columns, then this routine is no-op that always return iCol. If iCol
001131 ** is negative (indicating the ROWID column) then this routine return iCol.
001132 */
001133 i16 sqlite3TableColumnToStorage(Table *pTab, i16 iCol){
001134 int i;
001135 i16 n;
001136 assert( iCol<pTab->nCol );
001137 if( (pTab->tabFlags & TF_HasVirtual)==0 || iCol<0 ) return iCol;
001138 for(i=0, n=0; i<iCol; i++){
001139 if( (pTab->aCol[i].colFlags & COLFLAG_VIRTUAL)==0 ) n++;
001140 }
001141 if( pTab->aCol[i].colFlags & COLFLAG_VIRTUAL ){
001142 /* iCol is a virtual column itself */
001143 return pTab->nNVCol + i - n;
001144 }else{
001145 /* iCol is a normal or stored column */
001146 return n;
001147 }
001148 }
001149 #endif
001150
001151 /*
001152 ** Insert a single OP_JournalMode query opcode in order to force the
001153 ** prepared statement to return false for sqlite3_stmt_readonly(). This
001154 ** is used by CREATE TABLE IF NOT EXISTS and similar if the table already
001155 ** exists, so that the prepared statement for CREATE TABLE IF NOT EXISTS
001156 ** will return false for sqlite3_stmt_readonly() even if that statement
001157 ** is a read-only no-op.
001158 */
001159 static void sqlite3ForceNotReadOnly(Parse *pParse){
001160 int iReg = ++pParse->nMem;
001161 Vdbe *v = sqlite3GetVdbe(pParse);
001162 if( v ){
001163 sqlite3VdbeAddOp3(v, OP_JournalMode, 0, iReg, PAGER_JOURNALMODE_QUERY);
001164 sqlite3VdbeUsesBtree(v, 0);
001165 }
001166 }
001167
001168 /*
001169 ** Begin constructing a new table representation in memory. This is
001170 ** the first of several action routines that get called in response
001171 ** to a CREATE TABLE statement. In particular, this routine is called
001172 ** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
001173 ** flag is true if the table should be stored in the auxiliary database
001174 ** file instead of in the main database file. This is normally the case
001175 ** when the "TEMP" or "TEMPORARY" keyword occurs in between
001176 ** CREATE and TABLE.
001177 **
001178 ** The new table record is initialized and put in pParse->pNewTable.
001179 ** As more of the CREATE TABLE statement is parsed, additional action
001180 ** routines will be called to add more information to this record.
001181 ** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
001182 ** is called to complete the construction of the new table record.
001183 */
001184 void sqlite3StartTable(
001185 Parse *pParse, /* Parser context */
001186 Token *pName1, /* First part of the name of the table or view */
001187 Token *pName2, /* Second part of the name of the table or view */
001188 int isTemp, /* True if this is a TEMP table */
001189 int isView, /* True if this is a VIEW */
001190 int isVirtual, /* True if this is a VIRTUAL table */
001191 int noErr /* Do nothing if table already exists */
001192 ){
001193 Table *pTable;
001194 char *zName = 0; /* The name of the new table */
001195 sqlite3 *db = pParse->db;
001196 Vdbe *v;
001197 int iDb; /* Database number to create the table in */
001198 Token *pName; /* Unqualified name of the table to create */
001199
001200 if( db->init.busy && db->init.newTnum==1 ){
001201 /* Special case: Parsing the sqlite_schema or sqlite_temp_schema schema */
001202 iDb = db->init.iDb;
001203 zName = sqlite3DbStrDup(db, SCHEMA_TABLE(iDb));
001204 pName = pName1;
001205 }else{
001206 /* The common case */
001207 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
001208 if( iDb<0 ) return;
001209 if( !OMIT_TEMPDB && isTemp && pName2->n>0 && iDb!=1 ){
001210 /* If creating a temp table, the name may not be qualified. Unless
001211 ** the database name is "temp" anyway. */
001212 sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
001213 return;
001214 }
001215 if( !OMIT_TEMPDB && isTemp ) iDb = 1;
001216 zName = sqlite3NameFromToken(db, pName);
001217 if( IN_RENAME_OBJECT ){
001218 sqlite3RenameTokenMap(pParse, (void*)zName, pName);
001219 }
001220 }
001221 pParse->sNameToken = *pName;
001222 if( zName==0 ) return;
001223 if( sqlite3CheckObjectName(pParse, zName, isView?"view":"table", zName) ){
001224 goto begin_table_error;
001225 }
001226 if( db->init.iDb==1 ) isTemp = 1;
001227 #ifndef SQLITE_OMIT_AUTHORIZATION
001228 assert( isTemp==0 || isTemp==1 );
001229 assert( isView==0 || isView==1 );
001230 {
001231 static const u8 aCode[] = {
001232 SQLITE_CREATE_TABLE,
001233 SQLITE_CREATE_TEMP_TABLE,
001234 SQLITE_CREATE_VIEW,
001235 SQLITE_CREATE_TEMP_VIEW
001236 };
001237 char *zDb = db->aDb[iDb].zDbSName;
001238 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
001239 goto begin_table_error;
001240 }
001241 if( !isVirtual && sqlite3AuthCheck(pParse, (int)aCode[isTemp+2*isView],
001242 zName, 0, zDb) ){
001243 goto begin_table_error;
001244 }
001245 }
001246 #endif
001247
001248 /* Make sure the new table name does not collide with an existing
001249 ** index or table name in the same database. Issue an error message if
001250 ** it does. The exception is if the statement being parsed was passed
001251 ** to an sqlite3_declare_vtab() call. In that case only the column names
001252 ** and types will be used, so there is no need to test for namespace
001253 ** collisions.
001254 */
001255 if( !IN_SPECIAL_PARSE ){
001256 char *zDb = db->aDb[iDb].zDbSName;
001257 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
001258 goto begin_table_error;
001259 }
001260 pTable = sqlite3FindTable(db, zName, zDb);
001261 if( pTable ){
001262 if( !noErr ){
001263 sqlite3ErrorMsg(pParse, "%s %T already exists",
001264 (IsView(pTable)? "view" : "table"), pName);
001265 }else{
001266 assert( !db->init.busy || CORRUPT_DB );
001267 sqlite3CodeVerifySchema(pParse, iDb);
001268 sqlite3ForceNotReadOnly(pParse);
001269 }
001270 goto begin_table_error;
001271 }
001272 if( sqlite3FindIndex(db, zName, zDb)!=0 ){
001273 sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
001274 goto begin_table_error;
001275 }
001276 }
001277
001278 pTable = sqlite3DbMallocZero(db, sizeof(Table));
001279 if( pTable==0 ){
001280 assert( db->mallocFailed );
001281 pParse->rc = SQLITE_NOMEM_BKPT;
001282 pParse->nErr++;
001283 goto begin_table_error;
001284 }
001285 pTable->zName = zName;
001286 pTable->iPKey = -1;
001287 pTable->pSchema = db->aDb[iDb].pSchema;
001288 pTable->nTabRef = 1;
001289 #ifdef SQLITE_DEFAULT_ROWEST
001290 pTable->nRowLogEst = sqlite3LogEst(SQLITE_DEFAULT_ROWEST);
001291 #else
001292 pTable->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
001293 #endif
001294 assert( pParse->pNewTable==0 );
001295 pParse->pNewTable = pTable;
001296
001297 /* Begin generating the code that will insert the table record into
001298 ** the schema table. Note in particular that we must go ahead
001299 ** and allocate the record number for the table entry now. Before any
001300 ** PRIMARY KEY or UNIQUE keywords are parsed. Those keywords will cause
001301 ** indices to be created and the table record must come before the
001302 ** indices. Hence, the record number for the table must be allocated
001303 ** now.
001304 */
001305 if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
001306 int addr1;
001307 int fileFormat;
001308 int reg1, reg2, reg3;
001309 /* nullRow[] is an OP_Record encoding of a row containing 5 NULLs */
001310 static const char nullRow[] = { 6, 0, 0, 0, 0, 0 };
001311 sqlite3BeginWriteOperation(pParse, 1, iDb);
001312
001313 #ifndef SQLITE_OMIT_VIRTUALTABLE
001314 if( isVirtual ){
001315 sqlite3VdbeAddOp0(v, OP_VBegin);
001316 }
001317 #endif
001318
001319 /* If the file format and encoding in the database have not been set,
001320 ** set them now.
001321 */
001322 reg1 = pParse->regRowid = ++pParse->nMem;
001323 reg2 = pParse->regRoot = ++pParse->nMem;
001324 reg3 = ++pParse->nMem;
001325 sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT);
001326 sqlite3VdbeUsesBtree(v, iDb);
001327 addr1 = sqlite3VdbeAddOp1(v, OP_If, reg3); VdbeCoverage(v);
001328 fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
001329 1 : SQLITE_MAX_FILE_FORMAT;
001330 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, fileFormat);
001331 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, ENC(db));
001332 sqlite3VdbeJumpHere(v, addr1);
001333
001334 /* This just creates a place-holder record in the sqlite_schema table.
001335 ** The record created does not contain anything yet. It will be replaced
001336 ** by the real entry in code generated at sqlite3EndTable().
001337 **
001338 ** The rowid for the new entry is left in register pParse->regRowid.
001339 ** The root page number of the new table is left in reg pParse->regRoot.
001340 ** The rowid and root page number values are needed by the code that
001341 ** sqlite3EndTable will generate.
001342 */
001343 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
001344 if( isView || isVirtual ){
001345 sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2);
001346 }else
001347 #endif
001348 {
001349 assert( !pParse->bReturning );
001350 pParse->u1.addrCrTab =
001351 sqlite3VdbeAddOp3(v, OP_CreateBtree, iDb, reg2, BTREE_INTKEY);
001352 }
001353 sqlite3OpenSchemaTable(pParse, iDb);
001354 sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1);
001355 sqlite3VdbeAddOp4(v, OP_Blob, 6, reg3, 0, nullRow, P4_STATIC);
001356 sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1);
001357 sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
001358 sqlite3VdbeAddOp0(v, OP_Close);
001359 }
001360
001361 /* Normal (non-error) return. */
001362 return;
001363
001364 /* If an error occurs, we jump here */
001365 begin_table_error:
001366 pParse->checkSchema = 1;
001367 sqlite3DbFree(db, zName);
001368 return;
001369 }
001370
001371 /* Set properties of a table column based on the (magical)
001372 ** name of the column.
001373 */
001374 #if SQLITE_ENABLE_HIDDEN_COLUMNS
001375 void sqlite3ColumnPropertiesFromName(Table *pTab, Column *pCol){
001376 if( sqlite3_strnicmp(pCol->zCnName, "__hidden__", 10)==0 ){
001377 pCol->colFlags |= COLFLAG_HIDDEN;
001378 if( pTab ) pTab->tabFlags |= TF_HasHidden;
001379 }else if( pTab && pCol!=pTab->aCol && (pCol[-1].colFlags & COLFLAG_HIDDEN) ){
001380 pTab->tabFlags |= TF_OOOHidden;
001381 }
001382 }
001383 #endif
001384
001385 /*
001386 ** Clean up the data structures associated with the RETURNING clause.
001387 */
001388 static void sqlite3DeleteReturning(sqlite3 *db, void *pArg){
001389 Returning *pRet = (Returning*)pArg;
001390 Hash *pHash;
001391 pHash = &(db->aDb[1].pSchema->trigHash);
001392 sqlite3HashInsert(pHash, pRet->zName, 0);
001393 sqlite3ExprListDelete(db, pRet->pReturnEL);
001394 sqlite3DbFree(db, pRet);
001395 }
001396
001397 /*
001398 ** Add the RETURNING clause to the parse currently underway.
001399 **
001400 ** This routine creates a special TEMP trigger that will fire for each row
001401 ** of the DML statement. That TEMP trigger contains a single SELECT
001402 ** statement with a result set that is the argument of the RETURNING clause.
001403 ** The trigger has the Trigger.bReturning flag and an opcode of
001404 ** TK_RETURNING instead of TK_SELECT, so that the trigger code generator
001405 ** knows to handle it specially. The TEMP trigger is automatically
001406 ** removed at the end of the parse.
001407 **
001408 ** When this routine is called, we do not yet know if the RETURNING clause
001409 ** is attached to a DELETE, INSERT, or UPDATE, so construct it as a
001410 ** RETURNING trigger instead. It will then be converted into the appropriate
001411 ** type on the first call to sqlite3TriggersExist().
001412 */
001413 void sqlite3AddReturning(Parse *pParse, ExprList *pList){
001414 Returning *pRet;
001415 Hash *pHash;
001416 sqlite3 *db = pParse->db;
001417 if( pParse->pNewTrigger ){
001418 sqlite3ErrorMsg(pParse, "cannot use RETURNING in a trigger");
001419 }else{
001420 assert( pParse->bReturning==0 || pParse->ifNotExists );
001421 }
001422 pParse->bReturning = 1;
001423 pRet = sqlite3DbMallocZero(db, sizeof(*pRet));
001424 if( pRet==0 ){
001425 sqlite3ExprListDelete(db, pList);
001426 return;
001427 }
001428 pParse->u1.pReturning = pRet;
001429 pRet->pParse = pParse;
001430 pRet->pReturnEL = pList;
001431 sqlite3ParserAddCleanup(pParse, sqlite3DeleteReturning, pRet);
001432 testcase( pParse->earlyCleanup );
001433 if( db->mallocFailed ) return;
001434 sqlite3_snprintf(sizeof(pRet->zName), pRet->zName,
001435 "sqlite_returning_%p", pParse);
001436 pRet->retTrig.zName = pRet->zName;
001437 pRet->retTrig.op = TK_RETURNING;
001438 pRet->retTrig.tr_tm = TRIGGER_AFTER;
001439 pRet->retTrig.bReturning = 1;
001440 pRet->retTrig.pSchema = db->aDb[1].pSchema;
001441 pRet->retTrig.pTabSchema = db->aDb[1].pSchema;
001442 pRet->retTrig.step_list = &pRet->retTStep;
001443 pRet->retTStep.op = TK_RETURNING;
001444 pRet->retTStep.pTrig = &pRet->retTrig;
001445 pRet->retTStep.pExprList = pList;
001446 pHash = &(db->aDb[1].pSchema->trigHash);
001447 assert( sqlite3HashFind(pHash, pRet->zName)==0
001448 || pParse->nErr || pParse->ifNotExists );
001449 if( sqlite3HashInsert(pHash, pRet->zName, &pRet->retTrig)
001450 ==&pRet->retTrig ){
001451 sqlite3OomFault(db);
001452 }
001453 }
001454
001455 /*
001456 ** Add a new column to the table currently being constructed.
001457 **
001458 ** The parser calls this routine once for each column declaration
001459 ** in a CREATE TABLE statement. sqlite3StartTable() gets called
001460 ** first to get things going. Then this routine is called for each
001461 ** column.
001462 */
001463 void sqlite3AddColumn(Parse *pParse, Token sName, Token sType){
001464 Table *p;
001465 int i;
001466 char *z;
001467 char *zType;
001468 Column *pCol;
001469 sqlite3 *db = pParse->db;
001470 u8 hName;
001471 Column *aNew;
001472 u8 eType = COLTYPE_CUSTOM;
001473 u8 szEst = 1;
001474 char affinity = SQLITE_AFF_BLOB;
001475
001476 if( (p = pParse->pNewTable)==0 ) return;
001477 if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){
001478 sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
001479 return;
001480 }
001481 if( !IN_RENAME_OBJECT ) sqlite3DequoteToken(&sName);
001482
001483 /* Because keywords GENERATE ALWAYS can be converted into identifiers
001484 ** by the parser, we can sometimes end up with a typename that ends
001485 ** with "generated always". Check for this case and omit the surplus
001486 ** text. */
001487 if( sType.n>=16
001488 && sqlite3_strnicmp(sType.z+(sType.n-6),"always",6)==0
001489 ){
001490 sType.n -= 6;
001491 while( ALWAYS(sType.n>0) && sqlite3Isspace(sType.z[sType.n-1]) ) sType.n--;
001492 if( sType.n>=9
001493 && sqlite3_strnicmp(sType.z+(sType.n-9),"generated",9)==0
001494 ){
001495 sType.n -= 9;
001496 while( sType.n>0 && sqlite3Isspace(sType.z[sType.n-1]) ) sType.n--;
001497 }
001498 }
001499
001500 /* Check for standard typenames. For standard typenames we will
001501 ** set the Column.eType field rather than storing the typename after
001502 ** the column name, in order to save space. */
001503 if( sType.n>=3 ){
001504 sqlite3DequoteToken(&sType);
001505 for(i=0; i<SQLITE_N_STDTYPE; i++){
001506 if( sType.n==sqlite3StdTypeLen[i]
001507 && sqlite3_strnicmp(sType.z, sqlite3StdType[i], sType.n)==0
001508 ){
001509 sType.n = 0;
001510 eType = i+1;
001511 affinity = sqlite3StdTypeAffinity[i];
001512 if( affinity<=SQLITE_AFF_TEXT ) szEst = 5;
001513 break;
001514 }
001515 }
001516 }
001517
001518 z = sqlite3DbMallocRaw(db, (i64)sName.n + 1 + (i64)sType.n + (sType.n>0) );
001519 if( z==0 ) return;
001520 if( IN_RENAME_OBJECT ) sqlite3RenameTokenMap(pParse, (void*)z, &sName);
001521 memcpy(z, sName.z, sName.n);
001522 z[sName.n] = 0;
001523 sqlite3Dequote(z);
001524 hName = sqlite3StrIHash(z);
001525 for(i=0; i<p->nCol; i++){
001526 if( p->aCol[i].hName==hName && sqlite3StrICmp(z, p->aCol[i].zCnName)==0 ){
001527 sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
001528 sqlite3DbFree(db, z);
001529 return;
001530 }
001531 }
001532 aNew = sqlite3DbRealloc(db,p->aCol,((i64)p->nCol+1)*sizeof(p->aCol[0]));
001533 if( aNew==0 ){
001534 sqlite3DbFree(db, z);
001535 return;
001536 }
001537 p->aCol = aNew;
001538 pCol = &p->aCol[p->nCol];
001539 memset(pCol, 0, sizeof(p->aCol[0]));
001540 pCol->zCnName = z;
001541 pCol->hName = hName;
001542 sqlite3ColumnPropertiesFromName(p, pCol);
001543
001544 if( sType.n==0 ){
001545 /* If there is no type specified, columns have the default affinity
001546 ** 'BLOB' with a default size of 4 bytes. */
001547 pCol->affinity = affinity;
001548 pCol->eCType = eType;
001549 pCol->szEst = szEst;
001550 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
001551 if( affinity==SQLITE_AFF_BLOB ){
001552 if( 4>=sqlite3GlobalConfig.szSorterRef ){
001553 pCol->colFlags |= COLFLAG_SORTERREF;
001554 }
001555 }
001556 #endif
001557 }else{
001558 zType = z + sqlite3Strlen30(z) + 1;
001559 memcpy(zType, sType.z, sType.n);
001560 zType[sType.n] = 0;
001561 sqlite3Dequote(zType);
001562 pCol->affinity = sqlite3AffinityType(zType, pCol);
001563 pCol->colFlags |= COLFLAG_HASTYPE;
001564 }
001565 p->nCol++;
001566 p->nNVCol++;
001567 pParse->constraintName.n = 0;
001568 }
001569
001570 /*
001571 ** This routine is called by the parser while in the middle of
001572 ** parsing a CREATE TABLE statement. A "NOT NULL" constraint has
001573 ** been seen on a column. This routine sets the notNull flag on
001574 ** the column currently under construction.
001575 */
001576 void sqlite3AddNotNull(Parse *pParse, int onError){
001577 Table *p;
001578 Column *pCol;
001579 p = pParse->pNewTable;
001580 if( p==0 || NEVER(p->nCol<1) ) return;
001581 pCol = &p->aCol[p->nCol-1];
001582 pCol->notNull = (u8)onError;
001583 p->tabFlags |= TF_HasNotNull;
001584
001585 /* Set the uniqNotNull flag on any UNIQUE or PK indexes already created
001586 ** on this column. */
001587 if( pCol->colFlags & COLFLAG_UNIQUE ){
001588 Index *pIdx;
001589 for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
001590 assert( pIdx->nKeyCol==1 && pIdx->onError!=OE_None );
001591 if( pIdx->aiColumn[0]==p->nCol-1 ){
001592 pIdx->uniqNotNull = 1;
001593 }
001594 }
001595 }
001596 }
001597
001598 /*
001599 ** Scan the column type name zType (length nType) and return the
001600 ** associated affinity type.
001601 **
001602 ** This routine does a case-independent search of zType for the
001603 ** substrings in the following table. If one of the substrings is
001604 ** found, the corresponding affinity is returned. If zType contains
001605 ** more than one of the substrings, entries toward the top of
001606 ** the table take priority. For example, if zType is 'BLOBINT',
001607 ** SQLITE_AFF_INTEGER is returned.
001608 **
001609 ** Substring | Affinity
001610 ** --------------------------------
001611 ** 'INT' | SQLITE_AFF_INTEGER
001612 ** 'CHAR' | SQLITE_AFF_TEXT
001613 ** 'CLOB' | SQLITE_AFF_TEXT
001614 ** 'TEXT' | SQLITE_AFF_TEXT
001615 ** 'BLOB' | SQLITE_AFF_BLOB
001616 ** 'REAL' | SQLITE_AFF_REAL
001617 ** 'FLOA' | SQLITE_AFF_REAL
001618 ** 'DOUB' | SQLITE_AFF_REAL
001619 **
001620 ** If none of the substrings in the above table are found,
001621 ** SQLITE_AFF_NUMERIC is returned.
001622 */
001623 char sqlite3AffinityType(const char *zIn, Column *pCol){
001624 u32 h = 0;
001625 char aff = SQLITE_AFF_NUMERIC;
001626 const char *zChar = 0;
001627
001628 assert( zIn!=0 );
001629 while( zIn[0] ){
001630 u8 x = *(u8*)zIn;
001631 h = (h<<8) + sqlite3UpperToLower[x];
001632 zIn++;
001633 if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){ /* CHAR */
001634 aff = SQLITE_AFF_TEXT;
001635 zChar = zIn;
001636 }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){ /* CLOB */
001637 aff = SQLITE_AFF_TEXT;
001638 }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){ /* TEXT */
001639 aff = SQLITE_AFF_TEXT;
001640 }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b') /* BLOB */
001641 && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
001642 aff = SQLITE_AFF_BLOB;
001643 if( zIn[0]=='(' ) zChar = zIn;
001644 #ifndef SQLITE_OMIT_FLOATING_POINT
001645 }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l') /* REAL */
001646 && aff==SQLITE_AFF_NUMERIC ){
001647 aff = SQLITE_AFF_REAL;
001648 }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a') /* FLOA */
001649 && aff==SQLITE_AFF_NUMERIC ){
001650 aff = SQLITE_AFF_REAL;
001651 }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b') /* DOUB */
001652 && aff==SQLITE_AFF_NUMERIC ){
001653 aff = SQLITE_AFF_REAL;
001654 #endif
001655 }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){ /* INT */
001656 aff = SQLITE_AFF_INTEGER;
001657 break;
001658 }
001659 }
001660
001661 /* If pCol is not NULL, store an estimate of the field size. The
001662 ** estimate is scaled so that the size of an integer is 1. */
001663 if( pCol ){
001664 int v = 0; /* default size is approx 4 bytes */
001665 if( aff<SQLITE_AFF_NUMERIC ){
001666 if( zChar ){
001667 while( zChar[0] ){
001668 if( sqlite3Isdigit(zChar[0]) ){
001669 /* BLOB(k), VARCHAR(k), CHAR(k) -> r=(k/4+1) */
001670 sqlite3GetInt32(zChar, &v);
001671 break;
001672 }
001673 zChar++;
001674 }
001675 }else{
001676 v = 16; /* BLOB, TEXT, CLOB -> r=5 (approx 20 bytes)*/
001677 }
001678 }
001679 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
001680 if( v>=sqlite3GlobalConfig.szSorterRef ){
001681 pCol->colFlags |= COLFLAG_SORTERREF;
001682 }
001683 #endif
001684 v = v/4 + 1;
001685 if( v>255 ) v = 255;
001686 pCol->szEst = v;
001687 }
001688 return aff;
001689 }
001690
001691 /*
001692 ** The expression is the default value for the most recently added column
001693 ** of the table currently under construction.
001694 **
001695 ** Default value expressions must be constant. Raise an exception if this
001696 ** is not the case.
001697 **
001698 ** This routine is called by the parser while in the middle of
001699 ** parsing a CREATE TABLE statement.
001700 */
001701 void sqlite3AddDefaultValue(
001702 Parse *pParse, /* Parsing context */
001703 Expr *pExpr, /* The parsed expression of the default value */
001704 const char *zStart, /* Start of the default value text */
001705 const char *zEnd /* First character past end of default value text */
001706 ){
001707 Table *p;
001708 Column *pCol;
001709 sqlite3 *db = pParse->db;
001710 p = pParse->pNewTable;
001711 if( p!=0 ){
001712 int isInit = db->init.busy && db->init.iDb!=1;
001713 pCol = &(p->aCol[p->nCol-1]);
001714 if( !sqlite3ExprIsConstantOrFunction(pExpr, isInit) ){
001715 sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
001716 pCol->zCnName);
001717 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
001718 }else if( pCol->colFlags & COLFLAG_GENERATED ){
001719 testcase( pCol->colFlags & COLFLAG_VIRTUAL );
001720 testcase( pCol->colFlags & COLFLAG_STORED );
001721 sqlite3ErrorMsg(pParse, "cannot use DEFAULT on a generated column");
001722 #endif
001723 }else{
001724 /* A copy of pExpr is used instead of the original, as pExpr contains
001725 ** tokens that point to volatile memory.
001726 */
001727 Expr x, *pDfltExpr;
001728 memset(&x, 0, sizeof(x));
001729 x.op = TK_SPAN;
001730 x.u.zToken = sqlite3DbSpanDup(db, zStart, zEnd);
001731 x.pLeft = pExpr;
001732 x.flags = EP_Skip;
001733 pDfltExpr = sqlite3ExprDup(db, &x, EXPRDUP_REDUCE);
001734 sqlite3DbFree(db, x.u.zToken);
001735 sqlite3ColumnSetExpr(pParse, p, pCol, pDfltExpr);
001736 }
001737 }
001738 if( IN_RENAME_OBJECT ){
001739 sqlite3RenameExprUnmap(pParse, pExpr);
001740 }
001741 sqlite3ExprDelete(db, pExpr);
001742 }
001743
001744 /*
001745 ** Backwards Compatibility Hack:
001746 **
001747 ** Historical versions of SQLite accepted strings as column names in
001748 ** indexes and PRIMARY KEY constraints and in UNIQUE constraints. Example:
001749 **
001750 ** CREATE TABLE xyz(a,b,c,d,e,PRIMARY KEY('a'),UNIQUE('b','c' COLLATE trim)
001751 ** CREATE INDEX abc ON xyz('c','d' DESC,'e' COLLATE nocase DESC);
001752 **
001753 ** This is goofy. But to preserve backwards compatibility we continue to
001754 ** accept it. This routine does the necessary conversion. It converts
001755 ** the expression given in its argument from a TK_STRING into a TK_ID
001756 ** if the expression is just a TK_STRING with an optional COLLATE clause.
001757 ** If the expression is anything other than TK_STRING, the expression is
001758 ** unchanged.
001759 */
001760 static void sqlite3StringToId(Expr *p){
001761 if( p->op==TK_STRING ){
001762 p->op = TK_ID;
001763 }else if( p->op==TK_COLLATE && p->pLeft->op==TK_STRING ){
001764 p->pLeft->op = TK_ID;
001765 }
001766 }
001767
001768 /*
001769 ** Tag the given column as being part of the PRIMARY KEY
001770 */
001771 static void makeColumnPartOfPrimaryKey(Parse *pParse, Column *pCol){
001772 pCol->colFlags |= COLFLAG_PRIMKEY;
001773 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
001774 if( pCol->colFlags & COLFLAG_GENERATED ){
001775 testcase( pCol->colFlags & COLFLAG_VIRTUAL );
001776 testcase( pCol->colFlags & COLFLAG_STORED );
001777 sqlite3ErrorMsg(pParse,
001778 "generated columns cannot be part of the PRIMARY KEY");
001779 }
001780 #endif
001781 }
001782
001783 /*
001784 ** Designate the PRIMARY KEY for the table. pList is a list of names
001785 ** of columns that form the primary key. If pList is NULL, then the
001786 ** most recently added column of the table is the primary key.
001787 **
001788 ** A table can have at most one primary key. If the table already has
001789 ** a primary key (and this is the second primary key) then create an
001790 ** error.
001791 **
001792 ** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
001793 ** then we will try to use that column as the rowid. Set the Table.iPKey
001794 ** field of the table under construction to be the index of the
001795 ** INTEGER PRIMARY KEY column. Table.iPKey is set to -1 if there is
001796 ** no INTEGER PRIMARY KEY.
001797 **
001798 ** If the key is not an INTEGER PRIMARY KEY, then create a unique
001799 ** index for the key. No index is created for INTEGER PRIMARY KEYs.
001800 */
001801 void sqlite3AddPrimaryKey(
001802 Parse *pParse, /* Parsing context */
001803 ExprList *pList, /* List of field names to be indexed */
001804 int onError, /* What to do with a uniqueness conflict */
001805 int autoInc, /* True if the AUTOINCREMENT keyword is present */
001806 int sortOrder /* SQLITE_SO_ASC or SQLITE_SO_DESC */
001807 ){
001808 Table *pTab = pParse->pNewTable;
001809 Column *pCol = 0;
001810 int iCol = -1, i;
001811 int nTerm;
001812 if( pTab==0 ) goto primary_key_exit;
001813 if( pTab->tabFlags & TF_HasPrimaryKey ){
001814 sqlite3ErrorMsg(pParse,
001815 "table \"%s\" has more than one primary key", pTab->zName);
001816 goto primary_key_exit;
001817 }
001818 pTab->tabFlags |= TF_HasPrimaryKey;
001819 if( pList==0 ){
001820 iCol = pTab->nCol - 1;
001821 pCol = &pTab->aCol[iCol];
001822 makeColumnPartOfPrimaryKey(pParse, pCol);
001823 nTerm = 1;
001824 }else{
001825 nTerm = pList->nExpr;
001826 for(i=0; i<nTerm; i++){
001827 Expr *pCExpr = sqlite3ExprSkipCollate(pList->a[i].pExpr);
001828 assert( pCExpr!=0 );
001829 sqlite3StringToId(pCExpr);
001830 if( pCExpr->op==TK_ID ){
001831 const char *zCName;
001832 assert( !ExprHasProperty(pCExpr, EP_IntValue) );
001833 zCName = pCExpr->u.zToken;
001834 for(iCol=0; iCol<pTab->nCol; iCol++){
001835 if( sqlite3StrICmp(zCName, pTab->aCol[iCol].zCnName)==0 ){
001836 pCol = &pTab->aCol[iCol];
001837 makeColumnPartOfPrimaryKey(pParse, pCol);
001838 break;
001839 }
001840 }
001841 }
001842 }
001843 }
001844 if( nTerm==1
001845 && pCol
001846 && pCol->eCType==COLTYPE_INTEGER
001847 && sortOrder!=SQLITE_SO_DESC
001848 ){
001849 if( IN_RENAME_OBJECT && pList ){
001850 Expr *pCExpr = sqlite3ExprSkipCollate(pList->a[0].pExpr);
001851 sqlite3RenameTokenRemap(pParse, &pTab->iPKey, pCExpr);
001852 }
001853 pTab->iPKey = iCol;
001854 pTab->keyConf = (u8)onError;
001855 assert( autoInc==0 || autoInc==1 );
001856 pTab->tabFlags |= autoInc*TF_Autoincrement;
001857 if( pList ) pParse->iPkSortOrder = pList->a[0].fg.sortFlags;
001858 (void)sqlite3HasExplicitNulls(pParse, pList);
001859 }else if( autoInc ){
001860 #ifndef SQLITE_OMIT_AUTOINCREMENT
001861 sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
001862 "INTEGER PRIMARY KEY");
001863 #endif
001864 }else{
001865 sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0,
001866 0, sortOrder, 0, SQLITE_IDXTYPE_PRIMARYKEY);
001867 pList = 0;
001868 }
001869
001870 primary_key_exit:
001871 sqlite3ExprListDelete(pParse->db, pList);
001872 return;
001873 }
001874
001875 /*
001876 ** Add a new CHECK constraint to the table currently under construction.
001877 */
001878 void sqlite3AddCheckConstraint(
001879 Parse *pParse, /* Parsing context */
001880 Expr *pCheckExpr, /* The check expression */
001881 const char *zStart, /* Opening "(" */
001882 const char *zEnd /* Closing ")" */
001883 ){
001884 #ifndef SQLITE_OMIT_CHECK
001885 Table *pTab = pParse->pNewTable;
001886 sqlite3 *db = pParse->db;
001887 if( pTab && !IN_DECLARE_VTAB
001888 && !sqlite3BtreeIsReadonly(db->aDb[db->init.iDb].pBt)
001889 ){
001890 pTab->pCheck = sqlite3ExprListAppend(pParse, pTab->pCheck, pCheckExpr);
001891 if( pParse->constraintName.n ){
001892 sqlite3ExprListSetName(pParse, pTab->pCheck, &pParse->constraintName, 1);
001893 }else{
001894 Token t;
001895 for(zStart++; sqlite3Isspace(zStart[0]); zStart++){}
001896 while( sqlite3Isspace(zEnd[-1]) ){ zEnd--; }
001897 t.z = zStart;
001898 t.n = (int)(zEnd - t.z);
001899 sqlite3ExprListSetName(pParse, pTab->pCheck, &t, 1);
001900 }
001901 }else
001902 #endif
001903 {
001904 sqlite3ExprDelete(pParse->db, pCheckExpr);
001905 }
001906 }
001907
001908 /*
001909 ** Set the collation function of the most recently parsed table column
001910 ** to the CollSeq given.
001911 */
001912 void sqlite3AddCollateType(Parse *pParse, Token *pToken){
001913 Table *p;
001914 int i;
001915 char *zColl; /* Dequoted name of collation sequence */
001916 sqlite3 *db;
001917
001918 if( (p = pParse->pNewTable)==0 || IN_RENAME_OBJECT ) return;
001919 i = p->nCol-1;
001920 db = pParse->db;
001921 zColl = sqlite3NameFromToken(db, pToken);
001922 if( !zColl ) return;
001923
001924 if( sqlite3LocateCollSeq(pParse, zColl) ){
001925 Index *pIdx;
001926 sqlite3ColumnSetColl(db, &p->aCol[i], zColl);
001927
001928 /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
001929 ** then an index may have been created on this column before the
001930 ** collation type was added. Correct this if it is the case.
001931 */
001932 for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
001933 assert( pIdx->nKeyCol==1 );
001934 if( pIdx->aiColumn[0]==i ){
001935 pIdx->azColl[0] = sqlite3ColumnColl(&p->aCol[i]);
001936 }
001937 }
001938 }
001939 sqlite3DbFree(db, zColl);
001940 }
001941
001942 /* Change the most recently parsed column to be a GENERATED ALWAYS AS
001943 ** column.
001944 */
001945 void sqlite3AddGenerated(Parse *pParse, Expr *pExpr, Token *pType){
001946 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
001947 u8 eType = COLFLAG_VIRTUAL;
001948 Table *pTab = pParse->pNewTable;
001949 Column *pCol;
001950 if( pTab==0 ){
001951 /* generated column in an CREATE TABLE IF NOT EXISTS that already exists */
001952 goto generated_done;
001953 }
001954 pCol = &(pTab->aCol[pTab->nCol-1]);
001955 if( IN_DECLARE_VTAB ){
001956 sqlite3ErrorMsg(pParse, "virtual tables cannot use computed columns");
001957 goto generated_done;
001958 }
001959 if( pCol->iDflt>0 ) goto generated_error;
001960 if( pType ){
001961 if( pType->n==7 && sqlite3StrNICmp("virtual",pType->z,7)==0 ){
001962 /* no-op */
001963 }else if( pType->n==6 && sqlite3StrNICmp("stored",pType->z,6)==0 ){
001964 eType = COLFLAG_STORED;
001965 }else{
001966 goto generated_error;
001967 }
001968 }
001969 if( eType==COLFLAG_VIRTUAL ) pTab->nNVCol--;
001970 pCol->colFlags |= eType;
001971 assert( TF_HasVirtual==COLFLAG_VIRTUAL );
001972 assert( TF_HasStored==COLFLAG_STORED );
001973 pTab->tabFlags |= eType;
001974 if( pCol->colFlags & COLFLAG_PRIMKEY ){
001975 makeColumnPartOfPrimaryKey(pParse, pCol); /* For the error message */
001976 }
001977 if( ALWAYS(pExpr) && pExpr->op==TK_ID ){
001978 /* The value of a generated column needs to be a real expression, not
001979 ** just a reference to another column, in order for covering index
001980 ** optimizations to work correctly. So if the value is not an expression,
001981 ** turn it into one by adding a unary "+" operator. */
001982 pExpr = sqlite3PExpr(pParse, TK_UPLUS, pExpr, 0);
001983 }
001984 if( pExpr && pExpr->op!=TK_RAISE ) pExpr->affExpr = pCol->affinity;
001985 sqlite3ColumnSetExpr(pParse, pTab, pCol, pExpr);
001986 pExpr = 0;
001987 goto generated_done;
001988
001989 generated_error:
001990 sqlite3ErrorMsg(pParse, "error in generated column \"%s\"",
001991 pCol->zCnName);
001992 generated_done:
001993 sqlite3ExprDelete(pParse->db, pExpr);
001994 #else
001995 /* Throw and error for the GENERATED ALWAYS AS clause if the
001996 ** SQLITE_OMIT_GENERATED_COLUMNS compile-time option is used. */
001997 sqlite3ErrorMsg(pParse, "generated columns not supported");
001998 sqlite3ExprDelete(pParse->db, pExpr);
001999 #endif
002000 }
002001
002002 /*
002003 ** Generate code that will increment the schema cookie.
002004 **
002005 ** The schema cookie is used to determine when the schema for the
002006 ** database changes. After each schema change, the cookie value
002007 ** changes. When a process first reads the schema it records the
002008 ** cookie. Thereafter, whenever it goes to access the database,
002009 ** it checks the cookie to make sure the schema has not changed
002010 ** since it was last read.
002011 **
002012 ** This plan is not completely bullet-proof. It is possible for
002013 ** the schema to change multiple times and for the cookie to be
002014 ** set back to prior value. But schema changes are infrequent
002015 ** and the probability of hitting the same cookie value is only
002016 ** 1 chance in 2^32. So we're safe enough.
002017 **
002018 ** IMPLEMENTATION-OF: R-34230-56049 SQLite automatically increments
002019 ** the schema-version whenever the schema changes.
002020 */
002021 void sqlite3ChangeCookie(Parse *pParse, int iDb){
002022 sqlite3 *db = pParse->db;
002023 Vdbe *v = pParse->pVdbe;
002024 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
002025 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION,
002026 (int)(1+(unsigned)db->aDb[iDb].pSchema->schema_cookie));
002027 }
002028
002029 /*
002030 ** Measure the number of characters needed to output the given
002031 ** identifier. The number returned includes any quotes used
002032 ** but does not include the null terminator.
002033 **
002034 ** The estimate is conservative. It might be larger that what is
002035 ** really needed.
002036 */
002037 static int identLength(const char *z){
002038 int n;
002039 for(n=0; *z; n++, z++){
002040 if( *z=='"' ){ n++; }
002041 }
002042 return n + 2;
002043 }
002044
002045 /*
002046 ** The first parameter is a pointer to an output buffer. The second
002047 ** parameter is a pointer to an integer that contains the offset at
002048 ** which to write into the output buffer. This function copies the
002049 ** nul-terminated string pointed to by the third parameter, zSignedIdent,
002050 ** to the specified offset in the buffer and updates *pIdx to refer
002051 ** to the first byte after the last byte written before returning.
002052 **
002053 ** If the string zSignedIdent consists entirely of alphanumeric
002054 ** characters, does not begin with a digit and is not an SQL keyword,
002055 ** then it is copied to the output buffer exactly as it is. Otherwise,
002056 ** it is quoted using double-quotes.
002057 */
002058 static void identPut(char *z, int *pIdx, char *zSignedIdent){
002059 unsigned char *zIdent = (unsigned char*)zSignedIdent;
002060 int i, j, needQuote;
002061 i = *pIdx;
002062
002063 for(j=0; zIdent[j]; j++){
002064 if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
002065 }
002066 needQuote = sqlite3Isdigit(zIdent[0])
002067 || sqlite3KeywordCode(zIdent, j)!=TK_ID
002068 || zIdent[j]!=0
002069 || j==0;
002070
002071 if( needQuote ) z[i++] = '"';
002072 for(j=0; zIdent[j]; j++){
002073 z[i++] = zIdent[j];
002074 if( zIdent[j]=='"' ) z[i++] = '"';
002075 }
002076 if( needQuote ) z[i++] = '"';
002077 z[i] = 0;
002078 *pIdx = i;
002079 }
002080
002081 /*
002082 ** Generate a CREATE TABLE statement appropriate for the given
002083 ** table. Memory to hold the text of the statement is obtained
002084 ** from sqliteMalloc() and must be freed by the calling function.
002085 */
002086 static char *createTableStmt(sqlite3 *db, Table *p){
002087 int i, k, n;
002088 char *zStmt;
002089 char *zSep, *zSep2, *zEnd;
002090 Column *pCol;
002091 n = 0;
002092 for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
002093 n += identLength(pCol->zCnName) + 5;
002094 }
002095 n += identLength(p->zName);
002096 if( n<50 ){
002097 zSep = "";
002098 zSep2 = ",";
002099 zEnd = ")";
002100 }else{
002101 zSep = "\n ";
002102 zSep2 = ",\n ";
002103 zEnd = "\n)";
002104 }
002105 n += 35 + 6*p->nCol;
002106 zStmt = sqlite3DbMallocRaw(0, n);
002107 if( zStmt==0 ){
002108 sqlite3OomFault(db);
002109 return 0;
002110 }
002111 sqlite3_snprintf(n, zStmt, "CREATE TABLE ");
002112 k = sqlite3Strlen30(zStmt);
002113 identPut(zStmt, &k, p->zName);
002114 zStmt[k++] = '(';
002115 for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
002116 static const char * const azType[] = {
002117 /* SQLITE_AFF_BLOB */ "",
002118 /* SQLITE_AFF_TEXT */ " TEXT",
002119 /* SQLITE_AFF_NUMERIC */ " NUM",
002120 /* SQLITE_AFF_INTEGER */ " INT",
002121 /* SQLITE_AFF_REAL */ " REAL",
002122 /* SQLITE_AFF_FLEXNUM */ " NUM",
002123 };
002124 int len;
002125 const char *zType;
002126
002127 sqlite3_snprintf(n-k, &zStmt[k], zSep);
002128 k += sqlite3Strlen30(&zStmt[k]);
002129 zSep = zSep2;
002130 identPut(zStmt, &k, pCol->zCnName);
002131 assert( pCol->affinity-SQLITE_AFF_BLOB >= 0 );
002132 assert( pCol->affinity-SQLITE_AFF_BLOB < ArraySize(azType) );
002133 testcase( pCol->affinity==SQLITE_AFF_BLOB );
002134 testcase( pCol->affinity==SQLITE_AFF_TEXT );
002135 testcase( pCol->affinity==SQLITE_AFF_NUMERIC );
002136 testcase( pCol->affinity==SQLITE_AFF_INTEGER );
002137 testcase( pCol->affinity==SQLITE_AFF_REAL );
002138 testcase( pCol->affinity==SQLITE_AFF_FLEXNUM );
002139
002140 zType = azType[pCol->affinity - SQLITE_AFF_BLOB];
002141 len = sqlite3Strlen30(zType);
002142 assert( pCol->affinity==SQLITE_AFF_BLOB
002143 || pCol->affinity==SQLITE_AFF_FLEXNUM
002144 || pCol->affinity==sqlite3AffinityType(zType, 0) );
002145 memcpy(&zStmt[k], zType, len);
002146 k += len;
002147 assert( k<=n );
002148 }
002149 sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
002150 return zStmt;
002151 }
002152
002153 /*
002154 ** Resize an Index object to hold N columns total. Return SQLITE_OK
002155 ** on success and SQLITE_NOMEM on an OOM error.
002156 */
002157 static int resizeIndexObject(sqlite3 *db, Index *pIdx, int N){
002158 char *zExtra;
002159 int nByte;
002160 if( pIdx->nColumn>=N ) return SQLITE_OK;
002161 assert( pIdx->isResized==0 );
002162 nByte = (sizeof(char*) + sizeof(LogEst) + sizeof(i16) + 1)*N;
002163 zExtra = sqlite3DbMallocZero(db, nByte);
002164 if( zExtra==0 ) return SQLITE_NOMEM_BKPT;
002165 memcpy(zExtra, pIdx->azColl, sizeof(char*)*pIdx->nColumn);
002166 pIdx->azColl = (const char**)zExtra;
002167 zExtra += sizeof(char*)*N;
002168 memcpy(zExtra, pIdx->aiRowLogEst, sizeof(LogEst)*(pIdx->nKeyCol+1));
002169 pIdx->aiRowLogEst = (LogEst*)zExtra;
002170 zExtra += sizeof(LogEst)*N;
002171 memcpy(zExtra, pIdx->aiColumn, sizeof(i16)*pIdx->nColumn);
002172 pIdx->aiColumn = (i16*)zExtra;
002173 zExtra += sizeof(i16)*N;
002174 memcpy(zExtra, pIdx->aSortOrder, pIdx->nColumn);
002175 pIdx->aSortOrder = (u8*)zExtra;
002176 pIdx->nColumn = N;
002177 pIdx->isResized = 1;
002178 return SQLITE_OK;
002179 }
002180
002181 /*
002182 ** Estimate the total row width for a table.
002183 */
002184 static void estimateTableWidth(Table *pTab){
002185 unsigned wTable = 0;
002186 const Column *pTabCol;
002187 int i;
002188 for(i=pTab->nCol, pTabCol=pTab->aCol; i>0; i--, pTabCol++){
002189 wTable += pTabCol->szEst;
002190 }
002191 if( pTab->iPKey<0 ) wTable++;
002192 pTab->szTabRow = sqlite3LogEst(wTable*4);
002193 }
002194
002195 /*
002196 ** Estimate the average size of a row for an index.
002197 */
002198 static void estimateIndexWidth(Index *pIdx){
002199 unsigned wIndex = 0;
002200 int i;
002201 const Column *aCol = pIdx->pTable->aCol;
002202 for(i=0; i<pIdx->nColumn; i++){
002203 i16 x = pIdx->aiColumn[i];
002204 assert( x<pIdx->pTable->nCol );
002205 wIndex += x<0 ? 1 : aCol[x].szEst;
002206 }
002207 pIdx->szIdxRow = sqlite3LogEst(wIndex*4);
002208 }
002209
002210 /* Return true if column number x is any of the first nCol entries of aiCol[].
002211 ** This is used to determine if the column number x appears in any of the
002212 ** first nCol entries of an index.
002213 */
002214 static int hasColumn(const i16 *aiCol, int nCol, int x){
002215 while( nCol-- > 0 ){
002216 if( x==*(aiCol++) ){
002217 return 1;
002218 }
002219 }
002220 return 0;
002221 }
002222
002223 /*
002224 ** Return true if any of the first nKey entries of index pIdx exactly
002225 ** match the iCol-th entry of pPk. pPk is always a WITHOUT ROWID
002226 ** PRIMARY KEY index. pIdx is an index on the same table. pIdx may
002227 ** or may not be the same index as pPk.
002228 **
002229 ** The first nKey entries of pIdx are guaranteed to be ordinary columns,
002230 ** not a rowid or expression.
002231 **
002232 ** This routine differs from hasColumn() in that both the column and the
002233 ** collating sequence must match for this routine, but for hasColumn() only
002234 ** the column name must match.
002235 */
002236 static int isDupColumn(Index *pIdx, int nKey, Index *pPk, int iCol){
002237 int i, j;
002238 assert( nKey<=pIdx->nColumn );
002239 assert( iCol<MAX(pPk->nColumn,pPk->nKeyCol) );
002240 assert( pPk->idxType==SQLITE_IDXTYPE_PRIMARYKEY );
002241 assert( pPk->pTable->tabFlags & TF_WithoutRowid );
002242 assert( pPk->pTable==pIdx->pTable );
002243 testcase( pPk==pIdx );
002244 j = pPk->aiColumn[iCol];
002245 assert( j!=XN_ROWID && j!=XN_EXPR );
002246 for(i=0; i<nKey; i++){
002247 assert( pIdx->aiColumn[i]>=0 || j>=0 );
002248 if( pIdx->aiColumn[i]==j
002249 && sqlite3StrICmp(pIdx->azColl[i], pPk->azColl[iCol])==0
002250 ){
002251 return 1;
002252 }
002253 }
002254 return 0;
002255 }
002256
002257 /* Recompute the colNotIdxed field of the Index.
002258 **
002259 ** colNotIdxed is a bitmask that has a 0 bit representing each indexed
002260 ** columns that are within the first 63 columns of the table and a 1 for
002261 ** all other bits (all columns that are not in the index). The
002262 ** high-order bit of colNotIdxed is always 1. All unindexed columns
002263 ** of the table have a 1.
002264 **
002265 ** 2019-10-24: For the purpose of this computation, virtual columns are
002266 ** not considered to be covered by the index, even if they are in the
002267 ** index, because we do not trust the logic in whereIndexExprTrans() to be
002268 ** able to find all instances of a reference to the indexed table column
002269 ** and convert them into references to the index. Hence we always want
002270 ** the actual table at hand in order to recompute the virtual column, if
002271 ** necessary.
002272 **
002273 ** The colNotIdxed mask is AND-ed with the SrcList.a[].colUsed mask
002274 ** to determine if the index is covering index.
002275 */
002276 static void recomputeColumnsNotIndexed(Index *pIdx){
002277 Bitmask m = 0;
002278 int j;
002279 Table *pTab = pIdx->pTable;
002280 for(j=pIdx->nColumn-1; j>=0; j--){
002281 int x = pIdx->aiColumn[j];
002282 if( x>=0 && (pTab->aCol[x].colFlags & COLFLAG_VIRTUAL)==0 ){
002283 testcase( x==BMS-1 );
002284 testcase( x==BMS-2 );
002285 if( x<BMS-1 ) m |= MASKBIT(x);
002286 }
002287 }
002288 pIdx->colNotIdxed = ~m;
002289 assert( (pIdx->colNotIdxed>>63)==1 ); /* See note-20221022-a */
002290 }
002291
002292 /*
002293 ** This routine runs at the end of parsing a CREATE TABLE statement that
002294 ** has a WITHOUT ROWID clause. The job of this routine is to convert both
002295 ** internal schema data structures and the generated VDBE code so that they
002296 ** are appropriate for a WITHOUT ROWID table instead of a rowid table.
002297 ** Changes include:
002298 **
002299 ** (1) Set all columns of the PRIMARY KEY schema object to be NOT NULL.
002300 ** (2) Convert P3 parameter of the OP_CreateBtree from BTREE_INTKEY
002301 ** into BTREE_BLOBKEY.
002302 ** (3) Bypass the creation of the sqlite_schema table entry
002303 ** for the PRIMARY KEY as the primary key index is now
002304 ** identified by the sqlite_schema table entry of the table itself.
002305 ** (4) Set the Index.tnum of the PRIMARY KEY Index object in the
002306 ** schema to the rootpage from the main table.
002307 ** (5) Add all table columns to the PRIMARY KEY Index object
002308 ** so that the PRIMARY KEY is a covering index. The surplus
002309 ** columns are part of KeyInfo.nAllField and are not used for
002310 ** sorting or lookup or uniqueness checks.
002311 ** (6) Replace the rowid tail on all automatically generated UNIQUE
002312 ** indices with the PRIMARY KEY columns.
002313 **
002314 ** For virtual tables, only (1) is performed.
002315 */
002316 static void convertToWithoutRowidTable(Parse *pParse, Table *pTab){
002317 Index *pIdx;
002318 Index *pPk;
002319 int nPk;
002320 int nExtra;
002321 int i, j;
002322 sqlite3 *db = pParse->db;
002323 Vdbe *v = pParse->pVdbe;
002324
002325 /* Mark every PRIMARY KEY column as NOT NULL (except for imposter tables)
002326 */
002327 if( !db->init.imposterTable ){
002328 for(i=0; i<pTab->nCol; i++){
002329 if( (pTab->aCol[i].colFlags & COLFLAG_PRIMKEY)!=0
002330 && (pTab->aCol[i].notNull==OE_None)
002331 ){
002332 pTab->aCol[i].notNull = OE_Abort;
002333 }
002334 }
002335 pTab->tabFlags |= TF_HasNotNull;
002336 }
002337
002338 /* Convert the P3 operand of the OP_CreateBtree opcode from BTREE_INTKEY
002339 ** into BTREE_BLOBKEY.
002340 */
002341 assert( !pParse->bReturning );
002342 if( pParse->u1.addrCrTab ){
002343 assert( v );
002344 sqlite3VdbeChangeP3(v, pParse->u1.addrCrTab, BTREE_BLOBKEY);
002345 }
002346
002347 /* Locate the PRIMARY KEY index. Or, if this table was originally
002348 ** an INTEGER PRIMARY KEY table, create a new PRIMARY KEY index.
002349 */
002350 if( pTab->iPKey>=0 ){
002351 ExprList *pList;
002352 Token ipkToken;
002353 sqlite3TokenInit(&ipkToken, pTab->aCol[pTab->iPKey].zCnName);
002354 pList = sqlite3ExprListAppend(pParse, 0,
002355 sqlite3ExprAlloc(db, TK_ID, &ipkToken, 0));
002356 if( pList==0 ){
002357 pTab->tabFlags &= ~TF_WithoutRowid;
002358 return;
002359 }
002360 if( IN_RENAME_OBJECT ){
002361 sqlite3RenameTokenRemap(pParse, pList->a[0].pExpr, &pTab->iPKey);
002362 }
002363 pList->a[0].fg.sortFlags = pParse->iPkSortOrder;
002364 assert( pParse->pNewTable==pTab );
002365 pTab->iPKey = -1;
002366 sqlite3CreateIndex(pParse, 0, 0, 0, pList, pTab->keyConf, 0, 0, 0, 0,
002367 SQLITE_IDXTYPE_PRIMARYKEY);
002368 if( pParse->nErr ){
002369 pTab->tabFlags &= ~TF_WithoutRowid;
002370 return;
002371 }
002372 assert( db->mallocFailed==0 );
002373 pPk = sqlite3PrimaryKeyIndex(pTab);
002374 assert( pPk->nKeyCol==1 );
002375 }else{
002376 pPk = sqlite3PrimaryKeyIndex(pTab);
002377 assert( pPk!=0 );
002378
002379 /*
002380 ** Remove all redundant columns from the PRIMARY KEY. For example, change
002381 ** "PRIMARY KEY(a,b,a,b,c,b,c,d)" into just "PRIMARY KEY(a,b,c,d)". Later
002382 ** code assumes the PRIMARY KEY contains no repeated columns.
002383 */
002384 for(i=j=1; i<pPk->nKeyCol; i++){
002385 if( isDupColumn(pPk, j, pPk, i) ){
002386 pPk->nColumn--;
002387 }else{
002388 testcase( hasColumn(pPk->aiColumn, j, pPk->aiColumn[i]) );
002389 pPk->azColl[j] = pPk->azColl[i];
002390 pPk->aSortOrder[j] = pPk->aSortOrder[i];
002391 pPk->aiColumn[j++] = pPk->aiColumn[i];
002392 }
002393 }
002394 pPk->nKeyCol = j;
002395 }
002396 assert( pPk!=0 );
002397 pPk->isCovering = 1;
002398 if( !db->init.imposterTable ) pPk->uniqNotNull = 1;
002399 nPk = pPk->nColumn = pPk->nKeyCol;
002400
002401 /* Bypass the creation of the PRIMARY KEY btree and the sqlite_schema
002402 ** table entry. This is only required if currently generating VDBE
002403 ** code for a CREATE TABLE (not when parsing one as part of reading
002404 ** a database schema). */
002405 if( v && pPk->tnum>0 ){
002406 assert( db->init.busy==0 );
002407 sqlite3VdbeChangeOpcode(v, (int)pPk->tnum, OP_Goto);
002408 }
002409
002410 /* The root page of the PRIMARY KEY is the table root page */
002411 pPk->tnum = pTab->tnum;
002412
002413 /* Update the in-memory representation of all UNIQUE indices by converting
002414 ** the final rowid column into one or more columns of the PRIMARY KEY.
002415 */
002416 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
002417 int n;
002418 if( IsPrimaryKeyIndex(pIdx) ) continue;
002419 for(i=n=0; i<nPk; i++){
002420 if( !isDupColumn(pIdx, pIdx->nKeyCol, pPk, i) ){
002421 testcase( hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) );
002422 n++;
002423 }
002424 }
002425 if( n==0 ){
002426 /* This index is a superset of the primary key */
002427 pIdx->nColumn = pIdx->nKeyCol;
002428 continue;
002429 }
002430 if( resizeIndexObject(db, pIdx, pIdx->nKeyCol+n) ) return;
002431 for(i=0, j=pIdx->nKeyCol; i<nPk; i++){
002432 if( !isDupColumn(pIdx, pIdx->nKeyCol, pPk, i) ){
002433 testcase( hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) );
002434 pIdx->aiColumn[j] = pPk->aiColumn[i];
002435 pIdx->azColl[j] = pPk->azColl[i];
002436 if( pPk->aSortOrder[i] ){
002437 /* See ticket https://www.sqlite.org/src/info/bba7b69f9849b5bf */
002438 pIdx->bAscKeyBug = 1;
002439 }
002440 j++;
002441 }
002442 }
002443 assert( pIdx->nColumn>=pIdx->nKeyCol+n );
002444 assert( pIdx->nColumn>=j );
002445 }
002446
002447 /* Add all table columns to the PRIMARY KEY index
002448 */
002449 nExtra = 0;
002450 for(i=0; i<pTab->nCol; i++){
002451 if( !hasColumn(pPk->aiColumn, nPk, i)
002452 && (pTab->aCol[i].colFlags & COLFLAG_VIRTUAL)==0 ) nExtra++;
002453 }
002454 if( resizeIndexObject(db, pPk, nPk+nExtra) ) return;
002455 for(i=0, j=nPk; i<pTab->nCol; i++){
002456 if( !hasColumn(pPk->aiColumn, j, i)
002457 && (pTab->aCol[i].colFlags & COLFLAG_VIRTUAL)==0
002458 ){
002459 assert( j<pPk->nColumn );
002460 pPk->aiColumn[j] = i;
002461 pPk->azColl[j] = sqlite3StrBINARY;
002462 j++;
002463 }
002464 }
002465 assert( pPk->nColumn==j );
002466 assert( pTab->nNVCol<=j );
002467 recomputeColumnsNotIndexed(pPk);
002468 }
002469
002470
002471 #ifndef SQLITE_OMIT_VIRTUALTABLE
002472 /*
002473 ** Return true if pTab is a virtual table and zName is a shadow table name
002474 ** for that virtual table.
002475 */
002476 int sqlite3IsShadowTableOf(sqlite3 *db, Table *pTab, const char *zName){
002477 int nName; /* Length of zName */
002478 Module *pMod; /* Module for the virtual table */
002479
002480 if( !IsVirtual(pTab) ) return 0;
002481 nName = sqlite3Strlen30(pTab->zName);
002482 if( sqlite3_strnicmp(zName, pTab->zName, nName)!=0 ) return 0;
002483 if( zName[nName]!='_' ) return 0;
002484 pMod = (Module*)sqlite3HashFind(&db->aModule, pTab->u.vtab.azArg[0]);
002485 if( pMod==0 ) return 0;
002486 if( pMod->pModule->iVersion<3 ) return 0;
002487 if( pMod->pModule->xShadowName==0 ) return 0;
002488 return pMod->pModule->xShadowName(zName+nName+1);
002489 }
002490 #endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
002491
002492 #ifndef SQLITE_OMIT_VIRTUALTABLE
002493 /*
002494 ** Table pTab is a virtual table. If it the virtual table implementation
002495 ** exists and has an xShadowName method, then loop over all other ordinary
002496 ** tables within the same schema looking for shadow tables of pTab, and mark
002497 ** any shadow tables seen using the TF_Shadow flag.
002498 */
002499 void sqlite3MarkAllShadowTablesOf(sqlite3 *db, Table *pTab){
002500 int nName; /* Length of pTab->zName */
002501 Module *pMod; /* Module for the virtual table */
002502 HashElem *k; /* For looping through the symbol table */
002503
002504 assert( IsVirtual(pTab) );
002505 pMod = (Module*)sqlite3HashFind(&db->aModule, pTab->u.vtab.azArg[0]);
002506 if( pMod==0 ) return;
002507 if( NEVER(pMod->pModule==0) ) return;
002508 if( pMod->pModule->iVersion<3 ) return;
002509 if( pMod->pModule->xShadowName==0 ) return;
002510 assert( pTab->zName!=0 );
002511 nName = sqlite3Strlen30(pTab->zName);
002512 for(k=sqliteHashFirst(&pTab->pSchema->tblHash); k; k=sqliteHashNext(k)){
002513 Table *pOther = sqliteHashData(k);
002514 assert( pOther->zName!=0 );
002515 if( !IsOrdinaryTable(pOther) ) continue;
002516 if( pOther->tabFlags & TF_Shadow ) continue;
002517 if( sqlite3StrNICmp(pOther->zName, pTab->zName, nName)==0
002518 && pOther->zName[nName]=='_'
002519 && pMod->pModule->xShadowName(pOther->zName+nName+1)
002520 ){
002521 pOther->tabFlags |= TF_Shadow;
002522 }
002523 }
002524 }
002525 #endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
002526
002527 #ifndef SQLITE_OMIT_VIRTUALTABLE
002528 /*
002529 ** Return true if zName is a shadow table name in the current database
002530 ** connection.
002531 **
002532 ** zName is temporarily modified while this routine is running, but is
002533 ** restored to its original value prior to this routine returning.
002534 */
002535 int sqlite3ShadowTableName(sqlite3 *db, const char *zName){
002536 char *zTail; /* Pointer to the last "_" in zName */
002537 Table *pTab; /* Table that zName is a shadow of */
002538 zTail = strrchr(zName, '_');
002539 if( zTail==0 ) return 0;
002540 *zTail = 0;
002541 pTab = sqlite3FindTable(db, zName, 0);
002542 *zTail = '_';
002543 if( pTab==0 ) return 0;
002544 if( !IsVirtual(pTab) ) return 0;
002545 return sqlite3IsShadowTableOf(db, pTab, zName);
002546 }
002547 #endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
002548
002549
002550 #ifdef SQLITE_DEBUG
002551 /*
002552 ** Mark all nodes of an expression as EP_Immutable, indicating that
002553 ** they should not be changed. Expressions attached to a table or
002554 ** index definition are tagged this way to help ensure that we do
002555 ** not pass them into code generator routines by mistake.
002556 */
002557 static int markImmutableExprStep(Walker *pWalker, Expr *pExpr){
002558 (void)pWalker;
002559 ExprSetVVAProperty(pExpr, EP_Immutable);
002560 return WRC_Continue;
002561 }
002562 static void markExprListImmutable(ExprList *pList){
002563 if( pList ){
002564 Walker w;
002565 memset(&w, 0, sizeof(w));
002566 w.xExprCallback = markImmutableExprStep;
002567 w.xSelectCallback = sqlite3SelectWalkNoop;
002568 w.xSelectCallback2 = 0;
002569 sqlite3WalkExprList(&w, pList);
002570 }
002571 }
002572 #else
002573 #define markExprListImmutable(X) /* no-op */
002574 #endif /* SQLITE_DEBUG */
002575
002576
002577 /*
002578 ** This routine is called to report the final ")" that terminates
002579 ** a CREATE TABLE statement.
002580 **
002581 ** The table structure that other action routines have been building
002582 ** is added to the internal hash tables, assuming no errors have
002583 ** occurred.
002584 **
002585 ** An entry for the table is made in the schema table on disk, unless
002586 ** this is a temporary table or db->init.busy==1. When db->init.busy==1
002587 ** it means we are reading the sqlite_schema table because we just
002588 ** connected to the database or because the sqlite_schema table has
002589 ** recently changed, so the entry for this table already exists in
002590 ** the sqlite_schema table. We do not want to create it again.
002591 **
002592 ** If the pSelect argument is not NULL, it means that this routine
002593 ** was called to create a table generated from a
002594 ** "CREATE TABLE ... AS SELECT ..." statement. The column names of
002595 ** the new table will match the result set of the SELECT.
002596 */
002597 void sqlite3EndTable(
002598 Parse *pParse, /* Parse context */
002599 Token *pCons, /* The ',' token after the last column defn. */
002600 Token *pEnd, /* The ')' before options in the CREATE TABLE */
002601 u32 tabOpts, /* Extra table options. Usually 0. */
002602 Select *pSelect /* Select from a "CREATE ... AS SELECT" */
002603 ){
002604 Table *p; /* The new table */
002605 sqlite3 *db = pParse->db; /* The database connection */
002606 int iDb; /* Database in which the table lives */
002607 Index *pIdx; /* An implied index of the table */
002608
002609 if( pEnd==0 && pSelect==0 ){
002610 return;
002611 }
002612 p = pParse->pNewTable;
002613 if( p==0 ) return;
002614
002615 if( pSelect==0 && sqlite3ShadowTableName(db, p->zName) ){
002616 p->tabFlags |= TF_Shadow;
002617 }
002618
002619 /* If the db->init.busy is 1 it means we are reading the SQL off the
002620 ** "sqlite_schema" or "sqlite_temp_schema" table on the disk.
002621 ** So do not write to the disk again. Extract the root page number
002622 ** for the table from the db->init.newTnum field. (The page number
002623 ** should have been put there by the sqliteOpenCb routine.)
002624 **
002625 ** If the root page number is 1, that means this is the sqlite_schema
002626 ** table itself. So mark it read-only.
002627 */
002628 if( db->init.busy ){
002629 if( pSelect || (!IsOrdinaryTable(p) && db->init.newTnum) ){
002630 sqlite3ErrorMsg(pParse, "");
002631 return;
002632 }
002633 p->tnum = db->init.newTnum;
002634 if( p->tnum==1 ) p->tabFlags |= TF_Readonly;
002635 }
002636
002637 /* Special processing for tables that include the STRICT keyword:
002638 **
002639 ** * Do not allow custom column datatypes. Every column must have
002640 ** a datatype that is one of INT, INTEGER, REAL, TEXT, or BLOB.
002641 **
002642 ** * If a PRIMARY KEY is defined, other than the INTEGER PRIMARY KEY,
002643 ** then all columns of the PRIMARY KEY must have a NOT NULL
002644 ** constraint.
002645 */
002646 if( tabOpts & TF_Strict ){
002647 int ii;
002648 p->tabFlags |= TF_Strict;
002649 for(ii=0; ii<p->nCol; ii++){
002650 Column *pCol = &p->aCol[ii];
002651 if( pCol->eCType==COLTYPE_CUSTOM ){
002652 if( pCol->colFlags & COLFLAG_HASTYPE ){
002653 sqlite3ErrorMsg(pParse,
002654 "unknown datatype for %s.%s: \"%s\"",
002655 p->zName, pCol->zCnName, sqlite3ColumnType(pCol, "")
002656 );
002657 }else{
002658 sqlite3ErrorMsg(pParse, "missing datatype for %s.%s",
002659 p->zName, pCol->zCnName);
002660 }
002661 return;
002662 }else if( pCol->eCType==COLTYPE_ANY ){
002663 pCol->affinity = SQLITE_AFF_BLOB;
002664 }
002665 if( (pCol->colFlags & COLFLAG_PRIMKEY)!=0
002666 && p->iPKey!=ii
002667 && pCol->notNull == OE_None
002668 ){
002669 pCol->notNull = OE_Abort;
002670 p->tabFlags |= TF_HasNotNull;
002671 }
002672 }
002673 }
002674
002675 assert( (p->tabFlags & TF_HasPrimaryKey)==0
002676 || p->iPKey>=0 || sqlite3PrimaryKeyIndex(p)!=0 );
002677 assert( (p->tabFlags & TF_HasPrimaryKey)!=0
002678 || (p->iPKey<0 && sqlite3PrimaryKeyIndex(p)==0) );
002679
002680 /* Special processing for WITHOUT ROWID Tables */
002681 if( tabOpts & TF_WithoutRowid ){
002682 if( (p->tabFlags & TF_Autoincrement) ){
002683 sqlite3ErrorMsg(pParse,
002684 "AUTOINCREMENT not allowed on WITHOUT ROWID tables");
002685 return;
002686 }
002687 if( (p->tabFlags & TF_HasPrimaryKey)==0 ){
002688 sqlite3ErrorMsg(pParse, "PRIMARY KEY missing on table %s", p->zName);
002689 return;
002690 }
002691 p->tabFlags |= TF_WithoutRowid | TF_NoVisibleRowid;
002692 convertToWithoutRowidTable(pParse, p);
002693 }
002694 iDb = sqlite3SchemaToIndex(db, p->pSchema);
002695
002696 #ifndef SQLITE_OMIT_CHECK
002697 /* Resolve names in all CHECK constraint expressions.
002698 */
002699 if( p->pCheck ){
002700 sqlite3ResolveSelfReference(pParse, p, NC_IsCheck, 0, p->pCheck);
002701 if( pParse->nErr ){
002702 /* If errors are seen, delete the CHECK constraints now, else they might
002703 ** actually be used if PRAGMA writable_schema=ON is set. */
002704 sqlite3ExprListDelete(db, p->pCheck);
002705 p->pCheck = 0;
002706 }else{
002707 markExprListImmutable(p->pCheck);
002708 }
002709 }
002710 #endif /* !defined(SQLITE_OMIT_CHECK) */
002711 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
002712 if( p->tabFlags & TF_HasGenerated ){
002713 int ii, nNG = 0;
002714 testcase( p->tabFlags & TF_HasVirtual );
002715 testcase( p->tabFlags & TF_HasStored );
002716 for(ii=0; ii<p->nCol; ii++){
002717 u32 colFlags = p->aCol[ii].colFlags;
002718 if( (colFlags & COLFLAG_GENERATED)!=0 ){
002719 Expr *pX = sqlite3ColumnExpr(p, &p->aCol[ii]);
002720 testcase( colFlags & COLFLAG_VIRTUAL );
002721 testcase( colFlags & COLFLAG_STORED );
002722 if( sqlite3ResolveSelfReference(pParse, p, NC_GenCol, pX, 0) ){
002723 /* If there are errors in resolving the expression, change the
002724 ** expression to a NULL. This prevents code generators that operate
002725 ** on the expression from inserting extra parts into the expression
002726 ** tree that have been allocated from lookaside memory, which is
002727 ** illegal in a schema and will lead to errors or heap corruption
002728 ** when the database connection closes. */
002729 sqlite3ColumnSetExpr(pParse, p, &p->aCol[ii],
002730 sqlite3ExprAlloc(db, TK_NULL, 0, 0));
002731 }
002732 }else{
002733 nNG++;
002734 }
002735 }
002736 if( nNG==0 ){
002737 sqlite3ErrorMsg(pParse, "must have at least one non-generated column");
002738 return;
002739 }
002740 }
002741 #endif
002742
002743 /* Estimate the average row size for the table and for all implied indices */
002744 estimateTableWidth(p);
002745 for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
002746 estimateIndexWidth(pIdx);
002747 }
002748
002749 /* If not initializing, then create a record for the new table
002750 ** in the schema table of the database.
002751 **
002752 ** If this is a TEMPORARY table, write the entry into the auxiliary
002753 ** file instead of into the main database file.
002754 */
002755 if( !db->init.busy ){
002756 int n;
002757 Vdbe *v;
002758 char *zType; /* "view" or "table" */
002759 char *zType2; /* "VIEW" or "TABLE" */
002760 char *zStmt; /* Text of the CREATE TABLE or CREATE VIEW statement */
002761
002762 v = sqlite3GetVdbe(pParse);
002763 if( NEVER(v==0) ) return;
002764
002765 sqlite3VdbeAddOp1(v, OP_Close, 0);
002766
002767 /*
002768 ** Initialize zType for the new view or table.
002769 */
002770 if( IsOrdinaryTable(p) ){
002771 /* A regular table */
002772 zType = "table";
002773 zType2 = "TABLE";
002774 #ifndef SQLITE_OMIT_VIEW
002775 }else{
002776 /* A view */
002777 zType = "view";
002778 zType2 = "VIEW";
002779 #endif
002780 }
002781
002782 /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
002783 ** statement to populate the new table. The root-page number for the
002784 ** new table is in register pParse->regRoot.
002785 **
002786 ** Once the SELECT has been coded by sqlite3Select(), it is in a
002787 ** suitable state to query for the column names and types to be used
002788 ** by the new table.
002789 **
002790 ** A shared-cache write-lock is not required to write to the new table,
002791 ** as a schema-lock must have already been obtained to create it. Since
002792 ** a schema-lock excludes all other database users, the write-lock would
002793 ** be redundant.
002794 */
002795 if( pSelect ){
002796 SelectDest dest; /* Where the SELECT should store results */
002797 int regYield; /* Register holding co-routine entry-point */
002798 int addrTop; /* Top of the co-routine */
002799 int regRec; /* A record to be insert into the new table */
002800 int regRowid; /* Rowid of the next row to insert */
002801 int addrInsLoop; /* Top of the loop for inserting rows */
002802 Table *pSelTab; /* A table that describes the SELECT results */
002803 int iCsr; /* Write cursor on the new table */
002804
002805 if( IN_SPECIAL_PARSE ){
002806 pParse->rc = SQLITE_ERROR;
002807 pParse->nErr++;
002808 return;
002809 }
002810 iCsr = pParse->nTab++;
002811 regYield = ++pParse->nMem;
002812 regRec = ++pParse->nMem;
002813 regRowid = ++pParse->nMem;
002814 sqlite3MayAbort(pParse);
002815 sqlite3VdbeAddOp3(v, OP_OpenWrite, iCsr, pParse->regRoot, iDb);
002816 sqlite3VdbeChangeP5(v, OPFLAG_P2ISREG);
002817 addrTop = sqlite3VdbeCurrentAddr(v) + 1;
002818 sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, addrTop);
002819 if( pParse->nErr ) return;
002820 pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect, SQLITE_AFF_BLOB);
002821 if( pSelTab==0 ) return;
002822 assert( p->aCol==0 );
002823 p->nCol = p->nNVCol = pSelTab->nCol;
002824 p->aCol = pSelTab->aCol;
002825 pSelTab->nCol = 0;
002826 pSelTab->aCol = 0;
002827 sqlite3DeleteTable(db, pSelTab);
002828 sqlite3SelectDestInit(&dest, SRT_Coroutine, regYield);
002829 sqlite3Select(pParse, pSelect, &dest);
002830 if( pParse->nErr ) return;
002831 sqlite3VdbeEndCoroutine(v, regYield);
002832 sqlite3VdbeJumpHere(v, addrTop - 1);
002833 addrInsLoop = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
002834 VdbeCoverage(v);
002835 sqlite3VdbeAddOp3(v, OP_MakeRecord, dest.iSdst, dest.nSdst, regRec);
002836 sqlite3TableAffinity(v, p, 0);
002837 sqlite3VdbeAddOp2(v, OP_NewRowid, iCsr, regRowid);
002838 sqlite3VdbeAddOp3(v, OP_Insert, iCsr, regRec, regRowid);
002839 sqlite3VdbeGoto(v, addrInsLoop);
002840 sqlite3VdbeJumpHere(v, addrInsLoop);
002841 sqlite3VdbeAddOp1(v, OP_Close, iCsr);
002842 }
002843
002844 /* Compute the complete text of the CREATE statement */
002845 if( pSelect ){
002846 zStmt = createTableStmt(db, p);
002847 }else{
002848 Token *pEnd2 = tabOpts ? &pParse->sLastToken : pEnd;
002849 n = (int)(pEnd2->z - pParse->sNameToken.z);
002850 if( pEnd2->z[0]!=';' ) n += pEnd2->n;
002851 zStmt = sqlite3MPrintf(db,
002852 "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
002853 );
002854 }
002855
002856 /* A slot for the record has already been allocated in the
002857 ** schema table. We just need to update that slot with all
002858 ** the information we've collected.
002859 */
002860 sqlite3NestedParse(pParse,
002861 "UPDATE %Q." LEGACY_SCHEMA_TABLE
002862 " SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q"
002863 " WHERE rowid=#%d",
002864 db->aDb[iDb].zDbSName,
002865 zType,
002866 p->zName,
002867 p->zName,
002868 pParse->regRoot,
002869 zStmt,
002870 pParse->regRowid
002871 );
002872 sqlite3DbFree(db, zStmt);
002873 sqlite3ChangeCookie(pParse, iDb);
002874
002875 #ifndef SQLITE_OMIT_AUTOINCREMENT
002876 /* Check to see if we need to create an sqlite_sequence table for
002877 ** keeping track of autoincrement keys.
002878 */
002879 if( (p->tabFlags & TF_Autoincrement)!=0 && !IN_SPECIAL_PARSE ){
002880 Db *pDb = &db->aDb[iDb];
002881 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
002882 if( pDb->pSchema->pSeqTab==0 ){
002883 sqlite3NestedParse(pParse,
002884 "CREATE TABLE %Q.sqlite_sequence(name,seq)",
002885 pDb->zDbSName
002886 );
002887 }
002888 }
002889 #endif
002890
002891 /* Reparse everything to update our internal data structures */
002892 sqlite3VdbeAddParseSchemaOp(v, iDb,
002893 sqlite3MPrintf(db, "tbl_name='%q' AND type!='trigger'", p->zName),0);
002894
002895 /* Test for cycles in generated columns and illegal expressions
002896 ** in CHECK constraints and in DEFAULT clauses. */
002897 if( p->tabFlags & TF_HasGenerated ){
002898 sqlite3VdbeAddOp4(v, OP_SqlExec, 0x0001, 0, 0,
002899 sqlite3MPrintf(db, "SELECT*FROM\"%w\".\"%w\"",
002900 db->aDb[iDb].zDbSName, p->zName), P4_DYNAMIC);
002901 }
002902 }
002903
002904 /* Add the table to the in-memory representation of the database.
002905 */
002906 if( db->init.busy ){
002907 Table *pOld;
002908 Schema *pSchema = p->pSchema;
002909 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
002910 assert( HasRowid(p) || p->iPKey<0 );
002911 pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName, p);
002912 if( pOld ){
002913 assert( p==pOld ); /* Malloc must have failed inside HashInsert() */
002914 sqlite3OomFault(db);
002915 return;
002916 }
002917 pParse->pNewTable = 0;
002918 db->mDbFlags |= DBFLAG_SchemaChange;
002919
002920 /* If this is the magic sqlite_sequence table used by autoincrement,
002921 ** then record a pointer to this table in the main database structure
002922 ** so that INSERT can find the table easily. */
002923 assert( !pParse->nested );
002924 #ifndef SQLITE_OMIT_AUTOINCREMENT
002925 if( strcmp(p->zName, "sqlite_sequence")==0 ){
002926 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
002927 p->pSchema->pSeqTab = p;
002928 }
002929 #endif
002930 }
002931
002932 #ifndef SQLITE_OMIT_ALTERTABLE
002933 if( !pSelect && IsOrdinaryTable(p) ){
002934 assert( pCons && pEnd );
002935 if( pCons->z==0 ){
002936 pCons = pEnd;
002937 }
002938 p->u.tab.addColOffset = 13 + (int)(pCons->z - pParse->sNameToken.z);
002939 }
002940 #endif
002941 }
002942
002943 #ifndef SQLITE_OMIT_VIEW
002944 /*
002945 ** The parser calls this routine in order to create a new VIEW
002946 */
002947 void sqlite3CreateView(
002948 Parse *pParse, /* The parsing context */
002949 Token *pBegin, /* The CREATE token that begins the statement */
002950 Token *pName1, /* The token that holds the name of the view */
002951 Token *pName2, /* The token that holds the name of the view */
002952 ExprList *pCNames, /* Optional list of view column names */
002953 Select *pSelect, /* A SELECT statement that will become the new view */
002954 int isTemp, /* TRUE for a TEMPORARY view */
002955 int noErr /* Suppress error messages if VIEW already exists */
002956 ){
002957 Table *p;
002958 int n;
002959 const char *z;
002960 Token sEnd;
002961 DbFixer sFix;
002962 Token *pName = 0;
002963 int iDb;
002964 sqlite3 *db = pParse->db;
002965
002966 if( pParse->nVar>0 ){
002967 sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
002968 goto create_view_fail;
002969 }
002970 sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
002971 p = pParse->pNewTable;
002972 if( p==0 || pParse->nErr ) goto create_view_fail;
002973
002974 /* Legacy versions of SQLite allowed the use of the magic "rowid" column
002975 ** on a view, even though views do not have rowids. The following flag
002976 ** setting fixes this problem. But the fix can be disabled by compiling
002977 ** with -DSQLITE_ALLOW_ROWID_IN_VIEW in case there are legacy apps that
002978 ** depend upon the old buggy behavior. The ability can also be toggled
002979 ** using sqlite3_config(SQLITE_CONFIG_ROWID_IN_VIEW,...) */
002980 #ifdef SQLITE_ALLOW_ROWID_IN_VIEW
002981 p->tabFlags |= sqlite3Config.mNoVisibleRowid; /* Optional. Allow by default */
002982 #else
002983 p->tabFlags |= TF_NoVisibleRowid; /* Never allow rowid in view */
002984 #endif
002985
002986 sqlite3TwoPartName(pParse, pName1, pName2, &pName);
002987 iDb = sqlite3SchemaToIndex(db, p->pSchema);
002988 sqlite3FixInit(&sFix, pParse, iDb, "view", pName);
002989 if( sqlite3FixSelect(&sFix, pSelect) ) goto create_view_fail;
002990
002991 /* Make a copy of the entire SELECT statement that defines the view.
002992 ** This will force all the Expr.token.z values to be dynamically
002993 ** allocated rather than point to the input string - which means that
002994 ** they will persist after the current sqlite3_exec() call returns.
002995 */
002996 pSelect->selFlags |= SF_View;
002997 if( IN_RENAME_OBJECT ){
002998 p->u.view.pSelect = pSelect;
002999 pSelect = 0;
003000 }else{
003001 p->u.view.pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
003002 }
003003 p->pCheck = sqlite3ExprListDup(db, pCNames, EXPRDUP_REDUCE);
003004 p->eTabType = TABTYP_VIEW;
003005 if( db->mallocFailed ) goto create_view_fail;
003006
003007 /* Locate the end of the CREATE VIEW statement. Make sEnd point to
003008 ** the end.
003009 */
003010 sEnd = pParse->sLastToken;
003011 assert( sEnd.z[0]!=0 || sEnd.n==0 );
003012 if( sEnd.z[0]!=';' ){
003013 sEnd.z += sEnd.n;
003014 }
003015 sEnd.n = 0;
003016 n = (int)(sEnd.z - pBegin->z);
003017 assert( n>0 );
003018 z = pBegin->z;
003019 while( sqlite3Isspace(z[n-1]) ){ n--; }
003020 sEnd.z = &z[n-1];
003021 sEnd.n = 1;
003022
003023 /* Use sqlite3EndTable() to add the view to the schema table */
003024 sqlite3EndTable(pParse, 0, &sEnd, 0, 0);
003025
003026 create_view_fail:
003027 sqlite3SelectDelete(db, pSelect);
003028 if( IN_RENAME_OBJECT ){
003029 sqlite3RenameExprlistUnmap(pParse, pCNames);
003030 }
003031 sqlite3ExprListDelete(db, pCNames);
003032 return;
003033 }
003034 #endif /* SQLITE_OMIT_VIEW */
003035
003036 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
003037 /*
003038 ** The Table structure pTable is really a VIEW. Fill in the names of
003039 ** the columns of the view in the pTable structure. Return non-zero if
003040 ** there are errors. If an error is seen an error message is left
003041 ** in pParse->zErrMsg.
003042 */
003043 static SQLITE_NOINLINE int viewGetColumnNames(Parse *pParse, Table *pTable){
003044 Table *pSelTab; /* A fake table from which we get the result set */
003045 Select *pSel; /* Copy of the SELECT that implements the view */
003046 int nErr = 0; /* Number of errors encountered */
003047 sqlite3 *db = pParse->db; /* Database connection for malloc errors */
003048 #ifndef SQLITE_OMIT_VIRTUALTABLE
003049 int rc;
003050 #endif
003051 #ifndef SQLITE_OMIT_AUTHORIZATION
003052 sqlite3_xauth xAuth; /* Saved xAuth pointer */
003053 #endif
003054
003055 assert( pTable );
003056
003057 #ifndef SQLITE_OMIT_VIRTUALTABLE
003058 if( IsVirtual(pTable) ){
003059 db->nSchemaLock++;
003060 rc = sqlite3VtabCallConnect(pParse, pTable);
003061 db->nSchemaLock--;
003062 return rc;
003063 }
003064 #endif
003065
003066 #ifndef SQLITE_OMIT_VIEW
003067 /* A positive nCol means the columns names for this view are
003068 ** already known. This routine is not called unless either the
003069 ** table is virtual or nCol is zero.
003070 */
003071 assert( pTable->nCol<=0 );
003072
003073 /* A negative nCol is a special marker meaning that we are currently
003074 ** trying to compute the column names. If we enter this routine with
003075 ** a negative nCol, it means two or more views form a loop, like this:
003076 **
003077 ** CREATE VIEW one AS SELECT * FROM two;
003078 ** CREATE VIEW two AS SELECT * FROM one;
003079 **
003080 ** Actually, the error above is now caught prior to reaching this point.
003081 ** But the following test is still important as it does come up
003082 ** in the following:
003083 **
003084 ** CREATE TABLE main.ex1(a);
003085 ** CREATE TEMP VIEW ex1 AS SELECT a FROM ex1;
003086 ** SELECT * FROM temp.ex1;
003087 */
003088 if( pTable->nCol<0 ){
003089 sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
003090 return 1;
003091 }
003092 assert( pTable->nCol>=0 );
003093
003094 /* If we get this far, it means we need to compute the table names.
003095 ** Note that the call to sqlite3ResultSetOfSelect() will expand any
003096 ** "*" elements in the results set of the view and will assign cursors
003097 ** to the elements of the FROM clause. But we do not want these changes
003098 ** to be permanent. So the computation is done on a copy of the SELECT
003099 ** statement that defines the view.
003100 */
003101 assert( IsView(pTable) );
003102 pSel = sqlite3SelectDup(db, pTable->u.view.pSelect, 0);
003103 if( pSel ){
003104 u8 eParseMode = pParse->eParseMode;
003105 int nTab = pParse->nTab;
003106 int nSelect = pParse->nSelect;
003107 pParse->eParseMode = PARSE_MODE_NORMAL;
003108 sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
003109 pTable->nCol = -1;
003110 DisableLookaside;
003111 #ifndef SQLITE_OMIT_AUTHORIZATION
003112 xAuth = db->xAuth;
003113 db->xAuth = 0;
003114 pSelTab = sqlite3ResultSetOfSelect(pParse, pSel, SQLITE_AFF_NONE);
003115 db->xAuth = xAuth;
003116 #else
003117 pSelTab = sqlite3ResultSetOfSelect(pParse, pSel, SQLITE_AFF_NONE);
003118 #endif
003119 pParse->nTab = nTab;
003120 pParse->nSelect = nSelect;
003121 if( pSelTab==0 ){
003122 pTable->nCol = 0;
003123 nErr++;
003124 }else if( pTable->pCheck ){
003125 /* CREATE VIEW name(arglist) AS ...
003126 ** The names of the columns in the table are taken from
003127 ** arglist which is stored in pTable->pCheck. The pCheck field
003128 ** normally holds CHECK constraints on an ordinary table, but for
003129 ** a VIEW it holds the list of column names.
003130 */
003131 sqlite3ColumnsFromExprList(pParse, pTable->pCheck,
003132 &pTable->nCol, &pTable->aCol);
003133 if( pParse->nErr==0
003134 && pTable->nCol==pSel->pEList->nExpr
003135 ){
003136 assert( db->mallocFailed==0 );
003137 sqlite3SubqueryColumnTypes(pParse, pTable, pSel, SQLITE_AFF_NONE);
003138 }
003139 }else{
003140 /* CREATE VIEW name AS... without an argument list. Construct
003141 ** the column names from the SELECT statement that defines the view.
003142 */
003143 assert( pTable->aCol==0 );
003144 pTable->nCol = pSelTab->nCol;
003145 pTable->aCol = pSelTab->aCol;
003146 pTable->tabFlags |= (pSelTab->tabFlags & COLFLAG_NOINSERT);
003147 pSelTab->nCol = 0;
003148 pSelTab->aCol = 0;
003149 assert( sqlite3SchemaMutexHeld(db, 0, pTable->pSchema) );
003150 }
003151 pTable->nNVCol = pTable->nCol;
003152 sqlite3DeleteTable(db, pSelTab);
003153 sqlite3SelectDelete(db, pSel);
003154 EnableLookaside;
003155 pParse->eParseMode = eParseMode;
003156 } else {
003157 nErr++;
003158 }
003159 pTable->pSchema->schemaFlags |= DB_UnresetViews;
003160 if( db->mallocFailed ){
003161 sqlite3DeleteColumnNames(db, pTable);
003162 }
003163 #endif /* SQLITE_OMIT_VIEW */
003164 return nErr + pParse->nErr;
003165 }
003166 int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
003167 assert( pTable!=0 );
003168 if( !IsVirtual(pTable) && pTable->nCol>0 ) return 0;
003169 return viewGetColumnNames(pParse, pTable);
003170 }
003171 #endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
003172
003173 #ifndef SQLITE_OMIT_VIEW
003174 /*
003175 ** Clear the column names from every VIEW in database idx.
003176 */
003177 static void sqliteViewResetAll(sqlite3 *db, int idx){
003178 HashElem *i;
003179 assert( sqlite3SchemaMutexHeld(db, idx, 0) );
003180 if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
003181 for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
003182 Table *pTab = sqliteHashData(i);
003183 if( IsView(pTab) ){
003184 sqlite3DeleteColumnNames(db, pTab);
003185 }
003186 }
003187 DbClearProperty(db, idx, DB_UnresetViews);
003188 }
003189 #else
003190 # define sqliteViewResetAll(A,B)
003191 #endif /* SQLITE_OMIT_VIEW */
003192
003193 /*
003194 ** This function is called by the VDBE to adjust the internal schema
003195 ** used by SQLite when the btree layer moves a table root page. The
003196 ** root-page of a table or index in database iDb has changed from iFrom
003197 ** to iTo.
003198 **
003199 ** Ticket #1728: The symbol table might still contain information
003200 ** on tables and/or indices that are the process of being deleted.
003201 ** If you are unlucky, one of those deleted indices or tables might
003202 ** have the same rootpage number as the real table or index that is
003203 ** being moved. So we cannot stop searching after the first match
003204 ** because the first match might be for one of the deleted indices
003205 ** or tables and not the table/index that is actually being moved.
003206 ** We must continue looping until all tables and indices with
003207 ** rootpage==iFrom have been converted to have a rootpage of iTo
003208 ** in order to be certain that we got the right one.
003209 */
003210 #ifndef SQLITE_OMIT_AUTOVACUUM
003211 void sqlite3RootPageMoved(sqlite3 *db, int iDb, Pgno iFrom, Pgno iTo){
003212 HashElem *pElem;
003213 Hash *pHash;
003214 Db *pDb;
003215
003216 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
003217 pDb = &db->aDb[iDb];
003218 pHash = &pDb->pSchema->tblHash;
003219 for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
003220 Table *pTab = sqliteHashData(pElem);
003221 if( pTab->tnum==iFrom ){
003222 pTab->tnum = iTo;
003223 }
003224 }
003225 pHash = &pDb->pSchema->idxHash;
003226 for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
003227 Index *pIdx = sqliteHashData(pElem);
003228 if( pIdx->tnum==iFrom ){
003229 pIdx->tnum = iTo;
003230 }
003231 }
003232 }
003233 #endif
003234
003235 /*
003236 ** Write code to erase the table with root-page iTable from database iDb.
003237 ** Also write code to modify the sqlite_schema table and internal schema
003238 ** if a root-page of another table is moved by the btree-layer whilst
003239 ** erasing iTable (this can happen with an auto-vacuum database).
003240 */
003241 static void destroyRootPage(Parse *pParse, int iTable, int iDb){
003242 Vdbe *v = sqlite3GetVdbe(pParse);
003243 int r1 = sqlite3GetTempReg(pParse);
003244 if( iTable<2 ) sqlite3ErrorMsg(pParse, "corrupt schema");
003245 sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
003246 sqlite3MayAbort(pParse);
003247 #ifndef SQLITE_OMIT_AUTOVACUUM
003248 /* OP_Destroy stores an in integer r1. If this integer
003249 ** is non-zero, then it is the root page number of a table moved to
003250 ** location iTable. The following code modifies the sqlite_schema table to
003251 ** reflect this.
003252 **
003253 ** The "#NNN" in the SQL is a special constant that means whatever value
003254 ** is in register NNN. See grammar rules associated with the TK_REGISTER
003255 ** token for additional information.
003256 */
003257 sqlite3NestedParse(pParse,
003258 "UPDATE %Q." LEGACY_SCHEMA_TABLE
003259 " SET rootpage=%d WHERE #%d AND rootpage=#%d",
003260 pParse->db->aDb[iDb].zDbSName, iTable, r1, r1);
003261 #endif
003262 sqlite3ReleaseTempReg(pParse, r1);
003263 }
003264
003265 /*
003266 ** Write VDBE code to erase table pTab and all associated indices on disk.
003267 ** Code to update the sqlite_schema tables and internal schema definitions
003268 ** in case a root-page belonging to another table is moved by the btree layer
003269 ** is also added (this can happen with an auto-vacuum database).
003270 */
003271 static void destroyTable(Parse *pParse, Table *pTab){
003272 /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
003273 ** is not defined), then it is important to call OP_Destroy on the
003274 ** table and index root-pages in order, starting with the numerically
003275 ** largest root-page number. This guarantees that none of the root-pages
003276 ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
003277 ** following were coded:
003278 **
003279 ** OP_Destroy 4 0
003280 ** ...
003281 ** OP_Destroy 5 0
003282 **
003283 ** and root page 5 happened to be the largest root-page number in the
003284 ** database, then root page 5 would be moved to page 4 by the
003285 ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
003286 ** a free-list page.
003287 */
003288 Pgno iTab = pTab->tnum;
003289 Pgno iDestroyed = 0;
003290
003291 while( 1 ){
003292 Index *pIdx;
003293 Pgno iLargest = 0;
003294
003295 if( iDestroyed==0 || iTab<iDestroyed ){
003296 iLargest = iTab;
003297 }
003298 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
003299 Pgno iIdx = pIdx->tnum;
003300 assert( pIdx->pSchema==pTab->pSchema );
003301 if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
003302 iLargest = iIdx;
003303 }
003304 }
003305 if( iLargest==0 ){
003306 return;
003307 }else{
003308 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
003309 assert( iDb>=0 && iDb<pParse->db->nDb );
003310 destroyRootPage(pParse, iLargest, iDb);
003311 iDestroyed = iLargest;
003312 }
003313 }
003314 }
003315
003316 /*
003317 ** Remove entries from the sqlite_statN tables (for N in (1,2,3))
003318 ** after a DROP INDEX or DROP TABLE command.
003319 */
003320 static void sqlite3ClearStatTables(
003321 Parse *pParse, /* The parsing context */
003322 int iDb, /* The database number */
003323 const char *zType, /* "idx" or "tbl" */
003324 const char *zName /* Name of index or table */
003325 ){
003326 int i;
003327 const char *zDbName = pParse->db->aDb[iDb].zDbSName;
003328 for(i=1; i<=4; i++){
003329 char zTab[24];
003330 sqlite3_snprintf(sizeof(zTab),zTab,"sqlite_stat%d",i);
003331 if( sqlite3FindTable(pParse->db, zTab, zDbName) ){
003332 sqlite3NestedParse(pParse,
003333 "DELETE FROM %Q.%s WHERE %s=%Q",
003334 zDbName, zTab, zType, zName
003335 );
003336 }
003337 }
003338 }
003339
003340 /*
003341 ** Generate code to drop a table.
003342 */
003343 void sqlite3CodeDropTable(Parse *pParse, Table *pTab, int iDb, int isView){
003344 Vdbe *v;
003345 sqlite3 *db = pParse->db;
003346 Trigger *pTrigger;
003347 Db *pDb = &db->aDb[iDb];
003348
003349 v = sqlite3GetVdbe(pParse);
003350 assert( v!=0 );
003351 sqlite3BeginWriteOperation(pParse, 1, iDb);
003352
003353 #ifndef SQLITE_OMIT_VIRTUALTABLE
003354 if( IsVirtual(pTab) ){
003355 sqlite3VdbeAddOp0(v, OP_VBegin);
003356 }
003357 #endif
003358
003359 /* Drop all triggers associated with the table being dropped. Code
003360 ** is generated to remove entries from sqlite_schema and/or
003361 ** sqlite_temp_schema if required.
003362 */
003363 pTrigger = sqlite3TriggerList(pParse, pTab);
003364 while( pTrigger ){
003365 assert( pTrigger->pSchema==pTab->pSchema ||
003366 pTrigger->pSchema==db->aDb[1].pSchema );
003367 sqlite3DropTriggerPtr(pParse, pTrigger);
003368 pTrigger = pTrigger->pNext;
003369 }
003370
003371 #ifndef SQLITE_OMIT_AUTOINCREMENT
003372 /* Remove any entries of the sqlite_sequence table associated with
003373 ** the table being dropped. This is done before the table is dropped
003374 ** at the btree level, in case the sqlite_sequence table needs to
003375 ** move as a result of the drop (can happen in auto-vacuum mode).
003376 */
003377 if( pTab->tabFlags & TF_Autoincrement ){
003378 sqlite3NestedParse(pParse,
003379 "DELETE FROM %Q.sqlite_sequence WHERE name=%Q",
003380 pDb->zDbSName, pTab->zName
003381 );
003382 }
003383 #endif
003384
003385 /* Drop all entries in the schema table that refer to the
003386 ** table. The program name loops through the schema table and deletes
003387 ** every row that refers to a table of the same name as the one being
003388 ** dropped. Triggers are handled separately because a trigger can be
003389 ** created in the temp database that refers to a table in another
003390 ** database.
003391 */
003392 sqlite3NestedParse(pParse,
003393 "DELETE FROM %Q." LEGACY_SCHEMA_TABLE
003394 " WHERE tbl_name=%Q and type!='trigger'",
003395 pDb->zDbSName, pTab->zName);
003396 if( !isView && !IsVirtual(pTab) ){
003397 destroyTable(pParse, pTab);
003398 }
003399
003400 /* Remove the table entry from SQLite's internal schema and modify
003401 ** the schema cookie.
003402 */
003403 if( IsVirtual(pTab) ){
003404 sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
003405 sqlite3MayAbort(pParse);
003406 }
003407 sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
003408 sqlite3ChangeCookie(pParse, iDb);
003409 sqliteViewResetAll(db, iDb);
003410 }
003411
003412 /*
003413 ** Return TRUE if shadow tables should be read-only in the current
003414 ** context.
003415 */
003416 int sqlite3ReadOnlyShadowTables(sqlite3 *db){
003417 #ifndef SQLITE_OMIT_VIRTUALTABLE
003418 if( (db->flags & SQLITE_Defensive)!=0
003419 && db->pVtabCtx==0
003420 && db->nVdbeExec==0
003421 && !sqlite3VtabInSync(db)
003422 ){
003423 return 1;
003424 }
003425 #endif
003426 return 0;
003427 }
003428
003429 /*
003430 ** Return true if it is not allowed to drop the given table
003431 */
003432 static int tableMayNotBeDropped(sqlite3 *db, Table *pTab){
003433 if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
003434 if( sqlite3StrNICmp(pTab->zName+7, "stat", 4)==0 ) return 0;
003435 if( sqlite3StrNICmp(pTab->zName+7, "parameters", 10)==0 ) return 0;
003436 return 1;
003437 }
003438 if( (pTab->tabFlags & TF_Shadow)!=0 && sqlite3ReadOnlyShadowTables(db) ){
003439 return 1;
003440 }
003441 if( pTab->tabFlags & TF_Eponymous ){
003442 return 1;
003443 }
003444 return 0;
003445 }
003446
003447 /*
003448 ** This routine is called to do the work of a DROP TABLE statement.
003449 ** pName is the name of the table to be dropped.
003450 */
003451 void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
003452 Table *pTab;
003453 Vdbe *v;
003454 sqlite3 *db = pParse->db;
003455 int iDb;
003456
003457 if( db->mallocFailed ){
003458 goto exit_drop_table;
003459 }
003460 assert( pParse->nErr==0 );
003461 assert( pName->nSrc==1 );
003462 assert( pName->a[0].fg.fixedSchema==0 );
003463 assert( pName->a[0].fg.isSubquery==0 );
003464 if( sqlite3ReadSchema(pParse) ) goto exit_drop_table;
003465 if( noErr ) db->suppressErr++;
003466 assert( isView==0 || isView==LOCATE_VIEW );
003467 pTab = sqlite3LocateTableItem(pParse, isView, &pName->a[0]);
003468 if( noErr ) db->suppressErr--;
003469
003470 if( pTab==0 ){
003471 if( noErr ){
003472 sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].u4.zDatabase);
003473 sqlite3ForceNotReadOnly(pParse);
003474 }
003475 goto exit_drop_table;
003476 }
003477 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
003478 assert( iDb>=0 && iDb<db->nDb );
003479
003480 /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
003481 ** it is initialized.
003482 */
003483 if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){
003484 goto exit_drop_table;
003485 }
003486 #ifndef SQLITE_OMIT_AUTHORIZATION
003487 {
003488 int code;
003489 const char *zTab = SCHEMA_TABLE(iDb);
003490 const char *zDb = db->aDb[iDb].zDbSName;
003491 const char *zArg2 = 0;
003492 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
003493 goto exit_drop_table;
003494 }
003495 if( isView ){
003496 if( !OMIT_TEMPDB && iDb==1 ){
003497 code = SQLITE_DROP_TEMP_VIEW;
003498 }else{
003499 code = SQLITE_DROP_VIEW;
003500 }
003501 #ifndef SQLITE_OMIT_VIRTUALTABLE
003502 }else if( IsVirtual(pTab) ){
003503 code = SQLITE_DROP_VTABLE;
003504 zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName;
003505 #endif
003506 }else{
003507 if( !OMIT_TEMPDB && iDb==1 ){
003508 code = SQLITE_DROP_TEMP_TABLE;
003509 }else{
003510 code = SQLITE_DROP_TABLE;
003511 }
003512 }
003513 if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
003514 goto exit_drop_table;
003515 }
003516 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
003517 goto exit_drop_table;
003518 }
003519 }
003520 #endif
003521 if( tableMayNotBeDropped(db, pTab) ){
003522 sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
003523 goto exit_drop_table;
003524 }
003525
003526 #ifndef SQLITE_OMIT_VIEW
003527 /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
003528 ** on a table.
003529 */
003530 if( isView && !IsView(pTab) ){
003531 sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
003532 goto exit_drop_table;
003533 }
003534 if( !isView && IsView(pTab) ){
003535 sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
003536 goto exit_drop_table;
003537 }
003538 #endif
003539
003540 /* Generate code to remove the table from the schema table
003541 ** on disk.
003542 */
003543 v = sqlite3GetVdbe(pParse);
003544 if( v ){
003545 sqlite3BeginWriteOperation(pParse, 1, iDb);
003546 if( !isView ){
003547 sqlite3ClearStatTables(pParse, iDb, "tbl", pTab->zName);
003548 sqlite3FkDropTable(pParse, pName, pTab);
003549 }
003550 sqlite3CodeDropTable(pParse, pTab, iDb, isView);
003551 }
003552
003553 exit_drop_table:
003554 sqlite3SrcListDelete(db, pName);
003555 }
003556
003557 /*
003558 ** This routine is called to create a new foreign key on the table
003559 ** currently under construction. pFromCol determines which columns
003560 ** in the current table point to the foreign key. If pFromCol==0 then
003561 ** connect the key to the last column inserted. pTo is the name of
003562 ** the table referred to (a.k.a the "parent" table). pToCol is a list
003563 ** of tables in the parent pTo table. flags contains all
003564 ** information about the conflict resolution algorithms specified
003565 ** in the ON DELETE, ON UPDATE and ON INSERT clauses.
003566 **
003567 ** An FKey structure is created and added to the table currently
003568 ** under construction in the pParse->pNewTable field.
003569 **
003570 ** The foreign key is set for IMMEDIATE processing. A subsequent call
003571 ** to sqlite3DeferForeignKey() might change this to DEFERRED.
003572 */
003573 void sqlite3CreateForeignKey(
003574 Parse *pParse, /* Parsing context */
003575 ExprList *pFromCol, /* Columns in this table that point to other table */
003576 Token *pTo, /* Name of the other table */
003577 ExprList *pToCol, /* Columns in the other table */
003578 int flags /* Conflict resolution algorithms. */
003579 ){
003580 sqlite3 *db = pParse->db;
003581 #ifndef SQLITE_OMIT_FOREIGN_KEY
003582 FKey *pFKey = 0;
003583 FKey *pNextTo;
003584 Table *p = pParse->pNewTable;
003585 i64 nByte;
003586 int i;
003587 int nCol;
003588 char *z;
003589
003590 assert( pTo!=0 );
003591 if( p==0 || IN_DECLARE_VTAB ) goto fk_end;
003592 if( pFromCol==0 ){
003593 int iCol = p->nCol-1;
003594 if( NEVER(iCol<0) ) goto fk_end;
003595 if( pToCol && pToCol->nExpr!=1 ){
003596 sqlite3ErrorMsg(pParse, "foreign key on %s"
003597 " should reference only one column of table %T",
003598 p->aCol[iCol].zCnName, pTo);
003599 goto fk_end;
003600 }
003601 nCol = 1;
003602 }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
003603 sqlite3ErrorMsg(pParse,
003604 "number of columns in foreign key does not match the number of "
003605 "columns in the referenced table");
003606 goto fk_end;
003607 }else{
003608 nCol = pFromCol->nExpr;
003609 }
003610 nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1;
003611 if( pToCol ){
003612 for(i=0; i<pToCol->nExpr; i++){
003613 nByte += sqlite3Strlen30(pToCol->a[i].zEName) + 1;
003614 }
003615 }
003616 pFKey = sqlite3DbMallocZero(db, nByte );
003617 if( pFKey==0 ){
003618 goto fk_end;
003619 }
003620 pFKey->pFrom = p;
003621 assert( IsOrdinaryTable(p) );
003622 pFKey->pNextFrom = p->u.tab.pFKey;
003623 z = (char*)&pFKey->aCol[nCol];
003624 pFKey->zTo = z;
003625 if( IN_RENAME_OBJECT ){
003626 sqlite3RenameTokenMap(pParse, (void*)z, pTo);
003627 }
003628 memcpy(z, pTo->z, pTo->n);
003629 z[pTo->n] = 0;
003630 sqlite3Dequote(z);
003631 z += pTo->n+1;
003632 pFKey->nCol = nCol;
003633 if( pFromCol==0 ){
003634 pFKey->aCol[0].iFrom = p->nCol-1;
003635 }else{
003636 for(i=0; i<nCol; i++){
003637 int j;
003638 for(j=0; j<p->nCol; j++){
003639 if( sqlite3StrICmp(p->aCol[j].zCnName, pFromCol->a[i].zEName)==0 ){
003640 pFKey->aCol[i].iFrom = j;
003641 break;
003642 }
003643 }
003644 if( j>=p->nCol ){
003645 sqlite3ErrorMsg(pParse,
003646 "unknown column \"%s\" in foreign key definition",
003647 pFromCol->a[i].zEName);
003648 goto fk_end;
003649 }
003650 if( IN_RENAME_OBJECT ){
003651 sqlite3RenameTokenRemap(pParse, &pFKey->aCol[i], pFromCol->a[i].zEName);
003652 }
003653 }
003654 }
003655 if( pToCol ){
003656 for(i=0; i<nCol; i++){
003657 int n = sqlite3Strlen30(pToCol->a[i].zEName);
003658 pFKey->aCol[i].zCol = z;
003659 if( IN_RENAME_OBJECT ){
003660 sqlite3RenameTokenRemap(pParse, z, pToCol->a[i].zEName);
003661 }
003662 memcpy(z, pToCol->a[i].zEName, n);
003663 z[n] = 0;
003664 z += n+1;
003665 }
003666 }
003667 pFKey->isDeferred = 0;
003668 pFKey->aAction[0] = (u8)(flags & 0xff); /* ON DELETE action */
003669 pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff); /* ON UPDATE action */
003670
003671 assert( sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
003672 pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash,
003673 pFKey->zTo, (void *)pFKey
003674 );
003675 if( pNextTo==pFKey ){
003676 sqlite3OomFault(db);
003677 goto fk_end;
003678 }
003679 if( pNextTo ){
003680 assert( pNextTo->pPrevTo==0 );
003681 pFKey->pNextTo = pNextTo;
003682 pNextTo->pPrevTo = pFKey;
003683 }
003684
003685 /* Link the foreign key to the table as the last step.
003686 */
003687 assert( IsOrdinaryTable(p) );
003688 p->u.tab.pFKey = pFKey;
003689 pFKey = 0;
003690
003691 fk_end:
003692 sqlite3DbFree(db, pFKey);
003693 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
003694 sqlite3ExprListDelete(db, pFromCol);
003695 sqlite3ExprListDelete(db, pToCol);
003696 }
003697
003698 /*
003699 ** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
003700 ** clause is seen as part of a foreign key definition. The isDeferred
003701 ** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
003702 ** The behavior of the most recently created foreign key is adjusted
003703 ** accordingly.
003704 */
003705 void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
003706 #ifndef SQLITE_OMIT_FOREIGN_KEY
003707 Table *pTab;
003708 FKey *pFKey;
003709 if( (pTab = pParse->pNewTable)==0 ) return;
003710 if( NEVER(!IsOrdinaryTable(pTab)) ) return;
003711 if( (pFKey = pTab->u.tab.pFKey)==0 ) return;
003712 assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */
003713 pFKey->isDeferred = (u8)isDeferred;
003714 #endif
003715 }
003716
003717 /*
003718 ** Generate code that will erase and refill index *pIdx. This is
003719 ** used to initialize a newly created index or to recompute the
003720 ** content of an index in response to a REINDEX command.
003721 **
003722 ** if memRootPage is not negative, it means that the index is newly
003723 ** created. The register specified by memRootPage contains the
003724 ** root page number of the index. If memRootPage is negative, then
003725 ** the index already exists and must be cleared before being refilled and
003726 ** the root page number of the index is taken from pIndex->tnum.
003727 */
003728 static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
003729 Table *pTab = pIndex->pTable; /* The table that is indexed */
003730 int iTab = pParse->nTab++; /* Btree cursor used for pTab */
003731 int iIdx = pParse->nTab++; /* Btree cursor used for pIndex */
003732 int iSorter; /* Cursor opened by OpenSorter (if in use) */
003733 int addr1; /* Address of top of loop */
003734 int addr2; /* Address to jump to for next iteration */
003735 Pgno tnum; /* Root page of index */
003736 int iPartIdxLabel; /* Jump to this label to skip a row */
003737 Vdbe *v; /* Generate code into this virtual machine */
003738 KeyInfo *pKey; /* KeyInfo for index */
003739 int regRecord; /* Register holding assembled index record */
003740 sqlite3 *db = pParse->db; /* The database connection */
003741 int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
003742
003743 #ifndef SQLITE_OMIT_AUTHORIZATION
003744 if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
003745 db->aDb[iDb].zDbSName ) ){
003746 return;
003747 }
003748 #endif
003749
003750 /* Require a write-lock on the table to perform this operation */
003751 sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
003752
003753 v = sqlite3GetVdbe(pParse);
003754 if( v==0 ) return;
003755 if( memRootPage>=0 ){
003756 tnum = (Pgno)memRootPage;
003757 }else{
003758 tnum = pIndex->tnum;
003759 }
003760 pKey = sqlite3KeyInfoOfIndex(pParse, pIndex);
003761 assert( pKey!=0 || pParse->nErr );
003762
003763 /* Open the sorter cursor if we are to use one. */
003764 iSorter = pParse->nTab++;
003765 sqlite3VdbeAddOp4(v, OP_SorterOpen, iSorter, 0, pIndex->nKeyCol, (char*)
003766 sqlite3KeyInfoRef(pKey), P4_KEYINFO);
003767
003768 /* Open the table. Loop through all rows of the table, inserting index
003769 ** records into the sorter. */
003770 sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
003771 addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0); VdbeCoverage(v);
003772 regRecord = sqlite3GetTempReg(pParse);
003773 sqlite3MultiWrite(pParse);
003774
003775 sqlite3GenerateIndexKey(pParse,pIndex,iTab,regRecord,0,&iPartIdxLabel,0,0);
003776 sqlite3VdbeAddOp2(v, OP_SorterInsert, iSorter, regRecord);
003777 sqlite3ResolvePartIdxLabel(pParse, iPartIdxLabel);
003778 sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1); VdbeCoverage(v);
003779 sqlite3VdbeJumpHere(v, addr1);
003780 if( memRootPage<0 ) sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
003781 sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, (int)tnum, iDb,
003782 (char *)pKey, P4_KEYINFO);
003783 sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR|((memRootPage>=0)?OPFLAG_P2ISREG:0));
003784
003785 addr1 = sqlite3VdbeAddOp2(v, OP_SorterSort, iSorter, 0); VdbeCoverage(v);
003786 if( IsUniqueIndex(pIndex) ){
003787 int j2 = sqlite3VdbeGoto(v, 1);
003788 addr2 = sqlite3VdbeCurrentAddr(v);
003789 sqlite3VdbeVerifyAbortable(v, OE_Abort);
003790 sqlite3VdbeAddOp4Int(v, OP_SorterCompare, iSorter, j2, regRecord,
003791 pIndex->nKeyCol); VdbeCoverage(v);
003792 sqlite3UniqueConstraint(pParse, OE_Abort, pIndex);
003793 sqlite3VdbeJumpHere(v, j2);
003794 }else{
003795 /* Most CREATE INDEX and REINDEX statements that are not UNIQUE can not
003796 ** abort. The exception is if one of the indexed expressions contains a
003797 ** user function that throws an exception when it is evaluated. But the
003798 ** overhead of adding a statement journal to a CREATE INDEX statement is
003799 ** very small (since most of the pages written do not contain content that
003800 ** needs to be restored if the statement aborts), so we call
003801 ** sqlite3MayAbort() for all CREATE INDEX statements. */
003802 sqlite3MayAbort(pParse);
003803 addr2 = sqlite3VdbeCurrentAddr(v);
003804 }
003805 sqlite3VdbeAddOp3(v, OP_SorterData, iSorter, regRecord, iIdx);
003806 if( !pIndex->bAscKeyBug ){
003807 /* This OP_SeekEnd opcode makes index insert for a REINDEX go much
003808 ** faster by avoiding unnecessary seeks. But the optimization does
003809 ** not work for UNIQUE constraint indexes on WITHOUT ROWID tables
003810 ** with DESC primary keys, since those indexes have there keys in
003811 ** a different order from the main table.
003812 ** See ticket: https://www.sqlite.org/src/info/bba7b69f9849b5bf
003813 */
003814 sqlite3VdbeAddOp1(v, OP_SeekEnd, iIdx);
003815 }
003816 sqlite3VdbeAddOp2(v, OP_IdxInsert, iIdx, regRecord);
003817 sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
003818 sqlite3ReleaseTempReg(pParse, regRecord);
003819 sqlite3VdbeAddOp2(v, OP_SorterNext, iSorter, addr2); VdbeCoverage(v);
003820 sqlite3VdbeJumpHere(v, addr1);
003821
003822 sqlite3VdbeAddOp1(v, OP_Close, iTab);
003823 sqlite3VdbeAddOp1(v, OP_Close, iIdx);
003824 sqlite3VdbeAddOp1(v, OP_Close, iSorter);
003825 }
003826
003827 /*
003828 ** Allocate heap space to hold an Index object with nCol columns.
003829 **
003830 ** Increase the allocation size to provide an extra nExtra bytes
003831 ** of 8-byte aligned space after the Index object and return a
003832 ** pointer to this extra space in *ppExtra.
003833 */
003834 Index *sqlite3AllocateIndexObject(
003835 sqlite3 *db, /* Database connection */
003836 i16 nCol, /* Total number of columns in the index */
003837 int nExtra, /* Number of bytes of extra space to alloc */
003838 char **ppExtra /* Pointer to the "extra" space */
003839 ){
003840 Index *p; /* Allocated index object */
003841 int nByte; /* Bytes of space for Index object + arrays */
003842
003843 nByte = ROUND8(sizeof(Index)) + /* Index structure */
003844 ROUND8(sizeof(char*)*nCol) + /* Index.azColl */
003845 ROUND8(sizeof(LogEst)*(nCol+1) + /* Index.aiRowLogEst */
003846 sizeof(i16)*nCol + /* Index.aiColumn */
003847 sizeof(u8)*nCol); /* Index.aSortOrder */
003848 p = sqlite3DbMallocZero(db, nByte + nExtra);
003849 if( p ){
003850 char *pExtra = ((char*)p)+ROUND8(sizeof(Index));
003851 p->azColl = (const char**)pExtra; pExtra += ROUND8(sizeof(char*)*nCol);
003852 p->aiRowLogEst = (LogEst*)pExtra; pExtra += sizeof(LogEst)*(nCol+1);
003853 p->aiColumn = (i16*)pExtra; pExtra += sizeof(i16)*nCol;
003854 p->aSortOrder = (u8*)pExtra;
003855 p->nColumn = nCol;
003856 p->nKeyCol = nCol - 1;
003857 *ppExtra = ((char*)p) + nByte;
003858 }
003859 return p;
003860 }
003861
003862 /*
003863 ** If expression list pList contains an expression that was parsed with
003864 ** an explicit "NULLS FIRST" or "NULLS LAST" clause, leave an error in
003865 ** pParse and return non-zero. Otherwise, return zero.
003866 */
003867 int sqlite3HasExplicitNulls(Parse *pParse, ExprList *pList){
003868 if( pList ){
003869 int i;
003870 for(i=0; i<pList->nExpr; i++){
003871 if( pList->a[i].fg.bNulls ){
003872 u8 sf = pList->a[i].fg.sortFlags;
003873 sqlite3ErrorMsg(pParse, "unsupported use of NULLS %s",
003874 (sf==0 || sf==3) ? "FIRST" : "LAST"
003875 );
003876 return 1;
003877 }
003878 }
003879 }
003880 return 0;
003881 }
003882
003883 /*
003884 ** Create a new index for an SQL table. pName1.pName2 is the name of the index
003885 ** and pTblList is the name of the table that is to be indexed. Both will
003886 ** be NULL for a primary key or an index that is created to satisfy a
003887 ** UNIQUE constraint. If pTable and pIndex are NULL, use pParse->pNewTable
003888 ** as the table to be indexed. pParse->pNewTable is a table that is
003889 ** currently being constructed by a CREATE TABLE statement.
003890 **
003891 ** pList is a list of columns to be indexed. pList will be NULL if this
003892 ** is a primary key or unique-constraint on the most recent column added
003893 ** to the table currently under construction.
003894 */
003895 void sqlite3CreateIndex(
003896 Parse *pParse, /* All information about this parse */
003897 Token *pName1, /* First part of index name. May be NULL */
003898 Token *pName2, /* Second part of index name. May be NULL */
003899 SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
003900 ExprList *pList, /* A list of columns to be indexed */
003901 int onError, /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
003902 Token *pStart, /* The CREATE token that begins this statement */
003903 Expr *pPIWhere, /* WHERE clause for partial indices */
003904 int sortOrder, /* Sort order of primary key when pList==NULL */
003905 int ifNotExist, /* Omit error if index already exists */
003906 u8 idxType /* The index type */
003907 ){
003908 Table *pTab = 0; /* Table to be indexed */
003909 Index *pIndex = 0; /* The index to be created */
003910 char *zName = 0; /* Name of the index */
003911 int nName; /* Number of characters in zName */
003912 int i, j;
003913 DbFixer sFix; /* For assigning database names to pTable */
003914 int sortOrderMask; /* 1 to honor DESC in index. 0 to ignore. */
003915 sqlite3 *db = pParse->db;
003916 Db *pDb; /* The specific table containing the indexed database */
003917 int iDb; /* Index of the database that is being written */
003918 Token *pName = 0; /* Unqualified name of the index to create */
003919 struct ExprList_item *pListItem; /* For looping over pList */
003920 int nExtra = 0; /* Space allocated for zExtra[] */
003921 int nExtraCol; /* Number of extra columns needed */
003922 char *zExtra = 0; /* Extra space after the Index object */
003923 Index *pPk = 0; /* PRIMARY KEY index for WITHOUT ROWID tables */
003924
003925 assert( db->pParse==pParse );
003926 if( pParse->nErr ){
003927 goto exit_create_index;
003928 }
003929 assert( db->mallocFailed==0 );
003930 if( IN_DECLARE_VTAB && idxType!=SQLITE_IDXTYPE_PRIMARYKEY ){
003931 goto exit_create_index;
003932 }
003933 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
003934 goto exit_create_index;
003935 }
003936 if( sqlite3HasExplicitNulls(pParse, pList) ){
003937 goto exit_create_index;
003938 }
003939
003940 /*
003941 ** Find the table that is to be indexed. Return early if not found.
003942 */
003943 if( pTblName!=0 ){
003944
003945 /* Use the two-part index name to determine the database
003946 ** to search for the table. 'Fix' the table name to this db
003947 ** before looking up the table.
003948 */
003949 assert( pName1 && pName2 );
003950 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
003951 if( iDb<0 ) goto exit_create_index;
003952 assert( pName && pName->z );
003953
003954 #ifndef SQLITE_OMIT_TEMPDB
003955 /* If the index name was unqualified, check if the table
003956 ** is a temp table. If so, set the database to 1. Do not do this
003957 ** if initializing a database schema.
003958 */
003959 if( !db->init.busy ){
003960 pTab = sqlite3SrcListLookup(pParse, pTblName);
003961 if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
003962 iDb = 1;
003963 }
003964 }
003965 #endif
003966
003967 sqlite3FixInit(&sFix, pParse, iDb, "index", pName);
003968 if( sqlite3FixSrcList(&sFix, pTblName) ){
003969 /* Because the parser constructs pTblName from a single identifier,
003970 ** sqlite3FixSrcList can never fail. */
003971 assert(0);
003972 }
003973 pTab = sqlite3LocateTableItem(pParse, 0, &pTblName->a[0]);
003974 assert( db->mallocFailed==0 || pTab==0 );
003975 if( pTab==0 ) goto exit_create_index;
003976 if( iDb==1 && db->aDb[iDb].pSchema!=pTab->pSchema ){
003977 sqlite3ErrorMsg(pParse,
003978 "cannot create a TEMP index on non-TEMP table \"%s\"",
003979 pTab->zName);
003980 goto exit_create_index;
003981 }
003982 if( !HasRowid(pTab) ) pPk = sqlite3PrimaryKeyIndex(pTab);
003983 }else{
003984 assert( pName==0 );
003985 assert( pStart==0 );
003986 pTab = pParse->pNewTable;
003987 if( !pTab ) goto exit_create_index;
003988 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
003989 }
003990 pDb = &db->aDb[iDb];
003991
003992 assert( pTab!=0 );
003993 if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
003994 && db->init.busy==0
003995 && pTblName!=0
003996 ){
003997 sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
003998 goto exit_create_index;
003999 }
004000 #ifndef SQLITE_OMIT_VIEW
004001 if( IsView(pTab) ){
004002 sqlite3ErrorMsg(pParse, "views may not be indexed");
004003 goto exit_create_index;
004004 }
004005 #endif
004006 #ifndef SQLITE_OMIT_VIRTUALTABLE
004007 if( IsVirtual(pTab) ){
004008 sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
004009 goto exit_create_index;
004010 }
004011 #endif
004012
004013 /*
004014 ** Find the name of the index. Make sure there is not already another
004015 ** index or table with the same name.
004016 **
004017 ** Exception: If we are reading the names of permanent indices from the
004018 ** sqlite_schema table (because some other process changed the schema) and
004019 ** one of the index names collides with the name of a temporary table or
004020 ** index, then we will continue to process this index.
004021 **
004022 ** If pName==0 it means that we are
004023 ** dealing with a primary key or UNIQUE constraint. We have to invent our
004024 ** own name.
004025 */
004026 if( pName ){
004027 zName = sqlite3NameFromToken(db, pName);
004028 if( zName==0 ) goto exit_create_index;
004029 assert( pName->z!=0 );
004030 if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName,"index",pTab->zName) ){
004031 goto exit_create_index;
004032 }
004033 if( !IN_RENAME_OBJECT ){
004034 if( !db->init.busy ){
004035 if( sqlite3FindTable(db, zName, pDb->zDbSName)!=0 ){
004036 sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
004037 goto exit_create_index;
004038 }
004039 }
004040 if( sqlite3FindIndex(db, zName, pDb->zDbSName)!=0 ){
004041 if( !ifNotExist ){
004042 sqlite3ErrorMsg(pParse, "index %s already exists", zName);
004043 }else{
004044 assert( !db->init.busy );
004045 sqlite3CodeVerifySchema(pParse, iDb);
004046 sqlite3ForceNotReadOnly(pParse);
004047 }
004048 goto exit_create_index;
004049 }
004050 }
004051 }else{
004052 int n;
004053 Index *pLoop;
004054 for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
004055 zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n);
004056 if( zName==0 ){
004057 goto exit_create_index;
004058 }
004059
004060 /* Automatic index names generated from within sqlite3_declare_vtab()
004061 ** must have names that are distinct from normal automatic index names.
004062 ** The following statement converts "sqlite3_autoindex..." into
004063 ** "sqlite3_butoindex..." in order to make the names distinct.
004064 ** The "vtab_err.test" test demonstrates the need of this statement. */
004065 if( IN_SPECIAL_PARSE ) zName[7]++;
004066 }
004067
004068 /* Check for authorization to create an index.
004069 */
004070 #ifndef SQLITE_OMIT_AUTHORIZATION
004071 if( !IN_RENAME_OBJECT ){
004072 const char *zDb = pDb->zDbSName;
004073 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
004074 goto exit_create_index;
004075 }
004076 i = SQLITE_CREATE_INDEX;
004077 if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
004078 if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
004079 goto exit_create_index;
004080 }
004081 }
004082 #endif
004083
004084 /* If pList==0, it means this routine was called to make a primary
004085 ** key out of the last column added to the table under construction.
004086 ** So create a fake list to simulate this.
004087 */
004088 if( pList==0 ){
004089 Token prevCol;
004090 Column *pCol = &pTab->aCol[pTab->nCol-1];
004091 pCol->colFlags |= COLFLAG_UNIQUE;
004092 sqlite3TokenInit(&prevCol, pCol->zCnName);
004093 pList = sqlite3ExprListAppend(pParse, 0,
004094 sqlite3ExprAlloc(db, TK_ID, &prevCol, 0));
004095 if( pList==0 ) goto exit_create_index;
004096 assert( pList->nExpr==1 );
004097 sqlite3ExprListSetSortOrder(pList, sortOrder, SQLITE_SO_UNDEFINED);
004098 }else{
004099 sqlite3ExprListCheckLength(pParse, pList, "index");
004100 if( pParse->nErr ) goto exit_create_index;
004101 }
004102
004103 /* Figure out how many bytes of space are required to store explicitly
004104 ** specified collation sequence names.
004105 */
004106 for(i=0; i<pList->nExpr; i++){
004107 Expr *pExpr = pList->a[i].pExpr;
004108 assert( pExpr!=0 );
004109 if( pExpr->op==TK_COLLATE ){
004110 assert( !ExprHasProperty(pExpr, EP_IntValue) );
004111 nExtra += (1 + sqlite3Strlen30(pExpr->u.zToken));
004112 }
004113 }
004114
004115 /*
004116 ** Allocate the index structure.
004117 */
004118 nName = sqlite3Strlen30(zName);
004119 nExtraCol = pPk ? pPk->nKeyCol : 1;
004120 assert( pList->nExpr + nExtraCol <= 32767 /* Fits in i16 */ );
004121 pIndex = sqlite3AllocateIndexObject(db, pList->nExpr + nExtraCol,
004122 nName + nExtra + 1, &zExtra);
004123 if( db->mallocFailed ){
004124 goto exit_create_index;
004125 }
004126 assert( EIGHT_BYTE_ALIGNMENT(pIndex->aiRowLogEst) );
004127 assert( EIGHT_BYTE_ALIGNMENT(pIndex->azColl) );
004128 pIndex->zName = zExtra;
004129 zExtra += nName + 1;
004130 memcpy(pIndex->zName, zName, nName+1);
004131 pIndex->pTable = pTab;
004132 pIndex->onError = (u8)onError;
004133 pIndex->uniqNotNull = onError!=OE_None;
004134 pIndex->idxType = idxType;
004135 pIndex->pSchema = db->aDb[iDb].pSchema;
004136 pIndex->nKeyCol = pList->nExpr;
004137 if( pPIWhere ){
004138 sqlite3ResolveSelfReference(pParse, pTab, NC_PartIdx, pPIWhere, 0);
004139 pIndex->pPartIdxWhere = pPIWhere;
004140 pPIWhere = 0;
004141 }
004142 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
004143
004144 /* Check to see if we should honor DESC requests on index columns
004145 */
004146 if( pDb->pSchema->file_format>=4 ){
004147 sortOrderMask = -1; /* Honor DESC */
004148 }else{
004149 sortOrderMask = 0; /* Ignore DESC */
004150 }
004151
004152 /* Analyze the list of expressions that form the terms of the index and
004153 ** report any errors. In the common case where the expression is exactly
004154 ** a table column, store that column in aiColumn[]. For general expressions,
004155 ** populate pIndex->aColExpr and store XN_EXPR (-2) in aiColumn[].
004156 **
004157 ** TODO: Issue a warning if two or more columns of the index are identical.
004158 ** TODO: Issue a warning if the table primary key is used as part of the
004159 ** index key.
004160 */
004161 pListItem = pList->a;
004162 if( IN_RENAME_OBJECT ){
004163 pIndex->aColExpr = pList;
004164 pList = 0;
004165 }
004166 for(i=0; i<pIndex->nKeyCol; i++, pListItem++){
004167 Expr *pCExpr; /* The i-th index expression */
004168 int requestedSortOrder; /* ASC or DESC on the i-th expression */
004169 const char *zColl; /* Collation sequence name */
004170
004171 sqlite3StringToId(pListItem->pExpr);
004172 sqlite3ResolveSelfReference(pParse, pTab, NC_IdxExpr, pListItem->pExpr, 0);
004173 if( pParse->nErr ) goto exit_create_index;
004174 pCExpr = sqlite3ExprSkipCollate(pListItem->pExpr);
004175 if( pCExpr->op!=TK_COLUMN ){
004176 if( pTab==pParse->pNewTable ){
004177 sqlite3ErrorMsg(pParse, "expressions prohibited in PRIMARY KEY and "
004178 "UNIQUE constraints");
004179 goto exit_create_index;
004180 }
004181 if( pIndex->aColExpr==0 ){
004182 pIndex->aColExpr = pList;
004183 pList = 0;
004184 }
004185 j = XN_EXPR;
004186 pIndex->aiColumn[i] = XN_EXPR;
004187 pIndex->uniqNotNull = 0;
004188 pIndex->bHasExpr = 1;
004189 }else{
004190 j = pCExpr->iColumn;
004191 assert( j<=0x7fff );
004192 if( j<0 ){
004193 j = pTab->iPKey;
004194 }else{
004195 if( pTab->aCol[j].notNull==0 ){
004196 pIndex->uniqNotNull = 0;
004197 }
004198 if( pTab->aCol[j].colFlags & COLFLAG_VIRTUAL ){
004199 pIndex->bHasVCol = 1;
004200 pIndex->bHasExpr = 1;
004201 }
004202 }
004203 pIndex->aiColumn[i] = (i16)j;
004204 }
004205 zColl = 0;
004206 if( pListItem->pExpr->op==TK_COLLATE ){
004207 int nColl;
004208 assert( !ExprHasProperty(pListItem->pExpr, EP_IntValue) );
004209 zColl = pListItem->pExpr->u.zToken;
004210 nColl = sqlite3Strlen30(zColl) + 1;
004211 assert( nExtra>=nColl );
004212 memcpy(zExtra, zColl, nColl);
004213 zColl = zExtra;
004214 zExtra += nColl;
004215 nExtra -= nColl;
004216 }else if( j>=0 ){
004217 zColl = sqlite3ColumnColl(&pTab->aCol[j]);
004218 }
004219 if( !zColl ) zColl = sqlite3StrBINARY;
004220 if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){
004221 goto exit_create_index;
004222 }
004223 pIndex->azColl[i] = zColl;
004224 requestedSortOrder = pListItem->fg.sortFlags & sortOrderMask;
004225 pIndex->aSortOrder[i] = (u8)requestedSortOrder;
004226 }
004227
004228 /* Append the table key to the end of the index. For WITHOUT ROWID
004229 ** tables (when pPk!=0) this will be the declared PRIMARY KEY. For
004230 ** normal tables (when pPk==0) this will be the rowid.
004231 */
004232 if( pPk ){
004233 for(j=0; j<pPk->nKeyCol; j++){
004234 int x = pPk->aiColumn[j];
004235 assert( x>=0 );
004236 if( isDupColumn(pIndex, pIndex->nKeyCol, pPk, j) ){
004237 pIndex->nColumn--;
004238 }else{
004239 testcase( hasColumn(pIndex->aiColumn,pIndex->nKeyCol,x) );
004240 pIndex->aiColumn[i] = x;
004241 pIndex->azColl[i] = pPk->azColl[j];
004242 pIndex->aSortOrder[i] = pPk->aSortOrder[j];
004243 i++;
004244 }
004245 }
004246 assert( i==pIndex->nColumn );
004247 }else{
004248 pIndex->aiColumn[i] = XN_ROWID;
004249 pIndex->azColl[i] = sqlite3StrBINARY;
004250 }
004251 sqlite3DefaultRowEst(pIndex);
004252 if( pParse->pNewTable==0 ) estimateIndexWidth(pIndex);
004253
004254 /* If this index contains every column of its table, then mark
004255 ** it as a covering index */
004256 assert( HasRowid(pTab)
004257 || pTab->iPKey<0 || sqlite3TableColumnToIndex(pIndex, pTab->iPKey)>=0 );
004258 recomputeColumnsNotIndexed(pIndex);
004259 if( pTblName!=0 && pIndex->nColumn>=pTab->nCol ){
004260 pIndex->isCovering = 1;
004261 for(j=0; j<pTab->nCol; j++){
004262 if( j==pTab->iPKey ) continue;
004263 if( sqlite3TableColumnToIndex(pIndex,j)>=0 ) continue;
004264 pIndex->isCovering = 0;
004265 break;
004266 }
004267 }
004268
004269 if( pTab==pParse->pNewTable ){
004270 /* This routine has been called to create an automatic index as a
004271 ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
004272 ** a PRIMARY KEY or UNIQUE clause following the column definitions.
004273 ** i.e. one of:
004274 **
004275 ** CREATE TABLE t(x PRIMARY KEY, y);
004276 ** CREATE TABLE t(x, y, UNIQUE(x, y));
004277 **
004278 ** Either way, check to see if the table already has such an index. If
004279 ** so, don't bother creating this one. This only applies to
004280 ** automatically created indices. Users can do as they wish with
004281 ** explicit indices.
004282 **
004283 ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent
004284 ** (and thus suppressing the second one) even if they have different
004285 ** sort orders.
004286 **
004287 ** If there are different collating sequences or if the columns of
004288 ** the constraint occur in different orders, then the constraints are
004289 ** considered distinct and both result in separate indices.
004290 */
004291 Index *pIdx;
004292 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
004293 int k;
004294 assert( IsUniqueIndex(pIdx) );
004295 assert( pIdx->idxType!=SQLITE_IDXTYPE_APPDEF );
004296 assert( IsUniqueIndex(pIndex) );
004297
004298 if( pIdx->nKeyCol!=pIndex->nKeyCol ) continue;
004299 for(k=0; k<pIdx->nKeyCol; k++){
004300 const char *z1;
004301 const char *z2;
004302 assert( pIdx->aiColumn[k]>=0 );
004303 if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
004304 z1 = pIdx->azColl[k];
004305 z2 = pIndex->azColl[k];
004306 if( sqlite3StrICmp(z1, z2) ) break;
004307 }
004308 if( k==pIdx->nKeyCol ){
004309 if( pIdx->onError!=pIndex->onError ){
004310 /* This constraint creates the same index as a previous
004311 ** constraint specified somewhere in the CREATE TABLE statement.
004312 ** However the ON CONFLICT clauses are different. If both this
004313 ** constraint and the previous equivalent constraint have explicit
004314 ** ON CONFLICT clauses this is an error. Otherwise, use the
004315 ** explicitly specified behavior for the index.
004316 */
004317 if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
004318 sqlite3ErrorMsg(pParse,
004319 "conflicting ON CONFLICT clauses specified", 0);
004320 }
004321 if( pIdx->onError==OE_Default ){
004322 pIdx->onError = pIndex->onError;
004323 }
004324 }
004325 if( idxType==SQLITE_IDXTYPE_PRIMARYKEY ) pIdx->idxType = idxType;
004326 if( IN_RENAME_OBJECT ){
004327 pIndex->pNext = pParse->pNewIndex;
004328 pParse->pNewIndex = pIndex;
004329 pIndex = 0;
004330 }
004331 goto exit_create_index;
004332 }
004333 }
004334 }
004335
004336 if( !IN_RENAME_OBJECT ){
004337
004338 /* Link the new Index structure to its table and to the other
004339 ** in-memory database structures.
004340 */
004341 assert( pParse->nErr==0 );
004342 if( db->init.busy ){
004343 Index *p;
004344 assert( !IN_SPECIAL_PARSE );
004345 assert( sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
004346 if( pTblName!=0 ){
004347 pIndex->tnum = db->init.newTnum;
004348 if( sqlite3IndexHasDuplicateRootPage(pIndex) ){
004349 sqlite3ErrorMsg(pParse, "invalid rootpage");
004350 pParse->rc = SQLITE_CORRUPT_BKPT;
004351 goto exit_create_index;
004352 }
004353 }
004354 p = sqlite3HashInsert(&pIndex->pSchema->idxHash,
004355 pIndex->zName, pIndex);
004356 if( p ){
004357 assert( p==pIndex ); /* Malloc must have failed */
004358 sqlite3OomFault(db);
004359 goto exit_create_index;
004360 }
004361 db->mDbFlags |= DBFLAG_SchemaChange;
004362 }
004363
004364 /* If this is the initial CREATE INDEX statement (or CREATE TABLE if the
004365 ** index is an implied index for a UNIQUE or PRIMARY KEY constraint) then
004366 ** emit code to allocate the index rootpage on disk and make an entry for
004367 ** the index in the sqlite_schema table and populate the index with
004368 ** content. But, do not do this if we are simply reading the sqlite_schema
004369 ** table to parse the schema, or if this index is the PRIMARY KEY index
004370 ** of a WITHOUT ROWID table.
004371 **
004372 ** If pTblName==0 it means this index is generated as an implied PRIMARY KEY
004373 ** or UNIQUE index in a CREATE TABLE statement. Since the table
004374 ** has just been created, it contains no data and the index initialization
004375 ** step can be skipped.
004376 */
004377 else if( HasRowid(pTab) || pTblName!=0 ){
004378 Vdbe *v;
004379 char *zStmt;
004380 int iMem = ++pParse->nMem;
004381
004382 v = sqlite3GetVdbe(pParse);
004383 if( v==0 ) goto exit_create_index;
004384
004385 sqlite3BeginWriteOperation(pParse, 1, iDb);
004386
004387 /* Create the rootpage for the index using CreateIndex. But before
004388 ** doing so, code a Noop instruction and store its address in
004389 ** Index.tnum. This is required in case this index is actually a
004390 ** PRIMARY KEY and the table is actually a WITHOUT ROWID table. In
004391 ** that case the convertToWithoutRowidTable() routine will replace
004392 ** the Noop with a Goto to jump over the VDBE code generated below. */
004393 pIndex->tnum = (Pgno)sqlite3VdbeAddOp0(v, OP_Noop);
004394 sqlite3VdbeAddOp3(v, OP_CreateBtree, iDb, iMem, BTREE_BLOBKEY);
004395
004396 /* Gather the complete text of the CREATE INDEX statement into
004397 ** the zStmt variable
004398 */
004399 assert( pName!=0 || pStart==0 );
004400 if( pStart ){
004401 int n = (int)(pParse->sLastToken.z - pName->z) + pParse->sLastToken.n;
004402 if( pName->z[n-1]==';' ) n--;
004403 /* A named index with an explicit CREATE INDEX statement */
004404 zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
004405 onError==OE_None ? "" : " UNIQUE", n, pName->z);
004406 }else{
004407 /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
004408 /* zStmt = sqlite3MPrintf(""); */
004409 zStmt = 0;
004410 }
004411
004412 /* Add an entry in sqlite_schema for this index
004413 */
004414 sqlite3NestedParse(pParse,
004415 "INSERT INTO %Q." LEGACY_SCHEMA_TABLE " VALUES('index',%Q,%Q,#%d,%Q);",
004416 db->aDb[iDb].zDbSName,
004417 pIndex->zName,
004418 pTab->zName,
004419 iMem,
004420 zStmt
004421 );
004422 sqlite3DbFree(db, zStmt);
004423
004424 /* Fill the index with data and reparse the schema. Code an OP_Expire
004425 ** to invalidate all pre-compiled statements.
004426 */
004427 if( pTblName ){
004428 sqlite3RefillIndex(pParse, pIndex, iMem);
004429 sqlite3ChangeCookie(pParse, iDb);
004430 sqlite3VdbeAddParseSchemaOp(v, iDb,
004431 sqlite3MPrintf(db, "name='%q' AND type='index'", pIndex->zName), 0);
004432 sqlite3VdbeAddOp2(v, OP_Expire, 0, 1);
004433 }
004434
004435 sqlite3VdbeJumpHere(v, (int)pIndex->tnum);
004436 }
004437 }
004438 if( db->init.busy || pTblName==0 ){
004439 pIndex->pNext = pTab->pIndex;
004440 pTab->pIndex = pIndex;
004441 pIndex = 0;
004442 }
004443 else if( IN_RENAME_OBJECT ){
004444 assert( pParse->pNewIndex==0 );
004445 pParse->pNewIndex = pIndex;
004446 pIndex = 0;
004447 }
004448
004449 /* Clean up before exiting */
004450 exit_create_index:
004451 if( pIndex ) sqlite3FreeIndex(db, pIndex);
004452 if( pTab ){
004453 /* Ensure all REPLACE indexes on pTab are at the end of the pIndex list.
004454 ** The list was already ordered when this routine was entered, so at this
004455 ** point at most a single index (the newly added index) will be out of
004456 ** order. So we have to reorder at most one index. */
004457 Index **ppFrom;
004458 Index *pThis;
004459 for(ppFrom=&pTab->pIndex; (pThis = *ppFrom)!=0; ppFrom=&pThis->pNext){
004460 Index *pNext;
004461 if( pThis->onError!=OE_Replace ) continue;
004462 while( (pNext = pThis->pNext)!=0 && pNext->onError!=OE_Replace ){
004463 *ppFrom = pNext;
004464 pThis->pNext = pNext->pNext;
004465 pNext->pNext = pThis;
004466 ppFrom = &pNext->pNext;
004467 }
004468 break;
004469 }
004470 #ifdef SQLITE_DEBUG
004471 /* Verify that all REPLACE indexes really are now at the end
004472 ** of the index list. In other words, no other index type ever
004473 ** comes after a REPLACE index on the list. */
004474 for(pThis = pTab->pIndex; pThis; pThis=pThis->pNext){
004475 assert( pThis->onError!=OE_Replace
004476 || pThis->pNext==0
004477 || pThis->pNext->onError==OE_Replace );
004478 }
004479 #endif
004480 }
004481 sqlite3ExprDelete(db, pPIWhere);
004482 sqlite3ExprListDelete(db, pList);
004483 sqlite3SrcListDelete(db, pTblName);
004484 sqlite3DbFree(db, zName);
004485 }
004486
004487 /*
004488 ** Fill the Index.aiRowEst[] array with default information - information
004489 ** to be used when we have not run the ANALYZE command.
004490 **
004491 ** aiRowEst[0] is supposed to contain the number of elements in the index.
004492 ** Since we do not know, guess 1 million. aiRowEst[1] is an estimate of the
004493 ** number of rows in the table that match any particular value of the
004494 ** first column of the index. aiRowEst[2] is an estimate of the number
004495 ** of rows that match any particular combination of the first 2 columns
004496 ** of the index. And so forth. It must always be the case that
004497 *
004498 ** aiRowEst[N]<=aiRowEst[N-1]
004499 ** aiRowEst[N]>=1
004500 **
004501 ** Apart from that, we have little to go on besides intuition as to
004502 ** how aiRowEst[] should be initialized. The numbers generated here
004503 ** are based on typical values found in actual indices.
004504 */
004505 void sqlite3DefaultRowEst(Index *pIdx){
004506 /* 10, 9, 8, 7, 6 */
004507 static const LogEst aVal[] = { 33, 32, 30, 28, 26 };
004508 LogEst *a = pIdx->aiRowLogEst;
004509 LogEst x;
004510 int nCopy = MIN(ArraySize(aVal), pIdx->nKeyCol);
004511 int i;
004512
004513 /* Indexes with default row estimates should not have stat1 data */
004514 assert( !pIdx->hasStat1 );
004515
004516 /* Set the first entry (number of rows in the index) to the estimated
004517 ** number of rows in the table, or half the number of rows in the table
004518 ** for a partial index.
004519 **
004520 ** 2020-05-27: If some of the stat data is coming from the sqlite_stat1
004521 ** table but other parts we are having to guess at, then do not let the
004522 ** estimated number of rows in the table be less than 1000 (LogEst 99).
004523 ** Failure to do this can cause the indexes for which we do not have
004524 ** stat1 data to be ignored by the query planner.
004525 */
004526 x = pIdx->pTable->nRowLogEst;
004527 assert( 99==sqlite3LogEst(1000) );
004528 if( x<99 ){
004529 pIdx->pTable->nRowLogEst = x = 99;
004530 }
004531 if( pIdx->pPartIdxWhere!=0 ){ x -= 10; assert( 10==sqlite3LogEst(2) ); }
004532 a[0] = x;
004533
004534 /* Estimate that a[1] is 10, a[2] is 9, a[3] is 8, a[4] is 7, a[5] is
004535 ** 6 and each subsequent value (if any) is 5. */
004536 memcpy(&a[1], aVal, nCopy*sizeof(LogEst));
004537 for(i=nCopy+1; i<=pIdx->nKeyCol; i++){
004538 a[i] = 23; assert( 23==sqlite3LogEst(5) );
004539 }
004540
004541 assert( 0==sqlite3LogEst(1) );
004542 if( IsUniqueIndex(pIdx) ) a[pIdx->nKeyCol] = 0;
004543 }
004544
004545 /*
004546 ** This routine will drop an existing named index. This routine
004547 ** implements the DROP INDEX statement.
004548 */
004549 void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
004550 Index *pIndex;
004551 Vdbe *v;
004552 sqlite3 *db = pParse->db;
004553 int iDb;
004554
004555 if( db->mallocFailed ){
004556 goto exit_drop_index;
004557 }
004558 assert( pParse->nErr==0 ); /* Never called with prior non-OOM errors */
004559 assert( pName->nSrc==1 );
004560 assert( pName->a[0].fg.fixedSchema==0 );
004561 assert( pName->a[0].fg.isSubquery==0 );
004562 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
004563 goto exit_drop_index;
004564 }
004565 pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].u4.zDatabase);
004566 if( pIndex==0 ){
004567 if( !ifExists ){
004568 sqlite3ErrorMsg(pParse, "no such index: %S", pName->a);
004569 }else{
004570 sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].u4.zDatabase);
004571 sqlite3ForceNotReadOnly(pParse);
004572 }
004573 pParse->checkSchema = 1;
004574 goto exit_drop_index;
004575 }
004576 if( pIndex->idxType!=SQLITE_IDXTYPE_APPDEF ){
004577 sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
004578 "or PRIMARY KEY constraint cannot be dropped", 0);
004579 goto exit_drop_index;
004580 }
004581 iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
004582 #ifndef SQLITE_OMIT_AUTHORIZATION
004583 {
004584 int code = SQLITE_DROP_INDEX;
004585 Table *pTab = pIndex->pTable;
004586 const char *zDb = db->aDb[iDb].zDbSName;
004587 const char *zTab = SCHEMA_TABLE(iDb);
004588 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
004589 goto exit_drop_index;
004590 }
004591 if( !OMIT_TEMPDB && iDb==1 ) code = SQLITE_DROP_TEMP_INDEX;
004592 if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
004593 goto exit_drop_index;
004594 }
004595 }
004596 #endif
004597
004598 /* Generate code to remove the index and from the schema table */
004599 v = sqlite3GetVdbe(pParse);
004600 if( v ){
004601 sqlite3BeginWriteOperation(pParse, 1, iDb);
004602 sqlite3NestedParse(pParse,
004603 "DELETE FROM %Q." LEGACY_SCHEMA_TABLE " WHERE name=%Q AND type='index'",
004604 db->aDb[iDb].zDbSName, pIndex->zName
004605 );
004606 sqlite3ClearStatTables(pParse, iDb, "idx", pIndex->zName);
004607 sqlite3ChangeCookie(pParse, iDb);
004608 destroyRootPage(pParse, pIndex->tnum, iDb);
004609 sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
004610 }
004611
004612 exit_drop_index:
004613 sqlite3SrcListDelete(db, pName);
004614 }
004615
004616 /*
004617 ** pArray is a pointer to an array of objects. Each object in the
004618 ** array is szEntry bytes in size. This routine uses sqlite3DbRealloc()
004619 ** to extend the array so that there is space for a new object at the end.
004620 **
004621 ** When this function is called, *pnEntry contains the current size of
004622 ** the array (in entries - so the allocation is ((*pnEntry) * szEntry) bytes
004623 ** in total).
004624 **
004625 ** If the realloc() is successful (i.e. if no OOM condition occurs), the
004626 ** space allocated for the new object is zeroed, *pnEntry updated to
004627 ** reflect the new size of the array and a pointer to the new allocation
004628 ** returned. *pIdx is set to the index of the new array entry in this case.
004629 **
004630 ** Otherwise, if the realloc() fails, *pIdx is set to -1, *pnEntry remains
004631 ** unchanged and a copy of pArray returned.
004632 */
004633 void *sqlite3ArrayAllocate(
004634 sqlite3 *db, /* Connection to notify of malloc failures */
004635 void *pArray, /* Array of objects. Might be reallocated */
004636 int szEntry, /* Size of each object in the array */
004637 int *pnEntry, /* Number of objects currently in use */
004638 int *pIdx /* Write the index of a new slot here */
004639 ){
004640 char *z;
004641 sqlite3_int64 n = *pIdx = *pnEntry;
004642 if( (n & (n-1))==0 ){
004643 sqlite3_int64 sz = (n==0) ? 1 : 2*n;
004644 void *pNew = sqlite3DbRealloc(db, pArray, sz*szEntry);
004645 if( pNew==0 ){
004646 *pIdx = -1;
004647 return pArray;
004648 }
004649 pArray = pNew;
004650 }
004651 z = (char*)pArray;
004652 memset(&z[n * szEntry], 0, szEntry);
004653 ++*pnEntry;
004654 return pArray;
004655 }
004656
004657 /*
004658 ** Append a new element to the given IdList. Create a new IdList if
004659 ** need be.
004660 **
004661 ** A new IdList is returned, or NULL if malloc() fails.
004662 */
004663 IdList *sqlite3IdListAppend(Parse *pParse, IdList *pList, Token *pToken){
004664 sqlite3 *db = pParse->db;
004665 int i;
004666 if( pList==0 ){
004667 pList = sqlite3DbMallocZero(db, sizeof(IdList) );
004668 if( pList==0 ) return 0;
004669 }else{
004670 IdList *pNew;
004671 pNew = sqlite3DbRealloc(db, pList,
004672 sizeof(IdList) + pList->nId*sizeof(pList->a));
004673 if( pNew==0 ){
004674 sqlite3IdListDelete(db, pList);
004675 return 0;
004676 }
004677 pList = pNew;
004678 }
004679 i = pList->nId++;
004680 pList->a[i].zName = sqlite3NameFromToken(db, pToken);
004681 if( IN_RENAME_OBJECT && pList->a[i].zName ){
004682 sqlite3RenameTokenMap(pParse, (void*)pList->a[i].zName, pToken);
004683 }
004684 return pList;
004685 }
004686
004687 /*
004688 ** Delete an IdList.
004689 */
004690 void sqlite3IdListDelete(sqlite3 *db, IdList *pList){
004691 int i;
004692 assert( db!=0 );
004693 if( pList==0 ) return;
004694 for(i=0; i<pList->nId; i++){
004695 sqlite3DbFree(db, pList->a[i].zName);
004696 }
004697 sqlite3DbNNFreeNN(db, pList);
004698 }
004699
004700 /*
004701 ** Return the index in pList of the identifier named zId. Return -1
004702 ** if not found.
004703 */
004704 int sqlite3IdListIndex(IdList *pList, const char *zName){
004705 int i;
004706 assert( pList!=0 );
004707 for(i=0; i<pList->nId; i++){
004708 if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
004709 }
004710 return -1;
004711 }
004712
004713 /*
004714 ** Maximum size of a SrcList object.
004715 ** The SrcList object is used to represent the FROM clause of a
004716 ** SELECT statement, and the query planner cannot deal with more
004717 ** than 64 tables in a join. So any value larger than 64 here
004718 ** is sufficient for most uses. Smaller values, like say 10, are
004719 ** appropriate for small and memory-limited applications.
004720 */
004721 #ifndef SQLITE_MAX_SRCLIST
004722 # define SQLITE_MAX_SRCLIST 200
004723 #endif
004724
004725 /*
004726 ** Expand the space allocated for the given SrcList object by
004727 ** creating nExtra new slots beginning at iStart. iStart is zero based.
004728 ** New slots are zeroed.
004729 **
004730 ** For example, suppose a SrcList initially contains two entries: A,B.
004731 ** To append 3 new entries onto the end, do this:
004732 **
004733 ** sqlite3SrcListEnlarge(db, pSrclist, 3, 2);
004734 **
004735 ** After the call above it would contain: A, B, nil, nil, nil.
004736 ** If the iStart argument had been 1 instead of 2, then the result
004737 ** would have been: A, nil, nil, nil, B. To prepend the new slots,
004738 ** the iStart value would be 0. The result then would
004739 ** be: nil, nil, nil, A, B.
004740 **
004741 ** If a memory allocation fails or the SrcList becomes too large, leave
004742 ** the original SrcList unchanged, return NULL, and leave an error message
004743 ** in pParse.
004744 */
004745 SrcList *sqlite3SrcListEnlarge(
004746 Parse *pParse, /* Parsing context into which errors are reported */
004747 SrcList *pSrc, /* The SrcList to be enlarged */
004748 int nExtra, /* Number of new slots to add to pSrc->a[] */
004749 int iStart /* Index in pSrc->a[] of first new slot */
004750 ){
004751 int i;
004752
004753 /* Sanity checking on calling parameters */
004754 assert( iStart>=0 );
004755 assert( nExtra>=1 );
004756 assert( pSrc!=0 );
004757 assert( iStart<=pSrc->nSrc );
004758
004759 /* Allocate additional space if needed */
004760 if( (u32)pSrc->nSrc+nExtra>pSrc->nAlloc ){
004761 SrcList *pNew;
004762 sqlite3_int64 nAlloc = 2*(sqlite3_int64)pSrc->nSrc+nExtra;
004763 sqlite3 *db = pParse->db;
004764
004765 if( pSrc->nSrc+nExtra>=SQLITE_MAX_SRCLIST ){
004766 sqlite3ErrorMsg(pParse, "too many FROM clause terms, max: %d",
004767 SQLITE_MAX_SRCLIST);
004768 return 0;
004769 }
004770 if( nAlloc>SQLITE_MAX_SRCLIST ) nAlloc = SQLITE_MAX_SRCLIST;
004771 pNew = sqlite3DbRealloc(db, pSrc,
004772 sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) );
004773 if( pNew==0 ){
004774 assert( db->mallocFailed );
004775 return 0;
004776 }
004777 pSrc = pNew;
004778 pSrc->nAlloc = nAlloc;
004779 }
004780
004781 /* Move existing slots that come after the newly inserted slots
004782 ** out of the way */
004783 for(i=pSrc->nSrc-1; i>=iStart; i--){
004784 pSrc->a[i+nExtra] = pSrc->a[i];
004785 }
004786 pSrc->nSrc += nExtra;
004787
004788 /* Zero the newly allocated slots */
004789 memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
004790 for(i=iStart; i<iStart+nExtra; i++){
004791 pSrc->a[i].iCursor = -1;
004792 }
004793
004794 /* Return a pointer to the enlarged SrcList */
004795 return pSrc;
004796 }
004797
004798
004799 /*
004800 ** Append a new table name to the given SrcList. Create a new SrcList if
004801 ** need be. A new entry is created in the SrcList even if pTable is NULL.
004802 **
004803 ** A SrcList is returned, or NULL if there is an OOM error or if the
004804 ** SrcList grows to large. The returned
004805 ** SrcList might be the same as the SrcList that was input or it might be
004806 ** a new one. If an OOM error does occurs, then the prior value of pList
004807 ** that is input to this routine is automatically freed.
004808 **
004809 ** If pDatabase is not null, it means that the table has an optional
004810 ** database name prefix. Like this: "database.table". The pDatabase
004811 ** points to the table name and the pTable points to the database name.
004812 ** The SrcList.a[].zName field is filled with the table name which might
004813 ** come from pTable (if pDatabase is NULL) or from pDatabase.
004814 ** SrcList.a[].zDatabase is filled with the database name from pTable,
004815 ** or with NULL if no database is specified.
004816 **
004817 ** In other words, if call like this:
004818 **
004819 ** sqlite3SrcListAppend(D,A,B,0);
004820 **
004821 ** Then B is a table name and the database name is unspecified. If called
004822 ** like this:
004823 **
004824 ** sqlite3SrcListAppend(D,A,B,C);
004825 **
004826 ** Then C is the table name and B is the database name. If C is defined
004827 ** then so is B. In other words, we never have a case where:
004828 **
004829 ** sqlite3SrcListAppend(D,A,0,C);
004830 **
004831 ** Both pTable and pDatabase are assumed to be quoted. They are dequoted
004832 ** before being added to the SrcList.
004833 */
004834 SrcList *sqlite3SrcListAppend(
004835 Parse *pParse, /* Parsing context, in which errors are reported */
004836 SrcList *pList, /* Append to this SrcList. NULL creates a new SrcList */
004837 Token *pTable, /* Table to append */
004838 Token *pDatabase /* Database of the table */
004839 ){
004840 SrcItem *pItem;
004841 sqlite3 *db;
004842 assert( pDatabase==0 || pTable!=0 ); /* Cannot have C without B */
004843 assert( pParse!=0 );
004844 assert( pParse->db!=0 );
004845 db = pParse->db;
004846 if( pList==0 ){
004847 pList = sqlite3DbMallocRawNN(pParse->db, sizeof(SrcList) );
004848 if( pList==0 ) return 0;
004849 pList->nAlloc = 1;
004850 pList->nSrc = 1;
004851 memset(&pList->a[0], 0, sizeof(pList->a[0]));
004852 pList->a[0].iCursor = -1;
004853 }else{
004854 SrcList *pNew = sqlite3SrcListEnlarge(pParse, pList, 1, pList->nSrc);
004855 if( pNew==0 ){
004856 sqlite3SrcListDelete(db, pList);
004857 return 0;
004858 }else{
004859 pList = pNew;
004860 }
004861 }
004862 pItem = &pList->a[pList->nSrc-1];
004863 if( pDatabase && pDatabase->z==0 ){
004864 pDatabase = 0;
004865 }
004866 assert( pItem->fg.fixedSchema==0 );
004867 assert( pItem->fg.isSubquery==0 );
004868 if( pDatabase ){
004869 pItem->zName = sqlite3NameFromToken(db, pDatabase);
004870 pItem->u4.zDatabase = sqlite3NameFromToken(db, pTable);
004871 }else{
004872 pItem->zName = sqlite3NameFromToken(db, pTable);
004873 pItem->u4.zDatabase = 0;
004874 }
004875 return pList;
004876 }
004877
004878 /*
004879 ** Assign VdbeCursor index numbers to all tables in a SrcList
004880 */
004881 void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
004882 int i;
004883 SrcItem *pItem;
004884 assert( pList || pParse->db->mallocFailed );
004885 if( ALWAYS(pList) ){
004886 for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
004887 if( pItem->iCursor>=0 ) continue;
004888 pItem->iCursor = pParse->nTab++;
004889 if( pItem->fg.isSubquery ){
004890 assert( pItem->u4.pSubq!=0 );
004891 assert( pItem->u4.pSubq->pSelect!=0 );
004892 assert( pItem->u4.pSubq->pSelect->pSrc!=0 );
004893 sqlite3SrcListAssignCursors(pParse, pItem->u4.pSubq->pSelect->pSrc);
004894 }
004895 }
004896 }
004897 }
004898
004899 /*
004900 ** Delete a Subquery object and its substructure.
004901 */
004902 void sqlite3SubqueryDelete(sqlite3 *db, Subquery *pSubq){
004903 assert( pSubq!=0 && pSubq->pSelect!=0 );
004904 sqlite3SelectDelete(db, pSubq->pSelect);
004905 sqlite3DbFree(db, pSubq);
004906 }
004907
004908 /*
004909 ** Remove a Subquery from a SrcItem. Return the associated Select object.
004910 ** The returned Select becomes the responsibility of the caller.
004911 */
004912 Select *sqlite3SubqueryDetach(sqlite3 *db, SrcItem *pItem){
004913 Select *pSel;
004914 assert( pItem!=0 );
004915 assert( pItem->fg.isSubquery );
004916 pSel = pItem->u4.pSubq->pSelect;
004917 sqlite3DbFree(db, pItem->u4.pSubq);
004918 pItem->u4.pSubq = 0;
004919 pItem->fg.isSubquery = 0;
004920 return pSel;
004921 }
004922
004923 /*
004924 ** Delete an entire SrcList including all its substructure.
004925 */
004926 void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){
004927 int i;
004928 SrcItem *pItem;
004929 assert( db!=0 );
004930 if( pList==0 ) return;
004931 for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
004932
004933 /* Check invariants on SrcItem */
004934 assert( !pItem->fg.isIndexedBy || !pItem->fg.isTabFunc );
004935 assert( !pItem->fg.isCte || !pItem->fg.isIndexedBy );
004936 assert( !pItem->fg.fixedSchema || !pItem->fg.isSubquery );
004937 assert( !pItem->fg.isSubquery || (pItem->u4.pSubq!=0 &&
004938 pItem->u4.pSubq->pSelect!=0) );
004939
004940 if( pItem->zName ) sqlite3DbNNFreeNN(db, pItem->zName);
004941 if( pItem->zAlias ) sqlite3DbNNFreeNN(db, pItem->zAlias);
004942 if( pItem->fg.isSubquery ){
004943 sqlite3SubqueryDelete(db, pItem->u4.pSubq);
004944 }else if( pItem->fg.fixedSchema==0 && pItem->u4.zDatabase!=0 ){
004945 sqlite3DbNNFreeNN(db, pItem->u4.zDatabase);
004946 }
004947 if( pItem->fg.isIndexedBy ) sqlite3DbFree(db, pItem->u1.zIndexedBy);
004948 if( pItem->fg.isTabFunc ) sqlite3ExprListDelete(db, pItem->u1.pFuncArg);
004949 sqlite3DeleteTable(db, pItem->pSTab);
004950 if( pItem->fg.isUsing ){
004951 sqlite3IdListDelete(db, pItem->u3.pUsing);
004952 }else if( pItem->u3.pOn ){
004953 sqlite3ExprDelete(db, pItem->u3.pOn);
004954 }
004955 }
004956 sqlite3DbNNFreeNN(db, pList);
004957 }
004958
004959 /*
004960 ** Attach a Subquery object to pItem->uv.pSubq. Set the
004961 ** pSelect value but leave all the other values initialized
004962 ** to zero.
004963 **
004964 ** A copy of the Select object is made if dupSelect is true, and the
004965 ** SrcItem takes responsibility for deleting the copy. If dupSelect is
004966 ** false, ownership of the Select passes to the SrcItem. Either way,
004967 ** the SrcItem will take responsibility for deleting the Select.
004968 **
004969 ** When dupSelect is zero, that means the Select might get deleted right
004970 ** away if there is an OOM error. Beware.
004971 **
004972 ** Return non-zero on success. Return zero on an OOM error.
004973 */
004974 int sqlite3SrcItemAttachSubquery(
004975 Parse *pParse, /* Parsing context */
004976 SrcItem *pItem, /* Item to which the subquery is to be attached */
004977 Select *pSelect, /* The subquery SELECT. Must be non-NULL */
004978 int dupSelect /* If true, attach a copy of pSelect, not pSelect itself.*/
004979 ){
004980 Subquery *p;
004981 assert( pSelect!=0 );
004982 assert( pItem->fg.isSubquery==0 );
004983 if( pItem->fg.fixedSchema ){
004984 pItem->u4.pSchema = 0;
004985 pItem->fg.fixedSchema = 0;
004986 }else if( pItem->u4.zDatabase!=0 ){
004987 sqlite3DbFree(pParse->db, pItem->u4.zDatabase);
004988 pItem->u4.zDatabase = 0;
004989 }
004990 if( dupSelect ){
004991 pSelect = sqlite3SelectDup(pParse->db, pSelect, 0);
004992 if( pSelect==0 ) return 0;
004993 }
004994 p = pItem->u4.pSubq = sqlite3DbMallocRawNN(pParse->db, sizeof(Subquery));
004995 if( p==0 ){
004996 sqlite3SelectDelete(pParse->db, pSelect);
004997 return 0;
004998 }
004999 pItem->fg.isSubquery = 1;
005000 p->pSelect = pSelect;
005001 assert( offsetof(Subquery, pSelect)==0 );
005002 memset(((char*)p)+sizeof(p->pSelect), 0, sizeof(*p)-sizeof(p->pSelect));
005003 return 1;
005004 }
005005
005006
005007 /*
005008 ** This routine is called by the parser to add a new term to the
005009 ** end of a growing FROM clause. The "p" parameter is the part of
005010 ** the FROM clause that has already been constructed. "p" is NULL
005011 ** if this is the first term of the FROM clause. pTable and pDatabase
005012 ** are the name of the table and database named in the FROM clause term.
005013 ** pDatabase is NULL if the database name qualifier is missing - the
005014 ** usual case. If the term has an alias, then pAlias points to the
005015 ** alias token. If the term is a subquery, then pSubquery is the
005016 ** SELECT statement that the subquery encodes. The pTable and
005017 ** pDatabase parameters are NULL for subqueries. The pOn and pUsing
005018 ** parameters are the content of the ON and USING clauses.
005019 **
005020 ** Return a new SrcList which encodes is the FROM with the new
005021 ** term added.
005022 */
005023 SrcList *sqlite3SrcListAppendFromTerm(
005024 Parse *pParse, /* Parsing context */
005025 SrcList *p, /* The left part of the FROM clause already seen */
005026 Token *pTable, /* Name of the table to add to the FROM clause */
005027 Token *pDatabase, /* Name of the database containing pTable */
005028 Token *pAlias, /* The right-hand side of the AS subexpression */
005029 Select *pSubquery, /* A subquery used in place of a table name */
005030 OnOrUsing *pOnUsing /* Either the ON clause or the USING clause */
005031 ){
005032 SrcItem *pItem;
005033 sqlite3 *db = pParse->db;
005034 if( !p && pOnUsing!=0 && (pOnUsing->pOn || pOnUsing->pUsing) ){
005035 sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s",
005036 (pOnUsing->pOn ? "ON" : "USING")
005037 );
005038 goto append_from_error;
005039 }
005040 p = sqlite3SrcListAppend(pParse, p, pTable, pDatabase);
005041 if( p==0 ){
005042 goto append_from_error;
005043 }
005044 assert( p->nSrc>0 );
005045 pItem = &p->a[p->nSrc-1];
005046 assert( (pTable==0)==(pDatabase==0) );
005047 assert( pItem->zName==0 || pDatabase!=0 );
005048 if( IN_RENAME_OBJECT && pItem->zName ){
005049 Token *pToken = (ALWAYS(pDatabase) && pDatabase->z) ? pDatabase : pTable;
005050 sqlite3RenameTokenMap(pParse, pItem->zName, pToken);
005051 }
005052 assert( pAlias!=0 );
005053 if( pAlias->n ){
005054 pItem->zAlias = sqlite3NameFromToken(db, pAlias);
005055 }
005056 assert( pSubquery==0 || pDatabase==0 );
005057 if( pSubquery ){
005058 if( sqlite3SrcItemAttachSubquery(pParse, pItem, pSubquery, 0) ){
005059 if( pSubquery->selFlags & SF_NestedFrom ){
005060 pItem->fg.isNestedFrom = 1;
005061 }
005062 }
005063 }
005064 assert( pOnUsing==0 || pOnUsing->pOn==0 || pOnUsing->pUsing==0 );
005065 assert( pItem->fg.isUsing==0 );
005066 if( pOnUsing==0 ){
005067 pItem->u3.pOn = 0;
005068 }else if( pOnUsing->pUsing ){
005069 pItem->fg.isUsing = 1;
005070 pItem->u3.pUsing = pOnUsing->pUsing;
005071 }else{
005072 pItem->u3.pOn = pOnUsing->pOn;
005073 }
005074 return p;
005075
005076 append_from_error:
005077 assert( p==0 );
005078 sqlite3ClearOnOrUsing(db, pOnUsing);
005079 sqlite3SelectDelete(db, pSubquery);
005080 return 0;
005081 }
005082
005083 /*
005084 ** Add an INDEXED BY or NOT INDEXED clause to the most recently added
005085 ** element of the source-list passed as the second argument.
005086 */
005087 void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){
005088 assert( pIndexedBy!=0 );
005089 if( p && pIndexedBy->n>0 ){
005090 SrcItem *pItem;
005091 assert( p->nSrc>0 );
005092 pItem = &p->a[p->nSrc-1];
005093 assert( pItem->fg.notIndexed==0 );
005094 assert( pItem->fg.isIndexedBy==0 );
005095 assert( pItem->fg.isTabFunc==0 );
005096 if( pIndexedBy->n==1 && !pIndexedBy->z ){
005097 /* A "NOT INDEXED" clause was supplied. See parse.y
005098 ** construct "indexed_opt" for details. */
005099 pItem->fg.notIndexed = 1;
005100 }else{
005101 pItem->u1.zIndexedBy = sqlite3NameFromToken(pParse->db, pIndexedBy);
005102 pItem->fg.isIndexedBy = 1;
005103 assert( pItem->fg.isCte==0 ); /* No collision on union u2 */
005104 }
005105 }
005106 }
005107
005108 /*
005109 ** Append the contents of SrcList p2 to SrcList p1 and return the resulting
005110 ** SrcList. Or, if an error occurs, return NULL. In all cases, p1 and p2
005111 ** are deleted by this function.
005112 */
005113 SrcList *sqlite3SrcListAppendList(Parse *pParse, SrcList *p1, SrcList *p2){
005114 assert( p1 && p1->nSrc==1 );
005115 if( p2 ){
005116 SrcList *pNew = sqlite3SrcListEnlarge(pParse, p1, p2->nSrc, 1);
005117 if( pNew==0 ){
005118 sqlite3SrcListDelete(pParse->db, p2);
005119 }else{
005120 p1 = pNew;
005121 memcpy(&p1->a[1], p2->a, p2->nSrc*sizeof(SrcItem));
005122 sqlite3DbFree(pParse->db, p2);
005123 p1->a[0].fg.jointype |= (JT_LTORJ & p1->a[1].fg.jointype);
005124 }
005125 }
005126 return p1;
005127 }
005128
005129 /*
005130 ** Add the list of function arguments to the SrcList entry for a
005131 ** table-valued-function.
005132 */
005133 void sqlite3SrcListFuncArgs(Parse *pParse, SrcList *p, ExprList *pList){
005134 if( p ){
005135 SrcItem *pItem = &p->a[p->nSrc-1];
005136 assert( pItem->fg.notIndexed==0 );
005137 assert( pItem->fg.isIndexedBy==0 );
005138 assert( pItem->fg.isTabFunc==0 );
005139 pItem->u1.pFuncArg = pList;
005140 pItem->fg.isTabFunc = 1;
005141 }else{
005142 sqlite3ExprListDelete(pParse->db, pList);
005143 }
005144 }
005145
005146 /*
005147 ** When building up a FROM clause in the parser, the join operator
005148 ** is initially attached to the left operand. But the code generator
005149 ** expects the join operator to be on the right operand. This routine
005150 ** Shifts all join operators from left to right for an entire FROM
005151 ** clause.
005152 **
005153 ** Example: Suppose the join is like this:
005154 **
005155 ** A natural cross join B
005156 **
005157 ** The operator is "natural cross join". The A and B operands are stored
005158 ** in p->a[0] and p->a[1], respectively. The parser initially stores the
005159 ** operator with A. This routine shifts that operator over to B.
005160 **
005161 ** Additional changes:
005162 **
005163 ** * All tables to the left of the right-most RIGHT JOIN are tagged with
005164 ** JT_LTORJ (mnemonic: Left Table Of Right Join) so that the
005165 ** code generator can easily tell that the table is part of
005166 ** the left operand of at least one RIGHT JOIN.
005167 */
005168 void sqlite3SrcListShiftJoinType(Parse *pParse, SrcList *p){
005169 (void)pParse;
005170 if( p && p->nSrc>1 ){
005171 int i = p->nSrc-1;
005172 u8 allFlags = 0;
005173 do{
005174 allFlags |= p->a[i].fg.jointype = p->a[i-1].fg.jointype;
005175 }while( (--i)>0 );
005176 p->a[0].fg.jointype = 0;
005177
005178 /* All terms to the left of a RIGHT JOIN should be tagged with the
005179 ** JT_LTORJ flags */
005180 if( allFlags & JT_RIGHT ){
005181 for(i=p->nSrc-1; ALWAYS(i>0) && (p->a[i].fg.jointype&JT_RIGHT)==0; i--){}
005182 i--;
005183 assert( i>=0 );
005184 do{
005185 p->a[i].fg.jointype |= JT_LTORJ;
005186 }while( (--i)>=0 );
005187 }
005188 }
005189 }
005190
005191 /*
005192 ** Generate VDBE code for a BEGIN statement.
005193 */
005194 void sqlite3BeginTransaction(Parse *pParse, int type){
005195 sqlite3 *db;
005196 Vdbe *v;
005197 int i;
005198
005199 assert( pParse!=0 );
005200 db = pParse->db;
005201 assert( db!=0 );
005202 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){
005203 return;
005204 }
005205 v = sqlite3GetVdbe(pParse);
005206 if( !v ) return;
005207 if( type!=TK_DEFERRED ){
005208 for(i=0; i<db->nDb; i++){
005209 int eTxnType;
005210 Btree *pBt = db->aDb[i].pBt;
005211 if( pBt && sqlite3BtreeIsReadonly(pBt) ){
005212 eTxnType = 0; /* Read txn */
005213 }else if( type==TK_EXCLUSIVE ){
005214 eTxnType = 2; /* Exclusive txn */
005215 }else{
005216 eTxnType = 1; /* Write txn */
005217 }
005218 sqlite3VdbeAddOp2(v, OP_Transaction, i, eTxnType);
005219 sqlite3VdbeUsesBtree(v, i);
005220 }
005221 }
005222 sqlite3VdbeAddOp0(v, OP_AutoCommit);
005223 }
005224
005225 /*
005226 ** Generate VDBE code for a COMMIT or ROLLBACK statement.
005227 ** Code for ROLLBACK is generated if eType==TK_ROLLBACK. Otherwise
005228 ** code is generated for a COMMIT.
005229 */
005230 void sqlite3EndTransaction(Parse *pParse, int eType){
005231 Vdbe *v;
005232 int isRollback;
005233
005234 assert( pParse!=0 );
005235 assert( pParse->db!=0 );
005236 assert( eType==TK_COMMIT || eType==TK_END || eType==TK_ROLLBACK );
005237 isRollback = eType==TK_ROLLBACK;
005238 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION,
005239 isRollback ? "ROLLBACK" : "COMMIT", 0, 0) ){
005240 return;
005241 }
005242 v = sqlite3GetVdbe(pParse);
005243 if( v ){
005244 sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, isRollback);
005245 }
005246 }
005247
005248 /*
005249 ** This function is called by the parser when it parses a command to create,
005250 ** release or rollback an SQL savepoint.
005251 */
005252 void sqlite3Savepoint(Parse *pParse, int op, Token *pName){
005253 char *zName = sqlite3NameFromToken(pParse->db, pName);
005254 if( zName ){
005255 Vdbe *v = sqlite3GetVdbe(pParse);
005256 #ifndef SQLITE_OMIT_AUTHORIZATION
005257 static const char * const az[] = { "BEGIN", "RELEASE", "ROLLBACK" };
005258 assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 );
005259 #endif
005260 if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){
005261 sqlite3DbFree(pParse->db, zName);
005262 return;
005263 }
005264 sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC);
005265 }
005266 }
005267
005268 /*
005269 ** Make sure the TEMP database is open and available for use. Return
005270 ** the number of errors. Leave any error messages in the pParse structure.
005271 */
005272 int sqlite3OpenTempDatabase(Parse *pParse){
005273 sqlite3 *db = pParse->db;
005274 if( db->aDb[1].pBt==0 && !pParse->explain ){
005275 int rc;
005276 Btree *pBt;
005277 static const int flags =
005278 SQLITE_OPEN_READWRITE |
005279 SQLITE_OPEN_CREATE |
005280 SQLITE_OPEN_EXCLUSIVE |
005281 SQLITE_OPEN_DELETEONCLOSE |
005282 SQLITE_OPEN_TEMP_DB;
005283
005284 rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pBt, 0, flags);
005285 if( rc!=SQLITE_OK ){
005286 sqlite3ErrorMsg(pParse, "unable to open a temporary database "
005287 "file for storing temporary tables");
005288 pParse->rc = rc;
005289 return 1;
005290 }
005291 db->aDb[1].pBt = pBt;
005292 assert( db->aDb[1].pSchema );
005293 if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, 0, 0) ){
005294 sqlite3OomFault(db);
005295 return 1;
005296 }
005297 }
005298 return 0;
005299 }
005300
005301 /*
005302 ** Record the fact that the schema cookie will need to be verified
005303 ** for database iDb. The code to actually verify the schema cookie
005304 ** will occur at the end of the top-level VDBE and will be generated
005305 ** later, by sqlite3FinishCoding().
005306 */
005307 static void sqlite3CodeVerifySchemaAtToplevel(Parse *pToplevel, int iDb){
005308 assert( iDb>=0 && iDb<pToplevel->db->nDb );
005309 assert( pToplevel->db->aDb[iDb].pBt!=0 || iDb==1 );
005310 assert( iDb<SQLITE_MAX_DB );
005311 assert( sqlite3SchemaMutexHeld(pToplevel->db, iDb, 0) );
005312 if( DbMaskTest(pToplevel->cookieMask, iDb)==0 ){
005313 DbMaskSet(pToplevel->cookieMask, iDb);
005314 if( !OMIT_TEMPDB && iDb==1 ){
005315 sqlite3OpenTempDatabase(pToplevel);
005316 }
005317 }
005318 }
005319 void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
005320 sqlite3CodeVerifySchemaAtToplevel(sqlite3ParseToplevel(pParse), iDb);
005321 }
005322
005323
005324 /*
005325 ** If argument zDb is NULL, then call sqlite3CodeVerifySchema() for each
005326 ** attached database. Otherwise, invoke it for the database named zDb only.
005327 */
005328 void sqlite3CodeVerifyNamedSchema(Parse *pParse, const char *zDb){
005329 sqlite3 *db = pParse->db;
005330 int i;
005331 for(i=0; i<db->nDb; i++){
005332 Db *pDb = &db->aDb[i];
005333 if( pDb->pBt && (!zDb || 0==sqlite3StrICmp(zDb, pDb->zDbSName)) ){
005334 sqlite3CodeVerifySchema(pParse, i);
005335 }
005336 }
005337 }
005338
005339 /*
005340 ** Generate VDBE code that prepares for doing an operation that
005341 ** might change the database.
005342 **
005343 ** This routine starts a new transaction if we are not already within
005344 ** a transaction. If we are already within a transaction, then a checkpoint
005345 ** is set if the setStatement parameter is true. A checkpoint should
005346 ** be set for operations that might fail (due to a constraint) part of
005347 ** the way through and which will need to undo some writes without having to
005348 ** rollback the whole transaction. For operations where all constraints
005349 ** can be checked before any changes are made to the database, it is never
005350 ** necessary to undo a write and the checkpoint should not be set.
005351 */
005352 void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
005353 Parse *pToplevel = sqlite3ParseToplevel(pParse);
005354 sqlite3CodeVerifySchemaAtToplevel(pToplevel, iDb);
005355 DbMaskSet(pToplevel->writeMask, iDb);
005356 pToplevel->isMultiWrite |= setStatement;
005357 }
005358
005359 /*
005360 ** Indicate that the statement currently under construction might write
005361 ** more than one entry (example: deleting one row then inserting another,
005362 ** inserting multiple rows in a table, or inserting a row and index entries.)
005363 ** If an abort occurs after some of these writes have completed, then it will
005364 ** be necessary to undo the completed writes.
005365 */
005366 void sqlite3MultiWrite(Parse *pParse){
005367 Parse *pToplevel = sqlite3ParseToplevel(pParse);
005368 pToplevel->isMultiWrite = 1;
005369 }
005370
005371 /*
005372 ** The code generator calls this routine if is discovers that it is
005373 ** possible to abort a statement prior to completion. In order to
005374 ** perform this abort without corrupting the database, we need to make
005375 ** sure that the statement is protected by a statement transaction.
005376 **
005377 ** Technically, we only need to set the mayAbort flag if the
005378 ** isMultiWrite flag was previously set. There is a time dependency
005379 ** such that the abort must occur after the multiwrite. This makes
005380 ** some statements involving the REPLACE conflict resolution algorithm
005381 ** go a little faster. But taking advantage of this time dependency
005382 ** makes it more difficult to prove that the code is correct (in
005383 ** particular, it prevents us from writing an effective
005384 ** implementation of sqlite3AssertMayAbort()) and so we have chosen
005385 ** to take the safe route and skip the optimization.
005386 */
005387 void sqlite3MayAbort(Parse *pParse){
005388 Parse *pToplevel = sqlite3ParseToplevel(pParse);
005389 pToplevel->mayAbort = 1;
005390 }
005391
005392 /*
005393 ** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT
005394 ** error. The onError parameter determines which (if any) of the statement
005395 ** and/or current transaction is rolled back.
005396 */
005397 void sqlite3HaltConstraint(
005398 Parse *pParse, /* Parsing context */
005399 int errCode, /* extended error code */
005400 int onError, /* Constraint type */
005401 char *p4, /* Error message */
005402 i8 p4type, /* P4_STATIC or P4_TRANSIENT */
005403 u8 p5Errmsg /* P5_ErrMsg type */
005404 ){
005405 Vdbe *v;
005406 assert( pParse->pVdbe!=0 );
005407 v = sqlite3GetVdbe(pParse);
005408 assert( (errCode&0xff)==SQLITE_CONSTRAINT || pParse->nested );
005409 if( onError==OE_Abort ){
005410 sqlite3MayAbort(pParse);
005411 }
005412 sqlite3VdbeAddOp4(v, OP_Halt, errCode, onError, 0, p4, p4type);
005413 sqlite3VdbeChangeP5(v, p5Errmsg);
005414 }
005415
005416 /*
005417 ** Code an OP_Halt due to UNIQUE or PRIMARY KEY constraint violation.
005418 */
005419 void sqlite3UniqueConstraint(
005420 Parse *pParse, /* Parsing context */
005421 int onError, /* Constraint type */
005422 Index *pIdx /* The index that triggers the constraint */
005423 ){
005424 char *zErr;
005425 int j;
005426 StrAccum errMsg;
005427 Table *pTab = pIdx->pTable;
005428
005429 sqlite3StrAccumInit(&errMsg, pParse->db, 0, 0,
005430 pParse->db->aLimit[SQLITE_LIMIT_LENGTH]);
005431 if( pIdx->aColExpr ){
005432 sqlite3_str_appendf(&errMsg, "index '%q'", pIdx->zName);
005433 }else{
005434 for(j=0; j<pIdx->nKeyCol; j++){
005435 char *zCol;
005436 assert( pIdx->aiColumn[j]>=0 );
005437 zCol = pTab->aCol[pIdx->aiColumn[j]].zCnName;
005438 if( j ) sqlite3_str_append(&errMsg, ", ", 2);
005439 sqlite3_str_appendall(&errMsg, pTab->zName);
005440 sqlite3_str_append(&errMsg, ".", 1);
005441 sqlite3_str_appendall(&errMsg, zCol);
005442 }
005443 }
005444 zErr = sqlite3StrAccumFinish(&errMsg);
005445 sqlite3HaltConstraint(pParse,
005446 IsPrimaryKeyIndex(pIdx) ? SQLITE_CONSTRAINT_PRIMARYKEY
005447 : SQLITE_CONSTRAINT_UNIQUE,
005448 onError, zErr, P4_DYNAMIC, P5_ConstraintUnique);
005449 }
005450
005451
005452 /*
005453 ** Code an OP_Halt due to non-unique rowid.
005454 */
005455 void sqlite3RowidConstraint(
005456 Parse *pParse, /* Parsing context */
005457 int onError, /* Conflict resolution algorithm */
005458 Table *pTab /* The table with the non-unique rowid */
005459 ){
005460 char *zMsg;
005461 int rc;
005462 if( pTab->iPKey>=0 ){
005463 zMsg = sqlite3MPrintf(pParse->db, "%s.%s", pTab->zName,
005464 pTab->aCol[pTab->iPKey].zCnName);
005465 rc = SQLITE_CONSTRAINT_PRIMARYKEY;
005466 }else{
005467 zMsg = sqlite3MPrintf(pParse->db, "%s.rowid", pTab->zName);
005468 rc = SQLITE_CONSTRAINT_ROWID;
005469 }
005470 sqlite3HaltConstraint(pParse, rc, onError, zMsg, P4_DYNAMIC,
005471 P5_ConstraintUnique);
005472 }
005473
005474 /*
005475 ** Check to see if pIndex uses the collating sequence pColl. Return
005476 ** true if it does and false if it does not.
005477 */
005478 #ifndef SQLITE_OMIT_REINDEX
005479 static int collationMatch(const char *zColl, Index *pIndex){
005480 int i;
005481 assert( zColl!=0 );
005482 for(i=0; i<pIndex->nColumn; i++){
005483 const char *z = pIndex->azColl[i];
005484 assert( z!=0 || pIndex->aiColumn[i]<0 );
005485 if( pIndex->aiColumn[i]>=0 && 0==sqlite3StrICmp(z, zColl) ){
005486 return 1;
005487 }
005488 }
005489 return 0;
005490 }
005491 #endif
005492
005493 /*
005494 ** Recompute all indices of pTab that use the collating sequence pColl.
005495 ** If pColl==0 then recompute all indices of pTab.
005496 */
005497 #ifndef SQLITE_OMIT_REINDEX
005498 static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
005499 if( !IsVirtual(pTab) ){
005500 Index *pIndex; /* An index associated with pTab */
005501
005502 for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
005503 if( zColl==0 || collationMatch(zColl, pIndex) ){
005504 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
005505 sqlite3BeginWriteOperation(pParse, 0, iDb);
005506 sqlite3RefillIndex(pParse, pIndex, -1);
005507 }
005508 }
005509 }
005510 }
005511 #endif
005512
005513 /*
005514 ** Recompute all indices of all tables in all databases where the
005515 ** indices use the collating sequence pColl. If pColl==0 then recompute
005516 ** all indices everywhere.
005517 */
005518 #ifndef SQLITE_OMIT_REINDEX
005519 static void reindexDatabases(Parse *pParse, char const *zColl){
005520 Db *pDb; /* A single database */
005521 int iDb; /* The database index number */
005522 sqlite3 *db = pParse->db; /* The database connection */
005523 HashElem *k; /* For looping over tables in pDb */
005524 Table *pTab; /* A table in the database */
005525
005526 assert( sqlite3BtreeHoldsAllMutexes(db) ); /* Needed for schema access */
005527 for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
005528 assert( pDb!=0 );
005529 for(k=sqliteHashFirst(&pDb->pSchema->tblHash); k; k=sqliteHashNext(k)){
005530 pTab = (Table*)sqliteHashData(k);
005531 reindexTable(pParse, pTab, zColl);
005532 }
005533 }
005534 }
005535 #endif
005536
005537 /*
005538 ** Generate code for the REINDEX command.
005539 **
005540 ** REINDEX -- 1
005541 ** REINDEX <collation> -- 2
005542 ** REINDEX ?<database>.?<tablename> -- 3
005543 ** REINDEX ?<database>.?<indexname> -- 4
005544 **
005545 ** Form 1 causes all indices in all attached databases to be rebuilt.
005546 ** Form 2 rebuilds all indices in all databases that use the named
005547 ** collating function. Forms 3 and 4 rebuild the named index or all
005548 ** indices associated with the named table.
005549 */
005550 #ifndef SQLITE_OMIT_REINDEX
005551 void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
005552 CollSeq *pColl; /* Collating sequence to be reindexed, or NULL */
005553 char *z; /* Name of a table or index */
005554 const char *zDb; /* Name of the database */
005555 Table *pTab; /* A table in the database */
005556 Index *pIndex; /* An index associated with pTab */
005557 int iDb; /* The database index number */
005558 sqlite3 *db = pParse->db; /* The database connection */
005559 Token *pObjName; /* Name of the table or index to be reindexed */
005560
005561 /* Read the database schema. If an error occurs, leave an error message
005562 ** and code in pParse and return NULL. */
005563 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
005564 return;
005565 }
005566
005567 if( pName1==0 ){
005568 reindexDatabases(pParse, 0);
005569 return;
005570 }else if( NEVER(pName2==0) || pName2->z==0 ){
005571 char *zColl;
005572 assert( pName1->z );
005573 zColl = sqlite3NameFromToken(pParse->db, pName1);
005574 if( !zColl ) return;
005575 pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
005576 if( pColl ){
005577 reindexDatabases(pParse, zColl);
005578 sqlite3DbFree(db, zColl);
005579 return;
005580 }
005581 sqlite3DbFree(db, zColl);
005582 }
005583 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
005584 if( iDb<0 ) return;
005585 z = sqlite3NameFromToken(db, pObjName);
005586 if( z==0 ) return;
005587 zDb = pName2->n ? db->aDb[iDb].zDbSName : 0;
005588 pTab = sqlite3FindTable(db, z, zDb);
005589 if( pTab ){
005590 reindexTable(pParse, pTab, 0);
005591 sqlite3DbFree(db, z);
005592 return;
005593 }
005594 pIndex = sqlite3FindIndex(db, z, zDb);
005595 sqlite3DbFree(db, z);
005596 if( pIndex ){
005597 iDb = sqlite3SchemaToIndex(db, pIndex->pTable->pSchema);
005598 sqlite3BeginWriteOperation(pParse, 0, iDb);
005599 sqlite3RefillIndex(pParse, pIndex, -1);
005600 return;
005601 }
005602 sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
005603 }
005604 #endif
005605
005606 /*
005607 ** Return a KeyInfo structure that is appropriate for the given Index.
005608 **
005609 ** The caller should invoke sqlite3KeyInfoUnref() on the returned object
005610 ** when it has finished using it.
005611 */
005612 KeyInfo *sqlite3KeyInfoOfIndex(Parse *pParse, Index *pIdx){
005613 int i;
005614 int nCol = pIdx->nColumn;
005615 int nKey = pIdx->nKeyCol;
005616 KeyInfo *pKey;
005617 if( pParse->nErr ) return 0;
005618 if( pIdx->uniqNotNull ){
005619 pKey = sqlite3KeyInfoAlloc(pParse->db, nKey, nCol-nKey);
005620 }else{
005621 pKey = sqlite3KeyInfoAlloc(pParse->db, nCol, 0);
005622 }
005623 if( pKey ){
005624 assert( sqlite3KeyInfoIsWriteable(pKey) );
005625 for(i=0; i<nCol; i++){
005626 const char *zColl = pIdx->azColl[i];
005627 pKey->aColl[i] = zColl==sqlite3StrBINARY ? 0 :
005628 sqlite3LocateCollSeq(pParse, zColl);
005629 pKey->aSortFlags[i] = pIdx->aSortOrder[i];
005630 assert( 0==(pKey->aSortFlags[i] & KEYINFO_ORDER_BIGNULL) );
005631 }
005632 if( pParse->nErr ){
005633 assert( pParse->rc==SQLITE_ERROR_MISSING_COLLSEQ );
005634 if( pIdx->bNoQuery==0 ){
005635 /* Deactivate the index because it contains an unknown collating
005636 ** sequence. The only way to reactive the index is to reload the
005637 ** schema. Adding the missing collating sequence later does not
005638 ** reactive the index. The application had the chance to register
005639 ** the missing index using the collation-needed callback. For
005640 ** simplicity, SQLite will not give the application a second chance.
005641 */
005642 pIdx->bNoQuery = 1;
005643 pParse->rc = SQLITE_ERROR_RETRY;
005644 }
005645 sqlite3KeyInfoUnref(pKey);
005646 pKey = 0;
005647 }
005648 }
005649 return pKey;
005650 }
005651
005652 #ifndef SQLITE_OMIT_CTE
005653 /*
005654 ** Create a new CTE object
005655 */
005656 Cte *sqlite3CteNew(
005657 Parse *pParse, /* Parsing context */
005658 Token *pName, /* Name of the common-table */
005659 ExprList *pArglist, /* Optional column name list for the table */
005660 Select *pQuery, /* Query used to initialize the table */
005661 u8 eM10d /* The MATERIALIZED flag */
005662 ){
005663 Cte *pNew;
005664 sqlite3 *db = pParse->db;
005665
005666 pNew = sqlite3DbMallocZero(db, sizeof(*pNew));
005667 assert( pNew!=0 || db->mallocFailed );
005668
005669 if( db->mallocFailed ){
005670 sqlite3ExprListDelete(db, pArglist);
005671 sqlite3SelectDelete(db, pQuery);
005672 }else{
005673 pNew->pSelect = pQuery;
005674 pNew->pCols = pArglist;
005675 pNew->zName = sqlite3NameFromToken(pParse->db, pName);
005676 pNew->eM10d = eM10d;
005677 }
005678 return pNew;
005679 }
005680
005681 /*
005682 ** Clear information from a Cte object, but do not deallocate storage
005683 ** for the object itself.
005684 */
005685 static void cteClear(sqlite3 *db, Cte *pCte){
005686 assert( pCte!=0 );
005687 sqlite3ExprListDelete(db, pCte->pCols);
005688 sqlite3SelectDelete(db, pCte->pSelect);
005689 sqlite3DbFree(db, pCte->zName);
005690 }
005691
005692 /*
005693 ** Free the contents of the CTE object passed as the second argument.
005694 */
005695 void sqlite3CteDelete(sqlite3 *db, Cte *pCte){
005696 assert( pCte!=0 );
005697 cteClear(db, pCte);
005698 sqlite3DbFree(db, pCte);
005699 }
005700
005701 /*
005702 ** This routine is invoked once per CTE by the parser while parsing a
005703 ** WITH clause. The CTE described by the third argument is added to
005704 ** the WITH clause of the second argument. If the second argument is
005705 ** NULL, then a new WITH argument is created.
005706 */
005707 With *sqlite3WithAdd(
005708 Parse *pParse, /* Parsing context */
005709 With *pWith, /* Existing WITH clause, or NULL */
005710 Cte *pCte /* CTE to add to the WITH clause */
005711 ){
005712 sqlite3 *db = pParse->db;
005713 With *pNew;
005714 char *zName;
005715
005716 if( pCte==0 ){
005717 return pWith;
005718 }
005719
005720 /* Check that the CTE name is unique within this WITH clause. If
005721 ** not, store an error in the Parse structure. */
005722 zName = pCte->zName;
005723 if( zName && pWith ){
005724 int i;
005725 for(i=0; i<pWith->nCte; i++){
005726 if( sqlite3StrICmp(zName, pWith->a[i].zName)==0 ){
005727 sqlite3ErrorMsg(pParse, "duplicate WITH table name: %s", zName);
005728 }
005729 }
005730 }
005731
005732 if( pWith ){
005733 sqlite3_int64 nByte = sizeof(*pWith) + (sizeof(pWith->a[1]) * pWith->nCte);
005734 pNew = sqlite3DbRealloc(db, pWith, nByte);
005735 }else{
005736 pNew = sqlite3DbMallocZero(db, sizeof(*pWith));
005737 }
005738 assert( (pNew!=0 && zName!=0) || db->mallocFailed );
005739
005740 if( db->mallocFailed ){
005741 sqlite3CteDelete(db, pCte);
005742 pNew = pWith;
005743 }else{
005744 pNew->a[pNew->nCte++] = *pCte;
005745 sqlite3DbFree(db, pCte);
005746 }
005747
005748 return pNew;
005749 }
005750
005751 /*
005752 ** Free the contents of the With object passed as the second argument.
005753 */
005754 void sqlite3WithDelete(sqlite3 *db, With *pWith){
005755 if( pWith ){
005756 int i;
005757 for(i=0; i<pWith->nCte; i++){
005758 cteClear(db, &pWith->a[i]);
005759 }
005760 sqlite3DbFree(db, pWith);
005761 }
005762 }
005763 void sqlite3WithDeleteGeneric(sqlite3 *db, void *pWith){
005764 sqlite3WithDelete(db, (With*)pWith);
005765 }
005766 #endif /* !defined(SQLITE_OMIT_CTE) */