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 int 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 void sqlite3TableLock( 000050 Parse *pParse, /* Parsing context */ 000051 int iDb, /* Index of the database containing the table to lock */ 000052 int 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 = sqlite3ParseToplevel(pParse); 000057 int i; 000058 int nBytes; 000059 TableLock *p; 000060 assert( iDb>=0 ); 000061 000062 if( iDb==1 ) return; 000063 if( !sqlite3BtreeSharable(pParse->db->aDb[iDb].pBt) ) return; 000064 for(i=0; i<pToplevel->nTableLock; i++){ 000065 p = &pToplevel->aTableLock[i]; 000066 if( p->iDb==iDb && p->iTab==iTab ){ 000067 p->isWriteLock = (p->isWriteLock || isWriteLock); 000068 return; 000069 } 000070 } 000071 000072 nBytes = sizeof(TableLock) * (pToplevel->nTableLock+1); 000073 pToplevel->aTableLock = 000074 sqlite3DbReallocOrFree(pToplevel->db, pToplevel->aTableLock, nBytes); 000075 if( pToplevel->aTableLock ){ 000076 p = &pToplevel->aTableLock[pToplevel->nTableLock++]; 000077 p->iDb = iDb; 000078 p->iTab = iTab; 000079 p->isWriteLock = isWriteLock; 000080 p->zLockName = zName; 000081 }else{ 000082 pToplevel->nTableLock = 0; 000083 sqlite3OomFault(pToplevel->db); 000084 } 000085 } 000086 000087 /* 000088 ** Code an OP_TableLock instruction for each table locked by the 000089 ** statement (configured by calls to sqlite3TableLock()). 000090 */ 000091 static void codeTableLocks(Parse *pParse){ 000092 int i; 000093 Vdbe *pVdbe; 000094 000095 pVdbe = sqlite3GetVdbe(pParse); 000096 assert( pVdbe!=0 ); /* sqlite3GetVdbe cannot fail: VDBE already allocated */ 000097 000098 for(i=0; i<pParse->nTableLock; i++){ 000099 TableLock *p = &pParse->aTableLock[i]; 000100 int p1 = p->iDb; 000101 sqlite3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, p->isWriteLock, 000102 p->zLockName, P4_STATIC); 000103 } 000104 } 000105 #else 000106 #define codeTableLocks(x) 000107 #endif 000108 000109 /* 000110 ** Return TRUE if the given yDbMask object is empty - if it contains no 000111 ** 1 bits. This routine is used by the DbMaskAllZero() and DbMaskNotZero() 000112 ** macros when SQLITE_MAX_ATTACHED is greater than 30. 000113 */ 000114 #if SQLITE_MAX_ATTACHED>30 000115 int sqlite3DbMaskAllZero(yDbMask m){ 000116 int i; 000117 for(i=0; i<sizeof(yDbMask); i++) if( m[i] ) return 0; 000118 return 1; 000119 } 000120 #endif 000121 000122 /* 000123 ** This routine is called after a single SQL statement has been 000124 ** parsed and a VDBE program to execute that statement has been 000125 ** prepared. This routine puts the finishing touches on the 000126 ** VDBE program and resets the pParse structure for the next 000127 ** parse. 000128 ** 000129 ** Note that if an error occurred, it might be the case that 000130 ** no VDBE code was generated. 000131 */ 000132 void sqlite3FinishCoding(Parse *pParse){ 000133 sqlite3 *db; 000134 Vdbe *v; 000135 000136 assert( pParse->pToplevel==0 ); 000137 db = pParse->db; 000138 if( pParse->nested ) return; 000139 if( db->mallocFailed || pParse->nErr ){ 000140 if( pParse->rc==SQLITE_OK ) pParse->rc = SQLITE_ERROR; 000141 return; 000142 } 000143 000144 /* Begin by generating some termination code at the end of the 000145 ** vdbe program 000146 */ 000147 v = sqlite3GetVdbe(pParse); 000148 assert( !pParse->isMultiWrite 000149 || sqlite3VdbeAssertMayAbort(v, pParse->mayAbort)); 000150 if( v ){ 000151 sqlite3VdbeAddOp0(v, OP_Halt); 000152 000153 #if SQLITE_USER_AUTHENTICATION 000154 if( pParse->nTableLock>0 && db->init.busy==0 ){ 000155 sqlite3UserAuthInit(db); 000156 if( db->auth.authLevel<UAUTH_User ){ 000157 sqlite3ErrorMsg(pParse, "user not authenticated"); 000158 pParse->rc = SQLITE_AUTH_USER; 000159 return; 000160 } 000161 } 000162 #endif 000163 000164 /* The cookie mask contains one bit for each database file open. 000165 ** (Bit 0 is for main, bit 1 is for temp, and so forth.) Bits are 000166 ** set for each database that is used. Generate code to start a 000167 ** transaction on each used database and to verify the schema cookie 000168 ** on each used database. 000169 */ 000170 if( db->mallocFailed==0 000171 && (DbMaskNonZero(pParse->cookieMask) || pParse->pConstExpr) 000172 ){ 000173 int iDb, i; 000174 assert( sqlite3VdbeGetOp(v, 0)->opcode==OP_Init ); 000175 sqlite3VdbeJumpHere(v, 0); 000176 for(iDb=0; iDb<db->nDb; iDb++){ 000177 Schema *pSchema; 000178 if( DbMaskTest(pParse->cookieMask, iDb)==0 ) continue; 000179 sqlite3VdbeUsesBtree(v, iDb); 000180 pSchema = db->aDb[iDb].pSchema; 000181 sqlite3VdbeAddOp4Int(v, 000182 OP_Transaction, /* Opcode */ 000183 iDb, /* P1 */ 000184 DbMaskTest(pParse->writeMask,iDb), /* P2 */ 000185 pSchema->schema_cookie, /* P3 */ 000186 pSchema->iGeneration /* P4 */ 000187 ); 000188 if( db->init.busy==0 ) sqlite3VdbeChangeP5(v, 1); 000189 VdbeComment((v, 000190 "usesStmtJournal=%d", pParse->mayAbort && pParse->isMultiWrite)); 000191 } 000192 #ifndef SQLITE_OMIT_VIRTUALTABLE 000193 for(i=0; i<pParse->nVtabLock; i++){ 000194 char *vtab = (char *)sqlite3GetVTable(db, pParse->apVtabLock[i]); 000195 sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB); 000196 } 000197 pParse->nVtabLock = 0; 000198 #endif 000199 000200 /* Once all the cookies have been verified and transactions opened, 000201 ** obtain the required table-locks. This is a no-op unless the 000202 ** shared-cache feature is enabled. 000203 */ 000204 codeTableLocks(pParse); 000205 000206 /* Initialize any AUTOINCREMENT data structures required. 000207 */ 000208 sqlite3AutoincrementBegin(pParse); 000209 000210 /* Code constant expressions that where factored out of inner loops */ 000211 if( pParse->pConstExpr ){ 000212 ExprList *pEL = pParse->pConstExpr; 000213 pParse->okConstFactor = 0; 000214 for(i=0; i<pEL->nExpr; i++){ 000215 sqlite3ExprCode(pParse, pEL->a[i].pExpr, pEL->a[i].u.iConstExprReg); 000216 } 000217 } 000218 000219 /* Finally, jump back to the beginning of the executable code. */ 000220 sqlite3VdbeGoto(v, 1); 000221 } 000222 } 000223 000224 000225 /* Get the VDBE program ready for execution 000226 */ 000227 if( v && pParse->nErr==0 && !db->mallocFailed ){ 000228 assert( pParse->iCacheLevel==0 ); /* Disables and re-enables match */ 000229 /* A minimum of one cursor is required if autoincrement is used 000230 * See ticket [a696379c1f08866] */ 000231 if( pParse->pAinc!=0 && pParse->nTab==0 ) pParse->nTab = 1; 000232 sqlite3VdbeMakeReady(v, pParse); 000233 pParse->rc = SQLITE_DONE; 000234 }else{ 000235 pParse->rc = SQLITE_ERROR; 000236 } 000237 } 000238 000239 /* 000240 ** Run the parser and code generator recursively in order to generate 000241 ** code for the SQL statement given onto the end of the pParse context 000242 ** currently under construction. When the parser is run recursively 000243 ** this way, the final OP_Halt is not appended and other initialization 000244 ** and finalization steps are omitted because those are handling by the 000245 ** outermost parser. 000246 ** 000247 ** Not everything is nestable. This facility is designed to permit 000248 ** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER. Use 000249 ** care if you decide to try to use this routine for some other purposes. 000250 */ 000251 void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){ 000252 va_list ap; 000253 char *zSql; 000254 char *zErrMsg = 0; 000255 sqlite3 *db = pParse->db; 000256 char saveBuf[PARSE_TAIL_SZ]; 000257 000258 if( pParse->nErr ) return; 000259 assert( pParse->nested<10 ); /* Nesting should only be of limited depth */ 000260 va_start(ap, zFormat); 000261 zSql = sqlite3VMPrintf(db, zFormat, ap); 000262 va_end(ap); 000263 if( zSql==0 ){ 000264 return; /* A malloc must have failed */ 000265 } 000266 pParse->nested++; 000267 memcpy(saveBuf, PARSE_TAIL(pParse), PARSE_TAIL_SZ); 000268 memset(PARSE_TAIL(pParse), 0, PARSE_TAIL_SZ); 000269 sqlite3RunParser(pParse, zSql, &zErrMsg); 000270 sqlite3DbFree(db, zErrMsg); 000271 sqlite3DbFree(db, zSql); 000272 memcpy(PARSE_TAIL(pParse), saveBuf, PARSE_TAIL_SZ); 000273 pParse->nested--; 000274 } 000275 000276 #if SQLITE_USER_AUTHENTICATION 000277 /* 000278 ** Return TRUE if zTable is the name of the system table that stores the 000279 ** list of users and their access credentials. 000280 */ 000281 int sqlite3UserAuthTable(const char *zTable){ 000282 return sqlite3_stricmp(zTable, "sqlite_user")==0; 000283 } 000284 #endif 000285 000286 /* 000287 ** Locate the in-memory structure that describes a particular database 000288 ** table given the name of that table and (optionally) the name of the 000289 ** database containing the table. Return NULL if not found. 000290 ** 000291 ** If zDatabase is 0, all databases are searched for the table and the 000292 ** first matching table is returned. (No checking for duplicate table 000293 ** names is done.) The search order is TEMP first, then MAIN, then any 000294 ** auxiliary databases added using the ATTACH command. 000295 ** 000296 ** See also sqlite3LocateTable(). 000297 */ 000298 Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){ 000299 Table *p = 0; 000300 int i; 000301 000302 /* All mutexes are required for schema access. Make sure we hold them. */ 000303 assert( zDatabase!=0 || sqlite3BtreeHoldsAllMutexes(db) ); 000304 #if SQLITE_USER_AUTHENTICATION 000305 /* Only the admin user is allowed to know that the sqlite_user table 000306 ** exists */ 000307 if( db->auth.authLevel<UAUTH_Admin && sqlite3UserAuthTable(zName)!=0 ){ 000308 return 0; 000309 } 000310 #endif 000311 while(1){ 000312 for(i=OMIT_TEMPDB; i<db->nDb; i++){ 000313 int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */ 000314 if( zDatabase==0 || sqlite3StrICmp(zDatabase, db->aDb[j].zDbSName)==0 ){ 000315 assert( sqlite3SchemaMutexHeld(db, j, 0) ); 000316 p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName); 000317 if( p ) return p; 000318 } 000319 } 000320 /* Not found. If the name we were looking for was temp.sqlite_master 000321 ** then change the name to sqlite_temp_master and try again. */ 000322 if( sqlite3StrICmp(zName, MASTER_NAME)!=0 ) break; 000323 if( sqlite3_stricmp(zDatabase, db->aDb[1].zDbSName)!=0 ) break; 000324 zName = TEMP_MASTER_NAME; 000325 } 000326 return 0; 000327 } 000328 000329 /* 000330 ** Locate the in-memory structure that describes a particular database 000331 ** table given the name of that table and (optionally) the name of the 000332 ** database containing the table. Return NULL if not found. Also leave an 000333 ** error message in pParse->zErrMsg. 000334 ** 000335 ** The difference between this routine and sqlite3FindTable() is that this 000336 ** routine leaves an error message in pParse->zErrMsg where 000337 ** sqlite3FindTable() does not. 000338 */ 000339 Table *sqlite3LocateTable( 000340 Parse *pParse, /* context in which to report errors */ 000341 u32 flags, /* LOCATE_VIEW or LOCATE_NOERR */ 000342 const char *zName, /* Name of the table we are looking for */ 000343 const char *zDbase /* Name of the database. Might be NULL */ 000344 ){ 000345 Table *p; 000346 000347 /* Read the database schema. If an error occurs, leave an error message 000348 ** and code in pParse and return NULL. */ 000349 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){ 000350 return 0; 000351 } 000352 000353 p = sqlite3FindTable(pParse->db, zName, zDbase); 000354 if( p==0 ){ 000355 const char *zMsg = flags & LOCATE_VIEW ? "no such view" : "no such table"; 000356 #ifndef SQLITE_OMIT_VIRTUALTABLE 000357 if( sqlite3FindDbName(pParse->db, zDbase)<1 ){ 000358 /* If zName is the not the name of a table in the schema created using 000359 ** CREATE, then check to see if it is the name of an virtual table that 000360 ** can be an eponymous virtual table. */ 000361 Module *pMod = (Module*)sqlite3HashFind(&pParse->db->aModule, zName); 000362 if( pMod==0 && sqlite3_strnicmp(zName, "pragma_", 7)==0 ){ 000363 pMod = sqlite3PragmaVtabRegister(pParse->db, zName); 000364 } 000365 if( pMod && sqlite3VtabEponymousTableInit(pParse, pMod) ){ 000366 return pMod->pEpoTab; 000367 } 000368 } 000369 #endif 000370 if( (flags & LOCATE_NOERR)==0 ){ 000371 if( zDbase ){ 000372 sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName); 000373 }else{ 000374 sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName); 000375 } 000376 pParse->checkSchema = 1; 000377 } 000378 } 000379 000380 return p; 000381 } 000382 000383 /* 000384 ** Locate the table identified by *p. 000385 ** 000386 ** This is a wrapper around sqlite3LocateTable(). The difference between 000387 ** sqlite3LocateTable() and this function is that this function restricts 000388 ** the search to schema (p->pSchema) if it is not NULL. p->pSchema may be 000389 ** non-NULL if it is part of a view or trigger program definition. See 000390 ** sqlite3FixSrcList() for details. 000391 */ 000392 Table *sqlite3LocateTableItem( 000393 Parse *pParse, 000394 u32 flags, 000395 struct SrcList_item *p 000396 ){ 000397 const char *zDb; 000398 assert( p->pSchema==0 || p->zDatabase==0 ); 000399 if( p->pSchema ){ 000400 int iDb = sqlite3SchemaToIndex(pParse->db, p->pSchema); 000401 zDb = pParse->db->aDb[iDb].zDbSName; 000402 }else{ 000403 zDb = p->zDatabase; 000404 } 000405 return sqlite3LocateTable(pParse, flags, p->zName, zDb); 000406 } 000407 000408 /* 000409 ** Locate the in-memory structure that describes 000410 ** a particular index given the name of that index 000411 ** and the name of the database that contains the index. 000412 ** Return NULL if not found. 000413 ** 000414 ** If zDatabase is 0, all databases are searched for the 000415 ** table and the first matching index is returned. (No checking 000416 ** for duplicate index names is done.) The search order is 000417 ** TEMP first, then MAIN, then any auxiliary databases added 000418 ** using the ATTACH command. 000419 */ 000420 Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){ 000421 Index *p = 0; 000422 int i; 000423 /* All mutexes are required for schema access. Make sure we hold them. */ 000424 assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) ); 000425 for(i=OMIT_TEMPDB; i<db->nDb; i++){ 000426 int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */ 000427 Schema *pSchema = db->aDb[j].pSchema; 000428 assert( pSchema ); 000429 if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zDbSName) ) continue; 000430 assert( sqlite3SchemaMutexHeld(db, j, 0) ); 000431 p = sqlite3HashFind(&pSchema->idxHash, zName); 000432 if( p ) break; 000433 } 000434 return p; 000435 } 000436 000437 /* 000438 ** Reclaim the memory used by an index 000439 */ 000440 static void freeIndex(sqlite3 *db, Index *p){ 000441 #ifndef SQLITE_OMIT_ANALYZE 000442 sqlite3DeleteIndexSamples(db, p); 000443 #endif 000444 sqlite3ExprDelete(db, p->pPartIdxWhere); 000445 sqlite3ExprListDelete(db, p->aColExpr); 000446 sqlite3DbFree(db, p->zColAff); 000447 if( p->isResized ) sqlite3DbFree(db, (void *)p->azColl); 000448 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4 000449 sqlite3_free(p->aiRowEst); 000450 #endif 000451 sqlite3DbFree(db, p); 000452 } 000453 000454 /* 000455 ** For the index called zIdxName which is found in the database iDb, 000456 ** unlike that index from its Table then remove the index from 000457 ** the index hash table and free all memory structures associated 000458 ** with the index. 000459 */ 000460 void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){ 000461 Index *pIndex; 000462 Hash *pHash; 000463 000464 assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); 000465 pHash = &db->aDb[iDb].pSchema->idxHash; 000466 pIndex = sqlite3HashInsert(pHash, zIdxName, 0); 000467 if( ALWAYS(pIndex) ){ 000468 if( pIndex->pTable->pIndex==pIndex ){ 000469 pIndex->pTable->pIndex = pIndex->pNext; 000470 }else{ 000471 Index *p; 000472 /* Justification of ALWAYS(); The index must be on the list of 000473 ** indices. */ 000474 p = pIndex->pTable->pIndex; 000475 while( ALWAYS(p) && p->pNext!=pIndex ){ p = p->pNext; } 000476 if( ALWAYS(p && p->pNext==pIndex) ){ 000477 p->pNext = pIndex->pNext; 000478 } 000479 } 000480 freeIndex(db, pIndex); 000481 } 000482 db->flags |= SQLITE_InternChanges; 000483 } 000484 000485 /* 000486 ** Look through the list of open database files in db->aDb[] and if 000487 ** any have been closed, remove them from the list. Reallocate the 000488 ** db->aDb[] structure to a smaller size, if possible. 000489 ** 000490 ** Entry 0 (the "main" database) and entry 1 (the "temp" database) 000491 ** are never candidates for being collapsed. 000492 */ 000493 void sqlite3CollapseDatabaseArray(sqlite3 *db){ 000494 int i, j; 000495 for(i=j=2; i<db->nDb; i++){ 000496 struct Db *pDb = &db->aDb[i]; 000497 if( pDb->pBt==0 ){ 000498 sqlite3DbFree(db, pDb->zDbSName); 000499 pDb->zDbSName = 0; 000500 continue; 000501 } 000502 if( j<i ){ 000503 db->aDb[j] = db->aDb[i]; 000504 } 000505 j++; 000506 } 000507 db->nDb = j; 000508 if( db->nDb<=2 && db->aDb!=db->aDbStatic ){ 000509 memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0])); 000510 sqlite3DbFree(db, db->aDb); 000511 db->aDb = db->aDbStatic; 000512 } 000513 } 000514 000515 /* 000516 ** Reset the schema for the database at index iDb. Also reset the 000517 ** TEMP schema. 000518 */ 000519 void sqlite3ResetOneSchema(sqlite3 *db, int iDb){ 000520 Db *pDb; 000521 assert( iDb<db->nDb ); 000522 000523 /* Case 1: Reset the single schema identified by iDb */ 000524 pDb = &db->aDb[iDb]; 000525 assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); 000526 assert( pDb->pSchema!=0 ); 000527 sqlite3SchemaClear(pDb->pSchema); 000528 000529 /* If any database other than TEMP is reset, then also reset TEMP 000530 ** since TEMP might be holding triggers that reference tables in the 000531 ** other database. 000532 */ 000533 if( iDb!=1 ){ 000534 pDb = &db->aDb[1]; 000535 assert( pDb->pSchema!=0 ); 000536 sqlite3SchemaClear(pDb->pSchema); 000537 } 000538 return; 000539 } 000540 000541 /* 000542 ** Erase all schema information from all attached databases (including 000543 ** "main" and "temp") for a single database connection. 000544 */ 000545 void sqlite3ResetAllSchemasOfConnection(sqlite3 *db){ 000546 int i; 000547 sqlite3BtreeEnterAll(db); 000548 for(i=0; i<db->nDb; i++){ 000549 Db *pDb = &db->aDb[i]; 000550 if( pDb->pSchema ){ 000551 sqlite3SchemaClear(pDb->pSchema); 000552 } 000553 } 000554 db->flags &= ~SQLITE_InternChanges; 000555 sqlite3VtabUnlockList(db); 000556 sqlite3BtreeLeaveAll(db); 000557 sqlite3CollapseDatabaseArray(db); 000558 } 000559 000560 /* 000561 ** This routine is called when a commit occurs. 000562 */ 000563 void sqlite3CommitInternalChanges(sqlite3 *db){ 000564 db->flags &= ~SQLITE_InternChanges; 000565 } 000566 000567 /* 000568 ** Delete memory allocated for the column names of a table or view (the 000569 ** Table.aCol[] array). 000570 */ 000571 void sqlite3DeleteColumnNames(sqlite3 *db, Table *pTable){ 000572 int i; 000573 Column *pCol; 000574 assert( pTable!=0 ); 000575 if( (pCol = pTable->aCol)!=0 ){ 000576 for(i=0; i<pTable->nCol; i++, pCol++){ 000577 sqlite3DbFree(db, pCol->zName); 000578 sqlite3ExprDelete(db, pCol->pDflt); 000579 sqlite3DbFree(db, pCol->zColl); 000580 } 000581 sqlite3DbFree(db, pTable->aCol); 000582 } 000583 } 000584 000585 /* 000586 ** Remove the memory data structures associated with the given 000587 ** Table. No changes are made to disk by this routine. 000588 ** 000589 ** This routine just deletes the data structure. It does not unlink 000590 ** the table data structure from the hash table. But it does destroy 000591 ** memory structures of the indices and foreign keys associated with 000592 ** the table. 000593 ** 000594 ** The db parameter is optional. It is needed if the Table object 000595 ** contains lookaside memory. (Table objects in the schema do not use 000596 ** lookaside memory, but some ephemeral Table objects do.) Or the 000597 ** db parameter can be used with db->pnBytesFreed to measure the memory 000598 ** used by the Table object. 000599 */ 000600 static void SQLITE_NOINLINE deleteTable(sqlite3 *db, Table *pTable){ 000601 Index *pIndex, *pNext; 000602 TESTONLY( int nLookaside; ) /* Used to verify lookaside not used for schema */ 000603 000604 /* Record the number of outstanding lookaside allocations in schema Tables 000605 ** prior to doing any free() operations. Since schema Tables do not use 000606 ** lookaside, this number should not change. */ 000607 TESTONLY( nLookaside = (db && (pTable->tabFlags & TF_Ephemeral)==0) ? 000608 db->lookaside.nOut : 0 ); 000609 000610 /* Delete all indices associated with this table. */ 000611 for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){ 000612 pNext = pIndex->pNext; 000613 assert( pIndex->pSchema==pTable->pSchema 000614 || (IsVirtual(pTable) && pIndex->idxType!=SQLITE_IDXTYPE_APPDEF) ); 000615 if( (db==0 || db->pnBytesFreed==0) && !IsVirtual(pTable) ){ 000616 char *zName = pIndex->zName; 000617 TESTONLY ( Index *pOld = ) sqlite3HashInsert( 000618 &pIndex->pSchema->idxHash, zName, 0 000619 ); 000620 assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) ); 000621 assert( pOld==pIndex || pOld==0 ); 000622 } 000623 freeIndex(db, pIndex); 000624 } 000625 000626 /* Delete any foreign keys attached to this table. */ 000627 sqlite3FkDelete(db, pTable); 000628 000629 /* Delete the Table structure itself. 000630 */ 000631 sqlite3DeleteColumnNames(db, pTable); 000632 sqlite3DbFree(db, pTable->zName); 000633 sqlite3DbFree(db, pTable->zColAff); 000634 sqlite3SelectDelete(db, pTable->pSelect); 000635 sqlite3ExprListDelete(db, pTable->pCheck); 000636 #ifndef SQLITE_OMIT_VIRTUALTABLE 000637 sqlite3VtabClear(db, pTable); 000638 #endif 000639 sqlite3DbFree(db, pTable); 000640 000641 /* Verify that no lookaside memory was used by schema tables */ 000642 assert( nLookaside==0 || nLookaside==db->lookaside.nOut ); 000643 } 000644 void sqlite3DeleteTable(sqlite3 *db, Table *pTable){ 000645 /* Do not delete the table until the reference count reaches zero. */ 000646 if( !pTable ) return; 000647 if( ((!db || db->pnBytesFreed==0) && (--pTable->nTabRef)>0) ) return; 000648 deleteTable(db, pTable); 000649 } 000650 000651 000652 /* 000653 ** Unlink the given table from the hash tables and the delete the 000654 ** table structure with all its indices and foreign keys. 000655 */ 000656 void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){ 000657 Table *p; 000658 Db *pDb; 000659 000660 assert( db!=0 ); 000661 assert( iDb>=0 && iDb<db->nDb ); 000662 assert( zTabName ); 000663 assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); 000664 testcase( zTabName[0]==0 ); /* Zero-length table names are allowed */ 000665 pDb = &db->aDb[iDb]; 000666 p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName, 0); 000667 sqlite3DeleteTable(db, p); 000668 db->flags |= SQLITE_InternChanges; 000669 } 000670 000671 /* 000672 ** Given a token, return a string that consists of the text of that 000673 ** token. Space to hold the returned string 000674 ** is obtained from sqliteMalloc() and must be freed by the calling 000675 ** function. 000676 ** 000677 ** Any quotation marks (ex: "name", 'name', [name], or `name`) that 000678 ** surround the body of the token are removed. 000679 ** 000680 ** Tokens are often just pointers into the original SQL text and so 000681 ** are not \000 terminated and are not persistent. The returned string 000682 ** is \000 terminated and is persistent. 000683 */ 000684 char *sqlite3NameFromToken(sqlite3 *db, Token *pName){ 000685 char *zName; 000686 if( pName ){ 000687 zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n); 000688 sqlite3Dequote(zName); 000689 }else{ 000690 zName = 0; 000691 } 000692 return zName; 000693 } 000694 000695 /* 000696 ** Open the sqlite_master table stored in database number iDb for 000697 ** writing. The table is opened using cursor 0. 000698 */ 000699 void sqlite3OpenMasterTable(Parse *p, int iDb){ 000700 Vdbe *v = sqlite3GetVdbe(p); 000701 sqlite3TableLock(p, iDb, MASTER_ROOT, 1, MASTER_NAME); 000702 sqlite3VdbeAddOp4Int(v, OP_OpenWrite, 0, MASTER_ROOT, iDb, 5); 000703 if( p->nTab==0 ){ 000704 p->nTab = 1; 000705 } 000706 } 000707 000708 /* 000709 ** Parameter zName points to a nul-terminated buffer containing the name 000710 ** of a database ("main", "temp" or the name of an attached db). This 000711 ** function returns the index of the named database in db->aDb[], or 000712 ** -1 if the named db cannot be found. 000713 */ 000714 int sqlite3FindDbName(sqlite3 *db, const char *zName){ 000715 int i = -1; /* Database number */ 000716 if( zName ){ 000717 Db *pDb; 000718 for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){ 000719 if( 0==sqlite3_stricmp(pDb->zDbSName, zName) ) break; 000720 /* "main" is always an acceptable alias for the primary database 000721 ** even if it has been renamed using SQLITE_DBCONFIG_MAINDBNAME. */ 000722 if( i==0 && 0==sqlite3_stricmp("main", zName) ) break; 000723 } 000724 } 000725 return i; 000726 } 000727 000728 /* 000729 ** The token *pName contains the name of a database (either "main" or 000730 ** "temp" or the name of an attached db). This routine returns the 000731 ** index of the named database in db->aDb[], or -1 if the named db 000732 ** does not exist. 000733 */ 000734 int sqlite3FindDb(sqlite3 *db, Token *pName){ 000735 int i; /* Database number */ 000736 char *zName; /* Name we are searching for */ 000737 zName = sqlite3NameFromToken(db, pName); 000738 i = sqlite3FindDbName(db, zName); 000739 sqlite3DbFree(db, zName); 000740 return i; 000741 } 000742 000743 /* The table or view or trigger name is passed to this routine via tokens 000744 ** pName1 and pName2. If the table name was fully qualified, for example: 000745 ** 000746 ** CREATE TABLE xxx.yyy (...); 000747 ** 000748 ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if 000749 ** the table name is not fully qualified, i.e.: 000750 ** 000751 ** CREATE TABLE yyy(...); 000752 ** 000753 ** Then pName1 is set to "yyy" and pName2 is "". 000754 ** 000755 ** This routine sets the *ppUnqual pointer to point at the token (pName1 or 000756 ** pName2) that stores the unqualified table name. The index of the 000757 ** database "xxx" is returned. 000758 */ 000759 int sqlite3TwoPartName( 000760 Parse *pParse, /* Parsing and code generating context */ 000761 Token *pName1, /* The "xxx" in the name "xxx.yyy" or "xxx" */ 000762 Token *pName2, /* The "yyy" in the name "xxx.yyy" */ 000763 Token **pUnqual /* Write the unqualified object name here */ 000764 ){ 000765 int iDb; /* Database holding the object */ 000766 sqlite3 *db = pParse->db; 000767 000768 assert( pName2!=0 ); 000769 if( pName2->n>0 ){ 000770 if( db->init.busy ) { 000771 sqlite3ErrorMsg(pParse, "corrupt database"); 000772 return -1; 000773 } 000774 *pUnqual = pName2; 000775 iDb = sqlite3FindDb(db, pName1); 000776 if( iDb<0 ){ 000777 sqlite3ErrorMsg(pParse, "unknown database %T", pName1); 000778 return -1; 000779 } 000780 }else{ 000781 assert( db->init.iDb==0 || db->init.busy || (db->flags & SQLITE_Vacuum)!=0); 000782 iDb = db->init.iDb; 000783 *pUnqual = pName1; 000784 } 000785 return iDb; 000786 } 000787 000788 /* 000789 ** This routine is used to check if the UTF-8 string zName is a legal 000790 ** unqualified name for a new schema object (table, index, view or 000791 ** trigger). All names are legal except those that begin with the string 000792 ** "sqlite_" (in upper, lower or mixed case). This portion of the namespace 000793 ** is reserved for internal use. 000794 */ 000795 int sqlite3CheckObjectName(Parse *pParse, const char *zName){ 000796 if( !pParse->db->init.busy && pParse->nested==0 000797 && (pParse->db->flags & SQLITE_WriteSchema)==0 000798 && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){ 000799 sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName); 000800 return SQLITE_ERROR; 000801 } 000802 return SQLITE_OK; 000803 } 000804 000805 /* 000806 ** Return the PRIMARY KEY index of a table 000807 */ 000808 Index *sqlite3PrimaryKeyIndex(Table *pTab){ 000809 Index *p; 000810 for(p=pTab->pIndex; p && !IsPrimaryKeyIndex(p); p=p->pNext){} 000811 return p; 000812 } 000813 000814 /* 000815 ** Return the column of index pIdx that corresponds to table 000816 ** column iCol. Return -1 if not found. 000817 */ 000818 i16 sqlite3ColumnOfIndex(Index *pIdx, i16 iCol){ 000819 int i; 000820 for(i=0; i<pIdx->nColumn; i++){ 000821 if( iCol==pIdx->aiColumn[i] ) return i; 000822 } 000823 return -1; 000824 } 000825 000826 /* 000827 ** Begin constructing a new table representation in memory. This is 000828 ** the first of several action routines that get called in response 000829 ** to a CREATE TABLE statement. In particular, this routine is called 000830 ** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp 000831 ** flag is true if the table should be stored in the auxiliary database 000832 ** file instead of in the main database file. This is normally the case 000833 ** when the "TEMP" or "TEMPORARY" keyword occurs in between 000834 ** CREATE and TABLE. 000835 ** 000836 ** The new table record is initialized and put in pParse->pNewTable. 000837 ** As more of the CREATE TABLE statement is parsed, additional action 000838 ** routines will be called to add more information to this record. 000839 ** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine 000840 ** is called to complete the construction of the new table record. 000841 */ 000842 void sqlite3StartTable( 000843 Parse *pParse, /* Parser context */ 000844 Token *pName1, /* First part of the name of the table or view */ 000845 Token *pName2, /* Second part of the name of the table or view */ 000846 int isTemp, /* True if this is a TEMP table */ 000847 int isView, /* True if this is a VIEW */ 000848 int isVirtual, /* True if this is a VIRTUAL table */ 000849 int noErr /* Do nothing if table already exists */ 000850 ){ 000851 Table *pTable; 000852 char *zName = 0; /* The name of the new table */ 000853 sqlite3 *db = pParse->db; 000854 Vdbe *v; 000855 int iDb; /* Database number to create the table in */ 000856 Token *pName; /* Unqualified name of the table to create */ 000857 000858 if( db->init.busy && db->init.newTnum==1 ){ 000859 /* Special case: Parsing the sqlite_master or sqlite_temp_master schema */ 000860 iDb = db->init.iDb; 000861 zName = sqlite3DbStrDup(db, SCHEMA_TABLE(iDb)); 000862 pName = pName1; 000863 }else{ 000864 /* The common case */ 000865 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName); 000866 if( iDb<0 ) return; 000867 if( !OMIT_TEMPDB && isTemp && pName2->n>0 && iDb!=1 ){ 000868 /* If creating a temp table, the name may not be qualified. Unless 000869 ** the database name is "temp" anyway. */ 000870 sqlite3ErrorMsg(pParse, "temporary table name must be unqualified"); 000871 return; 000872 } 000873 if( !OMIT_TEMPDB && isTemp ) iDb = 1; 000874 zName = sqlite3NameFromToken(db, pName); 000875 } 000876 pParse->sNameToken = *pName; 000877 if( zName==0 ) return; 000878 if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){ 000879 goto begin_table_error; 000880 } 000881 if( db->init.iDb==1 ) isTemp = 1; 000882 #ifndef SQLITE_OMIT_AUTHORIZATION 000883 assert( isTemp==0 || isTemp==1 ); 000884 assert( isView==0 || isView==1 ); 000885 { 000886 static const u8 aCode[] = { 000887 SQLITE_CREATE_TABLE, 000888 SQLITE_CREATE_TEMP_TABLE, 000889 SQLITE_CREATE_VIEW, 000890 SQLITE_CREATE_TEMP_VIEW 000891 }; 000892 char *zDb = db->aDb[iDb].zDbSName; 000893 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){ 000894 goto begin_table_error; 000895 } 000896 if( !isVirtual && sqlite3AuthCheck(pParse, (int)aCode[isTemp+2*isView], 000897 zName, 0, zDb) ){ 000898 goto begin_table_error; 000899 } 000900 } 000901 #endif 000902 000903 /* Make sure the new table name does not collide with an existing 000904 ** index or table name in the same database. Issue an error message if 000905 ** it does. The exception is if the statement being parsed was passed 000906 ** to an sqlite3_declare_vtab() call. In that case only the column names 000907 ** and types will be used, so there is no need to test for namespace 000908 ** collisions. 000909 */ 000910 if( !IN_DECLARE_VTAB ){ 000911 char *zDb = db->aDb[iDb].zDbSName; 000912 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){ 000913 goto begin_table_error; 000914 } 000915 pTable = sqlite3FindTable(db, zName, zDb); 000916 if( pTable ){ 000917 if( !noErr ){ 000918 sqlite3ErrorMsg(pParse, "table %T already exists", pName); 000919 }else{ 000920 assert( !db->init.busy || CORRUPT_DB ); 000921 sqlite3CodeVerifySchema(pParse, iDb); 000922 } 000923 goto begin_table_error; 000924 } 000925 if( sqlite3FindIndex(db, zName, zDb)!=0 ){ 000926 sqlite3ErrorMsg(pParse, "there is already an index named %s", zName); 000927 goto begin_table_error; 000928 } 000929 } 000930 000931 pTable = sqlite3DbMallocZero(db, sizeof(Table)); 000932 if( pTable==0 ){ 000933 assert( db->mallocFailed ); 000934 pParse->rc = SQLITE_NOMEM_BKPT; 000935 pParse->nErr++; 000936 goto begin_table_error; 000937 } 000938 pTable->zName = zName; 000939 pTable->iPKey = -1; 000940 pTable->pSchema = db->aDb[iDb].pSchema; 000941 pTable->nTabRef = 1; 000942 pTable->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) ); 000943 assert( pParse->pNewTable==0 ); 000944 pParse->pNewTable = pTable; 000945 000946 /* If this is the magic sqlite_sequence table used by autoincrement, 000947 ** then record a pointer to this table in the main database structure 000948 ** so that INSERT can find the table easily. 000949 */ 000950 #ifndef SQLITE_OMIT_AUTOINCREMENT 000951 if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){ 000952 assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); 000953 pTable->pSchema->pSeqTab = pTable; 000954 } 000955 #endif 000956 000957 /* Begin generating the code that will insert the table record into 000958 ** the SQLITE_MASTER table. Note in particular that we must go ahead 000959 ** and allocate the record number for the table entry now. Before any 000960 ** PRIMARY KEY or UNIQUE keywords are parsed. Those keywords will cause 000961 ** indices to be created and the table record must come before the 000962 ** indices. Hence, the record number for the table must be allocated 000963 ** now. 000964 */ 000965 if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){ 000966 int addr1; 000967 int fileFormat; 000968 int reg1, reg2, reg3; 000969 /* nullRow[] is an OP_Record encoding of a row containing 5 NULLs */ 000970 static const char nullRow[] = { 6, 0, 0, 0, 0, 0 }; 000971 sqlite3BeginWriteOperation(pParse, 1, iDb); 000972 000973 #ifndef SQLITE_OMIT_VIRTUALTABLE 000974 if( isVirtual ){ 000975 sqlite3VdbeAddOp0(v, OP_VBegin); 000976 } 000977 #endif 000978 000979 /* If the file format and encoding in the database have not been set, 000980 ** set them now. 000981 */ 000982 reg1 = pParse->regRowid = ++pParse->nMem; 000983 reg2 = pParse->regRoot = ++pParse->nMem; 000984 reg3 = ++pParse->nMem; 000985 sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT); 000986 sqlite3VdbeUsesBtree(v, iDb); 000987 addr1 = sqlite3VdbeAddOp1(v, OP_If, reg3); VdbeCoverage(v); 000988 fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ? 000989 1 : SQLITE_MAX_FILE_FORMAT; 000990 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, fileFormat); 000991 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, ENC(db)); 000992 sqlite3VdbeJumpHere(v, addr1); 000993 000994 /* This just creates a place-holder record in the sqlite_master table. 000995 ** The record created does not contain anything yet. It will be replaced 000996 ** by the real entry in code generated at sqlite3EndTable(). 000997 ** 000998 ** The rowid for the new entry is left in register pParse->regRowid. 000999 ** The root page number of the new table is left in reg pParse->regRoot. 001000 ** The rowid and root page number values are needed by the code that 001001 ** sqlite3EndTable will generate. 001002 */ 001003 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) 001004 if( isView || isVirtual ){ 001005 sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2); 001006 }else 001007 #endif 001008 { 001009 pParse->addrCrTab = sqlite3VdbeAddOp2(v, OP_CreateTable, iDb, reg2); 001010 } 001011 sqlite3OpenMasterTable(pParse, iDb); 001012 sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1); 001013 sqlite3VdbeAddOp4(v, OP_Blob, 6, reg3, 0, nullRow, P4_STATIC); 001014 sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1); 001015 sqlite3VdbeChangeP5(v, OPFLAG_APPEND); 001016 sqlite3VdbeAddOp0(v, OP_Close); 001017 } 001018 001019 /* Normal (non-error) return. */ 001020 return; 001021 001022 /* If an error occurs, we jump here */ 001023 begin_table_error: 001024 sqlite3DbFree(db, zName); 001025 return; 001026 } 001027 001028 /* Set properties of a table column based on the (magical) 001029 ** name of the column. 001030 */ 001031 #if SQLITE_ENABLE_HIDDEN_COLUMNS 001032 void sqlite3ColumnPropertiesFromName(Table *pTab, Column *pCol){ 001033 if( sqlite3_strnicmp(pCol->zName, "__hidden__", 10)==0 ){ 001034 pCol->colFlags |= COLFLAG_HIDDEN; 001035 }else if( pTab && pCol!=pTab->aCol && (pCol[-1].colFlags & COLFLAG_HIDDEN) ){ 001036 pTab->tabFlags |= TF_OOOHidden; 001037 } 001038 } 001039 #endif 001040 001041 001042 /* 001043 ** Add a new column to the table currently being constructed. 001044 ** 001045 ** The parser calls this routine once for each column declaration 001046 ** in a CREATE TABLE statement. sqlite3StartTable() gets called 001047 ** first to get things going. Then this routine is called for each 001048 ** column. 001049 */ 001050 void sqlite3AddColumn(Parse *pParse, Token *pName, Token *pType){ 001051 Table *p; 001052 int i; 001053 char *z; 001054 char *zType; 001055 Column *pCol; 001056 sqlite3 *db = pParse->db; 001057 if( (p = pParse->pNewTable)==0 ) return; 001058 #if SQLITE_MAX_COLUMN 001059 if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){ 001060 sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName); 001061 return; 001062 } 001063 #endif 001064 z = sqlite3DbMallocRaw(db, pName->n + pType->n + 2); 001065 if( z==0 ) return; 001066 memcpy(z, pName->z, pName->n); 001067 z[pName->n] = 0; 001068 sqlite3Dequote(z); 001069 for(i=0; i<p->nCol; i++){ 001070 if( sqlite3_stricmp(z, p->aCol[i].zName)==0 ){ 001071 sqlite3ErrorMsg(pParse, "duplicate column name: %s", z); 001072 sqlite3DbFree(db, z); 001073 return; 001074 } 001075 } 001076 if( (p->nCol & 0x7)==0 ){ 001077 Column *aNew; 001078 aNew = sqlite3DbRealloc(db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0])); 001079 if( aNew==0 ){ 001080 sqlite3DbFree(db, z); 001081 return; 001082 } 001083 p->aCol = aNew; 001084 } 001085 pCol = &p->aCol[p->nCol]; 001086 memset(pCol, 0, sizeof(p->aCol[0])); 001087 pCol->zName = z; 001088 sqlite3ColumnPropertiesFromName(p, pCol); 001089 001090 if( pType->n==0 ){ 001091 /* If there is no type specified, columns have the default affinity 001092 ** 'BLOB'. */ 001093 pCol->affinity = SQLITE_AFF_BLOB; 001094 pCol->szEst = 1; 001095 }else{ 001096 zType = z + sqlite3Strlen30(z) + 1; 001097 memcpy(zType, pType->z, pType->n); 001098 zType[pType->n] = 0; 001099 sqlite3Dequote(zType); 001100 pCol->affinity = sqlite3AffinityType(zType, &pCol->szEst); 001101 pCol->colFlags |= COLFLAG_HASTYPE; 001102 } 001103 p->nCol++; 001104 pParse->constraintName.n = 0; 001105 } 001106 001107 /* 001108 ** This routine is called by the parser while in the middle of 001109 ** parsing a CREATE TABLE statement. A "NOT NULL" constraint has 001110 ** been seen on a column. This routine sets the notNull flag on 001111 ** the column currently under construction. 001112 */ 001113 void sqlite3AddNotNull(Parse *pParse, int onError){ 001114 Table *p; 001115 p = pParse->pNewTable; 001116 if( p==0 || NEVER(p->nCol<1) ) return; 001117 p->aCol[p->nCol-1].notNull = (u8)onError; 001118 } 001119 001120 /* 001121 ** Scan the column type name zType (length nType) and return the 001122 ** associated affinity type. 001123 ** 001124 ** This routine does a case-independent search of zType for the 001125 ** substrings in the following table. If one of the substrings is 001126 ** found, the corresponding affinity is returned. If zType contains 001127 ** more than one of the substrings, entries toward the top of 001128 ** the table take priority. For example, if zType is 'BLOBINT', 001129 ** SQLITE_AFF_INTEGER is returned. 001130 ** 001131 ** Substring | Affinity 001132 ** -------------------------------- 001133 ** 'INT' | SQLITE_AFF_INTEGER 001134 ** 'CHAR' | SQLITE_AFF_TEXT 001135 ** 'CLOB' | SQLITE_AFF_TEXT 001136 ** 'TEXT' | SQLITE_AFF_TEXT 001137 ** 'BLOB' | SQLITE_AFF_BLOB 001138 ** 'REAL' | SQLITE_AFF_REAL 001139 ** 'FLOA' | SQLITE_AFF_REAL 001140 ** 'DOUB' | SQLITE_AFF_REAL 001141 ** 001142 ** If none of the substrings in the above table are found, 001143 ** SQLITE_AFF_NUMERIC is returned. 001144 */ 001145 char sqlite3AffinityType(const char *zIn, u8 *pszEst){ 001146 u32 h = 0; 001147 char aff = SQLITE_AFF_NUMERIC; 001148 const char *zChar = 0; 001149 001150 assert( zIn!=0 ); 001151 while( zIn[0] ){ 001152 h = (h<<8) + sqlite3UpperToLower[(*zIn)&0xff]; 001153 zIn++; 001154 if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){ /* CHAR */ 001155 aff = SQLITE_AFF_TEXT; 001156 zChar = zIn; 001157 }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){ /* CLOB */ 001158 aff = SQLITE_AFF_TEXT; 001159 }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){ /* TEXT */ 001160 aff = SQLITE_AFF_TEXT; 001161 }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b') /* BLOB */ 001162 && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){ 001163 aff = SQLITE_AFF_BLOB; 001164 if( zIn[0]=='(' ) zChar = zIn; 001165 #ifndef SQLITE_OMIT_FLOATING_POINT 001166 }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l') /* REAL */ 001167 && aff==SQLITE_AFF_NUMERIC ){ 001168 aff = SQLITE_AFF_REAL; 001169 }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a') /* FLOA */ 001170 && aff==SQLITE_AFF_NUMERIC ){ 001171 aff = SQLITE_AFF_REAL; 001172 }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b') /* DOUB */ 001173 && aff==SQLITE_AFF_NUMERIC ){ 001174 aff = SQLITE_AFF_REAL; 001175 #endif 001176 }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){ /* INT */ 001177 aff = SQLITE_AFF_INTEGER; 001178 break; 001179 } 001180 } 001181 001182 /* If pszEst is not NULL, store an estimate of the field size. The 001183 ** estimate is scaled so that the size of an integer is 1. */ 001184 if( pszEst ){ 001185 *pszEst = 1; /* default size is approx 4 bytes */ 001186 if( aff<SQLITE_AFF_NUMERIC ){ 001187 if( zChar ){ 001188 while( zChar[0] ){ 001189 if( sqlite3Isdigit(zChar[0]) ){ 001190 int v = 0; 001191 sqlite3GetInt32(zChar, &v); 001192 v = v/4 + 1; 001193 if( v>255 ) v = 255; 001194 *pszEst = v; /* BLOB(k), VARCHAR(k), CHAR(k) -> r=(k/4+1) */ 001195 break; 001196 } 001197 zChar++; 001198 } 001199 }else{ 001200 *pszEst = 5; /* BLOB, TEXT, CLOB -> r=5 (approx 20 bytes)*/ 001201 } 001202 } 001203 } 001204 return aff; 001205 } 001206 001207 /* 001208 ** The expression is the default value for the most recently added column 001209 ** of the table currently under construction. 001210 ** 001211 ** Default value expressions must be constant. Raise an exception if this 001212 ** is not the case. 001213 ** 001214 ** This routine is called by the parser while in the middle of 001215 ** parsing a CREATE TABLE statement. 001216 */ 001217 void sqlite3AddDefaultValue(Parse *pParse, ExprSpan *pSpan){ 001218 Table *p; 001219 Column *pCol; 001220 sqlite3 *db = pParse->db; 001221 p = pParse->pNewTable; 001222 if( p!=0 ){ 001223 pCol = &(p->aCol[p->nCol-1]); 001224 if( !sqlite3ExprIsConstantOrFunction(pSpan->pExpr, db->init.busy) ){ 001225 sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant", 001226 pCol->zName); 001227 }else{ 001228 /* A copy of pExpr is used instead of the original, as pExpr contains 001229 ** tokens that point to volatile memory. The 'span' of the expression 001230 ** is required by pragma table_info. 001231 */ 001232 Expr x; 001233 sqlite3ExprDelete(db, pCol->pDflt); 001234 memset(&x, 0, sizeof(x)); 001235 x.op = TK_SPAN; 001236 x.u.zToken = sqlite3DbStrNDup(db, (char*)pSpan->zStart, 001237 (int)(pSpan->zEnd - pSpan->zStart)); 001238 x.pLeft = pSpan->pExpr; 001239 x.flags = EP_Skip; 001240 pCol->pDflt = sqlite3ExprDup(db, &x, EXPRDUP_REDUCE); 001241 sqlite3DbFree(db, x.u.zToken); 001242 } 001243 } 001244 sqlite3ExprDelete(db, pSpan->pExpr); 001245 } 001246 001247 /* 001248 ** Backwards Compatibility Hack: 001249 ** 001250 ** Historical versions of SQLite accepted strings as column names in 001251 ** indexes and PRIMARY KEY constraints and in UNIQUE constraints. Example: 001252 ** 001253 ** CREATE TABLE xyz(a,b,c,d,e,PRIMARY KEY('a'),UNIQUE('b','c' COLLATE trim) 001254 ** CREATE INDEX abc ON xyz('c','d' DESC,'e' COLLATE nocase DESC); 001255 ** 001256 ** This is goofy. But to preserve backwards compatibility we continue to 001257 ** accept it. This routine does the necessary conversion. It converts 001258 ** the expression given in its argument from a TK_STRING into a TK_ID 001259 ** if the expression is just a TK_STRING with an optional COLLATE clause. 001260 ** If the epxression is anything other than TK_STRING, the expression is 001261 ** unchanged. 001262 */ 001263 static void sqlite3StringToId(Expr *p){ 001264 if( p->op==TK_STRING ){ 001265 p->op = TK_ID; 001266 }else if( p->op==TK_COLLATE && p->pLeft->op==TK_STRING ){ 001267 p->pLeft->op = TK_ID; 001268 } 001269 } 001270 001271 /* 001272 ** Designate the PRIMARY KEY for the table. pList is a list of names 001273 ** of columns that form the primary key. If pList is NULL, then the 001274 ** most recently added column of the table is the primary key. 001275 ** 001276 ** A table can have at most one primary key. If the table already has 001277 ** a primary key (and this is the second primary key) then create an 001278 ** error. 001279 ** 001280 ** If the PRIMARY KEY is on a single column whose datatype is INTEGER, 001281 ** then we will try to use that column as the rowid. Set the Table.iPKey 001282 ** field of the table under construction to be the index of the 001283 ** INTEGER PRIMARY KEY column. Table.iPKey is set to -1 if there is 001284 ** no INTEGER PRIMARY KEY. 001285 ** 001286 ** If the key is not an INTEGER PRIMARY KEY, then create a unique 001287 ** index for the key. No index is created for INTEGER PRIMARY KEYs. 001288 */ 001289 void sqlite3AddPrimaryKey( 001290 Parse *pParse, /* Parsing context */ 001291 ExprList *pList, /* List of field names to be indexed */ 001292 int onError, /* What to do with a uniqueness conflict */ 001293 int autoInc, /* True if the AUTOINCREMENT keyword is present */ 001294 int sortOrder /* SQLITE_SO_ASC or SQLITE_SO_DESC */ 001295 ){ 001296 Table *pTab = pParse->pNewTable; 001297 Column *pCol = 0; 001298 int iCol = -1, i; 001299 int nTerm; 001300 if( pTab==0 ) goto primary_key_exit; 001301 if( pTab->tabFlags & TF_HasPrimaryKey ){ 001302 sqlite3ErrorMsg(pParse, 001303 "table \"%s\" has more than one primary key", pTab->zName); 001304 goto primary_key_exit; 001305 } 001306 pTab->tabFlags |= TF_HasPrimaryKey; 001307 if( pList==0 ){ 001308 iCol = pTab->nCol - 1; 001309 pCol = &pTab->aCol[iCol]; 001310 pCol->colFlags |= COLFLAG_PRIMKEY; 001311 nTerm = 1; 001312 }else{ 001313 nTerm = pList->nExpr; 001314 for(i=0; i<nTerm; i++){ 001315 Expr *pCExpr = sqlite3ExprSkipCollate(pList->a[i].pExpr); 001316 assert( pCExpr!=0 ); 001317 sqlite3StringToId(pCExpr); 001318 if( pCExpr->op==TK_ID ){ 001319 const char *zCName = pCExpr->u.zToken; 001320 for(iCol=0; iCol<pTab->nCol; iCol++){ 001321 if( sqlite3StrICmp(zCName, pTab->aCol[iCol].zName)==0 ){ 001322 pCol = &pTab->aCol[iCol]; 001323 pCol->colFlags |= COLFLAG_PRIMKEY; 001324 break; 001325 } 001326 } 001327 } 001328 } 001329 } 001330 if( nTerm==1 001331 && pCol 001332 && sqlite3StrICmp(sqlite3ColumnType(pCol,""), "INTEGER")==0 001333 && sortOrder!=SQLITE_SO_DESC 001334 ){ 001335 pTab->iPKey = iCol; 001336 pTab->keyConf = (u8)onError; 001337 assert( autoInc==0 || autoInc==1 ); 001338 pTab->tabFlags |= autoInc*TF_Autoincrement; 001339 if( pList ) pParse->iPkSortOrder = pList->a[0].sortOrder; 001340 }else if( autoInc ){ 001341 #ifndef SQLITE_OMIT_AUTOINCREMENT 001342 sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an " 001343 "INTEGER PRIMARY KEY"); 001344 #endif 001345 }else{ 001346 sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0, 001347 0, sortOrder, 0, SQLITE_IDXTYPE_PRIMARYKEY); 001348 pList = 0; 001349 } 001350 001351 primary_key_exit: 001352 sqlite3ExprListDelete(pParse->db, pList); 001353 return; 001354 } 001355 001356 /* 001357 ** Add a new CHECK constraint to the table currently under construction. 001358 */ 001359 void sqlite3AddCheckConstraint( 001360 Parse *pParse, /* Parsing context */ 001361 Expr *pCheckExpr /* The check expression */ 001362 ){ 001363 #ifndef SQLITE_OMIT_CHECK 001364 Table *pTab = pParse->pNewTable; 001365 sqlite3 *db = pParse->db; 001366 if( pTab && !IN_DECLARE_VTAB 001367 && !sqlite3BtreeIsReadonly(db->aDb[db->init.iDb].pBt) 001368 ){ 001369 pTab->pCheck = sqlite3ExprListAppend(pParse, pTab->pCheck, pCheckExpr); 001370 if( pParse->constraintName.n ){ 001371 sqlite3ExprListSetName(pParse, pTab->pCheck, &pParse->constraintName, 1); 001372 } 001373 }else 001374 #endif 001375 { 001376 sqlite3ExprDelete(pParse->db, pCheckExpr); 001377 } 001378 } 001379 001380 /* 001381 ** Set the collation function of the most recently parsed table column 001382 ** to the CollSeq given. 001383 */ 001384 void sqlite3AddCollateType(Parse *pParse, Token *pToken){ 001385 Table *p; 001386 int i; 001387 char *zColl; /* Dequoted name of collation sequence */ 001388 sqlite3 *db; 001389 001390 if( (p = pParse->pNewTable)==0 ) return; 001391 i = p->nCol-1; 001392 db = pParse->db; 001393 zColl = sqlite3NameFromToken(db, pToken); 001394 if( !zColl ) return; 001395 001396 if( sqlite3LocateCollSeq(pParse, zColl) ){ 001397 Index *pIdx; 001398 sqlite3DbFree(db, p->aCol[i].zColl); 001399 p->aCol[i].zColl = zColl; 001400 001401 /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>", 001402 ** then an index may have been created on this column before the 001403 ** collation type was added. Correct this if it is the case. 001404 */ 001405 for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){ 001406 assert( pIdx->nKeyCol==1 ); 001407 if( pIdx->aiColumn[0]==i ){ 001408 pIdx->azColl[0] = p->aCol[i].zColl; 001409 } 001410 } 001411 }else{ 001412 sqlite3DbFree(db, zColl); 001413 } 001414 } 001415 001416 /* 001417 ** This function returns the collation sequence for database native text 001418 ** encoding identified by the string zName, length nName. 001419 ** 001420 ** If the requested collation sequence is not available, or not available 001421 ** in the database native encoding, the collation factory is invoked to 001422 ** request it. If the collation factory does not supply such a sequence, 001423 ** and the sequence is available in another text encoding, then that is 001424 ** returned instead. 001425 ** 001426 ** If no versions of the requested collations sequence are available, or 001427 ** another error occurs, NULL is returned and an error message written into 001428 ** pParse. 001429 ** 001430 ** This routine is a wrapper around sqlite3FindCollSeq(). This routine 001431 ** invokes the collation factory if the named collation cannot be found 001432 ** and generates an error message. 001433 ** 001434 ** See also: sqlite3FindCollSeq(), sqlite3GetCollSeq() 001435 */ 001436 CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName){ 001437 sqlite3 *db = pParse->db; 001438 u8 enc = ENC(db); 001439 u8 initbusy = db->init.busy; 001440 CollSeq *pColl; 001441 001442 pColl = sqlite3FindCollSeq(db, enc, zName, initbusy); 001443 if( !initbusy && (!pColl || !pColl->xCmp) ){ 001444 pColl = sqlite3GetCollSeq(pParse, enc, pColl, zName); 001445 } 001446 001447 return pColl; 001448 } 001449 001450 001451 /* 001452 ** Generate code that will increment the schema cookie. 001453 ** 001454 ** The schema cookie is used to determine when the schema for the 001455 ** database changes. After each schema change, the cookie value 001456 ** changes. When a process first reads the schema it records the 001457 ** cookie. Thereafter, whenever it goes to access the database, 001458 ** it checks the cookie to make sure the schema has not changed 001459 ** since it was last read. 001460 ** 001461 ** This plan is not completely bullet-proof. It is possible for 001462 ** the schema to change multiple times and for the cookie to be 001463 ** set back to prior value. But schema changes are infrequent 001464 ** and the probability of hitting the same cookie value is only 001465 ** 1 chance in 2^32. So we're safe enough. 001466 ** 001467 ** IMPLEMENTATION-OF: R-34230-56049 SQLite automatically increments 001468 ** the schema-version whenever the schema changes. 001469 */ 001470 void sqlite3ChangeCookie(Parse *pParse, int iDb){ 001471 sqlite3 *db = pParse->db; 001472 Vdbe *v = pParse->pVdbe; 001473 assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); 001474 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION, 001475 db->aDb[iDb].pSchema->schema_cookie+1); 001476 } 001477 001478 /* 001479 ** Measure the number of characters needed to output the given 001480 ** identifier. The number returned includes any quotes used 001481 ** but does not include the null terminator. 001482 ** 001483 ** The estimate is conservative. It might be larger that what is 001484 ** really needed. 001485 */ 001486 static int identLength(const char *z){ 001487 int n; 001488 for(n=0; *z; n++, z++){ 001489 if( *z=='"' ){ n++; } 001490 } 001491 return n + 2; 001492 } 001493 001494 /* 001495 ** The first parameter is a pointer to an output buffer. The second 001496 ** parameter is a pointer to an integer that contains the offset at 001497 ** which to write into the output buffer. This function copies the 001498 ** nul-terminated string pointed to by the third parameter, zSignedIdent, 001499 ** to the specified offset in the buffer and updates *pIdx to refer 001500 ** to the first byte after the last byte written before returning. 001501 ** 001502 ** If the string zSignedIdent consists entirely of alpha-numeric 001503 ** characters, does not begin with a digit and is not an SQL keyword, 001504 ** then it is copied to the output buffer exactly as it is. Otherwise, 001505 ** it is quoted using double-quotes. 001506 */ 001507 static void identPut(char *z, int *pIdx, char *zSignedIdent){ 001508 unsigned char *zIdent = (unsigned char*)zSignedIdent; 001509 int i, j, needQuote; 001510 i = *pIdx; 001511 001512 for(j=0; zIdent[j]; j++){ 001513 if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break; 001514 } 001515 needQuote = sqlite3Isdigit(zIdent[0]) 001516 || sqlite3KeywordCode(zIdent, j)!=TK_ID 001517 || zIdent[j]!=0 001518 || j==0; 001519 001520 if( needQuote ) z[i++] = '"'; 001521 for(j=0; zIdent[j]; j++){ 001522 z[i++] = zIdent[j]; 001523 if( zIdent[j]=='"' ) z[i++] = '"'; 001524 } 001525 if( needQuote ) z[i++] = '"'; 001526 z[i] = 0; 001527 *pIdx = i; 001528 } 001529 001530 /* 001531 ** Generate a CREATE TABLE statement appropriate for the given 001532 ** table. Memory to hold the text of the statement is obtained 001533 ** from sqliteMalloc() and must be freed by the calling function. 001534 */ 001535 static char *createTableStmt(sqlite3 *db, Table *p){ 001536 int i, k, n; 001537 char *zStmt; 001538 char *zSep, *zSep2, *zEnd; 001539 Column *pCol; 001540 n = 0; 001541 for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){ 001542 n += identLength(pCol->zName) + 5; 001543 } 001544 n += identLength(p->zName); 001545 if( n<50 ){ 001546 zSep = ""; 001547 zSep2 = ","; 001548 zEnd = ")"; 001549 }else{ 001550 zSep = "\n "; 001551 zSep2 = ",\n "; 001552 zEnd = "\n)"; 001553 } 001554 n += 35 + 6*p->nCol; 001555 zStmt = sqlite3DbMallocRaw(0, n); 001556 if( zStmt==0 ){ 001557 sqlite3OomFault(db); 001558 return 0; 001559 } 001560 sqlite3_snprintf(n, zStmt, "CREATE TABLE "); 001561 k = sqlite3Strlen30(zStmt); 001562 identPut(zStmt, &k, p->zName); 001563 zStmt[k++] = '('; 001564 for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){ 001565 static const char * const azType[] = { 001566 /* SQLITE_AFF_BLOB */ "", 001567 /* SQLITE_AFF_TEXT */ " TEXT", 001568 /* SQLITE_AFF_NUMERIC */ " NUM", 001569 /* SQLITE_AFF_INTEGER */ " INT", 001570 /* SQLITE_AFF_REAL */ " REAL" 001571 }; 001572 int len; 001573 const char *zType; 001574 001575 sqlite3_snprintf(n-k, &zStmt[k], zSep); 001576 k += sqlite3Strlen30(&zStmt[k]); 001577 zSep = zSep2; 001578 identPut(zStmt, &k, pCol->zName); 001579 assert( pCol->affinity-SQLITE_AFF_BLOB >= 0 ); 001580 assert( pCol->affinity-SQLITE_AFF_BLOB < ArraySize(azType) ); 001581 testcase( pCol->affinity==SQLITE_AFF_BLOB ); 001582 testcase( pCol->affinity==SQLITE_AFF_TEXT ); 001583 testcase( pCol->affinity==SQLITE_AFF_NUMERIC ); 001584 testcase( pCol->affinity==SQLITE_AFF_INTEGER ); 001585 testcase( pCol->affinity==SQLITE_AFF_REAL ); 001586 001587 zType = azType[pCol->affinity - SQLITE_AFF_BLOB]; 001588 len = sqlite3Strlen30(zType); 001589 assert( pCol->affinity==SQLITE_AFF_BLOB 001590 || pCol->affinity==sqlite3AffinityType(zType, 0) ); 001591 memcpy(&zStmt[k], zType, len); 001592 k += len; 001593 assert( k<=n ); 001594 } 001595 sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd); 001596 return zStmt; 001597 } 001598 001599 /* 001600 ** Resize an Index object to hold N columns total. Return SQLITE_OK 001601 ** on success and SQLITE_NOMEM on an OOM error. 001602 */ 001603 static int resizeIndexObject(sqlite3 *db, Index *pIdx, int N){ 001604 char *zExtra; 001605 int nByte; 001606 if( pIdx->nColumn>=N ) return SQLITE_OK; 001607 assert( pIdx->isResized==0 ); 001608 nByte = (sizeof(char*) + sizeof(i16) + 1)*N; 001609 zExtra = sqlite3DbMallocZero(db, nByte); 001610 if( zExtra==0 ) return SQLITE_NOMEM_BKPT; 001611 memcpy(zExtra, pIdx->azColl, sizeof(char*)*pIdx->nColumn); 001612 pIdx->azColl = (const char**)zExtra; 001613 zExtra += sizeof(char*)*N; 001614 memcpy(zExtra, pIdx->aiColumn, sizeof(i16)*pIdx->nColumn); 001615 pIdx->aiColumn = (i16*)zExtra; 001616 zExtra += sizeof(i16)*N; 001617 memcpy(zExtra, pIdx->aSortOrder, pIdx->nColumn); 001618 pIdx->aSortOrder = (u8*)zExtra; 001619 pIdx->nColumn = N; 001620 pIdx->isResized = 1; 001621 return SQLITE_OK; 001622 } 001623 001624 /* 001625 ** Estimate the total row width for a table. 001626 */ 001627 static void estimateTableWidth(Table *pTab){ 001628 unsigned wTable = 0; 001629 const Column *pTabCol; 001630 int i; 001631 for(i=pTab->nCol, pTabCol=pTab->aCol; i>0; i--, pTabCol++){ 001632 wTable += pTabCol->szEst; 001633 } 001634 if( pTab->iPKey<0 ) wTable++; 001635 pTab->szTabRow = sqlite3LogEst(wTable*4); 001636 } 001637 001638 /* 001639 ** Estimate the average size of a row for an index. 001640 */ 001641 static void estimateIndexWidth(Index *pIdx){ 001642 unsigned wIndex = 0; 001643 int i; 001644 const Column *aCol = pIdx->pTable->aCol; 001645 for(i=0; i<pIdx->nColumn; i++){ 001646 i16 x = pIdx->aiColumn[i]; 001647 assert( x<pIdx->pTable->nCol ); 001648 wIndex += x<0 ? 1 : aCol[pIdx->aiColumn[i]].szEst; 001649 } 001650 pIdx->szIdxRow = sqlite3LogEst(wIndex*4); 001651 } 001652 001653 /* Return true if value x is found any of the first nCol entries of aiCol[] 001654 */ 001655 static int hasColumn(const i16 *aiCol, int nCol, int x){ 001656 while( nCol-- > 0 ) if( x==*(aiCol++) ) return 1; 001657 return 0; 001658 } 001659 001660 /* 001661 ** This routine runs at the end of parsing a CREATE TABLE statement that 001662 ** has a WITHOUT ROWID clause. The job of this routine is to convert both 001663 ** internal schema data structures and the generated VDBE code so that they 001664 ** are appropriate for a WITHOUT ROWID table instead of a rowid table. 001665 ** Changes include: 001666 ** 001667 ** (1) Set all columns of the PRIMARY KEY schema object to be NOT NULL. 001668 ** (2) Convert the OP_CreateTable into an OP_CreateIndex. There is 001669 ** no rowid btree for a WITHOUT ROWID. Instead, the canonical 001670 ** data storage is a covering index btree. 001671 ** (3) Bypass the creation of the sqlite_master table entry 001672 ** for the PRIMARY KEY as the primary key index is now 001673 ** identified by the sqlite_master table entry of the table itself. 001674 ** (4) Set the Index.tnum of the PRIMARY KEY Index object in the 001675 ** schema to the rootpage from the main table. 001676 ** (5) Add all table columns to the PRIMARY KEY Index object 001677 ** so that the PRIMARY KEY is a covering index. The surplus 001678 ** columns are part of KeyInfo.nXField and are not used for 001679 ** sorting or lookup or uniqueness checks. 001680 ** (6) Replace the rowid tail on all automatically generated UNIQUE 001681 ** indices with the PRIMARY KEY columns. 001682 ** 001683 ** For virtual tables, only (1) is performed. 001684 */ 001685 static void convertToWithoutRowidTable(Parse *pParse, Table *pTab){ 001686 Index *pIdx; 001687 Index *pPk; 001688 int nPk; 001689 int i, j; 001690 sqlite3 *db = pParse->db; 001691 Vdbe *v = pParse->pVdbe; 001692 001693 /* Mark every PRIMARY KEY column as NOT NULL (except for imposter tables) 001694 */ 001695 if( !db->init.imposterTable ){ 001696 for(i=0; i<pTab->nCol; i++){ 001697 if( (pTab->aCol[i].colFlags & COLFLAG_PRIMKEY)!=0 ){ 001698 pTab->aCol[i].notNull = OE_Abort; 001699 } 001700 } 001701 } 001702 001703 /* The remaining transformations only apply to b-tree tables, not to 001704 ** virtual tables */ 001705 if( IN_DECLARE_VTAB ) return; 001706 001707 /* Convert the OP_CreateTable opcode that would normally create the 001708 ** root-page for the table into an OP_CreateIndex opcode. The index 001709 ** created will become the PRIMARY KEY index. 001710 */ 001711 if( pParse->addrCrTab ){ 001712 assert( v ); 001713 sqlite3VdbeChangeOpcode(v, pParse->addrCrTab, OP_CreateIndex); 001714 } 001715 001716 /* Locate the PRIMARY KEY index. Or, if this table was originally 001717 ** an INTEGER PRIMARY KEY table, create a new PRIMARY KEY index. 001718 */ 001719 if( pTab->iPKey>=0 ){ 001720 ExprList *pList; 001721 Token ipkToken; 001722 sqlite3TokenInit(&ipkToken, pTab->aCol[pTab->iPKey].zName); 001723 pList = sqlite3ExprListAppend(pParse, 0, 001724 sqlite3ExprAlloc(db, TK_ID, &ipkToken, 0)); 001725 if( pList==0 ) return; 001726 pList->a[0].sortOrder = pParse->iPkSortOrder; 001727 assert( pParse->pNewTable==pTab ); 001728 sqlite3CreateIndex(pParse, 0, 0, 0, pList, pTab->keyConf, 0, 0, 0, 0, 001729 SQLITE_IDXTYPE_PRIMARYKEY); 001730 if( db->mallocFailed ) return; 001731 pPk = sqlite3PrimaryKeyIndex(pTab); 001732 pTab->iPKey = -1; 001733 }else{ 001734 pPk = sqlite3PrimaryKeyIndex(pTab); 001735 001736 /* Bypass the creation of the PRIMARY KEY btree and the sqlite_master 001737 ** table entry. This is only required if currently generating VDBE 001738 ** code for a CREATE TABLE (not when parsing one as part of reading 001739 ** a database schema). */ 001740 if( v ){ 001741 assert( db->init.busy==0 ); 001742 sqlite3VdbeChangeOpcode(v, pPk->tnum, OP_Goto); 001743 } 001744 001745 /* 001746 ** Remove all redundant columns from the PRIMARY KEY. For example, change 001747 ** "PRIMARY KEY(a,b,a,b,c,b,c,d)" into just "PRIMARY KEY(a,b,c,d)". Later 001748 ** code assumes the PRIMARY KEY contains no repeated columns. 001749 */ 001750 for(i=j=1; i<pPk->nKeyCol; i++){ 001751 if( hasColumn(pPk->aiColumn, j, pPk->aiColumn[i]) ){ 001752 pPk->nColumn--; 001753 }else{ 001754 pPk->aiColumn[j++] = pPk->aiColumn[i]; 001755 } 001756 } 001757 pPk->nKeyCol = j; 001758 } 001759 assert( pPk!=0 ); 001760 pPk->isCovering = 1; 001761 if( !db->init.imposterTable ) pPk->uniqNotNull = 1; 001762 nPk = pPk->nKeyCol; 001763 001764 /* The root page of the PRIMARY KEY is the table root page */ 001765 pPk->tnum = pTab->tnum; 001766 001767 /* Update the in-memory representation of all UNIQUE indices by converting 001768 ** the final rowid column into one or more columns of the PRIMARY KEY. 001769 */ 001770 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ 001771 int n; 001772 if( IsPrimaryKeyIndex(pIdx) ) continue; 001773 for(i=n=0; i<nPk; i++){ 001774 if( !hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) ) n++; 001775 } 001776 if( n==0 ){ 001777 /* This index is a superset of the primary key */ 001778 pIdx->nColumn = pIdx->nKeyCol; 001779 continue; 001780 } 001781 if( resizeIndexObject(db, pIdx, pIdx->nKeyCol+n) ) return; 001782 for(i=0, j=pIdx->nKeyCol; i<nPk; i++){ 001783 if( !hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) ){ 001784 pIdx->aiColumn[j] = pPk->aiColumn[i]; 001785 pIdx->azColl[j] = pPk->azColl[i]; 001786 j++; 001787 } 001788 } 001789 assert( pIdx->nColumn>=pIdx->nKeyCol+n ); 001790 assert( pIdx->nColumn>=j ); 001791 } 001792 001793 /* Add all table columns to the PRIMARY KEY index 001794 */ 001795 if( nPk<pTab->nCol ){ 001796 if( resizeIndexObject(db, pPk, pTab->nCol) ) return; 001797 for(i=0, j=nPk; i<pTab->nCol; i++){ 001798 if( !hasColumn(pPk->aiColumn, j, i) ){ 001799 assert( j<pPk->nColumn ); 001800 pPk->aiColumn[j] = i; 001801 pPk->azColl[j] = sqlite3StrBINARY; 001802 j++; 001803 } 001804 } 001805 assert( pPk->nColumn==j ); 001806 assert( pTab->nCol==j ); 001807 }else{ 001808 pPk->nColumn = pTab->nCol; 001809 } 001810 } 001811 001812 /* 001813 ** This routine is called to report the final ")" that terminates 001814 ** a CREATE TABLE statement. 001815 ** 001816 ** The table structure that other action routines have been building 001817 ** is added to the internal hash tables, assuming no errors have 001818 ** occurred. 001819 ** 001820 ** An entry for the table is made in the master table on disk, unless 001821 ** this is a temporary table or db->init.busy==1. When db->init.busy==1 001822 ** it means we are reading the sqlite_master table because we just 001823 ** connected to the database or because the sqlite_master table has 001824 ** recently changed, so the entry for this table already exists in 001825 ** the sqlite_master table. We do not want to create it again. 001826 ** 001827 ** If the pSelect argument is not NULL, it means that this routine 001828 ** was called to create a table generated from a 001829 ** "CREATE TABLE ... AS SELECT ..." statement. The column names of 001830 ** the new table will match the result set of the SELECT. 001831 */ 001832 void sqlite3EndTable( 001833 Parse *pParse, /* Parse context */ 001834 Token *pCons, /* The ',' token after the last column defn. */ 001835 Token *pEnd, /* The ')' before options in the CREATE TABLE */ 001836 u8 tabOpts, /* Extra table options. Usually 0. */ 001837 Select *pSelect /* Select from a "CREATE ... AS SELECT" */ 001838 ){ 001839 Table *p; /* The new table */ 001840 sqlite3 *db = pParse->db; /* The database connection */ 001841 int iDb; /* Database in which the table lives */ 001842 Index *pIdx; /* An implied index of the table */ 001843 001844 if( pEnd==0 && pSelect==0 ){ 001845 return; 001846 } 001847 assert( !db->mallocFailed ); 001848 p = pParse->pNewTable; 001849 if( p==0 ) return; 001850 001851 assert( !db->init.busy || !pSelect ); 001852 001853 /* If the db->init.busy is 1 it means we are reading the SQL off the 001854 ** "sqlite_master" or "sqlite_temp_master" table on the disk. 001855 ** So do not write to the disk again. Extract the root page number 001856 ** for the table from the db->init.newTnum field. (The page number 001857 ** should have been put there by the sqliteOpenCb routine.) 001858 ** 001859 ** If the root page number is 1, that means this is the sqlite_master 001860 ** table itself. So mark it read-only. 001861 */ 001862 if( db->init.busy ){ 001863 p->tnum = db->init.newTnum; 001864 if( p->tnum==1 ) p->tabFlags |= TF_Readonly; 001865 } 001866 001867 /* Special processing for WITHOUT ROWID Tables */ 001868 if( tabOpts & TF_WithoutRowid ){ 001869 if( (p->tabFlags & TF_Autoincrement) ){ 001870 sqlite3ErrorMsg(pParse, 001871 "AUTOINCREMENT not allowed on WITHOUT ROWID tables"); 001872 return; 001873 } 001874 if( (p->tabFlags & TF_HasPrimaryKey)==0 ){ 001875 sqlite3ErrorMsg(pParse, "PRIMARY KEY missing on table %s", p->zName); 001876 }else{ 001877 p->tabFlags |= TF_WithoutRowid | TF_NoVisibleRowid; 001878 convertToWithoutRowidTable(pParse, p); 001879 } 001880 } 001881 001882 iDb = sqlite3SchemaToIndex(db, p->pSchema); 001883 001884 #ifndef SQLITE_OMIT_CHECK 001885 /* Resolve names in all CHECK constraint expressions. 001886 */ 001887 if( p->pCheck ){ 001888 sqlite3ResolveSelfReference(pParse, p, NC_IsCheck, 0, p->pCheck); 001889 } 001890 #endif /* !defined(SQLITE_OMIT_CHECK) */ 001891 001892 /* Estimate the average row size for the table and for all implied indices */ 001893 estimateTableWidth(p); 001894 for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){ 001895 estimateIndexWidth(pIdx); 001896 } 001897 001898 /* If not initializing, then create a record for the new table 001899 ** in the SQLITE_MASTER table of the database. 001900 ** 001901 ** If this is a TEMPORARY table, write the entry into the auxiliary 001902 ** file instead of into the main database file. 001903 */ 001904 if( !db->init.busy ){ 001905 int n; 001906 Vdbe *v; 001907 char *zType; /* "view" or "table" */ 001908 char *zType2; /* "VIEW" or "TABLE" */ 001909 char *zStmt; /* Text of the CREATE TABLE or CREATE VIEW statement */ 001910 001911 v = sqlite3GetVdbe(pParse); 001912 if( NEVER(v==0) ) return; 001913 001914 sqlite3VdbeAddOp1(v, OP_Close, 0); 001915 001916 /* 001917 ** Initialize zType for the new view or table. 001918 */ 001919 if( p->pSelect==0 ){ 001920 /* A regular table */ 001921 zType = "table"; 001922 zType2 = "TABLE"; 001923 #ifndef SQLITE_OMIT_VIEW 001924 }else{ 001925 /* A view */ 001926 zType = "view"; 001927 zType2 = "VIEW"; 001928 #endif 001929 } 001930 001931 /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT 001932 ** statement to populate the new table. The root-page number for the 001933 ** new table is in register pParse->regRoot. 001934 ** 001935 ** Once the SELECT has been coded by sqlite3Select(), it is in a 001936 ** suitable state to query for the column names and types to be used 001937 ** by the new table. 001938 ** 001939 ** A shared-cache write-lock is not required to write to the new table, 001940 ** as a schema-lock must have already been obtained to create it. Since 001941 ** a schema-lock excludes all other database users, the write-lock would 001942 ** be redundant. 001943 */ 001944 if( pSelect ){ 001945 SelectDest dest; /* Where the SELECT should store results */ 001946 int regYield; /* Register holding co-routine entry-point */ 001947 int addrTop; /* Top of the co-routine */ 001948 int regRec; /* A record to be insert into the new table */ 001949 int regRowid; /* Rowid of the next row to insert */ 001950 int addrInsLoop; /* Top of the loop for inserting rows */ 001951 Table *pSelTab; /* A table that describes the SELECT results */ 001952 001953 regYield = ++pParse->nMem; 001954 regRec = ++pParse->nMem; 001955 regRowid = ++pParse->nMem; 001956 assert(pParse->nTab==1); 001957 sqlite3MayAbort(pParse); 001958 sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb); 001959 sqlite3VdbeChangeP5(v, OPFLAG_P2ISREG); 001960 pParse->nTab = 2; 001961 addrTop = sqlite3VdbeCurrentAddr(v) + 1; 001962 sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, addrTop); 001963 sqlite3SelectDestInit(&dest, SRT_Coroutine, regYield); 001964 sqlite3Select(pParse, pSelect, &dest); 001965 sqlite3VdbeEndCoroutine(v, regYield); 001966 sqlite3VdbeJumpHere(v, addrTop - 1); 001967 if( pParse->nErr ) return; 001968 pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect); 001969 if( pSelTab==0 ) return; 001970 assert( p->aCol==0 ); 001971 p->nCol = pSelTab->nCol; 001972 p->aCol = pSelTab->aCol; 001973 pSelTab->nCol = 0; 001974 pSelTab->aCol = 0; 001975 sqlite3DeleteTable(db, pSelTab); 001976 addrInsLoop = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm); 001977 VdbeCoverage(v); 001978 sqlite3VdbeAddOp3(v, OP_MakeRecord, dest.iSdst, dest.nSdst, regRec); 001979 sqlite3TableAffinity(v, p, 0); 001980 sqlite3VdbeAddOp2(v, OP_NewRowid, 1, regRowid); 001981 sqlite3VdbeAddOp3(v, OP_Insert, 1, regRec, regRowid); 001982 sqlite3VdbeGoto(v, addrInsLoop); 001983 sqlite3VdbeJumpHere(v, addrInsLoop); 001984 sqlite3VdbeAddOp1(v, OP_Close, 1); 001985 } 001986 001987 /* Compute the complete text of the CREATE statement */ 001988 if( pSelect ){ 001989 zStmt = createTableStmt(db, p); 001990 }else{ 001991 Token *pEnd2 = tabOpts ? &pParse->sLastToken : pEnd; 001992 n = (int)(pEnd2->z - pParse->sNameToken.z); 001993 if( pEnd2->z[0]!=';' ) n += pEnd2->n; 001994 zStmt = sqlite3MPrintf(db, 001995 "CREATE %s %.*s", zType2, n, pParse->sNameToken.z 001996 ); 001997 } 001998 001999 /* A slot for the record has already been allocated in the 002000 ** SQLITE_MASTER table. We just need to update that slot with all 002001 ** the information we've collected. 002002 */ 002003 sqlite3NestedParse(pParse, 002004 "UPDATE %Q.%s " 002005 "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q " 002006 "WHERE rowid=#%d", 002007 db->aDb[iDb].zDbSName, MASTER_NAME, 002008 zType, 002009 p->zName, 002010 p->zName, 002011 pParse->regRoot, 002012 zStmt, 002013 pParse->regRowid 002014 ); 002015 sqlite3DbFree(db, zStmt); 002016 sqlite3ChangeCookie(pParse, iDb); 002017 002018 #ifndef SQLITE_OMIT_AUTOINCREMENT 002019 /* Check to see if we need to create an sqlite_sequence table for 002020 ** keeping track of autoincrement keys. 002021 */ 002022 if( (p->tabFlags & TF_Autoincrement)!=0 ){ 002023 Db *pDb = &db->aDb[iDb]; 002024 assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); 002025 if( pDb->pSchema->pSeqTab==0 ){ 002026 sqlite3NestedParse(pParse, 002027 "CREATE TABLE %Q.sqlite_sequence(name,seq)", 002028 pDb->zDbSName 002029 ); 002030 } 002031 } 002032 #endif 002033 002034 /* Reparse everything to update our internal data structures */ 002035 sqlite3VdbeAddParseSchemaOp(v, iDb, 002036 sqlite3MPrintf(db, "tbl_name='%q' AND type!='trigger'", p->zName)); 002037 } 002038 002039 002040 /* Add the table to the in-memory representation of the database. 002041 */ 002042 if( db->init.busy ){ 002043 Table *pOld; 002044 Schema *pSchema = p->pSchema; 002045 assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); 002046 pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName, p); 002047 if( pOld ){ 002048 assert( p==pOld ); /* Malloc must have failed inside HashInsert() */ 002049 sqlite3OomFault(db); 002050 return; 002051 } 002052 pParse->pNewTable = 0; 002053 db->flags |= SQLITE_InternChanges; 002054 002055 #ifndef SQLITE_OMIT_ALTERTABLE 002056 if( !p->pSelect ){ 002057 const char *zName = (const char *)pParse->sNameToken.z; 002058 int nName; 002059 assert( !pSelect && pCons && pEnd ); 002060 if( pCons->z==0 ){ 002061 pCons = pEnd; 002062 } 002063 nName = (int)((const char *)pCons->z - zName); 002064 p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName); 002065 } 002066 #endif 002067 } 002068 } 002069 002070 #ifndef SQLITE_OMIT_VIEW 002071 /* 002072 ** The parser calls this routine in order to create a new VIEW 002073 */ 002074 void sqlite3CreateView( 002075 Parse *pParse, /* The parsing context */ 002076 Token *pBegin, /* The CREATE token that begins the statement */ 002077 Token *pName1, /* The token that holds the name of the view */ 002078 Token *pName2, /* The token that holds the name of the view */ 002079 ExprList *pCNames, /* Optional list of view column names */ 002080 Select *pSelect, /* A SELECT statement that will become the new view */ 002081 int isTemp, /* TRUE for a TEMPORARY view */ 002082 int noErr /* Suppress error messages if VIEW already exists */ 002083 ){ 002084 Table *p; 002085 int n; 002086 const char *z; 002087 Token sEnd; 002088 DbFixer sFix; 002089 Token *pName = 0; 002090 int iDb; 002091 sqlite3 *db = pParse->db; 002092 002093 if( pParse->nVar>0 ){ 002094 sqlite3ErrorMsg(pParse, "parameters are not allowed in views"); 002095 goto create_view_fail; 002096 } 002097 sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr); 002098 p = pParse->pNewTable; 002099 if( p==0 || pParse->nErr ) goto create_view_fail; 002100 sqlite3TwoPartName(pParse, pName1, pName2, &pName); 002101 iDb = sqlite3SchemaToIndex(db, p->pSchema); 002102 sqlite3FixInit(&sFix, pParse, iDb, "view", pName); 002103 if( sqlite3FixSelect(&sFix, pSelect) ) goto create_view_fail; 002104 002105 /* Make a copy of the entire SELECT statement that defines the view. 002106 ** This will force all the Expr.token.z values to be dynamically 002107 ** allocated rather than point to the input string - which means that 002108 ** they will persist after the current sqlite3_exec() call returns. 002109 */ 002110 p->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE); 002111 p->pCheck = sqlite3ExprListDup(db, pCNames, EXPRDUP_REDUCE); 002112 if( db->mallocFailed ) goto create_view_fail; 002113 002114 /* Locate the end of the CREATE VIEW statement. Make sEnd point to 002115 ** the end. 002116 */ 002117 sEnd = pParse->sLastToken; 002118 assert( sEnd.z[0]!=0 ); 002119 if( sEnd.z[0]!=';' ){ 002120 sEnd.z += sEnd.n; 002121 } 002122 sEnd.n = 0; 002123 n = (int)(sEnd.z - pBegin->z); 002124 assert( n>0 ); 002125 z = pBegin->z; 002126 while( sqlite3Isspace(z[n-1]) ){ n--; } 002127 sEnd.z = &z[n-1]; 002128 sEnd.n = 1; 002129 002130 /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */ 002131 sqlite3EndTable(pParse, 0, &sEnd, 0, 0); 002132 002133 create_view_fail: 002134 sqlite3SelectDelete(db, pSelect); 002135 sqlite3ExprListDelete(db, pCNames); 002136 return; 002137 } 002138 #endif /* SQLITE_OMIT_VIEW */ 002139 002140 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) 002141 /* 002142 ** The Table structure pTable is really a VIEW. Fill in the names of 002143 ** the columns of the view in the pTable structure. Return the number 002144 ** of errors. If an error is seen leave an error message in pParse->zErrMsg. 002145 */ 002146 int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){ 002147 Table *pSelTab; /* A fake table from which we get the result set */ 002148 Select *pSel; /* Copy of the SELECT that implements the view */ 002149 int nErr = 0; /* Number of errors encountered */ 002150 int n; /* Temporarily holds the number of cursors assigned */ 002151 sqlite3 *db = pParse->db; /* Database connection for malloc errors */ 002152 #ifndef SQLITE_OMIT_AUTHORIZATION 002153 sqlite3_xauth xAuth; /* Saved xAuth pointer */ 002154 #endif 002155 002156 assert( pTable ); 002157 002158 #ifndef SQLITE_OMIT_VIRTUALTABLE 002159 if( sqlite3VtabCallConnect(pParse, pTable) ){ 002160 return SQLITE_ERROR; 002161 } 002162 if( IsVirtual(pTable) ) return 0; 002163 #endif 002164 002165 #ifndef SQLITE_OMIT_VIEW 002166 /* A positive nCol means the columns names for this view are 002167 ** already known. 002168 */ 002169 if( pTable->nCol>0 ) return 0; 002170 002171 /* A negative nCol is a special marker meaning that we are currently 002172 ** trying to compute the column names. If we enter this routine with 002173 ** a negative nCol, it means two or more views form a loop, like this: 002174 ** 002175 ** CREATE VIEW one AS SELECT * FROM two; 002176 ** CREATE VIEW two AS SELECT * FROM one; 002177 ** 002178 ** Actually, the error above is now caught prior to reaching this point. 002179 ** But the following test is still important as it does come up 002180 ** in the following: 002181 ** 002182 ** CREATE TABLE main.ex1(a); 002183 ** CREATE TEMP VIEW ex1 AS SELECT a FROM ex1; 002184 ** SELECT * FROM temp.ex1; 002185 */ 002186 if( pTable->nCol<0 ){ 002187 sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName); 002188 return 1; 002189 } 002190 assert( pTable->nCol>=0 ); 002191 002192 /* If we get this far, it means we need to compute the table names. 002193 ** Note that the call to sqlite3ResultSetOfSelect() will expand any 002194 ** "*" elements in the results set of the view and will assign cursors 002195 ** to the elements of the FROM clause. But we do not want these changes 002196 ** to be permanent. So the computation is done on a copy of the SELECT 002197 ** statement that defines the view. 002198 */ 002199 assert( pTable->pSelect ); 002200 pSel = sqlite3SelectDup(db, pTable->pSelect, 0); 002201 if( pSel ){ 002202 n = pParse->nTab; 002203 sqlite3SrcListAssignCursors(pParse, pSel->pSrc); 002204 pTable->nCol = -1; 002205 db->lookaside.bDisable++; 002206 #ifndef SQLITE_OMIT_AUTHORIZATION 002207 xAuth = db->xAuth; 002208 db->xAuth = 0; 002209 pSelTab = sqlite3ResultSetOfSelect(pParse, pSel); 002210 db->xAuth = xAuth; 002211 #else 002212 pSelTab = sqlite3ResultSetOfSelect(pParse, pSel); 002213 #endif 002214 pParse->nTab = n; 002215 if( pTable->pCheck ){ 002216 /* CREATE VIEW name(arglist) AS ... 002217 ** The names of the columns in the table are taken from 002218 ** arglist which is stored in pTable->pCheck. The pCheck field 002219 ** normally holds CHECK constraints on an ordinary table, but for 002220 ** a VIEW it holds the list of column names. 002221 */ 002222 sqlite3ColumnsFromExprList(pParse, pTable->pCheck, 002223 &pTable->nCol, &pTable->aCol); 002224 if( db->mallocFailed==0 002225 && pParse->nErr==0 002226 && pTable->nCol==pSel->pEList->nExpr 002227 ){ 002228 sqlite3SelectAddColumnTypeAndCollation(pParse, pTable, pSel); 002229 } 002230 }else if( pSelTab ){ 002231 /* CREATE VIEW name AS... without an argument list. Construct 002232 ** the column names from the SELECT statement that defines the view. 002233 */ 002234 assert( pTable->aCol==0 ); 002235 pTable->nCol = pSelTab->nCol; 002236 pTable->aCol = pSelTab->aCol; 002237 pSelTab->nCol = 0; 002238 pSelTab->aCol = 0; 002239 assert( sqlite3SchemaMutexHeld(db, 0, pTable->pSchema) ); 002240 }else{ 002241 pTable->nCol = 0; 002242 nErr++; 002243 } 002244 sqlite3DeleteTable(db, pSelTab); 002245 sqlite3SelectDelete(db, pSel); 002246 db->lookaside.bDisable--; 002247 } else { 002248 nErr++; 002249 } 002250 pTable->pSchema->schemaFlags |= DB_UnresetViews; 002251 #endif /* SQLITE_OMIT_VIEW */ 002252 return nErr; 002253 } 002254 #endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */ 002255 002256 #ifndef SQLITE_OMIT_VIEW 002257 /* 002258 ** Clear the column names from every VIEW in database idx. 002259 */ 002260 static void sqliteViewResetAll(sqlite3 *db, int idx){ 002261 HashElem *i; 002262 assert( sqlite3SchemaMutexHeld(db, idx, 0) ); 002263 if( !DbHasProperty(db, idx, DB_UnresetViews) ) return; 002264 for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){ 002265 Table *pTab = sqliteHashData(i); 002266 if( pTab->pSelect ){ 002267 sqlite3DeleteColumnNames(db, pTab); 002268 pTab->aCol = 0; 002269 pTab->nCol = 0; 002270 } 002271 } 002272 DbClearProperty(db, idx, DB_UnresetViews); 002273 } 002274 #else 002275 # define sqliteViewResetAll(A,B) 002276 #endif /* SQLITE_OMIT_VIEW */ 002277 002278 /* 002279 ** This function is called by the VDBE to adjust the internal schema 002280 ** used by SQLite when the btree layer moves a table root page. The 002281 ** root-page of a table or index in database iDb has changed from iFrom 002282 ** to iTo. 002283 ** 002284 ** Ticket #1728: The symbol table might still contain information 002285 ** on tables and/or indices that are the process of being deleted. 002286 ** If you are unlucky, one of those deleted indices or tables might 002287 ** have the same rootpage number as the real table or index that is 002288 ** being moved. So we cannot stop searching after the first match 002289 ** because the first match might be for one of the deleted indices 002290 ** or tables and not the table/index that is actually being moved. 002291 ** We must continue looping until all tables and indices with 002292 ** rootpage==iFrom have been converted to have a rootpage of iTo 002293 ** in order to be certain that we got the right one. 002294 */ 002295 #ifndef SQLITE_OMIT_AUTOVACUUM 002296 void sqlite3RootPageMoved(sqlite3 *db, int iDb, int iFrom, int iTo){ 002297 HashElem *pElem; 002298 Hash *pHash; 002299 Db *pDb; 002300 002301 assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); 002302 pDb = &db->aDb[iDb]; 002303 pHash = &pDb->pSchema->tblHash; 002304 for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){ 002305 Table *pTab = sqliteHashData(pElem); 002306 if( pTab->tnum==iFrom ){ 002307 pTab->tnum = iTo; 002308 } 002309 } 002310 pHash = &pDb->pSchema->idxHash; 002311 for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){ 002312 Index *pIdx = sqliteHashData(pElem); 002313 if( pIdx->tnum==iFrom ){ 002314 pIdx->tnum = iTo; 002315 } 002316 } 002317 } 002318 #endif 002319 002320 /* 002321 ** Write code to erase the table with root-page iTable from database iDb. 002322 ** Also write code to modify the sqlite_master table and internal schema 002323 ** if a root-page of another table is moved by the btree-layer whilst 002324 ** erasing iTable (this can happen with an auto-vacuum database). 002325 */ 002326 static void destroyRootPage(Parse *pParse, int iTable, int iDb){ 002327 Vdbe *v = sqlite3GetVdbe(pParse); 002328 int r1 = sqlite3GetTempReg(pParse); 002329 assert( iTable>1 ); 002330 sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb); 002331 sqlite3MayAbort(pParse); 002332 #ifndef SQLITE_OMIT_AUTOVACUUM 002333 /* OP_Destroy stores an in integer r1. If this integer 002334 ** is non-zero, then it is the root page number of a table moved to 002335 ** location iTable. The following code modifies the sqlite_master table to 002336 ** reflect this. 002337 ** 002338 ** The "#NNN" in the SQL is a special constant that means whatever value 002339 ** is in register NNN. See grammar rules associated with the TK_REGISTER 002340 ** token for additional information. 002341 */ 002342 sqlite3NestedParse(pParse, 002343 "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d", 002344 pParse->db->aDb[iDb].zDbSName, MASTER_NAME, iTable, r1, r1); 002345 #endif 002346 sqlite3ReleaseTempReg(pParse, r1); 002347 } 002348 002349 /* 002350 ** Write VDBE code to erase table pTab and all associated indices on disk. 002351 ** Code to update the sqlite_master tables and internal schema definitions 002352 ** in case a root-page belonging to another table is moved by the btree layer 002353 ** is also added (this can happen with an auto-vacuum database). 002354 */ 002355 static void destroyTable(Parse *pParse, Table *pTab){ 002356 #ifdef SQLITE_OMIT_AUTOVACUUM 002357 Index *pIdx; 002358 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema); 002359 destroyRootPage(pParse, pTab->tnum, iDb); 002360 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ 002361 destroyRootPage(pParse, pIdx->tnum, iDb); 002362 } 002363 #else 002364 /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM 002365 ** is not defined), then it is important to call OP_Destroy on the 002366 ** table and index root-pages in order, starting with the numerically 002367 ** largest root-page number. This guarantees that none of the root-pages 002368 ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the 002369 ** following were coded: 002370 ** 002371 ** OP_Destroy 4 0 002372 ** ... 002373 ** OP_Destroy 5 0 002374 ** 002375 ** and root page 5 happened to be the largest root-page number in the 002376 ** database, then root page 5 would be moved to page 4 by the 002377 ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit 002378 ** a free-list page. 002379 */ 002380 int iTab = pTab->tnum; 002381 int iDestroyed = 0; 002382 002383 while( 1 ){ 002384 Index *pIdx; 002385 int iLargest = 0; 002386 002387 if( iDestroyed==0 || iTab<iDestroyed ){ 002388 iLargest = iTab; 002389 } 002390 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ 002391 int iIdx = pIdx->tnum; 002392 assert( pIdx->pSchema==pTab->pSchema ); 002393 if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){ 002394 iLargest = iIdx; 002395 } 002396 } 002397 if( iLargest==0 ){ 002398 return; 002399 }else{ 002400 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema); 002401 assert( iDb>=0 && iDb<pParse->db->nDb ); 002402 destroyRootPage(pParse, iLargest, iDb); 002403 iDestroyed = iLargest; 002404 } 002405 } 002406 #endif 002407 } 002408 002409 /* 002410 ** Remove entries from the sqlite_statN tables (for N in (1,2,3)) 002411 ** after a DROP INDEX or DROP TABLE command. 002412 */ 002413 static void sqlite3ClearStatTables( 002414 Parse *pParse, /* The parsing context */ 002415 int iDb, /* The database number */ 002416 const char *zType, /* "idx" or "tbl" */ 002417 const char *zName /* Name of index or table */ 002418 ){ 002419 int i; 002420 const char *zDbName = pParse->db->aDb[iDb].zDbSName; 002421 for(i=1; i<=4; i++){ 002422 char zTab[24]; 002423 sqlite3_snprintf(sizeof(zTab),zTab,"sqlite_stat%d",i); 002424 if( sqlite3FindTable(pParse->db, zTab, zDbName) ){ 002425 sqlite3NestedParse(pParse, 002426 "DELETE FROM %Q.%s WHERE %s=%Q", 002427 zDbName, zTab, zType, zName 002428 ); 002429 } 002430 } 002431 } 002432 002433 /* 002434 ** Generate code to drop a table. 002435 */ 002436 void sqlite3CodeDropTable(Parse *pParse, Table *pTab, int iDb, int isView){ 002437 Vdbe *v; 002438 sqlite3 *db = pParse->db; 002439 Trigger *pTrigger; 002440 Db *pDb = &db->aDb[iDb]; 002441 002442 v = sqlite3GetVdbe(pParse); 002443 assert( v!=0 ); 002444 sqlite3BeginWriteOperation(pParse, 1, iDb); 002445 002446 #ifndef SQLITE_OMIT_VIRTUALTABLE 002447 if( IsVirtual(pTab) ){ 002448 sqlite3VdbeAddOp0(v, OP_VBegin); 002449 } 002450 #endif 002451 002452 /* Drop all triggers associated with the table being dropped. Code 002453 ** is generated to remove entries from sqlite_master and/or 002454 ** sqlite_temp_master if required. 002455 */ 002456 pTrigger = sqlite3TriggerList(pParse, pTab); 002457 while( pTrigger ){ 002458 assert( pTrigger->pSchema==pTab->pSchema || 002459 pTrigger->pSchema==db->aDb[1].pSchema ); 002460 sqlite3DropTriggerPtr(pParse, pTrigger); 002461 pTrigger = pTrigger->pNext; 002462 } 002463 002464 #ifndef SQLITE_OMIT_AUTOINCREMENT 002465 /* Remove any entries of the sqlite_sequence table associated with 002466 ** the table being dropped. This is done before the table is dropped 002467 ** at the btree level, in case the sqlite_sequence table needs to 002468 ** move as a result of the drop (can happen in auto-vacuum mode). 002469 */ 002470 if( pTab->tabFlags & TF_Autoincrement ){ 002471 sqlite3NestedParse(pParse, 002472 "DELETE FROM %Q.sqlite_sequence WHERE name=%Q", 002473 pDb->zDbSName, pTab->zName 002474 ); 002475 } 002476 #endif 002477 002478 /* Drop all SQLITE_MASTER table and index entries that refer to the 002479 ** table. The program name loops through the master table and deletes 002480 ** every row that refers to a table of the same name as the one being 002481 ** dropped. Triggers are handled separately because a trigger can be 002482 ** created in the temp database that refers to a table in another 002483 ** database. 002484 */ 002485 sqlite3NestedParse(pParse, 002486 "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'", 002487 pDb->zDbSName, MASTER_NAME, pTab->zName); 002488 if( !isView && !IsVirtual(pTab) ){ 002489 destroyTable(pParse, pTab); 002490 } 002491 002492 /* Remove the table entry from SQLite's internal schema and modify 002493 ** the schema cookie. 002494 */ 002495 if( IsVirtual(pTab) ){ 002496 sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0); 002497 } 002498 sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0); 002499 sqlite3ChangeCookie(pParse, iDb); 002500 sqliteViewResetAll(db, iDb); 002501 } 002502 002503 /* 002504 ** This routine is called to do the work of a DROP TABLE statement. 002505 ** pName is the name of the table to be dropped. 002506 */ 002507 void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){ 002508 Table *pTab; 002509 Vdbe *v; 002510 sqlite3 *db = pParse->db; 002511 int iDb; 002512 002513 if( db->mallocFailed ){ 002514 goto exit_drop_table; 002515 } 002516 assert( pParse->nErr==0 ); 002517 assert( pName->nSrc==1 ); 002518 if( sqlite3ReadSchema(pParse) ) goto exit_drop_table; 002519 if( noErr ) db->suppressErr++; 002520 assert( isView==0 || isView==LOCATE_VIEW ); 002521 pTab = sqlite3LocateTableItem(pParse, isView, &pName->a[0]); 002522 if( noErr ) db->suppressErr--; 002523 002524 if( pTab==0 ){ 002525 if( noErr ) sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase); 002526 goto exit_drop_table; 002527 } 002528 iDb = sqlite3SchemaToIndex(db, pTab->pSchema); 002529 assert( iDb>=0 && iDb<db->nDb ); 002530 002531 /* If pTab is a virtual table, call ViewGetColumnNames() to ensure 002532 ** it is initialized. 002533 */ 002534 if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){ 002535 goto exit_drop_table; 002536 } 002537 #ifndef SQLITE_OMIT_AUTHORIZATION 002538 { 002539 int code; 002540 const char *zTab = SCHEMA_TABLE(iDb); 002541 const char *zDb = db->aDb[iDb].zDbSName; 002542 const char *zArg2 = 0; 002543 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){ 002544 goto exit_drop_table; 002545 } 002546 if( isView ){ 002547 if( !OMIT_TEMPDB && iDb==1 ){ 002548 code = SQLITE_DROP_TEMP_VIEW; 002549 }else{ 002550 code = SQLITE_DROP_VIEW; 002551 } 002552 #ifndef SQLITE_OMIT_VIRTUALTABLE 002553 }else if( IsVirtual(pTab) ){ 002554 code = SQLITE_DROP_VTABLE; 002555 zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName; 002556 #endif 002557 }else{ 002558 if( !OMIT_TEMPDB && iDb==1 ){ 002559 code = SQLITE_DROP_TEMP_TABLE; 002560 }else{ 002561 code = SQLITE_DROP_TABLE; 002562 } 002563 } 002564 if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){ 002565 goto exit_drop_table; 002566 } 002567 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){ 002568 goto exit_drop_table; 002569 } 002570 } 002571 #endif 002572 if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 002573 && sqlite3StrNICmp(pTab->zName, "sqlite_stat", 11)!=0 ){ 002574 sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName); 002575 goto exit_drop_table; 002576 } 002577 002578 #ifndef SQLITE_OMIT_VIEW 002579 /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used 002580 ** on a table. 002581 */ 002582 if( isView && pTab->pSelect==0 ){ 002583 sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName); 002584 goto exit_drop_table; 002585 } 002586 if( !isView && pTab->pSelect ){ 002587 sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName); 002588 goto exit_drop_table; 002589 } 002590 #endif 002591 002592 /* Generate code to remove the table from the master table 002593 ** on disk. 002594 */ 002595 v = sqlite3GetVdbe(pParse); 002596 if( v ){ 002597 sqlite3BeginWriteOperation(pParse, 1, iDb); 002598 sqlite3ClearStatTables(pParse, iDb, "tbl", pTab->zName); 002599 sqlite3FkDropTable(pParse, pName, pTab); 002600 sqlite3CodeDropTable(pParse, pTab, iDb, isView); 002601 } 002602 002603 exit_drop_table: 002604 sqlite3SrcListDelete(db, pName); 002605 } 002606 002607 /* 002608 ** This routine is called to create a new foreign key on the table 002609 ** currently under construction. pFromCol determines which columns 002610 ** in the current table point to the foreign key. If pFromCol==0 then 002611 ** connect the key to the last column inserted. pTo is the name of 002612 ** the table referred to (a.k.a the "parent" table). pToCol is a list 002613 ** of tables in the parent pTo table. flags contains all 002614 ** information about the conflict resolution algorithms specified 002615 ** in the ON DELETE, ON UPDATE and ON INSERT clauses. 002616 ** 002617 ** An FKey structure is created and added to the table currently 002618 ** under construction in the pParse->pNewTable field. 002619 ** 002620 ** The foreign key is set for IMMEDIATE processing. A subsequent call 002621 ** to sqlite3DeferForeignKey() might change this to DEFERRED. 002622 */ 002623 void sqlite3CreateForeignKey( 002624 Parse *pParse, /* Parsing context */ 002625 ExprList *pFromCol, /* Columns in this table that point to other table */ 002626 Token *pTo, /* Name of the other table */ 002627 ExprList *pToCol, /* Columns in the other table */ 002628 int flags /* Conflict resolution algorithms. */ 002629 ){ 002630 sqlite3 *db = pParse->db; 002631 #ifndef SQLITE_OMIT_FOREIGN_KEY 002632 FKey *pFKey = 0; 002633 FKey *pNextTo; 002634 Table *p = pParse->pNewTable; 002635 int nByte; 002636 int i; 002637 int nCol; 002638 char *z; 002639 002640 assert( pTo!=0 ); 002641 if( p==0 || IN_DECLARE_VTAB ) goto fk_end; 002642 if( pFromCol==0 ){ 002643 int iCol = p->nCol-1; 002644 if( NEVER(iCol<0) ) goto fk_end; 002645 if( pToCol && pToCol->nExpr!=1 ){ 002646 sqlite3ErrorMsg(pParse, "foreign key on %s" 002647 " should reference only one column of table %T", 002648 p->aCol[iCol].zName, pTo); 002649 goto fk_end; 002650 } 002651 nCol = 1; 002652 }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){ 002653 sqlite3ErrorMsg(pParse, 002654 "number of columns in foreign key does not match the number of " 002655 "columns in the referenced table"); 002656 goto fk_end; 002657 }else{ 002658 nCol = pFromCol->nExpr; 002659 } 002660 nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1; 002661 if( pToCol ){ 002662 for(i=0; i<pToCol->nExpr; i++){ 002663 nByte += sqlite3Strlen30(pToCol->a[i].zName) + 1; 002664 } 002665 } 002666 pFKey = sqlite3DbMallocZero(db, nByte ); 002667 if( pFKey==0 ){ 002668 goto fk_end; 002669 } 002670 pFKey->pFrom = p; 002671 pFKey->pNextFrom = p->pFKey; 002672 z = (char*)&pFKey->aCol[nCol]; 002673 pFKey->zTo = z; 002674 memcpy(z, pTo->z, pTo->n); 002675 z[pTo->n] = 0; 002676 sqlite3Dequote(z); 002677 z += pTo->n+1; 002678 pFKey->nCol = nCol; 002679 if( pFromCol==0 ){ 002680 pFKey->aCol[0].iFrom = p->nCol-1; 002681 }else{ 002682 for(i=0; i<nCol; i++){ 002683 int j; 002684 for(j=0; j<p->nCol; j++){ 002685 if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){ 002686 pFKey->aCol[i].iFrom = j; 002687 break; 002688 } 002689 } 002690 if( j>=p->nCol ){ 002691 sqlite3ErrorMsg(pParse, 002692 "unknown column \"%s\" in foreign key definition", 002693 pFromCol->a[i].zName); 002694 goto fk_end; 002695 } 002696 } 002697 } 002698 if( pToCol ){ 002699 for(i=0; i<nCol; i++){ 002700 int n = sqlite3Strlen30(pToCol->a[i].zName); 002701 pFKey->aCol[i].zCol = z; 002702 memcpy(z, pToCol->a[i].zName, n); 002703 z[n] = 0; 002704 z += n+1; 002705 } 002706 } 002707 pFKey->isDeferred = 0; 002708 pFKey->aAction[0] = (u8)(flags & 0xff); /* ON DELETE action */ 002709 pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff); /* ON UPDATE action */ 002710 002711 assert( sqlite3SchemaMutexHeld(db, 0, p->pSchema) ); 002712 pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash, 002713 pFKey->zTo, (void *)pFKey 002714 ); 002715 if( pNextTo==pFKey ){ 002716 sqlite3OomFault(db); 002717 goto fk_end; 002718 } 002719 if( pNextTo ){ 002720 assert( pNextTo->pPrevTo==0 ); 002721 pFKey->pNextTo = pNextTo; 002722 pNextTo->pPrevTo = pFKey; 002723 } 002724 002725 /* Link the foreign key to the table as the last step. 002726 */ 002727 p->pFKey = pFKey; 002728 pFKey = 0; 002729 002730 fk_end: 002731 sqlite3DbFree(db, pFKey); 002732 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */ 002733 sqlite3ExprListDelete(db, pFromCol); 002734 sqlite3ExprListDelete(db, pToCol); 002735 } 002736 002737 /* 002738 ** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED 002739 ** clause is seen as part of a foreign key definition. The isDeferred 002740 ** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE. 002741 ** The behavior of the most recently created foreign key is adjusted 002742 ** accordingly. 002743 */ 002744 void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){ 002745 #ifndef SQLITE_OMIT_FOREIGN_KEY 002746 Table *pTab; 002747 FKey *pFKey; 002748 if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return; 002749 assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */ 002750 pFKey->isDeferred = (u8)isDeferred; 002751 #endif 002752 } 002753 002754 /* 002755 ** Generate code that will erase and refill index *pIdx. This is 002756 ** used to initialize a newly created index or to recompute the 002757 ** content of an index in response to a REINDEX command. 002758 ** 002759 ** if memRootPage is not negative, it means that the index is newly 002760 ** created. The register specified by memRootPage contains the 002761 ** root page number of the index. If memRootPage is negative, then 002762 ** the index already exists and must be cleared before being refilled and 002763 ** the root page number of the index is taken from pIndex->tnum. 002764 */ 002765 static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){ 002766 Table *pTab = pIndex->pTable; /* The table that is indexed */ 002767 int iTab = pParse->nTab++; /* Btree cursor used for pTab */ 002768 int iIdx = pParse->nTab++; /* Btree cursor used for pIndex */ 002769 int iSorter; /* Cursor opened by OpenSorter (if in use) */ 002770 int addr1; /* Address of top of loop */ 002771 int addr2; /* Address to jump to for next iteration */ 002772 int tnum; /* Root page of index */ 002773 int iPartIdxLabel; /* Jump to this label to skip a row */ 002774 Vdbe *v; /* Generate code into this virtual machine */ 002775 KeyInfo *pKey; /* KeyInfo for index */ 002776 int regRecord; /* Register holding assembled index record */ 002777 sqlite3 *db = pParse->db; /* The database connection */ 002778 int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema); 002779 002780 #ifndef SQLITE_OMIT_AUTHORIZATION 002781 if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0, 002782 db->aDb[iDb].zDbSName ) ){ 002783 return; 002784 } 002785 #endif 002786 002787 /* Require a write-lock on the table to perform this operation */ 002788 sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName); 002789 002790 v = sqlite3GetVdbe(pParse); 002791 if( v==0 ) return; 002792 if( memRootPage>=0 ){ 002793 tnum = memRootPage; 002794 }else{ 002795 tnum = pIndex->tnum; 002796 } 002797 pKey = sqlite3KeyInfoOfIndex(pParse, pIndex); 002798 assert( pKey!=0 || db->mallocFailed || pParse->nErr ); 002799 002800 /* Open the sorter cursor if we are to use one. */ 002801 iSorter = pParse->nTab++; 002802 sqlite3VdbeAddOp4(v, OP_SorterOpen, iSorter, 0, pIndex->nKeyCol, (char*) 002803 sqlite3KeyInfoRef(pKey), P4_KEYINFO); 002804 002805 /* Open the table. Loop through all rows of the table, inserting index 002806 ** records into the sorter. */ 002807 sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead); 002808 addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0); VdbeCoverage(v); 002809 regRecord = sqlite3GetTempReg(pParse); 002810 002811 sqlite3GenerateIndexKey(pParse,pIndex,iTab,regRecord,0,&iPartIdxLabel,0,0); 002812 sqlite3VdbeAddOp2(v, OP_SorterInsert, iSorter, regRecord); 002813 sqlite3ResolvePartIdxLabel(pParse, iPartIdxLabel); 002814 sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1); VdbeCoverage(v); 002815 sqlite3VdbeJumpHere(v, addr1); 002816 if( memRootPage<0 ) sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb); 002817 sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb, 002818 (char *)pKey, P4_KEYINFO); 002819 sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR|((memRootPage>=0)?OPFLAG_P2ISREG:0)); 002820 002821 addr1 = sqlite3VdbeAddOp2(v, OP_SorterSort, iSorter, 0); VdbeCoverage(v); 002822 if( IsUniqueIndex(pIndex) ){ 002823 int j2 = sqlite3VdbeCurrentAddr(v) + 3; 002824 sqlite3VdbeGoto(v, j2); 002825 addr2 = sqlite3VdbeCurrentAddr(v); 002826 sqlite3VdbeAddOp4Int(v, OP_SorterCompare, iSorter, j2, regRecord, 002827 pIndex->nKeyCol); VdbeCoverage(v); 002828 sqlite3UniqueConstraint(pParse, OE_Abort, pIndex); 002829 }else{ 002830 addr2 = sqlite3VdbeCurrentAddr(v); 002831 } 002832 sqlite3VdbeAddOp3(v, OP_SorterData, iSorter, regRecord, iIdx); 002833 sqlite3VdbeAddOp3(v, OP_Last, iIdx, 0, -1); 002834 sqlite3VdbeAddOp2(v, OP_IdxInsert, iIdx, regRecord); 002835 sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT); 002836 sqlite3ReleaseTempReg(pParse, regRecord); 002837 sqlite3VdbeAddOp2(v, OP_SorterNext, iSorter, addr2); VdbeCoverage(v); 002838 sqlite3VdbeJumpHere(v, addr1); 002839 002840 sqlite3VdbeAddOp1(v, OP_Close, iTab); 002841 sqlite3VdbeAddOp1(v, OP_Close, iIdx); 002842 sqlite3VdbeAddOp1(v, OP_Close, iSorter); 002843 } 002844 002845 /* 002846 ** Allocate heap space to hold an Index object with nCol columns. 002847 ** 002848 ** Increase the allocation size to provide an extra nExtra bytes 002849 ** of 8-byte aligned space after the Index object and return a 002850 ** pointer to this extra space in *ppExtra. 002851 */ 002852 Index *sqlite3AllocateIndexObject( 002853 sqlite3 *db, /* Database connection */ 002854 i16 nCol, /* Total number of columns in the index */ 002855 int nExtra, /* Number of bytes of extra space to alloc */ 002856 char **ppExtra /* Pointer to the "extra" space */ 002857 ){ 002858 Index *p; /* Allocated index object */ 002859 int nByte; /* Bytes of space for Index object + arrays */ 002860 002861 nByte = ROUND8(sizeof(Index)) + /* Index structure */ 002862 ROUND8(sizeof(char*)*nCol) + /* Index.azColl */ 002863 ROUND8(sizeof(LogEst)*(nCol+1) + /* Index.aiRowLogEst */ 002864 sizeof(i16)*nCol + /* Index.aiColumn */ 002865 sizeof(u8)*nCol); /* Index.aSortOrder */ 002866 p = sqlite3DbMallocZero(db, nByte + nExtra); 002867 if( p ){ 002868 char *pExtra = ((char*)p)+ROUND8(sizeof(Index)); 002869 p->azColl = (const char**)pExtra; pExtra += ROUND8(sizeof(char*)*nCol); 002870 p->aiRowLogEst = (LogEst*)pExtra; pExtra += sizeof(LogEst)*(nCol+1); 002871 p->aiColumn = (i16*)pExtra; pExtra += sizeof(i16)*nCol; 002872 p->aSortOrder = (u8*)pExtra; 002873 p->nColumn = nCol; 002874 p->nKeyCol = nCol - 1; 002875 *ppExtra = ((char*)p) + nByte; 002876 } 002877 return p; 002878 } 002879 002880 /* 002881 ** Create a new index for an SQL table. pName1.pName2 is the name of the index 002882 ** and pTblList is the name of the table that is to be indexed. Both will 002883 ** be NULL for a primary key or an index that is created to satisfy a 002884 ** UNIQUE constraint. If pTable and pIndex are NULL, use pParse->pNewTable 002885 ** as the table to be indexed. pParse->pNewTable is a table that is 002886 ** currently being constructed by a CREATE TABLE statement. 002887 ** 002888 ** pList is a list of columns to be indexed. pList will be NULL if this 002889 ** is a primary key or unique-constraint on the most recent column added 002890 ** to the table currently under construction. 002891 */ 002892 void sqlite3CreateIndex( 002893 Parse *pParse, /* All information about this parse */ 002894 Token *pName1, /* First part of index name. May be NULL */ 002895 Token *pName2, /* Second part of index name. May be NULL */ 002896 SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */ 002897 ExprList *pList, /* A list of columns to be indexed */ 002898 int onError, /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */ 002899 Token *pStart, /* The CREATE token that begins this statement */ 002900 Expr *pPIWhere, /* WHERE clause for partial indices */ 002901 int sortOrder, /* Sort order of primary key when pList==NULL */ 002902 int ifNotExist, /* Omit error if index already exists */ 002903 u8 idxType /* The index type */ 002904 ){ 002905 Table *pTab = 0; /* Table to be indexed */ 002906 Index *pIndex = 0; /* The index to be created */ 002907 char *zName = 0; /* Name of the index */ 002908 int nName; /* Number of characters in zName */ 002909 int i, j; 002910 DbFixer sFix; /* For assigning database names to pTable */ 002911 int sortOrderMask; /* 1 to honor DESC in index. 0 to ignore. */ 002912 sqlite3 *db = pParse->db; 002913 Db *pDb; /* The specific table containing the indexed database */ 002914 int iDb; /* Index of the database that is being written */ 002915 Token *pName = 0; /* Unqualified name of the index to create */ 002916 struct ExprList_item *pListItem; /* For looping over pList */ 002917 int nExtra = 0; /* Space allocated for zExtra[] */ 002918 int nExtraCol; /* Number of extra columns needed */ 002919 char *zExtra = 0; /* Extra space after the Index object */ 002920 Index *pPk = 0; /* PRIMARY KEY index for WITHOUT ROWID tables */ 002921 002922 if( db->mallocFailed || pParse->nErr>0 ){ 002923 goto exit_create_index; 002924 } 002925 if( IN_DECLARE_VTAB && idxType!=SQLITE_IDXTYPE_PRIMARYKEY ){ 002926 goto exit_create_index; 002927 } 002928 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){ 002929 goto exit_create_index; 002930 } 002931 002932 /* 002933 ** Find the table that is to be indexed. Return early if not found. 002934 */ 002935 if( pTblName!=0 ){ 002936 002937 /* Use the two-part index name to determine the database 002938 ** to search for the table. 'Fix' the table name to this db 002939 ** before looking up the table. 002940 */ 002941 assert( pName1 && pName2 ); 002942 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName); 002943 if( iDb<0 ) goto exit_create_index; 002944 assert( pName && pName->z ); 002945 002946 #ifndef SQLITE_OMIT_TEMPDB 002947 /* If the index name was unqualified, check if the table 002948 ** is a temp table. If so, set the database to 1. Do not do this 002949 ** if initialising a database schema. 002950 */ 002951 if( !db->init.busy ){ 002952 pTab = sqlite3SrcListLookup(pParse, pTblName); 002953 if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){ 002954 iDb = 1; 002955 } 002956 } 002957 #endif 002958 002959 sqlite3FixInit(&sFix, pParse, iDb, "index", pName); 002960 if( sqlite3FixSrcList(&sFix, pTblName) ){ 002961 /* Because the parser constructs pTblName from a single identifier, 002962 ** sqlite3FixSrcList can never fail. */ 002963 assert(0); 002964 } 002965 pTab = sqlite3LocateTableItem(pParse, 0, &pTblName->a[0]); 002966 assert( db->mallocFailed==0 || pTab==0 ); 002967 if( pTab==0 ) goto exit_create_index; 002968 if( iDb==1 && db->aDb[iDb].pSchema!=pTab->pSchema ){ 002969 sqlite3ErrorMsg(pParse, 002970 "cannot create a TEMP index on non-TEMP table \"%s\"", 002971 pTab->zName); 002972 goto exit_create_index; 002973 } 002974 if( !HasRowid(pTab) ) pPk = sqlite3PrimaryKeyIndex(pTab); 002975 }else{ 002976 assert( pName==0 ); 002977 assert( pStart==0 ); 002978 pTab = pParse->pNewTable; 002979 if( !pTab ) goto exit_create_index; 002980 iDb = sqlite3SchemaToIndex(db, pTab->pSchema); 002981 } 002982 pDb = &db->aDb[iDb]; 002983 002984 assert( pTab!=0 ); 002985 assert( pParse->nErr==0 ); 002986 if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 002987 && db->init.busy==0 002988 #if SQLITE_USER_AUTHENTICATION 002989 && sqlite3UserAuthTable(pTab->zName)==0 002990 #endif 002991 && sqlite3StrNICmp(&pTab->zName[7],"altertab_",9)!=0 ){ 002992 sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName); 002993 goto exit_create_index; 002994 } 002995 #ifndef SQLITE_OMIT_VIEW 002996 if( pTab->pSelect ){ 002997 sqlite3ErrorMsg(pParse, "views may not be indexed"); 002998 goto exit_create_index; 002999 } 003000 #endif 003001 #ifndef SQLITE_OMIT_VIRTUALTABLE 003002 if( IsVirtual(pTab) ){ 003003 sqlite3ErrorMsg(pParse, "virtual tables may not be indexed"); 003004 goto exit_create_index; 003005 } 003006 #endif 003007 003008 /* 003009 ** Find the name of the index. Make sure there is not already another 003010 ** index or table with the same name. 003011 ** 003012 ** Exception: If we are reading the names of permanent indices from the 003013 ** sqlite_master table (because some other process changed the schema) and 003014 ** one of the index names collides with the name of a temporary table or 003015 ** index, then we will continue to process this index. 003016 ** 003017 ** If pName==0 it means that we are 003018 ** dealing with a primary key or UNIQUE constraint. We have to invent our 003019 ** own name. 003020 */ 003021 if( pName ){ 003022 zName = sqlite3NameFromToken(db, pName); 003023 if( zName==0 ) goto exit_create_index; 003024 assert( pName->z!=0 ); 003025 if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){ 003026 goto exit_create_index; 003027 } 003028 if( !db->init.busy ){ 003029 if( sqlite3FindTable(db, zName, 0)!=0 ){ 003030 sqlite3ErrorMsg(pParse, "there is already a table named %s", zName); 003031 goto exit_create_index; 003032 } 003033 } 003034 if( sqlite3FindIndex(db, zName, pDb->zDbSName)!=0 ){ 003035 if( !ifNotExist ){ 003036 sqlite3ErrorMsg(pParse, "index %s already exists", zName); 003037 }else{ 003038 assert( !db->init.busy ); 003039 sqlite3CodeVerifySchema(pParse, iDb); 003040 } 003041 goto exit_create_index; 003042 } 003043 }else{ 003044 int n; 003045 Index *pLoop; 003046 for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){} 003047 zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n); 003048 if( zName==0 ){ 003049 goto exit_create_index; 003050 } 003051 003052 /* Automatic index names generated from within sqlite3_declare_vtab() 003053 ** must have names that are distinct from normal automatic index names. 003054 ** The following statement converts "sqlite3_autoindex..." into 003055 ** "sqlite3_butoindex..." in order to make the names distinct. 003056 ** The "vtab_err.test" test demonstrates the need of this statement. */ 003057 if( IN_DECLARE_VTAB ) zName[7]++; 003058 } 003059 003060 /* Check for authorization to create an index. 003061 */ 003062 #ifndef SQLITE_OMIT_AUTHORIZATION 003063 { 003064 const char *zDb = pDb->zDbSName; 003065 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){ 003066 goto exit_create_index; 003067 } 003068 i = SQLITE_CREATE_INDEX; 003069 if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX; 003070 if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){ 003071 goto exit_create_index; 003072 } 003073 } 003074 #endif 003075 003076 /* If pList==0, it means this routine was called to make a primary 003077 ** key out of the last column added to the table under construction. 003078 ** So create a fake list to simulate this. 003079 */ 003080 if( pList==0 ){ 003081 Token prevCol; 003082 sqlite3TokenInit(&prevCol, pTab->aCol[pTab->nCol-1].zName); 003083 pList = sqlite3ExprListAppend(pParse, 0, 003084 sqlite3ExprAlloc(db, TK_ID, &prevCol, 0)); 003085 if( pList==0 ) goto exit_create_index; 003086 assert( pList->nExpr==1 ); 003087 sqlite3ExprListSetSortOrder(pList, sortOrder); 003088 }else{ 003089 sqlite3ExprListCheckLength(pParse, pList, "index"); 003090 } 003091 003092 /* Figure out how many bytes of space are required to store explicitly 003093 ** specified collation sequence names. 003094 */ 003095 for(i=0; i<pList->nExpr; i++){ 003096 Expr *pExpr = pList->a[i].pExpr; 003097 assert( pExpr!=0 ); 003098 if( pExpr->op==TK_COLLATE ){ 003099 nExtra += (1 + sqlite3Strlen30(pExpr->u.zToken)); 003100 } 003101 } 003102 003103 /* 003104 ** Allocate the index structure. 003105 */ 003106 nName = sqlite3Strlen30(zName); 003107 nExtraCol = pPk ? pPk->nKeyCol : 1; 003108 pIndex = sqlite3AllocateIndexObject(db, pList->nExpr + nExtraCol, 003109 nName + nExtra + 1, &zExtra); 003110 if( db->mallocFailed ){ 003111 goto exit_create_index; 003112 } 003113 assert( EIGHT_BYTE_ALIGNMENT(pIndex->aiRowLogEst) ); 003114 assert( EIGHT_BYTE_ALIGNMENT(pIndex->azColl) ); 003115 pIndex->zName = zExtra; 003116 zExtra += nName + 1; 003117 memcpy(pIndex->zName, zName, nName+1); 003118 pIndex->pTable = pTab; 003119 pIndex->onError = (u8)onError; 003120 pIndex->uniqNotNull = onError!=OE_None; 003121 pIndex->idxType = idxType; 003122 pIndex->pSchema = db->aDb[iDb].pSchema; 003123 pIndex->nKeyCol = pList->nExpr; 003124 if( pPIWhere ){ 003125 sqlite3ResolveSelfReference(pParse, pTab, NC_PartIdx, pPIWhere, 0); 003126 pIndex->pPartIdxWhere = pPIWhere; 003127 pPIWhere = 0; 003128 } 003129 assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); 003130 003131 /* Check to see if we should honor DESC requests on index columns 003132 */ 003133 if( pDb->pSchema->file_format>=4 ){ 003134 sortOrderMask = -1; /* Honor DESC */ 003135 }else{ 003136 sortOrderMask = 0; /* Ignore DESC */ 003137 } 003138 003139 /* Analyze the list of expressions that form the terms of the index and 003140 ** report any errors. In the common case where the expression is exactly 003141 ** a table column, store that column in aiColumn[]. For general expressions, 003142 ** populate pIndex->aColExpr and store XN_EXPR (-2) in aiColumn[]. 003143 ** 003144 ** TODO: Issue a warning if two or more columns of the index are identical. 003145 ** TODO: Issue a warning if the table primary key is used as part of the 003146 ** index key. 003147 */ 003148 for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){ 003149 Expr *pCExpr; /* The i-th index expression */ 003150 int requestedSortOrder; /* ASC or DESC on the i-th expression */ 003151 const char *zColl; /* Collation sequence name */ 003152 003153 sqlite3StringToId(pListItem->pExpr); 003154 sqlite3ResolveSelfReference(pParse, pTab, NC_IdxExpr, pListItem->pExpr, 0); 003155 if( pParse->nErr ) goto exit_create_index; 003156 pCExpr = sqlite3ExprSkipCollate(pListItem->pExpr); 003157 if( pCExpr->op!=TK_COLUMN ){ 003158 if( pTab==pParse->pNewTable ){ 003159 sqlite3ErrorMsg(pParse, "expressions prohibited in PRIMARY KEY and " 003160 "UNIQUE constraints"); 003161 goto exit_create_index; 003162 } 003163 if( pIndex->aColExpr==0 ){ 003164 ExprList *pCopy = sqlite3ExprListDup(db, pList, 0); 003165 pIndex->aColExpr = pCopy; 003166 if( !db->mallocFailed ){ 003167 assert( pCopy!=0 ); 003168 pListItem = &pCopy->a[i]; 003169 } 003170 } 003171 j = XN_EXPR; 003172 pIndex->aiColumn[i] = XN_EXPR; 003173 pIndex->uniqNotNull = 0; 003174 }else{ 003175 j = pCExpr->iColumn; 003176 assert( j<=0x7fff ); 003177 if( j<0 ){ 003178 j = pTab->iPKey; 003179 }else if( pTab->aCol[j].notNull==0 ){ 003180 pIndex->uniqNotNull = 0; 003181 } 003182 pIndex->aiColumn[i] = (i16)j; 003183 } 003184 zColl = 0; 003185 if( pListItem->pExpr->op==TK_COLLATE ){ 003186 int nColl; 003187 zColl = pListItem->pExpr->u.zToken; 003188 nColl = sqlite3Strlen30(zColl) + 1; 003189 assert( nExtra>=nColl ); 003190 memcpy(zExtra, zColl, nColl); 003191 zColl = zExtra; 003192 zExtra += nColl; 003193 nExtra -= nColl; 003194 }else if( j>=0 ){ 003195 zColl = pTab->aCol[j].zColl; 003196 } 003197 if( !zColl ) zColl = sqlite3StrBINARY; 003198 if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){ 003199 goto exit_create_index; 003200 } 003201 pIndex->azColl[i] = zColl; 003202 requestedSortOrder = pListItem->sortOrder & sortOrderMask; 003203 pIndex->aSortOrder[i] = (u8)requestedSortOrder; 003204 } 003205 003206 /* Append the table key to the end of the index. For WITHOUT ROWID 003207 ** tables (when pPk!=0) this will be the declared PRIMARY KEY. For 003208 ** normal tables (when pPk==0) this will be the rowid. 003209 */ 003210 if( pPk ){ 003211 for(j=0; j<pPk->nKeyCol; j++){ 003212 int x = pPk->aiColumn[j]; 003213 assert( x>=0 ); 003214 if( hasColumn(pIndex->aiColumn, pIndex->nKeyCol, x) ){ 003215 pIndex->nColumn--; 003216 }else{ 003217 pIndex->aiColumn[i] = x; 003218 pIndex->azColl[i] = pPk->azColl[j]; 003219 pIndex->aSortOrder[i] = pPk->aSortOrder[j]; 003220 i++; 003221 } 003222 } 003223 assert( i==pIndex->nColumn ); 003224 }else{ 003225 pIndex->aiColumn[i] = XN_ROWID; 003226 pIndex->azColl[i] = sqlite3StrBINARY; 003227 } 003228 sqlite3DefaultRowEst(pIndex); 003229 if( pParse->pNewTable==0 ) estimateIndexWidth(pIndex); 003230 003231 /* If this index contains every column of its table, then mark 003232 ** it as a covering index */ 003233 assert( HasRowid(pTab) 003234 || pTab->iPKey<0 || sqlite3ColumnOfIndex(pIndex, pTab->iPKey)>=0 ); 003235 if( pTblName!=0 && pIndex->nColumn>=pTab->nCol ){ 003236 pIndex->isCovering = 1; 003237 for(j=0; j<pTab->nCol; j++){ 003238 if( j==pTab->iPKey ) continue; 003239 if( sqlite3ColumnOfIndex(pIndex,j)>=0 ) continue; 003240 pIndex->isCovering = 0; 003241 break; 003242 } 003243 } 003244 003245 if( pTab==pParse->pNewTable ){ 003246 /* This routine has been called to create an automatic index as a 003247 ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or 003248 ** a PRIMARY KEY or UNIQUE clause following the column definitions. 003249 ** i.e. one of: 003250 ** 003251 ** CREATE TABLE t(x PRIMARY KEY, y); 003252 ** CREATE TABLE t(x, y, UNIQUE(x, y)); 003253 ** 003254 ** Either way, check to see if the table already has such an index. If 003255 ** so, don't bother creating this one. This only applies to 003256 ** automatically created indices. Users can do as they wish with 003257 ** explicit indices. 003258 ** 003259 ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent 003260 ** (and thus suppressing the second one) even if they have different 003261 ** sort orders. 003262 ** 003263 ** If there are different collating sequences or if the columns of 003264 ** the constraint occur in different orders, then the constraints are 003265 ** considered distinct and both result in separate indices. 003266 */ 003267 Index *pIdx; 003268 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ 003269 int k; 003270 assert( IsUniqueIndex(pIdx) ); 003271 assert( pIdx->idxType!=SQLITE_IDXTYPE_APPDEF ); 003272 assert( IsUniqueIndex(pIndex) ); 003273 003274 if( pIdx->nKeyCol!=pIndex->nKeyCol ) continue; 003275 for(k=0; k<pIdx->nKeyCol; k++){ 003276 const char *z1; 003277 const char *z2; 003278 assert( pIdx->aiColumn[k]>=0 ); 003279 if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break; 003280 z1 = pIdx->azColl[k]; 003281 z2 = pIndex->azColl[k]; 003282 if( sqlite3StrICmp(z1, z2) ) break; 003283 } 003284 if( k==pIdx->nKeyCol ){ 003285 if( pIdx->onError!=pIndex->onError ){ 003286 /* This constraint creates the same index as a previous 003287 ** constraint specified somewhere in the CREATE TABLE statement. 003288 ** However the ON CONFLICT clauses are different. If both this 003289 ** constraint and the previous equivalent constraint have explicit 003290 ** ON CONFLICT clauses this is an error. Otherwise, use the 003291 ** explicitly specified behavior for the index. 003292 */ 003293 if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){ 003294 sqlite3ErrorMsg(pParse, 003295 "conflicting ON CONFLICT clauses specified", 0); 003296 } 003297 if( pIdx->onError==OE_Default ){ 003298 pIdx->onError = pIndex->onError; 003299 } 003300 } 003301 if( idxType==SQLITE_IDXTYPE_PRIMARYKEY ) pIdx->idxType = idxType; 003302 goto exit_create_index; 003303 } 003304 } 003305 } 003306 003307 /* Link the new Index structure to its table and to the other 003308 ** in-memory database structures. 003309 */ 003310 assert( pParse->nErr==0 ); 003311 if( db->init.busy ){ 003312 Index *p; 003313 assert( !IN_DECLARE_VTAB ); 003314 assert( sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) ); 003315 p = sqlite3HashInsert(&pIndex->pSchema->idxHash, 003316 pIndex->zName, pIndex); 003317 if( p ){ 003318 assert( p==pIndex ); /* Malloc must have failed */ 003319 sqlite3OomFault(db); 003320 goto exit_create_index; 003321 } 003322 db->flags |= SQLITE_InternChanges; 003323 if( pTblName!=0 ){ 003324 pIndex->tnum = db->init.newTnum; 003325 } 003326 } 003327 003328 /* If this is the initial CREATE INDEX statement (or CREATE TABLE if the 003329 ** index is an implied index for a UNIQUE or PRIMARY KEY constraint) then 003330 ** emit code to allocate the index rootpage on disk and make an entry for 003331 ** the index in the sqlite_master table and populate the index with 003332 ** content. But, do not do this if we are simply reading the sqlite_master 003333 ** table to parse the schema, or if this index is the PRIMARY KEY index 003334 ** of a WITHOUT ROWID table. 003335 ** 003336 ** If pTblName==0 it means this index is generated as an implied PRIMARY KEY 003337 ** or UNIQUE index in a CREATE TABLE statement. Since the table 003338 ** has just been created, it contains no data and the index initialization 003339 ** step can be skipped. 003340 */ 003341 else if( HasRowid(pTab) || pTblName!=0 ){ 003342 Vdbe *v; 003343 char *zStmt; 003344 int iMem = ++pParse->nMem; 003345 003346 v = sqlite3GetVdbe(pParse); 003347 if( v==0 ) goto exit_create_index; 003348 003349 sqlite3BeginWriteOperation(pParse, 1, iDb); 003350 003351 /* Create the rootpage for the index using CreateIndex. But before 003352 ** doing so, code a Noop instruction and store its address in 003353 ** Index.tnum. This is required in case this index is actually a 003354 ** PRIMARY KEY and the table is actually a WITHOUT ROWID table. In 003355 ** that case the convertToWithoutRowidTable() routine will replace 003356 ** the Noop with a Goto to jump over the VDBE code generated below. */ 003357 pIndex->tnum = sqlite3VdbeAddOp0(v, OP_Noop); 003358 sqlite3VdbeAddOp2(v, OP_CreateIndex, iDb, iMem); 003359 003360 /* Gather the complete text of the CREATE INDEX statement into 003361 ** the zStmt variable 003362 */ 003363 if( pStart ){ 003364 int n = (int)(pParse->sLastToken.z - pName->z) + pParse->sLastToken.n; 003365 if( pName->z[n-1]==';' ) n--; 003366 /* A named index with an explicit CREATE INDEX statement */ 003367 zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s", 003368 onError==OE_None ? "" : " UNIQUE", n, pName->z); 003369 }else{ 003370 /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */ 003371 /* zStmt = sqlite3MPrintf(""); */ 003372 zStmt = 0; 003373 } 003374 003375 /* Add an entry in sqlite_master for this index 003376 */ 003377 sqlite3NestedParse(pParse, 003378 "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);", 003379 db->aDb[iDb].zDbSName, MASTER_NAME, 003380 pIndex->zName, 003381 pTab->zName, 003382 iMem, 003383 zStmt 003384 ); 003385 sqlite3DbFree(db, zStmt); 003386 003387 /* Fill the index with data and reparse the schema. Code an OP_Expire 003388 ** to invalidate all pre-compiled statements. 003389 */ 003390 if( pTblName ){ 003391 sqlite3RefillIndex(pParse, pIndex, iMem); 003392 sqlite3ChangeCookie(pParse, iDb); 003393 sqlite3VdbeAddParseSchemaOp(v, iDb, 003394 sqlite3MPrintf(db, "name='%q' AND type='index'", pIndex->zName)); 003395 sqlite3VdbeAddOp0(v, OP_Expire); 003396 } 003397 003398 sqlite3VdbeJumpHere(v, pIndex->tnum); 003399 } 003400 003401 /* When adding an index to the list of indices for a table, make 003402 ** sure all indices labeled OE_Replace come after all those labeled 003403 ** OE_Ignore. This is necessary for the correct constraint check 003404 ** processing (in sqlite3GenerateConstraintChecks()) as part of 003405 ** UPDATE and INSERT statements. 003406 */ 003407 if( db->init.busy || pTblName==0 ){ 003408 if( onError!=OE_Replace || pTab->pIndex==0 003409 || pTab->pIndex->onError==OE_Replace){ 003410 pIndex->pNext = pTab->pIndex; 003411 pTab->pIndex = pIndex; 003412 }else{ 003413 Index *pOther = pTab->pIndex; 003414 while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){ 003415 pOther = pOther->pNext; 003416 } 003417 pIndex->pNext = pOther->pNext; 003418 pOther->pNext = pIndex; 003419 } 003420 pIndex = 0; 003421 } 003422 003423 /* Clean up before exiting */ 003424 exit_create_index: 003425 if( pIndex ) freeIndex(db, pIndex); 003426 sqlite3ExprDelete(db, pPIWhere); 003427 sqlite3ExprListDelete(db, pList); 003428 sqlite3SrcListDelete(db, pTblName); 003429 sqlite3DbFree(db, zName); 003430 } 003431 003432 /* 003433 ** Fill the Index.aiRowEst[] array with default information - information 003434 ** to be used when we have not run the ANALYZE command. 003435 ** 003436 ** aiRowEst[0] is supposed to contain the number of elements in the index. 003437 ** Since we do not know, guess 1 million. aiRowEst[1] is an estimate of the 003438 ** number of rows in the table that match any particular value of the 003439 ** first column of the index. aiRowEst[2] is an estimate of the number 003440 ** of rows that match any particular combination of the first 2 columns 003441 ** of the index. And so forth. It must always be the case that 003442 * 003443 ** aiRowEst[N]<=aiRowEst[N-1] 003444 ** aiRowEst[N]>=1 003445 ** 003446 ** Apart from that, we have little to go on besides intuition as to 003447 ** how aiRowEst[] should be initialized. The numbers generated here 003448 ** are based on typical values found in actual indices. 003449 */ 003450 void sqlite3DefaultRowEst(Index *pIdx){ 003451 /* 10, 9, 8, 7, 6 */ 003452 LogEst aVal[] = { 33, 32, 30, 28, 26 }; 003453 LogEst *a = pIdx->aiRowLogEst; 003454 int nCopy = MIN(ArraySize(aVal), pIdx->nKeyCol); 003455 int i; 003456 003457 /* Set the first entry (number of rows in the index) to the estimated 003458 ** number of rows in the table, or half the number of rows in the table 003459 ** for a partial index. But do not let the estimate drop below 10. */ 003460 a[0] = pIdx->pTable->nRowLogEst; 003461 if( pIdx->pPartIdxWhere!=0 ) a[0] -= 10; assert( 10==sqlite3LogEst(2) ); 003462 if( a[0]<33 ) a[0] = 33; assert( 33==sqlite3LogEst(10) ); 003463 003464 /* Estimate that a[1] is 10, a[2] is 9, a[3] is 8, a[4] is 7, a[5] is 003465 ** 6 and each subsequent value (if any) is 5. */ 003466 memcpy(&a[1], aVal, nCopy*sizeof(LogEst)); 003467 for(i=nCopy+1; i<=pIdx->nKeyCol; i++){ 003468 a[i] = 23; assert( 23==sqlite3LogEst(5) ); 003469 } 003470 003471 assert( 0==sqlite3LogEst(1) ); 003472 if( IsUniqueIndex(pIdx) ) a[pIdx->nKeyCol] = 0; 003473 } 003474 003475 /* 003476 ** This routine will drop an existing named index. This routine 003477 ** implements the DROP INDEX statement. 003478 */ 003479 void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){ 003480 Index *pIndex; 003481 Vdbe *v; 003482 sqlite3 *db = pParse->db; 003483 int iDb; 003484 003485 assert( pParse->nErr==0 ); /* Never called with prior errors */ 003486 if( db->mallocFailed ){ 003487 goto exit_drop_index; 003488 } 003489 assert( pName->nSrc==1 ); 003490 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){ 003491 goto exit_drop_index; 003492 } 003493 pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase); 003494 if( pIndex==0 ){ 003495 if( !ifExists ){ 003496 sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0); 003497 }else{ 003498 sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase); 003499 } 003500 pParse->checkSchema = 1; 003501 goto exit_drop_index; 003502 } 003503 if( pIndex->idxType!=SQLITE_IDXTYPE_APPDEF ){ 003504 sqlite3ErrorMsg(pParse, "index associated with UNIQUE " 003505 "or PRIMARY KEY constraint cannot be dropped", 0); 003506 goto exit_drop_index; 003507 } 003508 iDb = sqlite3SchemaToIndex(db, pIndex->pSchema); 003509 #ifndef SQLITE_OMIT_AUTHORIZATION 003510 { 003511 int code = SQLITE_DROP_INDEX; 003512 Table *pTab = pIndex->pTable; 003513 const char *zDb = db->aDb[iDb].zDbSName; 003514 const char *zTab = SCHEMA_TABLE(iDb); 003515 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){ 003516 goto exit_drop_index; 003517 } 003518 if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX; 003519 if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){ 003520 goto exit_drop_index; 003521 } 003522 } 003523 #endif 003524 003525 /* Generate code to remove the index and from the master table */ 003526 v = sqlite3GetVdbe(pParse); 003527 if( v ){ 003528 sqlite3BeginWriteOperation(pParse, 1, iDb); 003529 sqlite3NestedParse(pParse, 003530 "DELETE FROM %Q.%s WHERE name=%Q AND type='index'", 003531 db->aDb[iDb].zDbSName, MASTER_NAME, pIndex->zName 003532 ); 003533 sqlite3ClearStatTables(pParse, iDb, "idx", pIndex->zName); 003534 sqlite3ChangeCookie(pParse, iDb); 003535 destroyRootPage(pParse, pIndex->tnum, iDb); 003536 sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0); 003537 } 003538 003539 exit_drop_index: 003540 sqlite3SrcListDelete(db, pName); 003541 } 003542 003543 /* 003544 ** pArray is a pointer to an array of objects. Each object in the 003545 ** array is szEntry bytes in size. This routine uses sqlite3DbRealloc() 003546 ** to extend the array so that there is space for a new object at the end. 003547 ** 003548 ** When this function is called, *pnEntry contains the current size of 003549 ** the array (in entries - so the allocation is ((*pnEntry) * szEntry) bytes 003550 ** in total). 003551 ** 003552 ** If the realloc() is successful (i.e. if no OOM condition occurs), the 003553 ** space allocated for the new object is zeroed, *pnEntry updated to 003554 ** reflect the new size of the array and a pointer to the new allocation 003555 ** returned. *pIdx is set to the index of the new array entry in this case. 003556 ** 003557 ** Otherwise, if the realloc() fails, *pIdx is set to -1, *pnEntry remains 003558 ** unchanged and a copy of pArray returned. 003559 */ 003560 void *sqlite3ArrayAllocate( 003561 sqlite3 *db, /* Connection to notify of malloc failures */ 003562 void *pArray, /* Array of objects. Might be reallocated */ 003563 int szEntry, /* Size of each object in the array */ 003564 int *pnEntry, /* Number of objects currently in use */ 003565 int *pIdx /* Write the index of a new slot here */ 003566 ){ 003567 char *z; 003568 int n = *pnEntry; 003569 if( (n & (n-1))==0 ){ 003570 int sz = (n==0) ? 1 : 2*n; 003571 void *pNew = sqlite3DbRealloc(db, pArray, sz*szEntry); 003572 if( pNew==0 ){ 003573 *pIdx = -1; 003574 return pArray; 003575 } 003576 pArray = pNew; 003577 } 003578 z = (char*)pArray; 003579 memset(&z[n * szEntry], 0, szEntry); 003580 *pIdx = n; 003581 ++*pnEntry; 003582 return pArray; 003583 } 003584 003585 /* 003586 ** Append a new element to the given IdList. Create a new IdList if 003587 ** need be. 003588 ** 003589 ** A new IdList is returned, or NULL if malloc() fails. 003590 */ 003591 IdList *sqlite3IdListAppend(sqlite3 *db, IdList *pList, Token *pToken){ 003592 int i; 003593 if( pList==0 ){ 003594 pList = sqlite3DbMallocZero(db, sizeof(IdList) ); 003595 if( pList==0 ) return 0; 003596 } 003597 pList->a = sqlite3ArrayAllocate( 003598 db, 003599 pList->a, 003600 sizeof(pList->a[0]), 003601 &pList->nId, 003602 &i 003603 ); 003604 if( i<0 ){ 003605 sqlite3IdListDelete(db, pList); 003606 return 0; 003607 } 003608 pList->a[i].zName = sqlite3NameFromToken(db, pToken); 003609 return pList; 003610 } 003611 003612 /* 003613 ** Delete an IdList. 003614 */ 003615 void sqlite3IdListDelete(sqlite3 *db, IdList *pList){ 003616 int i; 003617 if( pList==0 ) return; 003618 for(i=0; i<pList->nId; i++){ 003619 sqlite3DbFree(db, pList->a[i].zName); 003620 } 003621 sqlite3DbFree(db, pList->a); 003622 sqlite3DbFree(db, pList); 003623 } 003624 003625 /* 003626 ** Return the index in pList of the identifier named zId. Return -1 003627 ** if not found. 003628 */ 003629 int sqlite3IdListIndex(IdList *pList, const char *zName){ 003630 int i; 003631 if( pList==0 ) return -1; 003632 for(i=0; i<pList->nId; i++){ 003633 if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i; 003634 } 003635 return -1; 003636 } 003637 003638 /* 003639 ** Expand the space allocated for the given SrcList object by 003640 ** creating nExtra new slots beginning at iStart. iStart is zero based. 003641 ** New slots are zeroed. 003642 ** 003643 ** For example, suppose a SrcList initially contains two entries: A,B. 003644 ** To append 3 new entries onto the end, do this: 003645 ** 003646 ** sqlite3SrcListEnlarge(db, pSrclist, 3, 2); 003647 ** 003648 ** After the call above it would contain: A, B, nil, nil, nil. 003649 ** If the iStart argument had been 1 instead of 2, then the result 003650 ** would have been: A, nil, nil, nil, B. To prepend the new slots, 003651 ** the iStart value would be 0. The result then would 003652 ** be: nil, nil, nil, A, B. 003653 ** 003654 ** If a memory allocation fails the SrcList is unchanged. The 003655 ** db->mallocFailed flag will be set to true. 003656 */ 003657 SrcList *sqlite3SrcListEnlarge( 003658 sqlite3 *db, /* Database connection to notify of OOM errors */ 003659 SrcList *pSrc, /* The SrcList to be enlarged */ 003660 int nExtra, /* Number of new slots to add to pSrc->a[] */ 003661 int iStart /* Index in pSrc->a[] of first new slot */ 003662 ){ 003663 int i; 003664 003665 /* Sanity checking on calling parameters */ 003666 assert( iStart>=0 ); 003667 assert( nExtra>=1 ); 003668 assert( pSrc!=0 ); 003669 assert( iStart<=pSrc->nSrc ); 003670 003671 /* Allocate additional space if needed */ 003672 if( (u32)pSrc->nSrc+nExtra>pSrc->nAlloc ){ 003673 SrcList *pNew; 003674 int nAlloc = pSrc->nSrc*2+nExtra; 003675 int nGot; 003676 pNew = sqlite3DbRealloc(db, pSrc, 003677 sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) ); 003678 if( pNew==0 ){ 003679 assert( db->mallocFailed ); 003680 return pSrc; 003681 } 003682 pSrc = pNew; 003683 nGot = (sqlite3DbMallocSize(db, pNew) - sizeof(*pSrc))/sizeof(pSrc->a[0])+1; 003684 pSrc->nAlloc = nGot; 003685 } 003686 003687 /* Move existing slots that come after the newly inserted slots 003688 ** out of the way */ 003689 for(i=pSrc->nSrc-1; i>=iStart; i--){ 003690 pSrc->a[i+nExtra] = pSrc->a[i]; 003691 } 003692 pSrc->nSrc += nExtra; 003693 003694 /* Zero the newly allocated slots */ 003695 memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra); 003696 for(i=iStart; i<iStart+nExtra; i++){ 003697 pSrc->a[i].iCursor = -1; 003698 } 003699 003700 /* Return a pointer to the enlarged SrcList */ 003701 return pSrc; 003702 } 003703 003704 003705 /* 003706 ** Append a new table name to the given SrcList. Create a new SrcList if 003707 ** need be. A new entry is created in the SrcList even if pTable is NULL. 003708 ** 003709 ** A SrcList is returned, or NULL if there is an OOM error. The returned 003710 ** SrcList might be the same as the SrcList that was input or it might be 003711 ** a new one. If an OOM error does occurs, then the prior value of pList 003712 ** that is input to this routine is automatically freed. 003713 ** 003714 ** If pDatabase is not null, it means that the table has an optional 003715 ** database name prefix. Like this: "database.table". The pDatabase 003716 ** points to the table name and the pTable points to the database name. 003717 ** The SrcList.a[].zName field is filled with the table name which might 003718 ** come from pTable (if pDatabase is NULL) or from pDatabase. 003719 ** SrcList.a[].zDatabase is filled with the database name from pTable, 003720 ** or with NULL if no database is specified. 003721 ** 003722 ** In other words, if call like this: 003723 ** 003724 ** sqlite3SrcListAppend(D,A,B,0); 003725 ** 003726 ** Then B is a table name and the database name is unspecified. If called 003727 ** like this: 003728 ** 003729 ** sqlite3SrcListAppend(D,A,B,C); 003730 ** 003731 ** Then C is the table name and B is the database name. If C is defined 003732 ** then so is B. In other words, we never have a case where: 003733 ** 003734 ** sqlite3SrcListAppend(D,A,0,C); 003735 ** 003736 ** Both pTable and pDatabase are assumed to be quoted. They are dequoted 003737 ** before being added to the SrcList. 003738 */ 003739 SrcList *sqlite3SrcListAppend( 003740 sqlite3 *db, /* Connection to notify of malloc failures */ 003741 SrcList *pList, /* Append to this SrcList. NULL creates a new SrcList */ 003742 Token *pTable, /* Table to append */ 003743 Token *pDatabase /* Database of the table */ 003744 ){ 003745 struct SrcList_item *pItem; 003746 assert( pDatabase==0 || pTable!=0 ); /* Cannot have C without B */ 003747 assert( db!=0 ); 003748 if( pList==0 ){ 003749 pList = sqlite3DbMallocRawNN(db, sizeof(SrcList) ); 003750 if( pList==0 ) return 0; 003751 pList->nAlloc = 1; 003752 pList->nSrc = 1; 003753 memset(&pList->a[0], 0, sizeof(pList->a[0])); 003754 pList->a[0].iCursor = -1; 003755 }else{ 003756 pList = sqlite3SrcListEnlarge(db, pList, 1, pList->nSrc); 003757 } 003758 if( db->mallocFailed ){ 003759 sqlite3SrcListDelete(db, pList); 003760 return 0; 003761 } 003762 pItem = &pList->a[pList->nSrc-1]; 003763 if( pDatabase && pDatabase->z==0 ){ 003764 pDatabase = 0; 003765 } 003766 if( pDatabase ){ 003767 Token *pTemp = pDatabase; 003768 pDatabase = pTable; 003769 pTable = pTemp; 003770 } 003771 pItem->zName = sqlite3NameFromToken(db, pTable); 003772 pItem->zDatabase = sqlite3NameFromToken(db, pDatabase); 003773 return pList; 003774 } 003775 003776 /* 003777 ** Assign VdbeCursor index numbers to all tables in a SrcList 003778 */ 003779 void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){ 003780 int i; 003781 struct SrcList_item *pItem; 003782 assert(pList || pParse->db->mallocFailed ); 003783 if( pList ){ 003784 for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){ 003785 if( pItem->iCursor>=0 ) break; 003786 pItem->iCursor = pParse->nTab++; 003787 if( pItem->pSelect ){ 003788 sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc); 003789 } 003790 } 003791 } 003792 } 003793 003794 /* 003795 ** Delete an entire SrcList including all its substructure. 003796 */ 003797 void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){ 003798 int i; 003799 struct SrcList_item *pItem; 003800 if( pList==0 ) return; 003801 for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){ 003802 sqlite3DbFree(db, pItem->zDatabase); 003803 sqlite3DbFree(db, pItem->zName); 003804 sqlite3DbFree(db, pItem->zAlias); 003805 if( pItem->fg.isIndexedBy ) sqlite3DbFree(db, pItem->u1.zIndexedBy); 003806 if( pItem->fg.isTabFunc ) sqlite3ExprListDelete(db, pItem->u1.pFuncArg); 003807 sqlite3DeleteTable(db, pItem->pTab); 003808 sqlite3SelectDelete(db, pItem->pSelect); 003809 sqlite3ExprDelete(db, pItem->pOn); 003810 sqlite3IdListDelete(db, pItem->pUsing); 003811 } 003812 sqlite3DbFree(db, pList); 003813 } 003814 003815 /* 003816 ** This routine is called by the parser to add a new term to the 003817 ** end of a growing FROM clause. The "p" parameter is the part of 003818 ** the FROM clause that has already been constructed. "p" is NULL 003819 ** if this is the first term of the FROM clause. pTable and pDatabase 003820 ** are the name of the table and database named in the FROM clause term. 003821 ** pDatabase is NULL if the database name qualifier is missing - the 003822 ** usual case. If the term has an alias, then pAlias points to the 003823 ** alias token. If the term is a subquery, then pSubquery is the 003824 ** SELECT statement that the subquery encodes. The pTable and 003825 ** pDatabase parameters are NULL for subqueries. The pOn and pUsing 003826 ** parameters are the content of the ON and USING clauses. 003827 ** 003828 ** Return a new SrcList which encodes is the FROM with the new 003829 ** term added. 003830 */ 003831 SrcList *sqlite3SrcListAppendFromTerm( 003832 Parse *pParse, /* Parsing context */ 003833 SrcList *p, /* The left part of the FROM clause already seen */ 003834 Token *pTable, /* Name of the table to add to the FROM clause */ 003835 Token *pDatabase, /* Name of the database containing pTable */ 003836 Token *pAlias, /* The right-hand side of the AS subexpression */ 003837 Select *pSubquery, /* A subquery used in place of a table name */ 003838 Expr *pOn, /* The ON clause of a join */ 003839 IdList *pUsing /* The USING clause of a join */ 003840 ){ 003841 struct SrcList_item *pItem; 003842 sqlite3 *db = pParse->db; 003843 if( !p && (pOn || pUsing) ){ 003844 sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s", 003845 (pOn ? "ON" : "USING") 003846 ); 003847 goto append_from_error; 003848 } 003849 p = sqlite3SrcListAppend(db, p, pTable, pDatabase); 003850 if( p==0 || NEVER(p->nSrc==0) ){ 003851 goto append_from_error; 003852 } 003853 pItem = &p->a[p->nSrc-1]; 003854 assert( pAlias!=0 ); 003855 if( pAlias->n ){ 003856 pItem->zAlias = sqlite3NameFromToken(db, pAlias); 003857 } 003858 pItem->pSelect = pSubquery; 003859 pItem->pOn = pOn; 003860 pItem->pUsing = pUsing; 003861 return p; 003862 003863 append_from_error: 003864 assert( p==0 ); 003865 sqlite3ExprDelete(db, pOn); 003866 sqlite3IdListDelete(db, pUsing); 003867 sqlite3SelectDelete(db, pSubquery); 003868 return 0; 003869 } 003870 003871 /* 003872 ** Add an INDEXED BY or NOT INDEXED clause to the most recently added 003873 ** element of the source-list passed as the second argument. 003874 */ 003875 void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){ 003876 assert( pIndexedBy!=0 ); 003877 if( p && ALWAYS(p->nSrc>0) ){ 003878 struct SrcList_item *pItem = &p->a[p->nSrc-1]; 003879 assert( pItem->fg.notIndexed==0 ); 003880 assert( pItem->fg.isIndexedBy==0 ); 003881 assert( pItem->fg.isTabFunc==0 ); 003882 if( pIndexedBy->n==1 && !pIndexedBy->z ){ 003883 /* A "NOT INDEXED" clause was supplied. See parse.y 003884 ** construct "indexed_opt" for details. */ 003885 pItem->fg.notIndexed = 1; 003886 }else{ 003887 pItem->u1.zIndexedBy = sqlite3NameFromToken(pParse->db, pIndexedBy); 003888 pItem->fg.isIndexedBy = (pItem->u1.zIndexedBy!=0); 003889 } 003890 } 003891 } 003892 003893 /* 003894 ** Add the list of function arguments to the SrcList entry for a 003895 ** table-valued-function. 003896 */ 003897 void sqlite3SrcListFuncArgs(Parse *pParse, SrcList *p, ExprList *pList){ 003898 if( p ){ 003899 struct SrcList_item *pItem = &p->a[p->nSrc-1]; 003900 assert( pItem->fg.notIndexed==0 ); 003901 assert( pItem->fg.isIndexedBy==0 ); 003902 assert( pItem->fg.isTabFunc==0 ); 003903 pItem->u1.pFuncArg = pList; 003904 pItem->fg.isTabFunc = 1; 003905 }else{ 003906 sqlite3ExprListDelete(pParse->db, pList); 003907 } 003908 } 003909 003910 /* 003911 ** When building up a FROM clause in the parser, the join operator 003912 ** is initially attached to the left operand. But the code generator 003913 ** expects the join operator to be on the right operand. This routine 003914 ** Shifts all join operators from left to right for an entire FROM 003915 ** clause. 003916 ** 003917 ** Example: Suppose the join is like this: 003918 ** 003919 ** A natural cross join B 003920 ** 003921 ** The operator is "natural cross join". The A and B operands are stored 003922 ** in p->a[0] and p->a[1], respectively. The parser initially stores the 003923 ** operator with A. This routine shifts that operator over to B. 003924 */ 003925 void sqlite3SrcListShiftJoinType(SrcList *p){ 003926 if( p ){ 003927 int i; 003928 for(i=p->nSrc-1; i>0; i--){ 003929 p->a[i].fg.jointype = p->a[i-1].fg.jointype; 003930 } 003931 p->a[0].fg.jointype = 0; 003932 } 003933 } 003934 003935 /* 003936 ** Generate VDBE code for a BEGIN statement. 003937 */ 003938 void sqlite3BeginTransaction(Parse *pParse, int type){ 003939 sqlite3 *db; 003940 Vdbe *v; 003941 int i; 003942 003943 assert( pParse!=0 ); 003944 db = pParse->db; 003945 assert( db!=0 ); 003946 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){ 003947 return; 003948 } 003949 v = sqlite3GetVdbe(pParse); 003950 if( !v ) return; 003951 if( type!=TK_DEFERRED ){ 003952 for(i=0; i<db->nDb; i++){ 003953 sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1); 003954 sqlite3VdbeUsesBtree(v, i); 003955 } 003956 } 003957 sqlite3VdbeAddOp0(v, OP_AutoCommit); 003958 } 003959 003960 /* 003961 ** Generate VDBE code for a COMMIT statement. 003962 */ 003963 void sqlite3CommitTransaction(Parse *pParse){ 003964 Vdbe *v; 003965 003966 assert( pParse!=0 ); 003967 assert( pParse->db!=0 ); 003968 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ){ 003969 return; 003970 } 003971 v = sqlite3GetVdbe(pParse); 003972 if( v ){ 003973 sqlite3VdbeAddOp1(v, OP_AutoCommit, 1); 003974 } 003975 } 003976 003977 /* 003978 ** Generate VDBE code for a ROLLBACK statement. 003979 */ 003980 void sqlite3RollbackTransaction(Parse *pParse){ 003981 Vdbe *v; 003982 003983 assert( pParse!=0 ); 003984 assert( pParse->db!=0 ); 003985 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ){ 003986 return; 003987 } 003988 v = sqlite3GetVdbe(pParse); 003989 if( v ){ 003990 sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 1); 003991 } 003992 } 003993 003994 /* 003995 ** This function is called by the parser when it parses a command to create, 003996 ** release or rollback an SQL savepoint. 003997 */ 003998 void sqlite3Savepoint(Parse *pParse, int op, Token *pName){ 003999 char *zName = sqlite3NameFromToken(pParse->db, pName); 004000 if( zName ){ 004001 Vdbe *v = sqlite3GetVdbe(pParse); 004002 #ifndef SQLITE_OMIT_AUTHORIZATION 004003 static const char * const az[] = { "BEGIN", "RELEASE", "ROLLBACK" }; 004004 assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 ); 004005 #endif 004006 if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){ 004007 sqlite3DbFree(pParse->db, zName); 004008 return; 004009 } 004010 sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC); 004011 } 004012 } 004013 004014 /* 004015 ** Make sure the TEMP database is open and available for use. Return 004016 ** the number of errors. Leave any error messages in the pParse structure. 004017 */ 004018 int sqlite3OpenTempDatabase(Parse *pParse){ 004019 sqlite3 *db = pParse->db; 004020 if( db->aDb[1].pBt==0 && !pParse->explain ){ 004021 int rc; 004022 Btree *pBt; 004023 static const int flags = 004024 SQLITE_OPEN_READWRITE | 004025 SQLITE_OPEN_CREATE | 004026 SQLITE_OPEN_EXCLUSIVE | 004027 SQLITE_OPEN_DELETEONCLOSE | 004028 SQLITE_OPEN_TEMP_DB; 004029 004030 rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pBt, 0, flags); 004031 if( rc!=SQLITE_OK ){ 004032 sqlite3ErrorMsg(pParse, "unable to open a temporary database " 004033 "file for storing temporary tables"); 004034 pParse->rc = rc; 004035 return 1; 004036 } 004037 db->aDb[1].pBt = pBt; 004038 assert( db->aDb[1].pSchema ); 004039 if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){ 004040 sqlite3OomFault(db); 004041 return 1; 004042 } 004043 } 004044 return 0; 004045 } 004046 004047 /* 004048 ** Record the fact that the schema cookie will need to be verified 004049 ** for database iDb. The code to actually verify the schema cookie 004050 ** will occur at the end of the top-level VDBE and will be generated 004051 ** later, by sqlite3FinishCoding(). 004052 */ 004053 void sqlite3CodeVerifySchema(Parse *pParse, int iDb){ 004054 Parse *pToplevel = sqlite3ParseToplevel(pParse); 004055 004056 assert( iDb>=0 && iDb<pParse->db->nDb ); 004057 assert( pParse->db->aDb[iDb].pBt!=0 || iDb==1 ); 004058 assert( iDb<SQLITE_MAX_ATTACHED+2 ); 004059 assert( sqlite3SchemaMutexHeld(pParse->db, iDb, 0) ); 004060 if( DbMaskTest(pToplevel->cookieMask, iDb)==0 ){ 004061 DbMaskSet(pToplevel->cookieMask, iDb); 004062 if( !OMIT_TEMPDB && iDb==1 ){ 004063 sqlite3OpenTempDatabase(pToplevel); 004064 } 004065 } 004066 } 004067 004068 /* 004069 ** If argument zDb is NULL, then call sqlite3CodeVerifySchema() for each 004070 ** attached database. Otherwise, invoke it for the database named zDb only. 004071 */ 004072 void sqlite3CodeVerifyNamedSchema(Parse *pParse, const char *zDb){ 004073 sqlite3 *db = pParse->db; 004074 int i; 004075 for(i=0; i<db->nDb; i++){ 004076 Db *pDb = &db->aDb[i]; 004077 if( pDb->pBt && (!zDb || 0==sqlite3StrICmp(zDb, pDb->zDbSName)) ){ 004078 sqlite3CodeVerifySchema(pParse, i); 004079 } 004080 } 004081 } 004082 004083 /* 004084 ** Generate VDBE code that prepares for doing an operation that 004085 ** might change the database. 004086 ** 004087 ** This routine starts a new transaction if we are not already within 004088 ** a transaction. If we are already within a transaction, then a checkpoint 004089 ** is set if the setStatement parameter is true. A checkpoint should 004090 ** be set for operations that might fail (due to a constraint) part of 004091 ** the way through and which will need to undo some writes without having to 004092 ** rollback the whole transaction. For operations where all constraints 004093 ** can be checked before any changes are made to the database, it is never 004094 ** necessary to undo a write and the checkpoint should not be set. 004095 */ 004096 void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){ 004097 Parse *pToplevel = sqlite3ParseToplevel(pParse); 004098 sqlite3CodeVerifySchema(pParse, iDb); 004099 DbMaskSet(pToplevel->writeMask, iDb); 004100 pToplevel->isMultiWrite |= setStatement; 004101 } 004102 004103 /* 004104 ** Indicate that the statement currently under construction might write 004105 ** more than one entry (example: deleting one row then inserting another, 004106 ** inserting multiple rows in a table, or inserting a row and index entries.) 004107 ** If an abort occurs after some of these writes have completed, then it will 004108 ** be necessary to undo the completed writes. 004109 */ 004110 void sqlite3MultiWrite(Parse *pParse){ 004111 Parse *pToplevel = sqlite3ParseToplevel(pParse); 004112 pToplevel->isMultiWrite = 1; 004113 } 004114 004115 /* 004116 ** The code generator calls this routine if is discovers that it is 004117 ** possible to abort a statement prior to completion. In order to 004118 ** perform this abort without corrupting the database, we need to make 004119 ** sure that the statement is protected by a statement transaction. 004120 ** 004121 ** Technically, we only need to set the mayAbort flag if the 004122 ** isMultiWrite flag was previously set. There is a time dependency 004123 ** such that the abort must occur after the multiwrite. This makes 004124 ** some statements involving the REPLACE conflict resolution algorithm 004125 ** go a little faster. But taking advantage of this time dependency 004126 ** makes it more difficult to prove that the code is correct (in 004127 ** particular, it prevents us from writing an effective 004128 ** implementation of sqlite3AssertMayAbort()) and so we have chosen 004129 ** to take the safe route and skip the optimization. 004130 */ 004131 void sqlite3MayAbort(Parse *pParse){ 004132 Parse *pToplevel = sqlite3ParseToplevel(pParse); 004133 pToplevel->mayAbort = 1; 004134 } 004135 004136 /* 004137 ** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT 004138 ** error. The onError parameter determines which (if any) of the statement 004139 ** and/or current transaction is rolled back. 004140 */ 004141 void sqlite3HaltConstraint( 004142 Parse *pParse, /* Parsing context */ 004143 int errCode, /* extended error code */ 004144 int onError, /* Constraint type */ 004145 char *p4, /* Error message */ 004146 i8 p4type, /* P4_STATIC or P4_TRANSIENT */ 004147 u8 p5Errmsg /* P5_ErrMsg type */ 004148 ){ 004149 Vdbe *v = sqlite3GetVdbe(pParse); 004150 assert( (errCode&0xff)==SQLITE_CONSTRAINT ); 004151 if( onError==OE_Abort ){ 004152 sqlite3MayAbort(pParse); 004153 } 004154 sqlite3VdbeAddOp4(v, OP_Halt, errCode, onError, 0, p4, p4type); 004155 sqlite3VdbeChangeP5(v, p5Errmsg); 004156 } 004157 004158 /* 004159 ** Code an OP_Halt due to UNIQUE or PRIMARY KEY constraint violation. 004160 */ 004161 void sqlite3UniqueConstraint( 004162 Parse *pParse, /* Parsing context */ 004163 int onError, /* Constraint type */ 004164 Index *pIdx /* The index that triggers the constraint */ 004165 ){ 004166 char *zErr; 004167 int j; 004168 StrAccum errMsg; 004169 Table *pTab = pIdx->pTable; 004170 004171 sqlite3StrAccumInit(&errMsg, pParse->db, 0, 0, 200); 004172 if( pIdx->aColExpr ){ 004173 sqlite3XPrintf(&errMsg, "index '%q'", pIdx->zName); 004174 }else{ 004175 for(j=0; j<pIdx->nKeyCol; j++){ 004176 char *zCol; 004177 assert( pIdx->aiColumn[j]>=0 ); 004178 zCol = pTab->aCol[pIdx->aiColumn[j]].zName; 004179 if( j ) sqlite3StrAccumAppend(&errMsg, ", ", 2); 004180 sqlite3XPrintf(&errMsg, "%s.%s", pTab->zName, zCol); 004181 } 004182 } 004183 zErr = sqlite3StrAccumFinish(&errMsg); 004184 sqlite3HaltConstraint(pParse, 004185 IsPrimaryKeyIndex(pIdx) ? SQLITE_CONSTRAINT_PRIMARYKEY 004186 : SQLITE_CONSTRAINT_UNIQUE, 004187 onError, zErr, P4_DYNAMIC, P5_ConstraintUnique); 004188 } 004189 004190 004191 /* 004192 ** Code an OP_Halt due to non-unique rowid. 004193 */ 004194 void sqlite3RowidConstraint( 004195 Parse *pParse, /* Parsing context */ 004196 int onError, /* Conflict resolution algorithm */ 004197 Table *pTab /* The table with the non-unique rowid */ 004198 ){ 004199 char *zMsg; 004200 int rc; 004201 if( pTab->iPKey>=0 ){ 004202 zMsg = sqlite3MPrintf(pParse->db, "%s.%s", pTab->zName, 004203 pTab->aCol[pTab->iPKey].zName); 004204 rc = SQLITE_CONSTRAINT_PRIMARYKEY; 004205 }else{ 004206 zMsg = sqlite3MPrintf(pParse->db, "%s.rowid", pTab->zName); 004207 rc = SQLITE_CONSTRAINT_ROWID; 004208 } 004209 sqlite3HaltConstraint(pParse, rc, onError, zMsg, P4_DYNAMIC, 004210 P5_ConstraintUnique); 004211 } 004212 004213 /* 004214 ** Check to see if pIndex uses the collating sequence pColl. Return 004215 ** true if it does and false if it does not. 004216 */ 004217 #ifndef SQLITE_OMIT_REINDEX 004218 static int collationMatch(const char *zColl, Index *pIndex){ 004219 int i; 004220 assert( zColl!=0 ); 004221 for(i=0; i<pIndex->nColumn; i++){ 004222 const char *z = pIndex->azColl[i]; 004223 assert( z!=0 || pIndex->aiColumn[i]<0 ); 004224 if( pIndex->aiColumn[i]>=0 && 0==sqlite3StrICmp(z, zColl) ){ 004225 return 1; 004226 } 004227 } 004228 return 0; 004229 } 004230 #endif 004231 004232 /* 004233 ** Recompute all indices of pTab that use the collating sequence pColl. 004234 ** If pColl==0 then recompute all indices of pTab. 004235 */ 004236 #ifndef SQLITE_OMIT_REINDEX 004237 static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){ 004238 Index *pIndex; /* An index associated with pTab */ 004239 004240 for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){ 004241 if( zColl==0 || collationMatch(zColl, pIndex) ){ 004242 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema); 004243 sqlite3BeginWriteOperation(pParse, 0, iDb); 004244 sqlite3RefillIndex(pParse, pIndex, -1); 004245 } 004246 } 004247 } 004248 #endif 004249 004250 /* 004251 ** Recompute all indices of all tables in all databases where the 004252 ** indices use the collating sequence pColl. If pColl==0 then recompute 004253 ** all indices everywhere. 004254 */ 004255 #ifndef SQLITE_OMIT_REINDEX 004256 static void reindexDatabases(Parse *pParse, char const *zColl){ 004257 Db *pDb; /* A single database */ 004258 int iDb; /* The database index number */ 004259 sqlite3 *db = pParse->db; /* The database connection */ 004260 HashElem *k; /* For looping over tables in pDb */ 004261 Table *pTab; /* A table in the database */ 004262 004263 assert( sqlite3BtreeHoldsAllMutexes(db) ); /* Needed for schema access */ 004264 for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){ 004265 assert( pDb!=0 ); 004266 for(k=sqliteHashFirst(&pDb->pSchema->tblHash); k; k=sqliteHashNext(k)){ 004267 pTab = (Table*)sqliteHashData(k); 004268 reindexTable(pParse, pTab, zColl); 004269 } 004270 } 004271 } 004272 #endif 004273 004274 /* 004275 ** Generate code for the REINDEX command. 004276 ** 004277 ** REINDEX -- 1 004278 ** REINDEX <collation> -- 2 004279 ** REINDEX ?<database>.?<tablename> -- 3 004280 ** REINDEX ?<database>.?<indexname> -- 4 004281 ** 004282 ** Form 1 causes all indices in all attached databases to be rebuilt. 004283 ** Form 2 rebuilds all indices in all databases that use the named 004284 ** collating function. Forms 3 and 4 rebuild the named index or all 004285 ** indices associated with the named table. 004286 */ 004287 #ifndef SQLITE_OMIT_REINDEX 004288 void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){ 004289 CollSeq *pColl; /* Collating sequence to be reindexed, or NULL */ 004290 char *z; /* Name of a table or index */ 004291 const char *zDb; /* Name of the database */ 004292 Table *pTab; /* A table in the database */ 004293 Index *pIndex; /* An index associated with pTab */ 004294 int iDb; /* The database index number */ 004295 sqlite3 *db = pParse->db; /* The database connection */ 004296 Token *pObjName; /* Name of the table or index to be reindexed */ 004297 004298 /* Read the database schema. If an error occurs, leave an error message 004299 ** and code in pParse and return NULL. */ 004300 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){ 004301 return; 004302 } 004303 004304 if( pName1==0 ){ 004305 reindexDatabases(pParse, 0); 004306 return; 004307 }else if( NEVER(pName2==0) || pName2->z==0 ){ 004308 char *zColl; 004309 assert( pName1->z ); 004310 zColl = sqlite3NameFromToken(pParse->db, pName1); 004311 if( !zColl ) return; 004312 pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0); 004313 if( pColl ){ 004314 reindexDatabases(pParse, zColl); 004315 sqlite3DbFree(db, zColl); 004316 return; 004317 } 004318 sqlite3DbFree(db, zColl); 004319 } 004320 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName); 004321 if( iDb<0 ) return; 004322 z = sqlite3NameFromToken(db, pObjName); 004323 if( z==0 ) return; 004324 zDb = db->aDb[iDb].zDbSName; 004325 pTab = sqlite3FindTable(db, z, zDb); 004326 if( pTab ){ 004327 reindexTable(pParse, pTab, 0); 004328 sqlite3DbFree(db, z); 004329 return; 004330 } 004331 pIndex = sqlite3FindIndex(db, z, zDb); 004332 sqlite3DbFree(db, z); 004333 if( pIndex ){ 004334 sqlite3BeginWriteOperation(pParse, 0, iDb); 004335 sqlite3RefillIndex(pParse, pIndex, -1); 004336 return; 004337 } 004338 sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed"); 004339 } 004340 #endif 004341 004342 /* 004343 ** Return a KeyInfo structure that is appropriate for the given Index. 004344 ** 004345 ** The caller should invoke sqlite3KeyInfoUnref() on the returned object 004346 ** when it has finished using it. 004347 */ 004348 KeyInfo *sqlite3KeyInfoOfIndex(Parse *pParse, Index *pIdx){ 004349 int i; 004350 int nCol = pIdx->nColumn; 004351 int nKey = pIdx->nKeyCol; 004352 KeyInfo *pKey; 004353 if( pParse->nErr ) return 0; 004354 if( pIdx->uniqNotNull ){ 004355 pKey = sqlite3KeyInfoAlloc(pParse->db, nKey, nCol-nKey); 004356 }else{ 004357 pKey = sqlite3KeyInfoAlloc(pParse->db, nCol, 0); 004358 } 004359 if( pKey ){ 004360 assert( sqlite3KeyInfoIsWriteable(pKey) ); 004361 for(i=0; i<nCol; i++){ 004362 const char *zColl = pIdx->azColl[i]; 004363 pKey->aColl[i] = zColl==sqlite3StrBINARY ? 0 : 004364 sqlite3LocateCollSeq(pParse, zColl); 004365 pKey->aSortOrder[i] = pIdx->aSortOrder[i]; 004366 } 004367 if( pParse->nErr ){ 004368 sqlite3KeyInfoUnref(pKey); 004369 pKey = 0; 004370 } 004371 } 004372 return pKey; 004373 } 004374 004375 #ifndef SQLITE_OMIT_CTE 004376 /* 004377 ** This routine is invoked once per CTE by the parser while parsing a 004378 ** WITH clause. 004379 */ 004380 With *sqlite3WithAdd( 004381 Parse *pParse, /* Parsing context */ 004382 With *pWith, /* Existing WITH clause, or NULL */ 004383 Token *pName, /* Name of the common-table */ 004384 ExprList *pArglist, /* Optional column name list for the table */ 004385 Select *pQuery /* Query used to initialize the table */ 004386 ){ 004387 sqlite3 *db = pParse->db; 004388 With *pNew; 004389 char *zName; 004390 004391 /* Check that the CTE name is unique within this WITH clause. If 004392 ** not, store an error in the Parse structure. */ 004393 zName = sqlite3NameFromToken(pParse->db, pName); 004394 if( zName && pWith ){ 004395 int i; 004396 for(i=0; i<pWith->nCte; i++){ 004397 if( sqlite3StrICmp(zName, pWith->a[i].zName)==0 ){ 004398 sqlite3ErrorMsg(pParse, "duplicate WITH table name: %s", zName); 004399 } 004400 } 004401 } 004402 004403 if( pWith ){ 004404 int nByte = sizeof(*pWith) + (sizeof(pWith->a[1]) * pWith->nCte); 004405 pNew = sqlite3DbRealloc(db, pWith, nByte); 004406 }else{ 004407 pNew = sqlite3DbMallocZero(db, sizeof(*pWith)); 004408 } 004409 assert( (pNew!=0 && zName!=0) || db->mallocFailed ); 004410 004411 if( db->mallocFailed ){ 004412 sqlite3ExprListDelete(db, pArglist); 004413 sqlite3SelectDelete(db, pQuery); 004414 sqlite3DbFree(db, zName); 004415 pNew = pWith; 004416 }else{ 004417 pNew->a[pNew->nCte].pSelect = pQuery; 004418 pNew->a[pNew->nCte].pCols = pArglist; 004419 pNew->a[pNew->nCte].zName = zName; 004420 pNew->a[pNew->nCte].zCteErr = 0; 004421 pNew->nCte++; 004422 } 004423 004424 return pNew; 004425 } 004426 004427 /* 004428 ** Free the contents of the With object passed as the second argument. 004429 */ 004430 void sqlite3WithDelete(sqlite3 *db, With *pWith){ 004431 if( pWith ){ 004432 int i; 004433 for(i=0; i<pWith->nCte; i++){ 004434 struct Cte *pCte = &pWith->a[i]; 004435 sqlite3ExprListDelete(db, pCte->pCols); 004436 sqlite3SelectDelete(db, pCte->pSelect); 004437 sqlite3DbFree(db, pCte->zName); 004438 } 004439 sqlite3DbFree(db, pWith); 004440 } 004441 } 004442 #endif /* !defined(SQLITE_OMIT_CTE) */