175897234Sdrh /* 2b19a2bc6Sdrh ** 2001 September 15 375897234Sdrh ** 4b19a2bc6Sdrh ** The author disclaims copyright to this source code. In place of 5b19a2bc6Sdrh ** a legal notice, here is a blessing: 675897234Sdrh ** 7b19a2bc6Sdrh ** May you do good and not evil. 8b19a2bc6Sdrh ** May you find forgiveness for yourself and forgive others. 9b19a2bc6Sdrh ** May you share freely, never taking more than you give. 1075897234Sdrh ** 1175897234Sdrh ************************************************************************* 12b19a2bc6Sdrh ** This file contains C code routines that are called by the SQLite parser 13b19a2bc6Sdrh ** when syntax rules are reduced. The routines in this file handle the 14b19a2bc6Sdrh ** following kinds of SQL syntax: 1575897234Sdrh ** 16bed8690fSdrh ** CREATE TABLE 17bed8690fSdrh ** DROP TABLE 18bed8690fSdrh ** CREATE INDEX 19bed8690fSdrh ** DROP INDEX 20832508b7Sdrh ** creating ID lists 21b19a2bc6Sdrh ** BEGIN TRANSACTION 22b19a2bc6Sdrh ** COMMIT 23b19a2bc6Sdrh ** ROLLBACK 2475897234Sdrh */ 2575897234Sdrh #include "sqliteInt.h" 2675897234Sdrh 27c00da105Sdanielk1977 #ifndef SQLITE_OMIT_SHARED_CACHE 28c00da105Sdanielk1977 /* 29c00da105Sdanielk1977 ** The TableLock structure is only used by the sqlite3TableLock() and 30c00da105Sdanielk1977 ** codeTableLocks() functions. 31c00da105Sdanielk1977 */ 32c00da105Sdanielk1977 struct TableLock { 33d698bc15Sdrh int iDb; /* The database containing the table to be locked */ 34abc38158Sdrh Pgno iTab; /* The root page of the table to be locked */ 35d698bc15Sdrh u8 isWriteLock; /* True for write lock. False for a read lock */ 36e0a04a36Sdrh const char *zLockName; /* Name of the table */ 37c00da105Sdanielk1977 }; 38c00da105Sdanielk1977 39c00da105Sdanielk1977 /* 40d698bc15Sdrh ** Record the fact that we want to lock a table at run-time. 41c00da105Sdanielk1977 ** 42d698bc15Sdrh ** The table to be locked has root page iTab and is found in database iDb. 43d698bc15Sdrh ** A read or a write lock can be taken depending on isWritelock. 44d698bc15Sdrh ** 45d698bc15Sdrh ** This routine just records the fact that the lock is desired. The 46d698bc15Sdrh ** code to make the lock occur is generated by a later call to 47d698bc15Sdrh ** codeTableLocks() which occurs during sqlite3FinishCoding(). 48c00da105Sdanielk1977 */ 499430506dSdrh static SQLITE_NOINLINE void lockTable( 50d698bc15Sdrh Parse *pParse, /* Parsing context */ 51d698bc15Sdrh int iDb, /* Index of the database containing the table to lock */ 52abc38158Sdrh Pgno iTab, /* Root page number of the table to be locked */ 53d698bc15Sdrh u8 isWriteLock, /* True for a write lock */ 54d698bc15Sdrh const char *zName /* Name of the table to be locked */ 55c00da105Sdanielk1977 ){ 561d8f892aSdrh Parse *pToplevel; 57c00da105Sdanielk1977 int i; 58c00da105Sdanielk1977 int nBytes; 59c00da105Sdanielk1977 TableLock *p; 608af73d41Sdrh assert( iDb>=0 ); 61165921a7Sdan 621d8f892aSdrh pToplevel = sqlite3ParseToplevel(pParse); 6365a7cd16Sdan for(i=0; i<pToplevel->nTableLock; i++){ 6465a7cd16Sdan p = &pToplevel->aTableLock[i]; 65c00da105Sdanielk1977 if( p->iDb==iDb && p->iTab==iTab ){ 66c00da105Sdanielk1977 p->isWriteLock = (p->isWriteLock || isWriteLock); 67c00da105Sdanielk1977 return; 68c00da105Sdanielk1977 } 69c00da105Sdanielk1977 } 70c00da105Sdanielk1977 7165a7cd16Sdan nBytes = sizeof(TableLock) * (pToplevel->nTableLock+1); 7265a7cd16Sdan pToplevel->aTableLock = 7365a7cd16Sdan sqlite3DbReallocOrFree(pToplevel->db, pToplevel->aTableLock, nBytes); 7465a7cd16Sdan if( pToplevel->aTableLock ){ 7565a7cd16Sdan p = &pToplevel->aTableLock[pToplevel->nTableLock++]; 76c00da105Sdanielk1977 p->iDb = iDb; 77c00da105Sdanielk1977 p->iTab = iTab; 78c00da105Sdanielk1977 p->isWriteLock = isWriteLock; 79e0a04a36Sdrh p->zLockName = zName; 80f3a65f7eSdrh }else{ 8165a7cd16Sdan pToplevel->nTableLock = 0; 824a642b60Sdrh sqlite3OomFault(pToplevel->db); 83c00da105Sdanielk1977 } 84c00da105Sdanielk1977 } 859430506dSdrh void sqlite3TableLock( 869430506dSdrh Parse *pParse, /* Parsing context */ 879430506dSdrh int iDb, /* Index of the database containing the table to lock */ 889430506dSdrh Pgno iTab, /* Root page number of the table to be locked */ 899430506dSdrh u8 isWriteLock, /* True for a write lock */ 909430506dSdrh const char *zName /* Name of the table to be locked */ 919430506dSdrh ){ 929430506dSdrh if( iDb==1 ) return; 939430506dSdrh if( !sqlite3BtreeSharable(pParse->db->aDb[iDb].pBt) ) return; 949430506dSdrh lockTable(pParse, iDb, iTab, isWriteLock, zName); 959430506dSdrh } 96c00da105Sdanielk1977 97c00da105Sdanielk1977 /* 98c00da105Sdanielk1977 ** Code an OP_TableLock instruction for each table locked by the 99c00da105Sdanielk1977 ** statement (configured by calls to sqlite3TableLock()). 100c00da105Sdanielk1977 */ 101c00da105Sdanielk1977 static void codeTableLocks(Parse *pParse){ 102c00da105Sdanielk1977 int i; 103f0b41745Sdrh Vdbe *pVdbe = pParse->pVdbe; 104289a0c84Sdrh assert( pVdbe!=0 ); 105c00da105Sdanielk1977 106c00da105Sdanielk1977 for(i=0; i<pParse->nTableLock; i++){ 107c00da105Sdanielk1977 TableLock *p = &pParse->aTableLock[i]; 108c00da105Sdanielk1977 int p1 = p->iDb; 1096a9ad3daSdrh sqlite3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, p->isWriteLock, 110e0a04a36Sdrh p->zLockName, P4_STATIC); 111c00da105Sdanielk1977 } 112c00da105Sdanielk1977 } 113c00da105Sdanielk1977 #else 114c00da105Sdanielk1977 #define codeTableLocks(x) 115c00da105Sdanielk1977 #endif 116c00da105Sdanielk1977 117e0bc4048Sdrh /* 118a7ab6d81Sdrh ** Return TRUE if the given yDbMask object is empty - if it contains no 119a7ab6d81Sdrh ** 1 bits. This routine is used by the DbMaskAllZero() and DbMaskNotZero() 120a7ab6d81Sdrh ** macros when SQLITE_MAX_ATTACHED is greater than 30. 121a7ab6d81Sdrh */ 122a7ab6d81Sdrh #if SQLITE_MAX_ATTACHED>30 123a7ab6d81Sdrh int sqlite3DbMaskAllZero(yDbMask m){ 124a7ab6d81Sdrh int i; 125a7ab6d81Sdrh for(i=0; i<sizeof(yDbMask); i++) if( m[i] ) return 0; 126a7ab6d81Sdrh return 1; 127a7ab6d81Sdrh } 128a7ab6d81Sdrh #endif 129a7ab6d81Sdrh 130a7ab6d81Sdrh /* 13175897234Sdrh ** This routine is called after a single SQL statement has been 13280242055Sdrh ** parsed and a VDBE program to execute that statement has been 13380242055Sdrh ** prepared. This routine puts the finishing touches on the 13480242055Sdrh ** VDBE program and resets the pParse structure for the next 13580242055Sdrh ** parse. 13675897234Sdrh ** 13775897234Sdrh ** Note that if an error occurred, it might be the case that 13875897234Sdrh ** no VDBE code was generated. 13975897234Sdrh */ 14080242055Sdrh void sqlite3FinishCoding(Parse *pParse){ 1419bb575fdSdrh sqlite3 *db; 14280242055Sdrh Vdbe *v; 143b86ccfb2Sdrh 144f78baafeSdan assert( pParse->pToplevel==0 ); 14517435752Sdrh db = pParse->db; 146205f48e6Sdrh if( pParse->nested ) return; 147d99d2836Sdrh if( db->mallocFailed || pParse->nErr ){ 148d99d2836Sdrh if( pParse->rc==SQLITE_OK ) pParse->rc = SQLITE_ERROR; 149d99d2836Sdrh return; 150d99d2836Sdrh } 15148d0d866Sdanielk1977 15280242055Sdrh /* Begin by generating some termination code at the end of the 15380242055Sdrh ** vdbe program 15480242055Sdrh */ 15502c4aa39Sdrh v = pParse->pVdbe; 15602c4aa39Sdrh if( v==0 ){ 15702c4aa39Sdrh if( db->init.busy ){ 158c8af879eSdrh pParse->rc = SQLITE_DONE; 159c8af879eSdrh return; 160c8af879eSdrh } 16180242055Sdrh v = sqlite3GetVdbe(pParse); 16202c4aa39Sdrh if( v==0 ) pParse->rc = SQLITE_ERROR; 16302c4aa39Sdrh } 164f3677212Sdan assert( !pParse->isMultiWrite 165f3677212Sdan || sqlite3VdbeAssertMayAbort(v, pParse->mayAbort)); 16680242055Sdrh if( v ){ 167381bdaccSdrh if( pParse->bReturning ){ 168381bdaccSdrh Returning *pReturning = pParse->u1.pReturning; 169381bdaccSdrh int addrRewind; 170381bdaccSdrh int i; 171381bdaccSdrh int reg; 172381bdaccSdrh 173381bdaccSdrh addrRewind = 174381bdaccSdrh sqlite3VdbeAddOp1(v, OP_Rewind, pReturning->iRetCur); 1756859d324Sdrh VdbeCoverage(v); 176552562c4Sdrh reg = pReturning->iRetReg; 177381bdaccSdrh for(i=0; i<pReturning->nRetCol; i++){ 178381bdaccSdrh sqlite3VdbeAddOp3(v, OP_Column, pReturning->iRetCur, i, reg+i); 179381bdaccSdrh } 180381bdaccSdrh sqlite3VdbeAddOp2(v, OP_ResultRow, reg, i); 181381bdaccSdrh sqlite3VdbeAddOp2(v, OP_Next, pReturning->iRetCur, addrRewind+1); 1826859d324Sdrh VdbeCoverage(v); 183381bdaccSdrh sqlite3VdbeJumpHere(v, addrRewind); 184381bdaccSdrh } 18566a5167bSdrh sqlite3VdbeAddOp0(v, OP_Halt); 1860e3d7476Sdrh 187b2445d5eSdrh #if SQLITE_USER_AUTHENTICATION 188b2445d5eSdrh if( pParse->nTableLock>0 && db->init.busy==0 ){ 1897883ecfcSdrh sqlite3UserAuthInit(db); 190b2445d5eSdrh if( db->auth.authLevel<UAUTH_User ){ 191b2445d5eSdrh sqlite3ErrorMsg(pParse, "user not authenticated"); 1926ae3ab00Sdrh pParse->rc = SQLITE_AUTH_USER; 193b2445d5eSdrh return; 194b2445d5eSdrh } 195b2445d5eSdrh } 196b2445d5eSdrh #endif 197b2445d5eSdrh 1980e3d7476Sdrh /* The cookie mask contains one bit for each database file open. 1990e3d7476Sdrh ** (Bit 0 is for main, bit 1 is for temp, and so forth.) Bits are 2000e3d7476Sdrh ** set for each database that is used. Generate code to start a 2010e3d7476Sdrh ** transaction on each used database and to verify the schema cookie 2020e3d7476Sdrh ** on each used database. 2030e3d7476Sdrh */ 204a7ab6d81Sdrh if( db->mallocFailed==0 205a7ab6d81Sdrh && (DbMaskNonZero(pParse->cookieMask) || pParse->pConstExpr) 206a7ab6d81Sdrh ){ 207aceb31b1Sdrh int iDb, i; 208aceb31b1Sdrh assert( sqlite3VdbeGetOp(v, 0)->opcode==OP_Init ); 209aceb31b1Sdrh sqlite3VdbeJumpHere(v, 0); 210a7ab6d81Sdrh for(iDb=0; iDb<db->nDb; iDb++){ 2111d96cc60Sdrh Schema *pSchema; 212a7ab6d81Sdrh if( DbMaskTest(pParse->cookieMask, iDb)==0 ) continue; 213fb98264aSdrh sqlite3VdbeUsesBtree(v, iDb); 2141d96cc60Sdrh pSchema = db->aDb[iDb].pSchema; 215b22f7c83Sdrh sqlite3VdbeAddOp4Int(v, 216b22f7c83Sdrh OP_Transaction, /* Opcode */ 217b22f7c83Sdrh iDb, /* P1 */ 218a7ab6d81Sdrh DbMaskTest(pParse->writeMask,iDb), /* P2 */ 2191d96cc60Sdrh pSchema->schema_cookie, /* P3 */ 2201d96cc60Sdrh pSchema->iGeneration /* P4 */ 221b22f7c83Sdrh ); 222b22f7c83Sdrh if( db->init.busy==0 ) sqlite3VdbeChangeP5(v, 1); 223076e0f96Sdan VdbeComment((v, 224076e0f96Sdan "usesStmtJournal=%d", pParse->mayAbort && pParse->isMultiWrite)); 2258a939190Sdrh } 226f9e7dda7Sdanielk1977 #ifndef SQLITE_OMIT_VIRTUALTABLE 2274f3dd150Sdrh for(i=0; i<pParse->nVtabLock; i++){ 228595a523aSdanielk1977 char *vtab = (char *)sqlite3GetVTable(db, pParse->apVtabLock[i]); 22966a5167bSdrh sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB); 230f9e7dda7Sdanielk1977 } 2314f3dd150Sdrh pParse->nVtabLock = 0; 232f9e7dda7Sdanielk1977 #endif 233c00da105Sdanielk1977 234c00da105Sdanielk1977 /* Once all the cookies have been verified and transactions opened, 235c00da105Sdanielk1977 ** obtain the required table-locks. This is a no-op unless the 236c00da105Sdanielk1977 ** shared-cache feature is enabled. 237c00da105Sdanielk1977 */ 238c00da105Sdanielk1977 codeTableLocks(pParse); 2390b9f50d8Sdrh 2400b9f50d8Sdrh /* Initialize any AUTOINCREMENT data structures required. 2410b9f50d8Sdrh */ 2420b9f50d8Sdrh sqlite3AutoincrementBegin(pParse); 2430b9f50d8Sdrh 24489636628Sdrh /* Code constant expressions that where factored out of inner loops. 24589636628Sdrh ** 24689636628Sdrh ** The pConstExpr list might also contain expressions that we simply 24789636628Sdrh ** want to keep around until the Parse object is deleted. Such 24889636628Sdrh ** expressions have iConstExprReg==0. Do not generate code for 24989636628Sdrh ** those expressions, of course. 25089636628Sdrh */ 251f30a969bSdrh if( pParse->pConstExpr ){ 252f30a969bSdrh ExprList *pEL = pParse->pConstExpr; 253aceb31b1Sdrh pParse->okConstFactor = 0; 254f30a969bSdrh for(i=0; i<pEL->nExpr; i++){ 25589636628Sdrh int iReg = pEL->a[i].u.iConstExprReg; 25689636628Sdrh if( iReg>0 ){ 25789636628Sdrh sqlite3ExprCode(pParse, pEL->a[i].pExpr, iReg); 25889636628Sdrh } 259f30a969bSdrh } 260f30a969bSdrh } 261f30a969bSdrh 262381bdaccSdrh if( pParse->bReturning ){ 263381bdaccSdrh Returning *pRet = pParse->u1.pReturning; 264381bdaccSdrh sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pRet->iRetCur, pRet->nRetCol); 265381bdaccSdrh } 266381bdaccSdrh 2670b9f50d8Sdrh /* Finally, jump back to the beginning of the executable code. */ 268076e85f5Sdrh sqlite3VdbeGoto(v, 1); 26980242055Sdrh } 27071c697efSdrh } 27171c697efSdrh 27280242055Sdrh /* Get the VDBE program ready for execution 27380242055Sdrh */ 274126a6e26Sdrh if( v && pParse->nErr==0 && !db->mallocFailed ){ 2753492dd71Sdrh /* A minimum of one cursor is required if autoincrement is used 2763492dd71Sdrh * See ticket [a696379c1f08866] */ 27704ab586bSdrh assert( pParse->pAinc==0 || pParse->nTab>0 ); 278124c0b49Sdrh sqlite3VdbeMakeReady(v, pParse); 279441daf68Sdanielk1977 pParse->rc = SQLITE_DONE; 280e294da02Sdrh }else{ 281483750baSdrh pParse->rc = SQLITE_ERROR; 28275897234Sdrh } 28375897234Sdrh } 28475897234Sdrh 28575897234Sdrh /* 286205f48e6Sdrh ** Run the parser and code generator recursively in order to generate 287205f48e6Sdrh ** code for the SQL statement given onto the end of the pParse context 288205f48e6Sdrh ** currently under construction. When the parser is run recursively 289205f48e6Sdrh ** this way, the final OP_Halt is not appended and other initialization 290205f48e6Sdrh ** and finalization steps are omitted because those are handling by the 291205f48e6Sdrh ** outermost parser. 292205f48e6Sdrh ** 293205f48e6Sdrh ** Not everything is nestable. This facility is designed to permit 294346a70caSdrh ** INSERT, UPDATE, and DELETE operations against the schema table. Use 295f1974846Sdrh ** care if you decide to try to use this routine for some other purposes. 296205f48e6Sdrh */ 297205f48e6Sdrh void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){ 298205f48e6Sdrh va_list ap; 299205f48e6Sdrh char *zSql; 300fb45d8c5Sdrh char *zErrMsg = 0; 301633e6d57Sdrh sqlite3 *db = pParse->db; 302cd9af608Sdrh char saveBuf[PARSE_TAIL_SZ]; 303f1974846Sdrh 304205f48e6Sdrh if( pParse->nErr ) return; 305205f48e6Sdrh assert( pParse->nested<10 ); /* Nesting should only be of limited depth */ 306205f48e6Sdrh va_start(ap, zFormat); 307633e6d57Sdrh zSql = sqlite3VMPrintf(db, zFormat, ap); 308205f48e6Sdrh va_end(ap); 30973c42a13Sdrh if( zSql==0 ){ 310480c572fSdrh /* This can result either from an OOM or because the formatted string 311480c572fSdrh ** exceeds SQLITE_LIMIT_LENGTH. In the latter case, we need to set 312480c572fSdrh ** an error */ 313480c572fSdrh if( !db->mallocFailed ) pParse->rc = SQLITE_TOOBIG; 314a2b6806bSdrh pParse->nErr++; 315480c572fSdrh return; 31673c42a13Sdrh } 317205f48e6Sdrh pParse->nested++; 318cd9af608Sdrh memcpy(saveBuf, PARSE_TAIL(pParse), PARSE_TAIL_SZ); 319cd9af608Sdrh memset(PARSE_TAIL(pParse), 0, PARSE_TAIL_SZ); 320fb45d8c5Sdrh sqlite3RunParser(pParse, zSql, &zErrMsg); 321633e6d57Sdrh sqlite3DbFree(db, zErrMsg); 322633e6d57Sdrh sqlite3DbFree(db, zSql); 323cd9af608Sdrh memcpy(PARSE_TAIL(pParse), saveBuf, PARSE_TAIL_SZ); 324205f48e6Sdrh pParse->nested--; 325205f48e6Sdrh } 326205f48e6Sdrh 327d4530979Sdrh #if SQLITE_USER_AUTHENTICATION 328d4530979Sdrh /* 329d4530979Sdrh ** Return TRUE if zTable is the name of the system table that stores the 330d4530979Sdrh ** list of users and their access credentials. 331d4530979Sdrh */ 332d4530979Sdrh int sqlite3UserAuthTable(const char *zTable){ 333d4530979Sdrh return sqlite3_stricmp(zTable, "sqlite_user")==0; 334d4530979Sdrh } 335d4530979Sdrh #endif 336d4530979Sdrh 337205f48e6Sdrh /* 3388a41449eSdanielk1977 ** Locate the in-memory structure that describes a particular database 3398a41449eSdanielk1977 ** table given the name of that table and (optionally) the name of the 3408a41449eSdanielk1977 ** database containing the table. Return NULL if not found. 341a69d9168Sdrh ** 3428a41449eSdanielk1977 ** If zDatabase is 0, all databases are searched for the table and the 3438a41449eSdanielk1977 ** first matching table is returned. (No checking for duplicate table 3448a41449eSdanielk1977 ** names is done.) The search order is TEMP first, then MAIN, then any 3458a41449eSdanielk1977 ** auxiliary databases added using the ATTACH command. 346f26e09c8Sdrh ** 3474adee20fSdanielk1977 ** See also sqlite3LocateTable(). 34875897234Sdrh */ 3499bb575fdSdrh Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){ 350d24cc427Sdrh Table *p = 0; 351d24cc427Sdrh int i; 3529ca95730Sdrh 3532120608eSdrh /* All mutexes are required for schema access. Make sure we hold them. */ 3542120608eSdrh assert( zDatabase!=0 || sqlite3BtreeHoldsAllMutexes(db) ); 355d4530979Sdrh #if SQLITE_USER_AUTHENTICATION 356d4530979Sdrh /* Only the admin user is allowed to know that the sqlite_user table 357d4530979Sdrh ** exists */ 358e933b83fSdrh if( db->auth.authLevel<UAUTH_Admin && sqlite3UserAuthTable(zName)!=0 ){ 359e933b83fSdrh return 0; 360e933b83fSdrh } 361d4530979Sdrh #endif 362b2eb7e46Sdrh if( zDatabase ){ 363b2eb7e46Sdrh for(i=0; i<db->nDb; i++){ 364b2eb7e46Sdrh if( sqlite3StrICmp(zDatabase, db->aDb[i].zDbSName)==0 ) break; 365d24cc427Sdrh } 366b2eb7e46Sdrh if( i>=db->nDb ){ 367b2eb7e46Sdrh /* No match against the official names. But always match "main" 368b2eb7e46Sdrh ** to schema 0 as a legacy fallback. */ 369b2eb7e46Sdrh if( sqlite3StrICmp(zDatabase,"main")==0 ){ 370b2eb7e46Sdrh i = 0; 371b2eb7e46Sdrh }else{ 372e0a04a36Sdrh return 0; 37375897234Sdrh } 374b2eb7e46Sdrh } 375b2eb7e46Sdrh p = sqlite3HashFind(&db->aDb[i].pSchema->tblHash, zName); 376346a70caSdrh if( p==0 && sqlite3StrNICmp(zName, "sqlite_", 7)==0 ){ 377346a70caSdrh if( i==1 ){ 378a764709bSdrh if( sqlite3StrICmp(zName+7, &ALT_TEMP_SCHEMA_TABLE[7])==0 379a764709bSdrh || sqlite3StrICmp(zName+7, &ALT_SCHEMA_TABLE[7])==0 380a764709bSdrh || sqlite3StrICmp(zName+7, &DFLT_SCHEMA_TABLE[7])==0 381346a70caSdrh ){ 382346a70caSdrh p = sqlite3HashFind(&db->aDb[1].pSchema->tblHash, 383346a70caSdrh DFLT_TEMP_SCHEMA_TABLE); 384346a70caSdrh } 385346a70caSdrh }else{ 386a764709bSdrh if( sqlite3StrICmp(zName+7, &ALT_SCHEMA_TABLE[7])==0 ){ 387346a70caSdrh p = sqlite3HashFind(&db->aDb[i].pSchema->tblHash, 388346a70caSdrh DFLT_SCHEMA_TABLE); 389346a70caSdrh } 390346a70caSdrh } 391b2eb7e46Sdrh } 392b2eb7e46Sdrh }else{ 393b2eb7e46Sdrh /* Match against TEMP first */ 394b2eb7e46Sdrh p = sqlite3HashFind(&db->aDb[1].pSchema->tblHash, zName); 395b2eb7e46Sdrh if( p ) return p; 396b2eb7e46Sdrh /* The main database is second */ 397b2eb7e46Sdrh p = sqlite3HashFind(&db->aDb[0].pSchema->tblHash, zName); 398b2eb7e46Sdrh if( p ) return p; 399b2eb7e46Sdrh /* Attached databases are in order of attachment */ 400b2eb7e46Sdrh for(i=2; i<db->nDb; i++){ 401b2eb7e46Sdrh assert( sqlite3SchemaMutexHeld(db, i, 0) ); 402b2eb7e46Sdrh p = sqlite3HashFind(&db->aDb[i].pSchema->tblHash, zName); 403b2eb7e46Sdrh if( p ) break; 404b2eb7e46Sdrh } 405346a70caSdrh if( p==0 && sqlite3StrNICmp(zName, "sqlite_", 7)==0 ){ 406a764709bSdrh if( sqlite3StrICmp(zName+7, &ALT_SCHEMA_TABLE[7])==0 ){ 407346a70caSdrh p = sqlite3HashFind(&db->aDb[0].pSchema->tblHash, DFLT_SCHEMA_TABLE); 408a764709bSdrh }else if( sqlite3StrICmp(zName+7, &ALT_TEMP_SCHEMA_TABLE[7])==0 ){ 409346a70caSdrh p = sqlite3HashFind(&db->aDb[1].pSchema->tblHash, 410346a70caSdrh DFLT_TEMP_SCHEMA_TABLE); 411346a70caSdrh } 412346a70caSdrh } 413b2eb7e46Sdrh } 414b2eb7e46Sdrh return p; 415b2eb7e46Sdrh } 41675897234Sdrh 41775897234Sdrh /* 4188a41449eSdanielk1977 ** Locate the in-memory structure that describes a particular database 4198a41449eSdanielk1977 ** table given the name of that table and (optionally) the name of the 4208a41449eSdanielk1977 ** database containing the table. Return NULL if not found. Also leave an 4218a41449eSdanielk1977 ** error message in pParse->zErrMsg. 422a69d9168Sdrh ** 4238a41449eSdanielk1977 ** The difference between this routine and sqlite3FindTable() is that this 4248a41449eSdanielk1977 ** routine leaves an error message in pParse->zErrMsg where 4258a41449eSdanielk1977 ** sqlite3FindTable() does not. 426a69d9168Sdrh */ 427ca424114Sdrh Table *sqlite3LocateTable( 428ca424114Sdrh Parse *pParse, /* context in which to report errors */ 4294d249e61Sdrh u32 flags, /* LOCATE_VIEW or LOCATE_NOERR */ 430ca424114Sdrh const char *zName, /* Name of the table we are looking for */ 431ca424114Sdrh const char *zDbase /* Name of the database. Might be NULL */ 432ca424114Sdrh ){ 433a69d9168Sdrh Table *p; 434b2c8559fSdrh sqlite3 *db = pParse->db; 435f26e09c8Sdrh 4368a41449eSdanielk1977 /* Read the database schema. If an error occurs, leave an error message 4378a41449eSdanielk1977 ** and code in pParse and return NULL. */ 438b2c8559fSdrh if( (db->mDbFlags & DBFLAG_SchemaKnownOk)==0 439b2c8559fSdrh && SQLITE_OK!=sqlite3ReadSchema(pParse) 440b2c8559fSdrh ){ 4418a41449eSdanielk1977 return 0; 4428a41449eSdanielk1977 } 4438a41449eSdanielk1977 444b2c8559fSdrh p = sqlite3FindTable(db, zName, zDbase); 445a69d9168Sdrh if( p==0 ){ 446d2975928Sdrh #ifndef SQLITE_OMIT_VIRTUALTABLE 44751be3873Sdrh /* If zName is the not the name of a table in the schema created using 44851be3873Sdrh ** CREATE, then check to see if it is the name of an virtual table that 44951be3873Sdrh ** can be an eponymous virtual table. */ 450bb0eec43Sdan if( pParse->disableVtab==0 && db->init.busy==0 ){ 451b2c8559fSdrh Module *pMod = (Module*)sqlite3HashFind(&db->aModule, zName); 4522fcc1590Sdrh if( pMod==0 && sqlite3_strnicmp(zName, "pragma_", 7)==0 ){ 453b2c8559fSdrh pMod = sqlite3PragmaVtabRegister(db, zName); 4542fcc1590Sdrh } 45551be3873Sdrh if( pMod && sqlite3VtabEponymousTableInit(pParse, pMod) ){ 456bd24e8faSdan testcase( pMod->pEpoTab==0 ); 45751be3873Sdrh return pMod->pEpoTab; 45851be3873Sdrh } 4591ea0443cSdan } 46051be3873Sdrh #endif 4611ea0443cSdan if( flags & LOCATE_NOERR ) return 0; 4621ea0443cSdan pParse->checkSchema = 1; 4631ea0443cSdan }else if( IsVirtual(p) && pParse->disableVtab ){ 4641ea0443cSdan p = 0; 4651ea0443cSdan } 4661ea0443cSdan 4671ea0443cSdan if( p==0 ){ 4681ea0443cSdan const char *zMsg = flags & LOCATE_VIEW ? "no such view" : "no such table"; 4698a41449eSdanielk1977 if( zDbase ){ 470ca424114Sdrh sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName); 471a69d9168Sdrh }else{ 472ca424114Sdrh sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName); 473a69d9168Sdrh } 4741bb89e9cSdrh }else{ 4751bb89e9cSdrh assert( HasRowid(p) || p->iPKey<0 ); 4764d249e61Sdrh } 477fab1d401Sdan 478a69d9168Sdrh return p; 479a69d9168Sdrh } 480a69d9168Sdrh 481a69d9168Sdrh /* 48241fb5cd1Sdan ** Locate the table identified by *p. 48341fb5cd1Sdan ** 48441fb5cd1Sdan ** This is a wrapper around sqlite3LocateTable(). The difference between 48541fb5cd1Sdan ** sqlite3LocateTable() and this function is that this function restricts 48641fb5cd1Sdan ** the search to schema (p->pSchema) if it is not NULL. p->pSchema may be 48741fb5cd1Sdan ** non-NULL if it is part of a view or trigger program definition. See 48841fb5cd1Sdan ** sqlite3FixSrcList() for details. 48941fb5cd1Sdan */ 49041fb5cd1Sdan Table *sqlite3LocateTableItem( 49141fb5cd1Sdan Parse *pParse, 4924d249e61Sdrh u32 flags, 4937601294aSdrh SrcItem *p 49441fb5cd1Sdan ){ 49541fb5cd1Sdan const char *zDb; 496cd1499f4Sdrh assert( p->pSchema==0 || p->zDatabase==0 ); 49741fb5cd1Sdan if( p->pSchema ){ 49841fb5cd1Sdan int iDb = sqlite3SchemaToIndex(pParse->db, p->pSchema); 49969c33826Sdrh zDb = pParse->db->aDb[iDb].zDbSName; 50041fb5cd1Sdan }else{ 50141fb5cd1Sdan zDb = p->zDatabase; 50241fb5cd1Sdan } 5034d249e61Sdrh return sqlite3LocateTable(pParse, flags, p->zName, zDb); 50441fb5cd1Sdan } 50541fb5cd1Sdan 50641fb5cd1Sdan /* 507a69d9168Sdrh ** Locate the in-memory structure that describes 508a69d9168Sdrh ** a particular index given the name of that index 509a69d9168Sdrh ** and the name of the database that contains the index. 510f57b3399Sdrh ** Return NULL if not found. 511f26e09c8Sdrh ** 512f26e09c8Sdrh ** If zDatabase is 0, all databases are searched for the 513f26e09c8Sdrh ** table and the first matching index is returned. (No checking 514f26e09c8Sdrh ** for duplicate index names is done.) The search order is 515f26e09c8Sdrh ** TEMP first, then MAIN, then any auxiliary databases added 516f26e09c8Sdrh ** using the ATTACH command. 51775897234Sdrh */ 5189bb575fdSdrh Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){ 519d24cc427Sdrh Index *p = 0; 520d24cc427Sdrh int i; 5212120608eSdrh /* All mutexes are required for schema access. Make sure we hold them. */ 5222120608eSdrh assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) ); 52353c0f748Sdanielk1977 for(i=OMIT_TEMPDB; i<db->nDb; i++){ 524812d7a21Sdrh int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */ 525e501b89aSdanielk1977 Schema *pSchema = db->aDb[j].pSchema; 5260449171eSdrh assert( pSchema ); 527465c2b89Sdan if( zDb && sqlite3DbIsNamed(db, j, zDb)==0 ) continue; 5282120608eSdrh assert( sqlite3SchemaMutexHeld(db, j, 0) ); 529acbcb7e0Sdrh p = sqlite3HashFind(&pSchema->idxHash, zName); 530d24cc427Sdrh if( p ) break; 531d24cc427Sdrh } 53274e24cd0Sdrh return p; 53375897234Sdrh } 53475897234Sdrh 53575897234Sdrh /* 536956bc92cSdrh ** Reclaim the memory used by an index 537956bc92cSdrh */ 538cf8f2895Sdan void sqlite3FreeIndex(sqlite3 *db, Index *p){ 53992aa5eacSdrh #ifndef SQLITE_OMIT_ANALYZE 540d46def77Sdan sqlite3DeleteIndexSamples(db, p); 54192aa5eacSdrh #endif 5421fe0537eSdrh sqlite3ExprDelete(db, p->pPartIdxWhere); 5431f9ca2c8Sdrh sqlite3ExprListDelete(db, p->aColExpr); 544633e6d57Sdrh sqlite3DbFree(db, p->zColAff); 5455905f86bSmistachkin if( p->isResized ) sqlite3DbFree(db, (void *)p->azColl); 546175b8f06Sdrh #ifdef SQLITE_ENABLE_STAT4 54775b170b1Sdrh sqlite3_free(p->aiRowEst); 54875b170b1Sdrh #endif 549633e6d57Sdrh sqlite3DbFree(db, p); 550956bc92cSdrh } 551956bc92cSdrh 552956bc92cSdrh /* 553c96d8530Sdrh ** For the index called zIdxName which is found in the database iDb, 554c96d8530Sdrh ** unlike that index from its Table then remove the index from 555c96d8530Sdrh ** the index hash table and free all memory structures associated 556c96d8530Sdrh ** with the index. 5575e00f6c7Sdrh */ 5589bb575fdSdrh void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){ 559956bc92cSdrh Index *pIndex; 5602120608eSdrh Hash *pHash; 561956bc92cSdrh 5622120608eSdrh assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); 5632120608eSdrh pHash = &db->aDb[iDb].pSchema->idxHash; 564acbcb7e0Sdrh pIndex = sqlite3HashInsert(pHash, zIdxName, 0); 56522645842Sdrh if( ALWAYS(pIndex) ){ 5665e00f6c7Sdrh if( pIndex->pTable->pIndex==pIndex ){ 5675e00f6c7Sdrh pIndex->pTable->pIndex = pIndex->pNext; 5685e00f6c7Sdrh }else{ 5695e00f6c7Sdrh Index *p; 5700449171eSdrh /* Justification of ALWAYS(); The index must be on the list of 5710449171eSdrh ** indices. */ 5720449171eSdrh p = pIndex->pTable->pIndex; 5730449171eSdrh while( ALWAYS(p) && p->pNext!=pIndex ){ p = p->pNext; } 5740449171eSdrh if( ALWAYS(p && p->pNext==pIndex) ){ 5755e00f6c7Sdrh p->pNext = pIndex->pNext; 5765e00f6c7Sdrh } 5775e00f6c7Sdrh } 578cf8f2895Sdan sqlite3FreeIndex(db, pIndex); 579956bc92cSdrh } 5808257aa8dSdrh db->mDbFlags |= DBFLAG_SchemaChange; 5815e00f6c7Sdrh } 5825e00f6c7Sdrh 5835e00f6c7Sdrh /* 58481028a45Sdrh ** Look through the list of open database files in db->aDb[] and if 58581028a45Sdrh ** any have been closed, remove them from the list. Reallocate the 58681028a45Sdrh ** db->aDb[] structure to a smaller size, if possible. 5871c2d8414Sdrh ** 58881028a45Sdrh ** Entry 0 (the "main" database) and entry 1 (the "temp" database) 58981028a45Sdrh ** are never candidates for being collapsed. 59074e24cd0Sdrh */ 59181028a45Sdrh void sqlite3CollapseDatabaseArray(sqlite3 *db){ 5921c2d8414Sdrh int i, j; 5931c2d8414Sdrh for(i=j=2; i<db->nDb; i++){ 5944d189ca4Sdrh struct Db *pDb = &db->aDb[i]; 5954d189ca4Sdrh if( pDb->pBt==0 ){ 59669c33826Sdrh sqlite3DbFree(db, pDb->zDbSName); 59769c33826Sdrh pDb->zDbSName = 0; 5981c2d8414Sdrh continue; 5991c2d8414Sdrh } 6001c2d8414Sdrh if( j<i ){ 6018bf8dc92Sdrh db->aDb[j] = db->aDb[i]; 6021c2d8414Sdrh } 6038bf8dc92Sdrh j++; 6041c2d8414Sdrh } 6051c2d8414Sdrh db->nDb = j; 6061c2d8414Sdrh if( db->nDb<=2 && db->aDb!=db->aDbStatic ){ 6071c2d8414Sdrh memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0])); 608633e6d57Sdrh sqlite3DbFree(db, db->aDb); 6091c2d8414Sdrh db->aDb = db->aDbStatic; 6101c2d8414Sdrh } 611e0bc4048Sdrh } 612e0bc4048Sdrh 613e0bc4048Sdrh /* 61481028a45Sdrh ** Reset the schema for the database at index iDb. Also reset the 615dc6b41edSdrh ** TEMP schema. The reset is deferred if db->nSchemaLock is not zero. 616dc6b41edSdrh ** Deferred resets may be run by calling with iDb<0. 61781028a45Sdrh */ 61881028a45Sdrh void sqlite3ResetOneSchema(sqlite3 *db, int iDb){ 619dc6b41edSdrh int i; 62081028a45Sdrh assert( iDb<db->nDb ); 62181028a45Sdrh 622dc6b41edSdrh if( iDb>=0 ){ 62381028a45Sdrh assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); 624dc6b41edSdrh DbSetProperty(db, iDb, DB_ResetWanted); 625dc6b41edSdrh DbSetProperty(db, 1, DB_ResetWanted); 626b2c8559fSdrh db->mDbFlags &= ~DBFLAG_SchemaKnownOk; 62781028a45Sdrh } 628dc6b41edSdrh 629dc6b41edSdrh if( db->nSchemaLock==0 ){ 630dc6b41edSdrh for(i=0; i<db->nDb; i++){ 631dc6b41edSdrh if( DbHasProperty(db, i, DB_ResetWanted) ){ 632dc6b41edSdrh sqlite3SchemaClear(db->aDb[i].pSchema); 633dc6b41edSdrh } 634dc6b41edSdrh } 635dc6b41edSdrh } 63681028a45Sdrh } 63781028a45Sdrh 63881028a45Sdrh /* 63981028a45Sdrh ** Erase all schema information from all attached databases (including 64081028a45Sdrh ** "main" and "temp") for a single database connection. 64181028a45Sdrh */ 64281028a45Sdrh void sqlite3ResetAllSchemasOfConnection(sqlite3 *db){ 64381028a45Sdrh int i; 64481028a45Sdrh sqlite3BtreeEnterAll(db); 64581028a45Sdrh for(i=0; i<db->nDb; i++){ 64681028a45Sdrh Db *pDb = &db->aDb[i]; 64781028a45Sdrh if( pDb->pSchema ){ 64863e50b9eSdan if( db->nSchemaLock==0 ){ 64981028a45Sdrh sqlite3SchemaClear(pDb->pSchema); 65063e50b9eSdan }else{ 65163e50b9eSdan DbSetProperty(db, i, DB_ResetWanted); 65263e50b9eSdan } 65381028a45Sdrh } 65481028a45Sdrh } 655b2c8559fSdrh db->mDbFlags &= ~(DBFLAG_SchemaChange|DBFLAG_SchemaKnownOk); 65681028a45Sdrh sqlite3VtabUnlockList(db); 65781028a45Sdrh sqlite3BtreeLeaveAll(db); 65863e50b9eSdan if( db->nSchemaLock==0 ){ 65981028a45Sdrh sqlite3CollapseDatabaseArray(db); 66081028a45Sdrh } 66163e50b9eSdan } 66281028a45Sdrh 66381028a45Sdrh /* 664e0bc4048Sdrh ** This routine is called when a commit occurs. 665e0bc4048Sdrh */ 6669bb575fdSdrh void sqlite3CommitInternalChanges(sqlite3 *db){ 6678257aa8dSdrh db->mDbFlags &= ~DBFLAG_SchemaChange; 66874e24cd0Sdrh } 66974e24cd0Sdrh 67074e24cd0Sdrh /* 671d46def77Sdan ** Delete memory allocated for the column names of a table or view (the 672d46def77Sdan ** Table.aCol[] array). 673956bc92cSdrh */ 67451be3873Sdrh void sqlite3DeleteColumnNames(sqlite3 *db, Table *pTable){ 675956bc92cSdrh int i; 676956bc92cSdrh Column *pCol; 677956bc92cSdrh assert( pTable!=0 ); 678dd5b2fa5Sdrh if( (pCol = pTable->aCol)!=0 ){ 679dd5b2fa5Sdrh for(i=0; i<pTable->nCol; i++, pCol++){ 680d44390c8Sdrh assert( pCol->zName==0 || pCol->hName==sqlite3StrIHash(pCol->zName) ); 681633e6d57Sdrh sqlite3DbFree(db, pCol->zName); 682633e6d57Sdrh sqlite3ExprDelete(db, pCol->pDflt); 683633e6d57Sdrh sqlite3DbFree(db, pCol->zColl); 684956bc92cSdrh } 685633e6d57Sdrh sqlite3DbFree(db, pTable->aCol); 686dd5b2fa5Sdrh } 687956bc92cSdrh } 688956bc92cSdrh 689956bc92cSdrh /* 69075897234Sdrh ** Remove the memory data structures associated with the given 691967e8b73Sdrh ** Table. No changes are made to disk by this routine. 69275897234Sdrh ** 69375897234Sdrh ** This routine just deletes the data structure. It does not unlink 694e61922a6Sdrh ** the table data structure from the hash table. But it does destroy 695c2eef3b3Sdrh ** memory structures of the indices and foreign keys associated with 696c2eef3b3Sdrh ** the table. 69729ddd3acSdrh ** 69829ddd3acSdrh ** The db parameter is optional. It is needed if the Table object 69929ddd3acSdrh ** contains lookaside memory. (Table objects in the schema do not use 70029ddd3acSdrh ** lookaside memory, but some ephemeral Table objects do.) Or the 70129ddd3acSdrh ** db parameter can be used with db->pnBytesFreed to measure the memory 70229ddd3acSdrh ** used by the Table object. 70375897234Sdrh */ 704e8da01c1Sdrh static void SQLITE_NOINLINE deleteTable(sqlite3 *db, Table *pTable){ 70575897234Sdrh Index *pIndex, *pNext; 706c2eef3b3Sdrh 70752fb8e19Sdrh #ifdef SQLITE_DEBUG 70829ddd3acSdrh /* Record the number of outstanding lookaside allocations in schema Tables 70929ddd3acSdrh ** prior to doing any free() operations. Since schema Tables do not use 710bedf84c1Sdan ** lookaside, this number should not change. 711bedf84c1Sdan ** 712bedf84c1Sdan ** If malloc has already failed, it may be that it failed while allocating 713bedf84c1Sdan ** a Table object that was going to be marked ephemeral. So do not check 714bedf84c1Sdan ** that no lookaside memory is used in this case either. */ 71552fb8e19Sdrh int nLookaside = 0; 716bedf84c1Sdan if( db && !db->mallocFailed && (pTable->tabFlags & TF_Ephemeral)==0 ){ 71752fb8e19Sdrh nLookaside = sqlite3LookasideUsed(db, 0); 71852fb8e19Sdrh } 71952fb8e19Sdrh #endif 72029ddd3acSdrh 721d46def77Sdan /* Delete all indices associated with this table. */ 722c2eef3b3Sdrh for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){ 723c2eef3b3Sdrh pNext = pIndex->pNext; 72462340f84Sdrh assert( pIndex->pSchema==pTable->pSchema 72562340f84Sdrh || (IsVirtual(pTable) && pIndex->idxType!=SQLITE_IDXTYPE_APPDEF) ); 726273bfe9fSdrh if( (db==0 || db->pnBytesFreed==0) && !IsVirtual(pTable) ){ 727d46def77Sdan char *zName = pIndex->zName; 728d46def77Sdan TESTONLY ( Index *pOld = ) sqlite3HashInsert( 729acbcb7e0Sdrh &pIndex->pSchema->idxHash, zName, 0 730d46def77Sdan ); 7312120608eSdrh assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) ); 732d46def77Sdan assert( pOld==pIndex || pOld==0 ); 733d46def77Sdan } 734cf8f2895Sdan sqlite3FreeIndex(db, pIndex); 735c2eef3b3Sdrh } 736c2eef3b3Sdrh 7371da40a38Sdan /* Delete any foreign keys attached to this table. */ 7381feeaed2Sdan sqlite3FkDelete(db, pTable); 739c2eef3b3Sdrh 740c2eef3b3Sdrh /* Delete the Table structure itself. 741c2eef3b3Sdrh */ 74251be3873Sdrh sqlite3DeleteColumnNames(db, pTable); 743633e6d57Sdrh sqlite3DbFree(db, pTable->zName); 744633e6d57Sdrh sqlite3DbFree(db, pTable->zColAff); 745633e6d57Sdrh sqlite3SelectDelete(db, pTable->pSelect); 7462938f924Sdrh sqlite3ExprListDelete(db, pTable->pCheck); 747078e4084Sdrh #ifndef SQLITE_OMIT_VIRTUALTABLE 7481feeaed2Sdan sqlite3VtabClear(db, pTable); 749078e4084Sdrh #endif 750633e6d57Sdrh sqlite3DbFree(db, pTable); 75129ddd3acSdrh 75229ddd3acSdrh /* Verify that no lookaside memory was used by schema tables */ 75352fb8e19Sdrh assert( nLookaside==0 || nLookaside==sqlite3LookasideUsed(db,0) ); 75475897234Sdrh } 755e8da01c1Sdrh void sqlite3DeleteTable(sqlite3 *db, Table *pTable){ 756e8da01c1Sdrh /* Do not delete the table until the reference count reaches zero. */ 757e8da01c1Sdrh if( !pTable ) return; 75879df7782Sdrh if( ((!db || db->pnBytesFreed==0) && (--pTable->nTabRef)>0) ) return; 759e8da01c1Sdrh deleteTable(db, pTable); 760e8da01c1Sdrh } 761e8da01c1Sdrh 76275897234Sdrh 76375897234Sdrh /* 7645edc3124Sdrh ** Unlink the given table from the hash tables and the delete the 765c2eef3b3Sdrh ** table structure with all its indices and foreign keys. 7665edc3124Sdrh */ 7679bb575fdSdrh void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){ 768956bc92cSdrh Table *p; 769956bc92cSdrh Db *pDb; 770956bc92cSdrh 771d229ca94Sdrh assert( db!=0 ); 772956bc92cSdrh assert( iDb>=0 && iDb<db->nDb ); 773972a2311Sdrh assert( zTabName ); 7742120608eSdrh assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); 775972a2311Sdrh testcase( zTabName[0]==0 ); /* Zero-length table names are allowed */ 776956bc92cSdrh pDb = &db->aDb[iDb]; 777acbcb7e0Sdrh p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName, 0); 7781feeaed2Sdan sqlite3DeleteTable(db, p); 7798257aa8dSdrh db->mDbFlags |= DBFLAG_SchemaChange; 780956bc92cSdrh } 78174e24cd0Sdrh 78274e24cd0Sdrh /* 783a99db3b6Sdrh ** Given a token, return a string that consists of the text of that 78424fb627aSdrh ** token. Space to hold the returned string 785a99db3b6Sdrh ** is obtained from sqliteMalloc() and must be freed by the calling 786a99db3b6Sdrh ** function. 78775897234Sdrh ** 78824fb627aSdrh ** Any quotation marks (ex: "name", 'name', [name], or `name`) that 78924fb627aSdrh ** surround the body of the token are removed. 79024fb627aSdrh ** 791c96d8530Sdrh ** Tokens are often just pointers into the original SQL text and so 792a99db3b6Sdrh ** are not \000 terminated and are not persistent. The returned string 793a99db3b6Sdrh ** is \000 terminated and is persistent. 79475897234Sdrh */ 79517435752Sdrh char *sqlite3NameFromToken(sqlite3 *db, Token *pName){ 796a99db3b6Sdrh char *zName; 797a99db3b6Sdrh if( pName ){ 79817435752Sdrh zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n); 799b7916a78Sdrh sqlite3Dequote(zName); 800a99db3b6Sdrh }else{ 801a99db3b6Sdrh zName = 0; 802a99db3b6Sdrh } 80375897234Sdrh return zName; 80475897234Sdrh } 80575897234Sdrh 80675897234Sdrh /* 8071e32bed3Sdrh ** Open the sqlite_schema table stored in database number iDb for 808cbb18d22Sdanielk1977 ** writing. The table is opened using cursor 0. 809e0bc4048Sdrh */ 810346a70caSdrh void sqlite3OpenSchemaTable(Parse *p, int iDb){ 811c00da105Sdanielk1977 Vdbe *v = sqlite3GetVdbe(p); 812346a70caSdrh sqlite3TableLock(p, iDb, SCHEMA_ROOT, 1, DFLT_SCHEMA_TABLE); 813346a70caSdrh sqlite3VdbeAddOp4Int(v, OP_OpenWrite, 0, SCHEMA_ROOT, iDb, 5); 8146ab3a2ecSdanielk1977 if( p->nTab==0 ){ 8156ab3a2ecSdanielk1977 p->nTab = 1; 8166ab3a2ecSdanielk1977 } 817e0bc4048Sdrh } 818e0bc4048Sdrh 819e0bc4048Sdrh /* 8200410302eSdanielk1977 ** Parameter zName points to a nul-terminated buffer containing the name 8210410302eSdanielk1977 ** of a database ("main", "temp" or the name of an attached db). This 8220410302eSdanielk1977 ** function returns the index of the named database in db->aDb[], or 8230410302eSdanielk1977 ** -1 if the named db cannot be found. 824cbb18d22Sdanielk1977 */ 8250410302eSdanielk1977 int sqlite3FindDbName(sqlite3 *db, const char *zName){ 826576ec6b3Sdanielk1977 int i = -1; /* Database number */ 82773c42a13Sdrh if( zName ){ 8280410302eSdanielk1977 Db *pDb; 829576ec6b3Sdanielk1977 for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){ 8302951809eSdrh if( 0==sqlite3_stricmp(pDb->zDbSName, zName) ) break; 8312951809eSdrh /* "main" is always an acceptable alias for the primary database 8322951809eSdrh ** even if it has been renamed using SQLITE_DBCONFIG_MAINDBNAME. */ 8332951809eSdrh if( i==0 && 0==sqlite3_stricmp("main", zName) ) break; 834576ec6b3Sdanielk1977 } 835576ec6b3Sdanielk1977 } 836cbb18d22Sdanielk1977 return i; 837cbb18d22Sdanielk1977 } 838cbb18d22Sdanielk1977 8390410302eSdanielk1977 /* 8400410302eSdanielk1977 ** The token *pName contains the name of a database (either "main" or 8410410302eSdanielk1977 ** "temp" or the name of an attached db). This routine returns the 8420410302eSdanielk1977 ** index of the named database in db->aDb[], or -1 if the named db 8430410302eSdanielk1977 ** does not exist. 8440410302eSdanielk1977 */ 8450410302eSdanielk1977 int sqlite3FindDb(sqlite3 *db, Token *pName){ 8460410302eSdanielk1977 int i; /* Database number */ 8470410302eSdanielk1977 char *zName; /* Name we are searching for */ 8480410302eSdanielk1977 zName = sqlite3NameFromToken(db, pName); 8490410302eSdanielk1977 i = sqlite3FindDbName(db, zName); 8500410302eSdanielk1977 sqlite3DbFree(db, zName); 8510410302eSdanielk1977 return i; 8520410302eSdanielk1977 } 8530410302eSdanielk1977 8540e3d7476Sdrh /* The table or view or trigger name is passed to this routine via tokens 8550e3d7476Sdrh ** pName1 and pName2. If the table name was fully qualified, for example: 8560e3d7476Sdrh ** 8570e3d7476Sdrh ** CREATE TABLE xxx.yyy (...); 8580e3d7476Sdrh ** 8590e3d7476Sdrh ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if 8600e3d7476Sdrh ** the table name is not fully qualified, i.e.: 8610e3d7476Sdrh ** 8620e3d7476Sdrh ** CREATE TABLE yyy(...); 8630e3d7476Sdrh ** 8640e3d7476Sdrh ** Then pName1 is set to "yyy" and pName2 is "". 8650e3d7476Sdrh ** 8660e3d7476Sdrh ** This routine sets the *ppUnqual pointer to point at the token (pName1 or 8670e3d7476Sdrh ** pName2) that stores the unqualified table name. The index of the 8680e3d7476Sdrh ** database "xxx" is returned. 8690e3d7476Sdrh */ 870ef2cb63eSdanielk1977 int sqlite3TwoPartName( 8710e3d7476Sdrh Parse *pParse, /* Parsing and code generating context */ 87290f5ecb3Sdrh Token *pName1, /* The "xxx" in the name "xxx.yyy" or "xxx" */ 8730e3d7476Sdrh Token *pName2, /* The "yyy" in the name "xxx.yyy" */ 8740e3d7476Sdrh Token **pUnqual /* Write the unqualified object name here */ 875cbb18d22Sdanielk1977 ){ 8760e3d7476Sdrh int iDb; /* Database holding the object */ 877cbb18d22Sdanielk1977 sqlite3 *db = pParse->db; 878cbb18d22Sdanielk1977 879055f298aSdrh assert( pName2!=0 ); 880055f298aSdrh if( pName2->n>0 ){ 881dcc50b74Sshane if( db->init.busy ) { 882dcc50b74Sshane sqlite3ErrorMsg(pParse, "corrupt database"); 883dcc50b74Sshane return -1; 884dcc50b74Sshane } 885cbb18d22Sdanielk1977 *pUnqual = pName2; 886ff2d5ea4Sdrh iDb = sqlite3FindDb(db, pName1); 887cbb18d22Sdanielk1977 if( iDb<0 ){ 888cbb18d22Sdanielk1977 sqlite3ErrorMsg(pParse, "unknown database %T", pName1); 889cbb18d22Sdanielk1977 return -1; 890cbb18d22Sdanielk1977 } 891cbb18d22Sdanielk1977 }else{ 892d36bcec9Sdrh assert( db->init.iDb==0 || db->init.busy || IN_SPECIAL_PARSE 8938257aa8dSdrh || (db->mDbFlags & DBFLAG_Vacuum)!=0); 894cbb18d22Sdanielk1977 iDb = db->init.iDb; 895cbb18d22Sdanielk1977 *pUnqual = pName1; 896cbb18d22Sdanielk1977 } 897cbb18d22Sdanielk1977 return iDb; 898cbb18d22Sdanielk1977 } 899cbb18d22Sdanielk1977 900cbb18d22Sdanielk1977 /* 9010f1c2eb5Sdrh ** True if PRAGMA writable_schema is ON 9020f1c2eb5Sdrh */ 9030f1c2eb5Sdrh int sqlite3WritableSchema(sqlite3 *db){ 9040f1c2eb5Sdrh testcase( (db->flags&(SQLITE_WriteSchema|SQLITE_Defensive))==0 ); 9050f1c2eb5Sdrh testcase( (db->flags&(SQLITE_WriteSchema|SQLITE_Defensive))== 9060f1c2eb5Sdrh SQLITE_WriteSchema ); 9070f1c2eb5Sdrh testcase( (db->flags&(SQLITE_WriteSchema|SQLITE_Defensive))== 9080f1c2eb5Sdrh SQLITE_Defensive ); 9090f1c2eb5Sdrh testcase( (db->flags&(SQLITE_WriteSchema|SQLITE_Defensive))== 9100f1c2eb5Sdrh (SQLITE_WriteSchema|SQLITE_Defensive) ); 9110f1c2eb5Sdrh return (db->flags&(SQLITE_WriteSchema|SQLITE_Defensive))==SQLITE_WriteSchema; 9120f1c2eb5Sdrh } 9130f1c2eb5Sdrh 9140f1c2eb5Sdrh /* 915d8123366Sdanielk1977 ** This routine is used to check if the UTF-8 string zName is a legal 916d8123366Sdanielk1977 ** unqualified name for a new schema object (table, index, view or 917d8123366Sdanielk1977 ** trigger). All names are legal except those that begin with the string 918d8123366Sdanielk1977 ** "sqlite_" (in upper, lower or mixed case). This portion of the namespace 919d8123366Sdanielk1977 ** is reserved for internal use. 920c5a93d4cSdrh ** 9211e32bed3Sdrh ** When parsing the sqlite_schema table, this routine also checks to 922c5a93d4cSdrh ** make sure the "type", "name", and "tbl_name" columns are consistent 923c5a93d4cSdrh ** with the SQL. 924d8123366Sdanielk1977 */ 925c5a93d4cSdrh int sqlite3CheckObjectName( 926c5a93d4cSdrh Parse *pParse, /* Parsing context */ 927c5a93d4cSdrh const char *zName, /* Name of the object to check */ 928c5a93d4cSdrh const char *zType, /* Type of this object */ 929c5a93d4cSdrh const char *zTblName /* Parent table name for triggers and indexes */ 930c5a93d4cSdrh ){ 931c5a93d4cSdrh sqlite3 *db = pParse->db; 932ca439a49Sdrh if( sqlite3WritableSchema(db) 933ca439a49Sdrh || db->init.imposterTable 934ca439a49Sdrh || !sqlite3Config.bExtraSchemaChecks 935ca439a49Sdrh ){ 936c5a93d4cSdrh /* Skip these error checks for writable_schema=ON */ 937c5a93d4cSdrh return SQLITE_OK; 938c5a93d4cSdrh } 939c5a93d4cSdrh if( db->init.busy ){ 940c5a93d4cSdrh if( sqlite3_stricmp(zType, db->init.azInit[0]) 941c5a93d4cSdrh || sqlite3_stricmp(zName, db->init.azInit[1]) 942c5a93d4cSdrh || sqlite3_stricmp(zTblName, db->init.azInit[2]) 943c5a93d4cSdrh ){ 944c5a93d4cSdrh sqlite3ErrorMsg(pParse, ""); /* corruptSchema() will supply the error */ 945d8123366Sdanielk1977 return SQLITE_ERROR; 946d8123366Sdanielk1977 } 947c5a93d4cSdrh }else{ 948527cbd4aSdrh if( (pParse->nested==0 && 0==sqlite3StrNICmp(zName, "sqlite_", 7)) 949527cbd4aSdrh || (sqlite3ReadOnlyShadowTables(db) && sqlite3ShadowTableName(db, zName)) 950c5a93d4cSdrh ){ 951c5a93d4cSdrh sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", 952c5a93d4cSdrh zName); 953c5a93d4cSdrh return SQLITE_ERROR; 954c5a93d4cSdrh } 955527cbd4aSdrh 956c5a93d4cSdrh } 957d8123366Sdanielk1977 return SQLITE_OK; 958d8123366Sdanielk1977 } 959d8123366Sdanielk1977 960d8123366Sdanielk1977 /* 9614415628aSdrh ** Return the PRIMARY KEY index of a table 9624415628aSdrh */ 9634415628aSdrh Index *sqlite3PrimaryKeyIndex(Table *pTab){ 9644415628aSdrh Index *p; 96548dd1d8eSdrh for(p=pTab->pIndex; p && !IsPrimaryKeyIndex(p); p=p->pNext){} 9664415628aSdrh return p; 9674415628aSdrh } 9684415628aSdrh 9694415628aSdrh /* 970b9bcf7caSdrh ** Convert an table column number into a index column number. That is, 971b9bcf7caSdrh ** for the column iCol in the table (as defined by the CREATE TABLE statement) 972b9bcf7caSdrh ** find the (first) offset of that column in index pIdx. Or return -1 973b9bcf7caSdrh ** if column iCol is not used in index pIdx. 9744415628aSdrh */ 975b9bcf7caSdrh i16 sqlite3TableColumnToIndex(Index *pIdx, i16 iCol){ 9764415628aSdrh int i; 9774415628aSdrh for(i=0; i<pIdx->nColumn; i++){ 9784415628aSdrh if( iCol==pIdx->aiColumn[i] ) return i; 9794415628aSdrh } 9804415628aSdrh return -1; 9814415628aSdrh } 9824415628aSdrh 98381f7b372Sdrh #ifndef SQLITE_OMIT_GENERATED_COLUMNS 984b9bcf7caSdrh /* Convert a storage column number into a table column number. 98581f7b372Sdrh ** 9868e10d74bSdrh ** The storage column number (0,1,2,....) is the index of the value 9878e10d74bSdrh ** as it appears in the record on disk. The true column number 9888e10d74bSdrh ** is the index (0,1,2,...) of the column in the CREATE TABLE statement. 9898e10d74bSdrh ** 990b9bcf7caSdrh ** The storage column number is less than the table column number if 991b9bcf7caSdrh ** and only there are VIRTUAL columns to the left. 9928e10d74bSdrh ** 9938e10d74bSdrh ** If SQLITE_OMIT_GENERATED_COLUMNS, this routine is a no-op macro. 9948e10d74bSdrh */ 995b9bcf7caSdrh i16 sqlite3StorageColumnToTable(Table *pTab, i16 iCol){ 9968e10d74bSdrh if( pTab->tabFlags & TF_HasVirtual ){ 9978e10d74bSdrh int i; 9988e10d74bSdrh for(i=0; i<=iCol; i++){ 9998e10d74bSdrh if( pTab->aCol[i].colFlags & COLFLAG_VIRTUAL ) iCol++; 10008e10d74bSdrh } 10018e10d74bSdrh } 10028e10d74bSdrh return iCol; 10038e10d74bSdrh } 10048e10d74bSdrh #endif 10058e10d74bSdrh 10068e10d74bSdrh #ifndef SQLITE_OMIT_GENERATED_COLUMNS 1007b9bcf7caSdrh /* Convert a table column number into a storage column number. 10088e10d74bSdrh ** 10098e10d74bSdrh ** The storage column number (0,1,2,....) is the index of the value 1010dd6cc9b5Sdrh ** as it appears in the record on disk. Or, if the input column is 1011dd6cc9b5Sdrh ** the N-th virtual column (zero-based) then the storage number is 1012dd6cc9b5Sdrh ** the number of non-virtual columns in the table plus N. 10138e10d74bSdrh ** 1014dd6cc9b5Sdrh ** The true column number is the index (0,1,2,...) of the column in 1015dd6cc9b5Sdrh ** the CREATE TABLE statement. 10168e10d74bSdrh ** 1017dd6cc9b5Sdrh ** If the input column is a VIRTUAL column, then it should not appear 1018dd6cc9b5Sdrh ** in storage. But the value sometimes is cached in registers that 1019dd6cc9b5Sdrh ** follow the range of registers used to construct storage. This 1020dd6cc9b5Sdrh ** avoids computing the same VIRTUAL column multiple times, and provides 1021dd6cc9b5Sdrh ** values for use by OP_Param opcodes in triggers. Hence, if the 1022dd6cc9b5Sdrh ** input column is a VIRTUAL table, put it after all the other columns. 1023dd6cc9b5Sdrh ** 1024dd6cc9b5Sdrh ** In the following, N means "normal column", S means STORED, and 1025dd6cc9b5Sdrh ** V means VIRTUAL. Suppose the CREATE TABLE has columns like this: 1026dd6cc9b5Sdrh ** 1027dd6cc9b5Sdrh ** CREATE TABLE ex(N,S,V,N,S,V,N,S,V); 1028dd6cc9b5Sdrh ** -- 0 1 2 3 4 5 6 7 8 1029dd6cc9b5Sdrh ** 1030dd6cc9b5Sdrh ** Then the mapping from this function is as follows: 1031dd6cc9b5Sdrh ** 1032dd6cc9b5Sdrh ** INPUTS: 0 1 2 3 4 5 6 7 8 1033dd6cc9b5Sdrh ** OUTPUTS: 0 1 6 2 3 7 4 5 8 1034dd6cc9b5Sdrh ** 1035dd6cc9b5Sdrh ** So, in other words, this routine shifts all the virtual columns to 1036dd6cc9b5Sdrh ** the end. 1037dd6cc9b5Sdrh ** 1038dd6cc9b5Sdrh ** If SQLITE_OMIT_GENERATED_COLUMNS then there are no virtual columns and 10397fe2fc0dSdrh ** this routine is a no-op macro. If the pTab does not have any virtual 10407fe2fc0dSdrh ** columns, then this routine is no-op that always return iCol. If iCol 10417fe2fc0dSdrh ** is negative (indicating the ROWID column) then this routine return iCol. 104281f7b372Sdrh */ 1043b9bcf7caSdrh i16 sqlite3TableColumnToStorage(Table *pTab, i16 iCol){ 104481f7b372Sdrh int i; 104581f7b372Sdrh i16 n; 104681f7b372Sdrh assert( iCol<pTab->nCol ); 10477fe2fc0dSdrh if( (pTab->tabFlags & TF_HasVirtual)==0 || iCol<0 ) return iCol; 104881f7b372Sdrh for(i=0, n=0; i<iCol; i++){ 104981f7b372Sdrh if( (pTab->aCol[i].colFlags & COLFLAG_VIRTUAL)==0 ) n++; 105081f7b372Sdrh } 1051dd6cc9b5Sdrh if( pTab->aCol[i].colFlags & COLFLAG_VIRTUAL ){ 1052dd6cc9b5Sdrh /* iCol is a virtual column itself */ 1053dd6cc9b5Sdrh return pTab->nNVCol + i - n; 1054dd6cc9b5Sdrh }else{ 1055dd6cc9b5Sdrh /* iCol is a normal or stored column */ 105681f7b372Sdrh return n; 105781f7b372Sdrh } 1058dd6cc9b5Sdrh } 105981f7b372Sdrh #endif 106081f7b372Sdrh 10614415628aSdrh /* 106231da7be9Sdrh ** Insert a single OP_JournalMode query opcode in order to force the 106331da7be9Sdrh ** prepared statement to return false for sqlite3_stmt_readonly(). This 106431da7be9Sdrh ** is used by CREATE TABLE IF NOT EXISTS and similar if the table already 106531da7be9Sdrh ** exists, so that the prepared statement for CREATE TABLE IF NOT EXISTS 106631da7be9Sdrh ** will return false for sqlite3_stmt_readonly() even if that statement 106731da7be9Sdrh ** is a read-only no-op. 106831da7be9Sdrh */ 106931da7be9Sdrh static void sqlite3ForceNotReadOnly(Parse *pParse){ 107031da7be9Sdrh int iReg = ++pParse->nMem; 107131da7be9Sdrh Vdbe *v = sqlite3GetVdbe(pParse); 107231da7be9Sdrh if( v ){ 107331da7be9Sdrh sqlite3VdbeAddOp3(v, OP_JournalMode, 0, iReg, PAGER_JOURNALMODE_QUERY); 1074a8f249f1Sdan sqlite3VdbeUsesBtree(v, 0); 107531da7be9Sdrh } 107631da7be9Sdrh } 107731da7be9Sdrh 107831da7be9Sdrh /* 107975897234Sdrh ** Begin constructing a new table representation in memory. This is 108075897234Sdrh ** the first of several action routines that get called in response 1081d9b0257aSdrh ** to a CREATE TABLE statement. In particular, this routine is called 108274161705Sdrh ** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp 1083e0bc4048Sdrh ** flag is true if the table should be stored in the auxiliary database 1084e0bc4048Sdrh ** file instead of in the main database file. This is normally the case 1085e0bc4048Sdrh ** when the "TEMP" or "TEMPORARY" keyword occurs in between 1086f57b3399Sdrh ** CREATE and TABLE. 1087d9b0257aSdrh ** 1088f57b3399Sdrh ** The new table record is initialized and put in pParse->pNewTable. 1089f57b3399Sdrh ** As more of the CREATE TABLE statement is parsed, additional action 1090f57b3399Sdrh ** routines will be called to add more information to this record. 10914adee20fSdanielk1977 ** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine 1092f57b3399Sdrh ** is called to complete the construction of the new table record. 109375897234Sdrh */ 10944adee20fSdanielk1977 void sqlite3StartTable( 1095e5f9c644Sdrh Parse *pParse, /* Parser context */ 1096cbb18d22Sdanielk1977 Token *pName1, /* First part of the name of the table or view */ 1097cbb18d22Sdanielk1977 Token *pName2, /* Second part of the name of the table or view */ 1098e5f9c644Sdrh int isTemp, /* True if this is a TEMP table */ 1099faa59554Sdrh int isView, /* True if this is a VIEW */ 1100f1a381e7Sdanielk1977 int isVirtual, /* True if this is a VIRTUAL table */ 1101faa59554Sdrh int noErr /* Do nothing if table already exists */ 1102e5f9c644Sdrh ){ 110375897234Sdrh Table *pTable; 110423bf66d6Sdrh char *zName = 0; /* The name of the new table */ 11059bb575fdSdrh sqlite3 *db = pParse->db; 1106adbca9cfSdrh Vdbe *v; 1107cbb18d22Sdanielk1977 int iDb; /* Database number to create the table in */ 1108cbb18d22Sdanielk1977 Token *pName; /* Unqualified name of the table to create */ 110975897234Sdrh 1110055f298aSdrh if( db->init.busy && db->init.newTnum==1 ){ 11111e32bed3Sdrh /* Special case: Parsing the sqlite_schema or sqlite_temp_schema schema */ 1112055f298aSdrh iDb = db->init.iDb; 1113055f298aSdrh zName = sqlite3DbStrDup(db, SCHEMA_TABLE(iDb)); 1114055f298aSdrh pName = pName1; 1115055f298aSdrh }else{ 1116055f298aSdrh /* The common case */ 1117ef2cb63eSdanielk1977 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName); 1118cbb18d22Sdanielk1977 if( iDb<0 ) return; 111972c5ea32Sdan if( !OMIT_TEMPDB && isTemp && pName2->n>0 && iDb!=1 ){ 112072c5ea32Sdan /* If creating a temp table, the name may not be qualified. Unless 112172c5ea32Sdan ** the database name is "temp" anyway. */ 1122cbb18d22Sdanielk1977 sqlite3ErrorMsg(pParse, "temporary table name must be unqualified"); 1123cbb18d22Sdanielk1977 return; 1124cbb18d22Sdanielk1977 } 112553c0f748Sdanielk1977 if( !OMIT_TEMPDB && isTemp ) iDb = 1; 112617435752Sdrh zName = sqlite3NameFromToken(db, pName); 1127c9461eccSdan if( IN_RENAME_OBJECT ){ 1128c9461eccSdan sqlite3RenameTokenMap(pParse, (void*)zName, pName); 1129c9461eccSdan } 1130055f298aSdrh } 1131055f298aSdrh pParse->sNameToken = *pName; 1132e0048400Sdanielk1977 if( zName==0 ) return; 1133c5a93d4cSdrh if( sqlite3CheckObjectName(pParse, zName, isView?"view":"table", zName) ){ 113423bf66d6Sdrh goto begin_table_error; 1135d8123366Sdanielk1977 } 11361d85d931Sdrh if( db->init.iDb==1 ) isTemp = 1; 1137e5f9c644Sdrh #ifndef SQLITE_OMIT_AUTHORIZATION 1138055f298aSdrh assert( isTemp==0 || isTemp==1 ); 1139055f298aSdrh assert( isView==0 || isView==1 ); 1140e22a334bSdrh { 1141055f298aSdrh static const u8 aCode[] = { 1142055f298aSdrh SQLITE_CREATE_TABLE, 1143055f298aSdrh SQLITE_CREATE_TEMP_TABLE, 1144055f298aSdrh SQLITE_CREATE_VIEW, 1145055f298aSdrh SQLITE_CREATE_TEMP_VIEW 1146055f298aSdrh }; 114769c33826Sdrh char *zDb = db->aDb[iDb].zDbSName; 11484adee20fSdanielk1977 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){ 114923bf66d6Sdrh goto begin_table_error; 1150ed6c8671Sdrh } 1151055f298aSdrh if( !isVirtual && sqlite3AuthCheck(pParse, (int)aCode[isTemp+2*isView], 1152055f298aSdrh zName, 0, zDb) ){ 115323bf66d6Sdrh goto begin_table_error; 1154e5f9c644Sdrh } 1155e5f9c644Sdrh } 1156e5f9c644Sdrh #endif 1157e5f9c644Sdrh 1158f57b3399Sdrh /* Make sure the new table name does not collide with an existing 11593df6b257Sdanielk1977 ** index or table name in the same database. Issue an error message if 11607e6ebfb2Sdanielk1977 ** it does. The exception is if the statement being parsed was passed 11617e6ebfb2Sdanielk1977 ** to an sqlite3_declare_vtab() call. In that case only the column names 11627e6ebfb2Sdanielk1977 ** and types will be used, so there is no need to test for namespace 11637e6ebfb2Sdanielk1977 ** collisions. 1164f57b3399Sdrh */ 1165cf8f2895Sdan if( !IN_SPECIAL_PARSE ){ 116669c33826Sdrh char *zDb = db->aDb[iDb].zDbSName; 11675558a8a6Sdanielk1977 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){ 11685558a8a6Sdanielk1977 goto begin_table_error; 11695558a8a6Sdanielk1977 } 1170a16d1060Sdan pTable = sqlite3FindTable(db, zName, zDb); 11713df6b257Sdanielk1977 if( pTable ){ 1172faa59554Sdrh if( !noErr ){ 11734adee20fSdanielk1977 sqlite3ErrorMsg(pParse, "table %T already exists", pName); 11747687c83dSdan }else{ 117533c59ecaSdrh assert( !db->init.busy || CORRUPT_DB ); 11767687c83dSdan sqlite3CodeVerifySchema(pParse, iDb); 117731da7be9Sdrh sqlite3ForceNotReadOnly(pParse); 1178faa59554Sdrh } 117923bf66d6Sdrh goto begin_table_error; 118075897234Sdrh } 11818a8a0d1dSdrh if( sqlite3FindIndex(db, zName, zDb)!=0 ){ 11824adee20fSdanielk1977 sqlite3ErrorMsg(pParse, "there is already an index named %s", zName); 118323bf66d6Sdrh goto begin_table_error; 118475897234Sdrh } 11857e6ebfb2Sdanielk1977 } 11867e6ebfb2Sdanielk1977 118726783a58Sdanielk1977 pTable = sqlite3DbMallocZero(db, sizeof(Table)); 11886d4abfbeSdrh if( pTable==0 ){ 11894df86af3Sdrh assert( db->mallocFailed ); 1190fad3039cSmistachkin pParse->rc = SQLITE_NOMEM_BKPT; 1191e0048400Sdanielk1977 pParse->nErr++; 119223bf66d6Sdrh goto begin_table_error; 11936d4abfbeSdrh } 119475897234Sdrh pTable->zName = zName; 11954a32431cSdrh pTable->iPKey = -1; 1196da184236Sdanielk1977 pTable->pSchema = db->aDb[iDb].pSchema; 119779df7782Sdrh pTable->nTabRef = 1; 1198d1417ee1Sdrh #ifdef SQLITE_DEFAULT_ROWEST 1199d1417ee1Sdrh pTable->nRowLogEst = sqlite3LogEst(SQLITE_DEFAULT_ROWEST); 1200d1417ee1Sdrh #else 1201cfc9df76Sdan pTable->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) ); 1202d1417ee1Sdrh #endif 1203c4a64facSdrh assert( pParse->pNewTable==0 ); 120475897234Sdrh pParse->pNewTable = pTable; 120517f71934Sdrh 120617f71934Sdrh /* Begin generating the code that will insert the table record into 1207346a70caSdrh ** the schema table. Note in particular that we must go ahead 120817f71934Sdrh ** and allocate the record number for the table entry now. Before any 120917f71934Sdrh ** PRIMARY KEY or UNIQUE keywords are parsed. Those keywords will cause 121017f71934Sdrh ** indices to be created and the table record must come before the 121117f71934Sdrh ** indices. Hence, the record number for the table must be allocated 121217f71934Sdrh ** now. 121317f71934Sdrh */ 12144adee20fSdanielk1977 if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){ 1215728e0f91Sdrh int addr1; 1216e321c29aSdrh int fileFormat; 1217b7654111Sdrh int reg1, reg2, reg3; 12183c03afd3Sdrh /* nullRow[] is an OP_Record encoding of a row containing 5 NULLs */ 12193c03afd3Sdrh static const char nullRow[] = { 6, 0, 0, 0, 0, 0 }; 12200dd5cdaeSdrh sqlite3BeginWriteOperation(pParse, 1, iDb); 1221b17131a0Sdrh 122220b1eaffSdanielk1977 #ifndef SQLITE_OMIT_VIRTUALTABLE 122320b1eaffSdanielk1977 if( isVirtual ){ 122466a5167bSdrh sqlite3VdbeAddOp0(v, OP_VBegin); 122520b1eaffSdanielk1977 } 122620b1eaffSdanielk1977 #endif 122720b1eaffSdanielk1977 122836963fdcSdanielk1977 /* If the file format and encoding in the database have not been set, 122936963fdcSdanielk1977 ** set them now. 1230cbb18d22Sdanielk1977 */ 1231b7654111Sdrh reg1 = pParse->regRowid = ++pParse->nMem; 1232b7654111Sdrh reg2 = pParse->regRoot = ++pParse->nMem; 1233b7654111Sdrh reg3 = ++pParse->nMem; 12340d19f7acSdanielk1977 sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT); 1235fb98264aSdrh sqlite3VdbeUsesBtree(v, iDb); 1236728e0f91Sdrh addr1 = sqlite3VdbeAddOp1(v, OP_If, reg3); VdbeCoverage(v); 1237e321c29aSdrh fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ? 123876fe8032Sdrh 1 : SQLITE_MAX_FILE_FORMAT; 12391861afcdSdrh sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, fileFormat); 12401861afcdSdrh sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, ENC(db)); 1241728e0f91Sdrh sqlite3VdbeJumpHere(v, addr1); 1242d008cfe3Sdanielk1977 12431e32bed3Sdrh /* This just creates a place-holder record in the sqlite_schema table. 12444794f735Sdrh ** The record created does not contain anything yet. It will be replaced 12454794f735Sdrh ** by the real entry in code generated at sqlite3EndTable(). 1246b17131a0Sdrh ** 12470fa991b9Sdrh ** The rowid for the new entry is left in register pParse->regRowid. 12480fa991b9Sdrh ** The root page number of the new table is left in reg pParse->regRoot. 12490fa991b9Sdrh ** The rowid and root page number values are needed by the code that 12500fa991b9Sdrh ** sqlite3EndTable will generate. 12514794f735Sdrh */ 1252f1a381e7Sdanielk1977 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) 1253f1a381e7Sdanielk1977 if( isView || isVirtual ){ 1254b7654111Sdrh sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2); 1255a21c6b6fSdanielk1977 }else 1256a21c6b6fSdanielk1977 #endif 1257a21c6b6fSdanielk1977 { 1258381bdaccSdrh assert( !pParse->bReturning ); 1259381bdaccSdrh pParse->u1.addrCrTab = 12600f3f7664Sdrh sqlite3VdbeAddOp3(v, OP_CreateBtree, iDb, reg2, BTREE_INTKEY); 1261a21c6b6fSdanielk1977 } 1262346a70caSdrh sqlite3OpenSchemaTable(pParse, iDb); 1263b7654111Sdrh sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1); 12643c03afd3Sdrh sqlite3VdbeAddOp4(v, OP_Blob, 6, reg3, 0, nullRow, P4_STATIC); 1265b7654111Sdrh sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1); 1266b7654111Sdrh sqlite3VdbeChangeP5(v, OPFLAG_APPEND); 126766a5167bSdrh sqlite3VdbeAddOp0(v, OP_Close); 12685e00f6c7Sdrh } 126923bf66d6Sdrh 127023bf66d6Sdrh /* Normal (non-error) return. */ 127123bf66d6Sdrh return; 127223bf66d6Sdrh 127323bf66d6Sdrh /* If an error occurs, we jump here */ 127423bf66d6Sdrh begin_table_error: 1275c0495e8cSdrh pParse->checkSchema = 1; 1276633e6d57Sdrh sqlite3DbFree(db, zName); 127723bf66d6Sdrh return; 127875897234Sdrh } 127975897234Sdrh 128003d69a68Sdrh /* Set properties of a table column based on the (magical) 128103d69a68Sdrh ** name of the column. 128203d69a68Sdrh */ 128303d69a68Sdrh #if SQLITE_ENABLE_HIDDEN_COLUMNS 1284e6110505Sdrh void sqlite3ColumnPropertiesFromName(Table *pTab, Column *pCol){ 128503d69a68Sdrh if( sqlite3_strnicmp(pCol->zName, "__hidden__", 10)==0 ){ 128603d69a68Sdrh pCol->colFlags |= COLFLAG_HIDDEN; 12876f6e60ddSdrh if( pTab ) pTab->tabFlags |= TF_HasHidden; 1288ba68f8f3Sdan }else if( pTab && pCol!=pTab->aCol && (pCol[-1].colFlags & COLFLAG_HIDDEN) ){ 1289ba68f8f3Sdan pTab->tabFlags |= TF_OOOHidden; 129003d69a68Sdrh } 129103d69a68Sdrh } 1292e6110505Sdrh #endif 129303d69a68Sdrh 12942053f313Sdrh /* 129528828c55Sdrh ** Name of the special TEMP trigger used to implement RETURNING. The 129628828c55Sdrh ** name begins with "sqlite_" so that it is guaranteed not to collide 129728828c55Sdrh ** with any application-generated triggers. 1298b8352479Sdrh */ 129928828c55Sdrh #define RETURNING_TRIGGER_NAME "sqlite_returning" 1300b8352479Sdrh 1301b8352479Sdrh /* 130228828c55Sdrh ** Clean up the data structures associated with the RETURNING clause. 1303b8352479Sdrh */ 1304b8352479Sdrh static void sqlite3DeleteReturning(sqlite3 *db, Returning *pRet){ 1305b8352479Sdrh Hash *pHash; 1306b8352479Sdrh pHash = &(db->aDb[1].pSchema->trigHash); 130728828c55Sdrh sqlite3HashInsert(pHash, RETURNING_TRIGGER_NAME, 0); 1308b8352479Sdrh sqlite3ExprListDelete(db, pRet->pReturnEL); 1309b8352479Sdrh sqlite3DbFree(db, pRet); 1310b8352479Sdrh } 1311b8352479Sdrh 1312b8352479Sdrh /* 131328828c55Sdrh ** Add the RETURNING clause to the parse currently underway. 131428828c55Sdrh ** 131528828c55Sdrh ** This routine creates a special TEMP trigger that will fire for each row 131628828c55Sdrh ** of the DML statement. That TEMP trigger contains a single SELECT 131728828c55Sdrh ** statement with a result set that is the argument of the RETURNING clause. 131828828c55Sdrh ** The trigger has the Trigger.bReturning flag and an opcode of 131928828c55Sdrh ** TK_RETURNING instead of TK_SELECT, so that the trigger code generator 132028828c55Sdrh ** knows to handle it specially. The TEMP trigger is automatically 132128828c55Sdrh ** removed at the end of the parse. 132228828c55Sdrh ** 132328828c55Sdrh ** When this routine is called, we do not yet know if the RETURNING clause 132428828c55Sdrh ** is attached to a DELETE, INSERT, or UPDATE, so construct it as a 132528828c55Sdrh ** RETURNING trigger instead. It will then be converted into the appropriate 132628828c55Sdrh ** type on the first call to sqlite3TriggersExist(). 13272053f313Sdrh */ 13282053f313Sdrh void sqlite3AddReturning(Parse *pParse, ExprList *pList){ 1329b8352479Sdrh Returning *pRet; 1330b8352479Sdrh Hash *pHash; 1331b8352479Sdrh sqlite3 *db = pParse->db; 1332e1c9a4ebSdrh if( pParse->pNewTrigger ){ 1333e1c9a4ebSdrh sqlite3ErrorMsg(pParse, "cannot use RETURNING in a trigger"); 1334e1c9a4ebSdrh }else{ 1335e1c9a4ebSdrh assert( pParse->bReturning==0 ); 1336e1c9a4ebSdrh } 1337d086aa0aSdrh pParse->bReturning = 1; 1338b8352479Sdrh pRet = sqlite3DbMallocZero(db, sizeof(*pRet)); 1339b8352479Sdrh if( pRet==0 ){ 1340b8352479Sdrh sqlite3ExprListDelete(db, pList); 1341b8352479Sdrh return; 1342b8352479Sdrh } 1343381bdaccSdrh pParse->u1.pReturning = pRet; 1344b8352479Sdrh pRet->pParse = pParse; 1345b8352479Sdrh pRet->pReturnEL = pList; 13462053f313Sdrh sqlite3ParserAddCleanup(pParse, 1347b8352479Sdrh (void(*)(sqlite3*,void*))sqlite3DeleteReturning, pRet); 13486d0053cfSdrh testcase( pParse->earlyCleanup ); 1349cf4108bbSdrh if( db->mallocFailed ) return; 135028828c55Sdrh pRet->retTrig.zName = RETURNING_TRIGGER_NAME; 1351b8352479Sdrh pRet->retTrig.op = TK_RETURNING; 1352b8352479Sdrh pRet->retTrig.tr_tm = TRIGGER_AFTER; 1353b8352479Sdrh pRet->retTrig.bReturning = 1; 1354b8352479Sdrh pRet->retTrig.pSchema = db->aDb[1].pSchema; 1355a4767683Sdrh pRet->retTrig.pTabSchema = db->aDb[1].pSchema; 1356b8352479Sdrh pRet->retTrig.step_list = &pRet->retTStep; 1357dac9a5f7Sdrh pRet->retTStep.op = TK_RETURNING; 1358b8352479Sdrh pRet->retTStep.pTrig = &pRet->retTrig; 1359381bdaccSdrh pRet->retTStep.pExprList = pList; 1360b8352479Sdrh pHash = &(db->aDb[1].pSchema->trigHash); 1361e1c9a4ebSdrh assert( sqlite3HashFind(pHash, RETURNING_TRIGGER_NAME)==0 || pParse->nErr ); 136228828c55Sdrh if( sqlite3HashInsert(pHash, RETURNING_TRIGGER_NAME, &pRet->retTrig) 13630166df0bSdrh ==&pRet->retTrig ){ 13640166df0bSdrh sqlite3OomFault(db); 13650166df0bSdrh } 13662053f313Sdrh } 136703d69a68Sdrh 136875897234Sdrh /* 136975897234Sdrh ** Add a new column to the table currently being constructed. 1370d9b0257aSdrh ** 1371d9b0257aSdrh ** The parser calls this routine once for each column declaration 13724adee20fSdanielk1977 ** in a CREATE TABLE statement. sqlite3StartTable() gets called 1373d9b0257aSdrh ** first to get things going. Then this routine is called for each 1374d9b0257aSdrh ** column. 137575897234Sdrh */ 13762881ab62Sdrh void sqlite3AddColumn(Parse *pParse, Token *pName, Token *pType){ 137775897234Sdrh Table *p; 137897fc3d06Sdrh int i; 1379a99db3b6Sdrh char *z; 138094eaafa9Sdrh char *zType; 1381c9b84a1fSdrh Column *pCol; 1382bb4957f8Sdrh sqlite3 *db = pParse->db; 13833e992d1aSdrh u8 hName; 1384*7b3c514bSdrh Column *aNew; 13853e992d1aSdrh 138675897234Sdrh if( (p = pParse->pNewTable)==0 ) return; 1387bb4957f8Sdrh if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){ 1388e5c941b8Sdrh sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName); 1389e5c941b8Sdrh return; 1390e5c941b8Sdrh } 139194eaafa9Sdrh z = sqlite3DbMallocRaw(db, pName->n + pType->n + 2); 139297fc3d06Sdrh if( z==0 ) return; 1393c9461eccSdan if( IN_RENAME_OBJECT ) sqlite3RenameTokenMap(pParse, (void*)z, pName); 139494eaafa9Sdrh memcpy(z, pName->z, pName->n); 139594eaafa9Sdrh z[pName->n] = 0; 139694eaafa9Sdrh sqlite3Dequote(z); 13973e992d1aSdrh hName = sqlite3StrIHash(z); 139897fc3d06Sdrh for(i=0; i<p->nCol; i++){ 13993e992d1aSdrh if( p->aCol[i].hName==hName && sqlite3StrICmp(z, p->aCol[i].zName)==0 ){ 14004adee20fSdanielk1977 sqlite3ErrorMsg(pParse, "duplicate column name: %s", z); 1401633e6d57Sdrh sqlite3DbFree(db, z); 140297fc3d06Sdrh return; 140397fc3d06Sdrh } 140497fc3d06Sdrh } 1405*7b3c514bSdrh aNew = sqlite3DbRealloc(db,p->aCol,(p->nCol+1)*sizeof(p->aCol[0])); 1406d5d56523Sdanielk1977 if( aNew==0 ){ 1407633e6d57Sdrh sqlite3DbFree(db, z); 1408d5d56523Sdanielk1977 return; 1409d5d56523Sdanielk1977 } 14106d4abfbeSdrh p->aCol = aNew; 1411c9b84a1fSdrh pCol = &p->aCol[p->nCol]; 1412c9b84a1fSdrh memset(pCol, 0, sizeof(p->aCol[0])); 1413c9b84a1fSdrh pCol->zName = z; 14143e992d1aSdrh pCol->hName = hName; 1415ba68f8f3Sdan sqlite3ColumnPropertiesFromName(p, pCol); 1416a37cdde0Sdanielk1977 1417986dde70Sdrh if( pType->n==0 ){ 1418a37cdde0Sdanielk1977 /* If there is no type specified, columns have the default affinity 1419bbade8d1Sdrh ** 'BLOB' with a default size of 4 bytes. */ 142005883a34Sdrh pCol->affinity = SQLITE_AFF_BLOB; 1421fdaac671Sdrh pCol->szEst = 1; 1422bbade8d1Sdrh #ifdef SQLITE_ENABLE_SORTER_REFERENCES 14232e3a5a81Sdan if( 4>=sqlite3GlobalConfig.szSorterRef ){ 14242e3a5a81Sdan pCol->colFlags |= COLFLAG_SORTERREF; 14252e3a5a81Sdan } 1426bbade8d1Sdrh #endif 14272881ab62Sdrh }else{ 1428ddb2b4a3Sdrh zType = z + sqlite3Strlen30(z) + 1; 1429ddb2b4a3Sdrh memcpy(zType, pType->z, pType->n); 1430ddb2b4a3Sdrh zType[pType->n] = 0; 1431a6dddd9bSdrh sqlite3Dequote(zType); 14322e3a5a81Sdan pCol->affinity = sqlite3AffinityType(zType, pCol); 1433d7564865Sdrh pCol->colFlags |= COLFLAG_HASTYPE; 14342881ab62Sdrh } 1435c9b84a1fSdrh p->nCol++; 1436f95909c7Sdrh p->nNVCol++; 1437986dde70Sdrh pParse->constraintName.n = 0; 143875897234Sdrh } 143975897234Sdrh 144075897234Sdrh /* 1441382c0247Sdrh ** This routine is called by the parser while in the middle of 1442382c0247Sdrh ** parsing a CREATE TABLE statement. A "NOT NULL" constraint has 1443382c0247Sdrh ** been seen on a column. This routine sets the notNull flag on 1444382c0247Sdrh ** the column currently under construction. 1445382c0247Sdrh */ 14464adee20fSdanielk1977 void sqlite3AddNotNull(Parse *pParse, int onError){ 1447382c0247Sdrh Table *p; 144826e731ccSdan Column *pCol; 1449c4a64facSdrh p = pParse->pNewTable; 1450c4a64facSdrh if( p==0 || NEVER(p->nCol<1) ) return; 145126e731ccSdan pCol = &p->aCol[p->nCol-1]; 145226e731ccSdan pCol->notNull = (u8)onError; 14538b174f29Sdrh p->tabFlags |= TF_HasNotNull; 145426e731ccSdan 145526e731ccSdan /* Set the uniqNotNull flag on any UNIQUE or PK indexes already created 145626e731ccSdan ** on this column. */ 145726e731ccSdan if( pCol->colFlags & COLFLAG_UNIQUE ){ 145826e731ccSdan Index *pIdx; 145926e731ccSdan for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){ 146026e731ccSdan assert( pIdx->nKeyCol==1 && pIdx->onError!=OE_None ); 146126e731ccSdan if( pIdx->aiColumn[0]==p->nCol-1 ){ 146226e731ccSdan pIdx->uniqNotNull = 1; 146326e731ccSdan } 146426e731ccSdan } 146526e731ccSdan } 1466382c0247Sdrh } 1467382c0247Sdrh 1468382c0247Sdrh /* 146952a83fbbSdanielk1977 ** Scan the column type name zType (length nType) and return the 147052a83fbbSdanielk1977 ** associated affinity type. 1471b3dff964Sdanielk1977 ** 1472b3dff964Sdanielk1977 ** This routine does a case-independent search of zType for the 1473b3dff964Sdanielk1977 ** substrings in the following table. If one of the substrings is 1474b3dff964Sdanielk1977 ** found, the corresponding affinity is returned. If zType contains 1475b3dff964Sdanielk1977 ** more than one of the substrings, entries toward the top of 1476b3dff964Sdanielk1977 ** the table take priority. For example, if zType is 'BLOBINT', 14778a51256cSdrh ** SQLITE_AFF_INTEGER is returned. 1478b3dff964Sdanielk1977 ** 1479b3dff964Sdanielk1977 ** Substring | Affinity 1480b3dff964Sdanielk1977 ** -------------------------------- 1481b3dff964Sdanielk1977 ** 'INT' | SQLITE_AFF_INTEGER 1482b3dff964Sdanielk1977 ** 'CHAR' | SQLITE_AFF_TEXT 1483b3dff964Sdanielk1977 ** 'CLOB' | SQLITE_AFF_TEXT 1484b3dff964Sdanielk1977 ** 'TEXT' | SQLITE_AFF_TEXT 148505883a34Sdrh ** 'BLOB' | SQLITE_AFF_BLOB 14868a51256cSdrh ** 'REAL' | SQLITE_AFF_REAL 14878a51256cSdrh ** 'FLOA' | SQLITE_AFF_REAL 14888a51256cSdrh ** 'DOUB' | SQLITE_AFF_REAL 1489b3dff964Sdanielk1977 ** 1490b3dff964Sdanielk1977 ** If none of the substrings in the above table are found, 1491b3dff964Sdanielk1977 ** SQLITE_AFF_NUMERIC is returned. 149252a83fbbSdanielk1977 */ 14932e3a5a81Sdan char sqlite3AffinityType(const char *zIn, Column *pCol){ 1494b3dff964Sdanielk1977 u32 h = 0; 1495b3dff964Sdanielk1977 char aff = SQLITE_AFF_NUMERIC; 1496d3037a41Sdrh const char *zChar = 0; 149752a83fbbSdanielk1977 14982f1e02e8Sdrh assert( zIn!=0 ); 1499fdaac671Sdrh while( zIn[0] ){ 1500b7916a78Sdrh h = (h<<8) + sqlite3UpperToLower[(*zIn)&0xff]; 1501b3dff964Sdanielk1977 zIn++; 1502201f7168Sdanielk1977 if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){ /* CHAR */ 1503201f7168Sdanielk1977 aff = SQLITE_AFF_TEXT; 1504fdaac671Sdrh zChar = zIn; 1505201f7168Sdanielk1977 }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){ /* CLOB */ 1506201f7168Sdanielk1977 aff = SQLITE_AFF_TEXT; 1507201f7168Sdanielk1977 }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){ /* TEXT */ 1508201f7168Sdanielk1977 aff = SQLITE_AFF_TEXT; 1509201f7168Sdanielk1977 }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b') /* BLOB */ 15108a51256cSdrh && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){ 151105883a34Sdrh aff = SQLITE_AFF_BLOB; 1512d3037a41Sdrh if( zIn[0]=='(' ) zChar = zIn; 15138a51256cSdrh #ifndef SQLITE_OMIT_FLOATING_POINT 15148a51256cSdrh }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l') /* REAL */ 15158a51256cSdrh && aff==SQLITE_AFF_NUMERIC ){ 15168a51256cSdrh aff = SQLITE_AFF_REAL; 15178a51256cSdrh }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a') /* FLOA */ 15188a51256cSdrh && aff==SQLITE_AFF_NUMERIC ){ 15198a51256cSdrh aff = SQLITE_AFF_REAL; 15208a51256cSdrh }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b') /* DOUB */ 15218a51256cSdrh && aff==SQLITE_AFF_NUMERIC ){ 15228a51256cSdrh aff = SQLITE_AFF_REAL; 15238a51256cSdrh #endif 1524201f7168Sdanielk1977 }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){ /* INT */ 15258a51256cSdrh aff = SQLITE_AFF_INTEGER; 1526b3dff964Sdanielk1977 break; 152752a83fbbSdanielk1977 } 152852a83fbbSdanielk1977 } 1529d3037a41Sdrh 15302e3a5a81Sdan /* If pCol is not NULL, store an estimate of the field size. The 1531d3037a41Sdrh ** estimate is scaled so that the size of an integer is 1. */ 15322e3a5a81Sdan if( pCol ){ 15332e3a5a81Sdan int v = 0; /* default size is approx 4 bytes */ 15347ea31ccbSdrh if( aff<SQLITE_AFF_NUMERIC ){ 1535d3037a41Sdrh if( zChar ){ 1536fdaac671Sdrh while( zChar[0] ){ 1537d3037a41Sdrh if( sqlite3Isdigit(zChar[0]) ){ 15382e3a5a81Sdan /* BLOB(k), VARCHAR(k), CHAR(k) -> r=(k/4+1) */ 1539d3037a41Sdrh sqlite3GetInt32(zChar, &v); 1540fdaac671Sdrh break; 1541fdaac671Sdrh } 1542fdaac671Sdrh zChar++; 1543fdaac671Sdrh } 1544fdaac671Sdrh }else{ 15452e3a5a81Sdan v = 16; /* BLOB, TEXT, CLOB -> r=5 (approx 20 bytes)*/ 1546d3037a41Sdrh } 1547fdaac671Sdrh } 1548bbade8d1Sdrh #ifdef SQLITE_ENABLE_SORTER_REFERENCES 15492e3a5a81Sdan if( v>=sqlite3GlobalConfig.szSorterRef ){ 15502e3a5a81Sdan pCol->colFlags |= COLFLAG_SORTERREF; 15512e3a5a81Sdan } 1552bbade8d1Sdrh #endif 15532e3a5a81Sdan v = v/4 + 1; 15542e3a5a81Sdan if( v>255 ) v = 255; 15552e3a5a81Sdan pCol->szEst = v; 1556fdaac671Sdrh } 1557b3dff964Sdanielk1977 return aff; 155852a83fbbSdanielk1977 } 155952a83fbbSdanielk1977 156052a83fbbSdanielk1977 /* 15617977a17fSdanielk1977 ** The expression is the default value for the most recently added column 15627977a17fSdanielk1977 ** of the table currently under construction. 15637977a17fSdanielk1977 ** 15647977a17fSdanielk1977 ** Default value expressions must be constant. Raise an exception if this 15657977a17fSdanielk1977 ** is not the case. 1566d9b0257aSdrh ** 1567d9b0257aSdrh ** This routine is called by the parser while in the middle of 1568d9b0257aSdrh ** parsing a CREATE TABLE statement. 15697020f651Sdrh */ 15701be266baSdrh void sqlite3AddDefaultValue( 15711be266baSdrh Parse *pParse, /* Parsing context */ 15721be266baSdrh Expr *pExpr, /* The parsed expression of the default value */ 15731be266baSdrh const char *zStart, /* Start of the default value text */ 15741be266baSdrh const char *zEnd /* First character past end of defaut value text */ 15751be266baSdrh ){ 15767020f651Sdrh Table *p; 15777977a17fSdanielk1977 Column *pCol; 1578633e6d57Sdrh sqlite3 *db = pParse->db; 1579c4a64facSdrh p = pParse->pNewTable; 1580c4a64facSdrh if( p!=0 ){ 1581014fff20Sdrh int isInit = db->init.busy && db->init.iDb!=1; 15827977a17fSdanielk1977 pCol = &(p->aCol[p->nCol-1]); 1583014fff20Sdrh if( !sqlite3ExprIsConstantOrFunction(pExpr, isInit) ){ 15847977a17fSdanielk1977 sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant", 15857977a17fSdanielk1977 pCol->zName); 15867e7fd73bSdrh #ifndef SQLITE_OMIT_GENERATED_COLUMNS 15877e7fd73bSdrh }else if( pCol->colFlags & COLFLAG_GENERATED ){ 1588ab0992f0Sdrh testcase( pCol->colFlags & COLFLAG_VIRTUAL ); 1589ab0992f0Sdrh testcase( pCol->colFlags & COLFLAG_STORED ); 15907e7fd73bSdrh sqlite3ErrorMsg(pParse, "cannot use DEFAULT on a generated column"); 15917e7fd73bSdrh #endif 15927977a17fSdanielk1977 }else{ 15936ab3a2ecSdanielk1977 /* A copy of pExpr is used instead of the original, as pExpr contains 15941be266baSdrh ** tokens that point to volatile memory. 15956ab3a2ecSdanielk1977 */ 159694fa9c41Sdrh Expr x; 1597633e6d57Sdrh sqlite3ExprDelete(db, pCol->pDflt); 159894fa9c41Sdrh memset(&x, 0, sizeof(x)); 159994fa9c41Sdrh x.op = TK_SPAN; 16009b2e0435Sdrh x.u.zToken = sqlite3DbSpanDup(db, zStart, zEnd); 16011be266baSdrh x.pLeft = pExpr; 160294fa9c41Sdrh x.flags = EP_Skip; 160394fa9c41Sdrh pCol->pDflt = sqlite3ExprDup(db, &x, EXPRDUP_REDUCE); 160494fa9c41Sdrh sqlite3DbFree(db, x.u.zToken); 16057977a17fSdanielk1977 } 160642b9d7c5Sdrh } 16078900a48bSdan if( IN_RENAME_OBJECT ){ 16088900a48bSdan sqlite3RenameExprUnmap(pParse, pExpr); 16098900a48bSdan } 16101be266baSdrh sqlite3ExprDelete(db, pExpr); 16117020f651Sdrh } 16127020f651Sdrh 16137020f651Sdrh /* 1614153110a7Sdrh ** Backwards Compatibility Hack: 1615153110a7Sdrh ** 1616153110a7Sdrh ** Historical versions of SQLite accepted strings as column names in 1617153110a7Sdrh ** indexes and PRIMARY KEY constraints and in UNIQUE constraints. Example: 1618153110a7Sdrh ** 1619153110a7Sdrh ** CREATE TABLE xyz(a,b,c,d,e,PRIMARY KEY('a'),UNIQUE('b','c' COLLATE trim) 1620153110a7Sdrh ** CREATE INDEX abc ON xyz('c','d' DESC,'e' COLLATE nocase DESC); 1621153110a7Sdrh ** 1622153110a7Sdrh ** This is goofy. But to preserve backwards compatibility we continue to 1623153110a7Sdrh ** accept it. This routine does the necessary conversion. It converts 1624153110a7Sdrh ** the expression given in its argument from a TK_STRING into a TK_ID 1625153110a7Sdrh ** if the expression is just a TK_STRING with an optional COLLATE clause. 16266c591364Sdrh ** If the expression is anything other than TK_STRING, the expression is 1627153110a7Sdrh ** unchanged. 1628153110a7Sdrh */ 1629153110a7Sdrh static void sqlite3StringToId(Expr *p){ 1630153110a7Sdrh if( p->op==TK_STRING ){ 1631153110a7Sdrh p->op = TK_ID; 1632153110a7Sdrh }else if( p->op==TK_COLLATE && p->pLeft->op==TK_STRING ){ 1633153110a7Sdrh p->pLeft->op = TK_ID; 1634153110a7Sdrh } 1635153110a7Sdrh } 1636153110a7Sdrh 1637153110a7Sdrh /* 1638f4b1d8dcSdrh ** Tag the given column as being part of the PRIMARY KEY 1639f4b1d8dcSdrh */ 1640f4b1d8dcSdrh static void makeColumnPartOfPrimaryKey(Parse *pParse, Column *pCol){ 1641f4b1d8dcSdrh pCol->colFlags |= COLFLAG_PRIMKEY; 1642f4b1d8dcSdrh #ifndef SQLITE_OMIT_GENERATED_COLUMNS 1643f4b1d8dcSdrh if( pCol->colFlags & COLFLAG_GENERATED ){ 1644f4b1d8dcSdrh testcase( pCol->colFlags & COLFLAG_VIRTUAL ); 1645f4b1d8dcSdrh testcase( pCol->colFlags & COLFLAG_STORED ); 1646f4b1d8dcSdrh sqlite3ErrorMsg(pParse, 1647f4b1d8dcSdrh "generated columns cannot be part of the PRIMARY KEY"); 1648f4b1d8dcSdrh } 1649f4b1d8dcSdrh #endif 1650f4b1d8dcSdrh } 1651f4b1d8dcSdrh 1652f4b1d8dcSdrh /* 16534a32431cSdrh ** Designate the PRIMARY KEY for the table. pList is a list of names 16544a32431cSdrh ** of columns that form the primary key. If pList is NULL, then the 16554a32431cSdrh ** most recently added column of the table is the primary key. 16564a32431cSdrh ** 16574a32431cSdrh ** A table can have at most one primary key. If the table already has 16584a32431cSdrh ** a primary key (and this is the second primary key) then create an 16594a32431cSdrh ** error. 16604a32431cSdrh ** 16614a32431cSdrh ** If the PRIMARY KEY is on a single column whose datatype is INTEGER, 166223bf66d6Sdrh ** then we will try to use that column as the rowid. Set the Table.iPKey 16634a32431cSdrh ** field of the table under construction to be the index of the 16644a32431cSdrh ** INTEGER PRIMARY KEY column. Table.iPKey is set to -1 if there is 16654a32431cSdrh ** no INTEGER PRIMARY KEY. 16664a32431cSdrh ** 16674a32431cSdrh ** If the key is not an INTEGER PRIMARY KEY, then create a unique 16684a32431cSdrh ** index for the key. No index is created for INTEGER PRIMARY KEYs. 16694a32431cSdrh */ 1670205f48e6Sdrh void sqlite3AddPrimaryKey( 1671205f48e6Sdrh Parse *pParse, /* Parsing context */ 1672205f48e6Sdrh ExprList *pList, /* List of field names to be indexed */ 1673205f48e6Sdrh int onError, /* What to do with a uniqueness conflict */ 1674fdd6e85aSdrh int autoInc, /* True if the AUTOINCREMENT keyword is present */ 1675fdd6e85aSdrh int sortOrder /* SQLITE_SO_ASC or SQLITE_SO_DESC */ 1676205f48e6Sdrh ){ 16774a32431cSdrh Table *pTab = pParse->pNewTable; 1678d7564865Sdrh Column *pCol = 0; 167978100cc9Sdrh int iCol = -1, i; 16808ea30bfcSdrh int nTerm; 168162340f84Sdrh if( pTab==0 ) goto primary_key_exit; 16827d10d5a6Sdrh if( pTab->tabFlags & TF_HasPrimaryKey ){ 16834adee20fSdanielk1977 sqlite3ErrorMsg(pParse, 1684f7a9e1acSdrh "table \"%s\" has more than one primary key", pTab->zName); 1685e0194f2bSdrh goto primary_key_exit; 16864a32431cSdrh } 16877d10d5a6Sdrh pTab->tabFlags |= TF_HasPrimaryKey; 16884a32431cSdrh if( pList==0 ){ 16894a32431cSdrh iCol = pTab->nCol - 1; 1690d7564865Sdrh pCol = &pTab->aCol[iCol]; 1691f4b1d8dcSdrh makeColumnPartOfPrimaryKey(pParse, pCol); 16928ea30bfcSdrh nTerm = 1; 169378100cc9Sdrh }else{ 16948ea30bfcSdrh nTerm = pList->nExpr; 16958ea30bfcSdrh for(i=0; i<nTerm; i++){ 1696108aa00aSdrh Expr *pCExpr = sqlite3ExprSkipCollate(pList->a[i].pExpr); 16977d3d9daeSdrh assert( pCExpr!=0 ); 1698153110a7Sdrh sqlite3StringToId(pCExpr); 16997d3d9daeSdrh if( pCExpr->op==TK_ID ){ 1700108aa00aSdrh const char *zCName = pCExpr->u.zToken; 17014a32431cSdrh for(iCol=0; iCol<pTab->nCol; iCol++){ 1702108aa00aSdrh if( sqlite3StrICmp(zCName, pTab->aCol[iCol].zName)==0 ){ 1703d7564865Sdrh pCol = &pTab->aCol[iCol]; 1704f4b1d8dcSdrh makeColumnPartOfPrimaryKey(pParse, pCol); 1705d3d39e93Sdrh break; 1706d3d39e93Sdrh } 17074a32431cSdrh } 17086e4fc2caSdrh } 170978100cc9Sdrh } 1710108aa00aSdrh } 17118ea30bfcSdrh if( nTerm==1 1712d7564865Sdrh && pCol 1713d7564865Sdrh && sqlite3StrICmp(sqlite3ColumnType(pCol,""), "INTEGER")==0 1714bc622bc0Sdrh && sortOrder!=SQLITE_SO_DESC 17158ea30bfcSdrh ){ 1716c9461eccSdan if( IN_RENAME_OBJECT && pList ){ 17172381f6d7Sdan Expr *pCExpr = sqlite3ExprSkipCollate(pList->a[0].pExpr); 17182381f6d7Sdan sqlite3RenameTokenRemap(pParse, &pTab->iPKey, pCExpr); 1719987db767Sdan } 17204a32431cSdrh pTab->iPKey = iCol; 17211bd10f8aSdrh pTab->keyConf = (u8)onError; 17227d10d5a6Sdrh assert( autoInc==0 || autoInc==1 ); 17237d10d5a6Sdrh pTab->tabFlags |= autoInc*TF_Autoincrement; 17246e11892dSdan if( pList ) pParse->iPkSortOrder = pList->a[0].sortFlags; 172534ab941eSdrh (void)sqlite3HasExplicitNulls(pParse, pList); 1726205f48e6Sdrh }else if( autoInc ){ 17274794f735Sdrh #ifndef SQLITE_OMIT_AUTOINCREMENT 1728205f48e6Sdrh sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an " 1729205f48e6Sdrh "INTEGER PRIMARY KEY"); 17304794f735Sdrh #endif 17314a32431cSdrh }else{ 173262340f84Sdrh sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0, 173362340f84Sdrh 0, sortOrder, 0, SQLITE_IDXTYPE_PRIMARYKEY); 1734e0194f2bSdrh pList = 0; 17354a32431cSdrh } 1736e0194f2bSdrh 1737e0194f2bSdrh primary_key_exit: 1738633e6d57Sdrh sqlite3ExprListDelete(pParse->db, pList); 1739e0194f2bSdrh return; 17404a32431cSdrh } 17414a32431cSdrh 17424a32431cSdrh /* 1743ffe07b2dSdrh ** Add a new CHECK constraint to the table currently under construction. 1744ffe07b2dSdrh */ 1745ffe07b2dSdrh void sqlite3AddCheckConstraint( 1746ffe07b2dSdrh Parse *pParse, /* Parsing context */ 174792e21ef0Sdrh Expr *pCheckExpr, /* The check expression */ 174892e21ef0Sdrh const char *zStart, /* Opening "(" */ 174992e21ef0Sdrh const char *zEnd /* Closing ")" */ 1750ffe07b2dSdrh ){ 1751ffe07b2dSdrh #ifndef SQLITE_OMIT_CHECK 1752ffe07b2dSdrh Table *pTab = pParse->pNewTable; 1753c9bbb011Sdrh sqlite3 *db = pParse->db; 1754c9bbb011Sdrh if( pTab && !IN_DECLARE_VTAB 1755c9bbb011Sdrh && !sqlite3BtreeIsReadonly(db->aDb[db->init.iDb].pBt) 1756c9bbb011Sdrh ){ 17572938f924Sdrh pTab->pCheck = sqlite3ExprListAppend(pParse, pTab->pCheck, pCheckExpr); 17582938f924Sdrh if( pParse->constraintName.n ){ 17592938f924Sdrh sqlite3ExprListSetName(pParse, pTab->pCheck, &pParse->constraintName, 1); 176092e21ef0Sdrh }else{ 176192e21ef0Sdrh Token t; 176292e21ef0Sdrh for(zStart++; sqlite3Isspace(zStart[0]); zStart++){} 176392e21ef0Sdrh while( sqlite3Isspace(zEnd[-1]) ){ zEnd--; } 176492e21ef0Sdrh t.z = zStart; 176592e21ef0Sdrh t.n = (int)(zEnd - t.z); 176692e21ef0Sdrh sqlite3ExprListSetName(pParse, pTab->pCheck, &t, 1); 17672938f924Sdrh } 176833e619fcSdrh }else 1769ffe07b2dSdrh #endif 177033e619fcSdrh { 17712938f924Sdrh sqlite3ExprDelete(pParse->db, pCheckExpr); 1772ffe07b2dSdrh } 177333e619fcSdrh } 1774ffe07b2dSdrh 1775ffe07b2dSdrh /* 1776d3d39e93Sdrh ** Set the collation function of the most recently parsed table column 1777d3d39e93Sdrh ** to the CollSeq given. 17788e2ca029Sdrh */ 177939002505Sdanielk1977 void sqlite3AddCollateType(Parse *pParse, Token *pToken){ 17808e2ca029Sdrh Table *p; 17810202b29eSdanielk1977 int i; 178239002505Sdanielk1977 char *zColl; /* Dequoted name of collation sequence */ 1783633e6d57Sdrh sqlite3 *db; 1784a37cdde0Sdanielk1977 1785936a3059Sdan if( (p = pParse->pNewTable)==0 || IN_RENAME_OBJECT ) return; 17860202b29eSdanielk1977 i = p->nCol-1; 1787633e6d57Sdrh db = pParse->db; 1788633e6d57Sdrh zColl = sqlite3NameFromToken(db, pToken); 178939002505Sdanielk1977 if( !zColl ) return; 179039002505Sdanielk1977 1791c4a64facSdrh if( sqlite3LocateCollSeq(pParse, zColl) ){ 1792b3bf556eSdanielk1977 Index *pIdx; 1793fe685c83Sdrh sqlite3DbFree(db, p->aCol[i].zColl); 179439002505Sdanielk1977 p->aCol[i].zColl = zColl; 17950202b29eSdanielk1977 17960202b29eSdanielk1977 /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>", 17970202b29eSdanielk1977 ** then an index may have been created on this column before the 17980202b29eSdanielk1977 ** collation type was added. Correct this if it is the case. 17990202b29eSdanielk1977 */ 18000202b29eSdanielk1977 for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){ 1801bbbdc83bSdrh assert( pIdx->nKeyCol==1 ); 1802b3bf556eSdanielk1977 if( pIdx->aiColumn[0]==i ){ 1803b3bf556eSdanielk1977 pIdx->azColl[0] = p->aCol[i].zColl; 18047cedc8d4Sdanielk1977 } 18057cedc8d4Sdanielk1977 } 180639002505Sdanielk1977 }else{ 1807633e6d57Sdrh sqlite3DbFree(db, zColl); 18087cedc8d4Sdanielk1977 } 18097cedc8d4Sdanielk1977 } 18107cedc8d4Sdanielk1977 181181f7b372Sdrh /* Change the most recently parsed column to be a GENERATED ALWAYS AS 181281f7b372Sdrh ** column. 181381f7b372Sdrh */ 181481f7b372Sdrh void sqlite3AddGenerated(Parse *pParse, Expr *pExpr, Token *pType){ 181581f7b372Sdrh #ifndef SQLITE_OMIT_GENERATED_COLUMNS 181681f7b372Sdrh u8 eType = COLFLAG_VIRTUAL; 181781f7b372Sdrh Table *pTab = pParse->pNewTable; 181881f7b372Sdrh Column *pCol; 1819f68bf5fbSdrh if( pTab==0 ){ 1820f68bf5fbSdrh /* generated column in an CREATE TABLE IF NOT EXISTS that already exists */ 1821f68bf5fbSdrh goto generated_done; 1822f68bf5fbSdrh } 182381f7b372Sdrh pCol = &(pTab->aCol[pTab->nCol-1]); 1824b9bcf7caSdrh if( IN_DECLARE_VTAB ){ 1825b9bcf7caSdrh sqlite3ErrorMsg(pParse, "virtual tables cannot use computed columns"); 1826b9bcf7caSdrh goto generated_done; 1827b9bcf7caSdrh } 182881f7b372Sdrh if( pCol->pDflt ) goto generated_error; 182981f7b372Sdrh if( pType ){ 183081f7b372Sdrh if( pType->n==7 && sqlite3StrNICmp("virtual",pType->z,7)==0 ){ 183181f7b372Sdrh /* no-op */ 183281f7b372Sdrh }else if( pType->n==6 && sqlite3StrNICmp("stored",pType->z,6)==0 ){ 183381f7b372Sdrh eType = COLFLAG_STORED; 183481f7b372Sdrh }else{ 183581f7b372Sdrh goto generated_error; 183681f7b372Sdrh } 183781f7b372Sdrh } 1838f95909c7Sdrh if( eType==COLFLAG_VIRTUAL ) pTab->nNVCol--; 183981f7b372Sdrh pCol->colFlags |= eType; 1840c1431144Sdrh assert( TF_HasVirtual==COLFLAG_VIRTUAL ); 1841c1431144Sdrh assert( TF_HasStored==COLFLAG_STORED ); 1842c1431144Sdrh pTab->tabFlags |= eType; 1843a0e16a22Sdrh if( pCol->colFlags & COLFLAG_PRIMKEY ){ 1844a0e16a22Sdrh makeColumnPartOfPrimaryKey(pParse, pCol); /* For the error message */ 1845a0e16a22Sdrh } 1846b9bcf7caSdrh pCol->pDflt = pExpr; 1847b9bcf7caSdrh pExpr = 0; 184881f7b372Sdrh goto generated_done; 184981f7b372Sdrh 185081f7b372Sdrh generated_error: 18517e7fd73bSdrh sqlite3ErrorMsg(pParse, "error in generated column \"%s\"", 185281f7b372Sdrh pCol->zName); 185381f7b372Sdrh generated_done: 185481f7b372Sdrh sqlite3ExprDelete(pParse->db, pExpr); 185581f7b372Sdrh #else 185681f7b372Sdrh /* Throw and error for the GENERATED ALWAYS AS clause if the 185781f7b372Sdrh ** SQLITE_OMIT_GENERATED_COLUMNS compile-time option is used. */ 18587e7fd73bSdrh sqlite3ErrorMsg(pParse, "generated columns not supported"); 185981f7b372Sdrh sqlite3ExprDelete(pParse->db, pExpr); 186081f7b372Sdrh #endif 186181f7b372Sdrh } 186281f7b372Sdrh 1863466be56bSdanielk1977 /* 18643f7d4e49Sdrh ** Generate code that will increment the schema cookie. 186550e5dadfSdrh ** 186650e5dadfSdrh ** The schema cookie is used to determine when the schema for the 186750e5dadfSdrh ** database changes. After each schema change, the cookie value 186850e5dadfSdrh ** changes. When a process first reads the schema it records the 186950e5dadfSdrh ** cookie. Thereafter, whenever it goes to access the database, 187050e5dadfSdrh ** it checks the cookie to make sure the schema has not changed 187150e5dadfSdrh ** since it was last read. 187250e5dadfSdrh ** 187350e5dadfSdrh ** This plan is not completely bullet-proof. It is possible for 187450e5dadfSdrh ** the schema to change multiple times and for the cookie to be 187550e5dadfSdrh ** set back to prior value. But schema changes are infrequent 187650e5dadfSdrh ** and the probability of hitting the same cookie value is only 187750e5dadfSdrh ** 1 chance in 2^32. So we're safe enough. 187896fdcb40Sdrh ** 187996fdcb40Sdrh ** IMPLEMENTATION-OF: R-34230-56049 SQLite automatically increments 188096fdcb40Sdrh ** the schema-version whenever the schema changes. 188150e5dadfSdrh */ 18829cbf3425Sdrh void sqlite3ChangeCookie(Parse *pParse, int iDb){ 18839cbf3425Sdrh sqlite3 *db = pParse->db; 18849cbf3425Sdrh Vdbe *v = pParse->pVdbe; 18852120608eSdrh assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); 18861861afcdSdrh sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION, 18873517b312Sdrh (int)(1+(unsigned)db->aDb[iDb].pSchema->schema_cookie)); 188850e5dadfSdrh } 188950e5dadfSdrh 189050e5dadfSdrh /* 1891969fa7c1Sdrh ** Measure the number of characters needed to output the given 1892969fa7c1Sdrh ** identifier. The number returned includes any quotes used 1893969fa7c1Sdrh ** but does not include the null terminator. 1894234c39dfSdrh ** 1895234c39dfSdrh ** The estimate is conservative. It might be larger that what is 1896234c39dfSdrh ** really needed. 1897969fa7c1Sdrh */ 1898969fa7c1Sdrh static int identLength(const char *z){ 1899969fa7c1Sdrh int n; 190017f71934Sdrh for(n=0; *z; n++, z++){ 1901234c39dfSdrh if( *z=='"' ){ n++; } 1902969fa7c1Sdrh } 1903234c39dfSdrh return n + 2; 1904969fa7c1Sdrh } 1905969fa7c1Sdrh 1906969fa7c1Sdrh /* 19071b870de6Sdanielk1977 ** The first parameter is a pointer to an output buffer. The second 19081b870de6Sdanielk1977 ** parameter is a pointer to an integer that contains the offset at 19091b870de6Sdanielk1977 ** which to write into the output buffer. This function copies the 19101b870de6Sdanielk1977 ** nul-terminated string pointed to by the third parameter, zSignedIdent, 19111b870de6Sdanielk1977 ** to the specified offset in the buffer and updates *pIdx to refer 19121b870de6Sdanielk1977 ** to the first byte after the last byte written before returning. 19131b870de6Sdanielk1977 ** 19141b870de6Sdanielk1977 ** If the string zSignedIdent consists entirely of alpha-numeric 19151b870de6Sdanielk1977 ** characters, does not begin with a digit and is not an SQL keyword, 19161b870de6Sdanielk1977 ** then it is copied to the output buffer exactly as it is. Otherwise, 19171b870de6Sdanielk1977 ** it is quoted using double-quotes. 19181b870de6Sdanielk1977 */ 1919c4a64facSdrh static void identPut(char *z, int *pIdx, char *zSignedIdent){ 19204c755c0fSdrh unsigned char *zIdent = (unsigned char*)zSignedIdent; 192117f71934Sdrh int i, j, needQuote; 1922969fa7c1Sdrh i = *pIdx; 19231b870de6Sdanielk1977 192417f71934Sdrh for(j=0; zIdent[j]; j++){ 192578ca0e7eSdanielk1977 if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break; 192617f71934Sdrh } 1927c7407524Sdrh needQuote = sqlite3Isdigit(zIdent[0]) 1928c7407524Sdrh || sqlite3KeywordCode(zIdent, j)!=TK_ID 1929c7407524Sdrh || zIdent[j]!=0 1930c7407524Sdrh || j==0; 19311b870de6Sdanielk1977 1932234c39dfSdrh if( needQuote ) z[i++] = '"'; 1933969fa7c1Sdrh for(j=0; zIdent[j]; j++){ 1934969fa7c1Sdrh z[i++] = zIdent[j]; 1935234c39dfSdrh if( zIdent[j]=='"' ) z[i++] = '"'; 1936969fa7c1Sdrh } 1937234c39dfSdrh if( needQuote ) z[i++] = '"'; 1938969fa7c1Sdrh z[i] = 0; 1939969fa7c1Sdrh *pIdx = i; 1940969fa7c1Sdrh } 1941969fa7c1Sdrh 1942969fa7c1Sdrh /* 1943969fa7c1Sdrh ** Generate a CREATE TABLE statement appropriate for the given 1944969fa7c1Sdrh ** table. Memory to hold the text of the statement is obtained 1945969fa7c1Sdrh ** from sqliteMalloc() and must be freed by the calling function. 1946969fa7c1Sdrh */ 19471d34fdecSdrh static char *createTableStmt(sqlite3 *db, Table *p){ 1948969fa7c1Sdrh int i, k, n; 1949969fa7c1Sdrh char *zStmt; 1950c4a64facSdrh char *zSep, *zSep2, *zEnd; 1951234c39dfSdrh Column *pCol; 1952969fa7c1Sdrh n = 0; 1953234c39dfSdrh for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){ 1954c4a64facSdrh n += identLength(pCol->zName) + 5; 1955969fa7c1Sdrh } 1956969fa7c1Sdrh n += identLength(p->zName); 1957234c39dfSdrh if( n<50 ){ 1958969fa7c1Sdrh zSep = ""; 1959969fa7c1Sdrh zSep2 = ","; 1960969fa7c1Sdrh zEnd = ")"; 1961969fa7c1Sdrh }else{ 1962969fa7c1Sdrh zSep = "\n "; 1963969fa7c1Sdrh zSep2 = ",\n "; 1964969fa7c1Sdrh zEnd = "\n)"; 1965969fa7c1Sdrh } 1966e0bc4048Sdrh n += 35 + 6*p->nCol; 1967b975598eSdrh zStmt = sqlite3DbMallocRaw(0, n); 1968820a9069Sdrh if( zStmt==0 ){ 19694a642b60Sdrh sqlite3OomFault(db); 1970820a9069Sdrh return 0; 1971820a9069Sdrh } 1972bdb339ffSdrh sqlite3_snprintf(n, zStmt, "CREATE TABLE "); 1973ea678832Sdrh k = sqlite3Strlen30(zStmt); 1974c4a64facSdrh identPut(zStmt, &k, p->zName); 1975969fa7c1Sdrh zStmt[k++] = '('; 1976234c39dfSdrh for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){ 1977c4a64facSdrh static const char * const azType[] = { 197805883a34Sdrh /* SQLITE_AFF_BLOB */ "", 19797ea31ccbSdrh /* SQLITE_AFF_TEXT */ " TEXT", 1980c4a64facSdrh /* SQLITE_AFF_NUMERIC */ " NUM", 1981c4a64facSdrh /* SQLITE_AFF_INTEGER */ " INT", 1982c4a64facSdrh /* SQLITE_AFF_REAL */ " REAL" 1983c4a64facSdrh }; 1984c4a64facSdrh int len; 1985c4a64facSdrh const char *zType; 1986c4a64facSdrh 19875bb3eb9bSdrh sqlite3_snprintf(n-k, &zStmt[k], zSep); 1988ea678832Sdrh k += sqlite3Strlen30(&zStmt[k]); 1989969fa7c1Sdrh zSep = zSep2; 1990c4a64facSdrh identPut(zStmt, &k, pCol->zName); 199105883a34Sdrh assert( pCol->affinity-SQLITE_AFF_BLOB >= 0 ); 199205883a34Sdrh assert( pCol->affinity-SQLITE_AFF_BLOB < ArraySize(azType) ); 199305883a34Sdrh testcase( pCol->affinity==SQLITE_AFF_BLOB ); 19947ea31ccbSdrh testcase( pCol->affinity==SQLITE_AFF_TEXT ); 1995c4a64facSdrh testcase( pCol->affinity==SQLITE_AFF_NUMERIC ); 1996c4a64facSdrh testcase( pCol->affinity==SQLITE_AFF_INTEGER ); 1997c4a64facSdrh testcase( pCol->affinity==SQLITE_AFF_REAL ); 1998c4a64facSdrh 199905883a34Sdrh zType = azType[pCol->affinity - SQLITE_AFF_BLOB]; 2000c4a64facSdrh len = sqlite3Strlen30(zType); 200105883a34Sdrh assert( pCol->affinity==SQLITE_AFF_BLOB 2002fdaac671Sdrh || pCol->affinity==sqlite3AffinityType(zType, 0) ); 2003c4a64facSdrh memcpy(&zStmt[k], zType, len); 2004c4a64facSdrh k += len; 2005c4a64facSdrh assert( k<=n ); 2006969fa7c1Sdrh } 20075bb3eb9bSdrh sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd); 2008969fa7c1Sdrh return zStmt; 2009969fa7c1Sdrh } 2010969fa7c1Sdrh 2011969fa7c1Sdrh /* 20127f9c5dbfSdrh ** Resize an Index object to hold N columns total. Return SQLITE_OK 20137f9c5dbfSdrh ** on success and SQLITE_NOMEM on an OOM error. 20147f9c5dbfSdrh */ 20157f9c5dbfSdrh static int resizeIndexObject(sqlite3 *db, Index *pIdx, int N){ 20167f9c5dbfSdrh char *zExtra; 20177f9c5dbfSdrh int nByte; 20187f9c5dbfSdrh if( pIdx->nColumn>=N ) return SQLITE_OK; 20197f9c5dbfSdrh assert( pIdx->isResized==0 ); 2020b5a69238Sdan nByte = (sizeof(char*) + sizeof(LogEst) + sizeof(i16) + 1)*N; 20217f9c5dbfSdrh zExtra = sqlite3DbMallocZero(db, nByte); 2022fad3039cSmistachkin if( zExtra==0 ) return SQLITE_NOMEM_BKPT; 20237f9c5dbfSdrh memcpy(zExtra, pIdx->azColl, sizeof(char*)*pIdx->nColumn); 2024f19aa5faSdrh pIdx->azColl = (const char**)zExtra; 20257f9c5dbfSdrh zExtra += sizeof(char*)*N; 2026b5a69238Sdan memcpy(zExtra, pIdx->aiRowLogEst, sizeof(LogEst)*(pIdx->nKeyCol+1)); 2027b5a69238Sdan pIdx->aiRowLogEst = (LogEst*)zExtra; 2028b5a69238Sdan zExtra += sizeof(LogEst)*N; 20297f9c5dbfSdrh memcpy(zExtra, pIdx->aiColumn, sizeof(i16)*pIdx->nColumn); 20307f9c5dbfSdrh pIdx->aiColumn = (i16*)zExtra; 20317f9c5dbfSdrh zExtra += sizeof(i16)*N; 20327f9c5dbfSdrh memcpy(zExtra, pIdx->aSortOrder, pIdx->nColumn); 20337f9c5dbfSdrh pIdx->aSortOrder = (u8*)zExtra; 20347f9c5dbfSdrh pIdx->nColumn = N; 20357f9c5dbfSdrh pIdx->isResized = 1; 20367f9c5dbfSdrh return SQLITE_OK; 20377f9c5dbfSdrh } 20387f9c5dbfSdrh 20397f9c5dbfSdrh /* 2040fdaac671Sdrh ** Estimate the total row width for a table. 2041fdaac671Sdrh */ 2042e13e9f54Sdrh static void estimateTableWidth(Table *pTab){ 2043fdaac671Sdrh unsigned wTable = 0; 2044fdaac671Sdrh const Column *pTabCol; 2045fdaac671Sdrh int i; 2046fdaac671Sdrh for(i=pTab->nCol, pTabCol=pTab->aCol; i>0; i--, pTabCol++){ 2047fdaac671Sdrh wTable += pTabCol->szEst; 2048fdaac671Sdrh } 2049fdaac671Sdrh if( pTab->iPKey<0 ) wTable++; 2050e13e9f54Sdrh pTab->szTabRow = sqlite3LogEst(wTable*4); 2051fdaac671Sdrh } 2052fdaac671Sdrh 2053fdaac671Sdrh /* 2054e13e9f54Sdrh ** Estimate the average size of a row for an index. 2055fdaac671Sdrh */ 2056e13e9f54Sdrh static void estimateIndexWidth(Index *pIdx){ 2057bbbdc83bSdrh unsigned wIndex = 0; 2058fdaac671Sdrh int i; 2059fdaac671Sdrh const Column *aCol = pIdx->pTable->aCol; 2060fdaac671Sdrh for(i=0; i<pIdx->nColumn; i++){ 2061bbbdc83bSdrh i16 x = pIdx->aiColumn[i]; 2062bbbdc83bSdrh assert( x<pIdx->pTable->nCol ); 2063bbbdc83bSdrh wIndex += x<0 ? 1 : aCol[pIdx->aiColumn[i]].szEst; 2064fdaac671Sdrh } 2065e13e9f54Sdrh pIdx->szIdxRow = sqlite3LogEst(wIndex*4); 2066fdaac671Sdrh } 2067fdaac671Sdrh 2068f78d0f42Sdrh /* Return true if column number x is any of the first nCol entries of aiCol[]. 2069f78d0f42Sdrh ** This is used to determine if the column number x appears in any of the 2070f78d0f42Sdrh ** first nCol entries of an index. 20717f9c5dbfSdrh */ 20727f9c5dbfSdrh static int hasColumn(const i16 *aiCol, int nCol, int x){ 2073f78d0f42Sdrh while( nCol-- > 0 ){ 2074f78d0f42Sdrh assert( aiCol[0]>=0 ); 2075f78d0f42Sdrh if( x==*(aiCol++) ){ 2076f78d0f42Sdrh return 1; 2077f78d0f42Sdrh } 2078f78d0f42Sdrh } 2079f78d0f42Sdrh return 0; 2080f78d0f42Sdrh } 2081f78d0f42Sdrh 2082f78d0f42Sdrh /* 2083c19b63c9Sdrh ** Return true if any of the first nKey entries of index pIdx exactly 2084c19b63c9Sdrh ** match the iCol-th entry of pPk. pPk is always a WITHOUT ROWID 2085c19b63c9Sdrh ** PRIMARY KEY index. pIdx is an index on the same table. pIdx may 2086c19b63c9Sdrh ** or may not be the same index as pPk. 2087f78d0f42Sdrh ** 2088c19b63c9Sdrh ** The first nKey entries of pIdx are guaranteed to be ordinary columns, 2089f78d0f42Sdrh ** not a rowid or expression. 2090f78d0f42Sdrh ** 2091f78d0f42Sdrh ** This routine differs from hasColumn() in that both the column and the 2092f78d0f42Sdrh ** collating sequence must match for this routine, but for hasColumn() only 2093f78d0f42Sdrh ** the column name must match. 2094f78d0f42Sdrh */ 2095c19b63c9Sdrh static int isDupColumn(Index *pIdx, int nKey, Index *pPk, int iCol){ 2096f78d0f42Sdrh int i, j; 2097c19b63c9Sdrh assert( nKey<=pIdx->nColumn ); 2098c19b63c9Sdrh assert( iCol<MAX(pPk->nColumn,pPk->nKeyCol) ); 2099c19b63c9Sdrh assert( pPk->idxType==SQLITE_IDXTYPE_PRIMARYKEY ); 2100c19b63c9Sdrh assert( pPk->pTable->tabFlags & TF_WithoutRowid ); 2101c19b63c9Sdrh assert( pPk->pTable==pIdx->pTable ); 2102c19b63c9Sdrh testcase( pPk==pIdx ); 2103c19b63c9Sdrh j = pPk->aiColumn[iCol]; 2104c19b63c9Sdrh assert( j!=XN_ROWID && j!=XN_EXPR ); 2105f78d0f42Sdrh for(i=0; i<nKey; i++){ 2106c19b63c9Sdrh assert( pIdx->aiColumn[i]>=0 || j>=0 ); 2107c19b63c9Sdrh if( pIdx->aiColumn[i]==j 2108c19b63c9Sdrh && sqlite3StrICmp(pIdx->azColl[i], pPk->azColl[iCol])==0 2109f78d0f42Sdrh ){ 2110f78d0f42Sdrh return 1; 2111f78d0f42Sdrh } 2112f78d0f42Sdrh } 21137f9c5dbfSdrh return 0; 21147f9c5dbfSdrh } 21157f9c5dbfSdrh 21161fe3ac73Sdrh /* Recompute the colNotIdxed field of the Index. 21171fe3ac73Sdrh ** 21181fe3ac73Sdrh ** colNotIdxed is a bitmask that has a 0 bit representing each indexed 21191fe3ac73Sdrh ** columns that are within the first 63 columns of the table. The 21201fe3ac73Sdrh ** high-order bit of colNotIdxed is always 1. All unindexed columns 21211fe3ac73Sdrh ** of the table have a 1. 21221fe3ac73Sdrh ** 2123c7476735Sdrh ** 2019-10-24: For the purpose of this computation, virtual columns are 2124c7476735Sdrh ** not considered to be covered by the index, even if they are in the 2125c7476735Sdrh ** index, because we do not trust the logic in whereIndexExprTrans() to be 2126c7476735Sdrh ** able to find all instances of a reference to the indexed table column 2127c7476735Sdrh ** and convert them into references to the index. Hence we always want 2128c7476735Sdrh ** the actual table at hand in order to recompute the virtual column, if 2129c7476735Sdrh ** necessary. 2130c7476735Sdrh ** 21311fe3ac73Sdrh ** The colNotIdxed mask is AND-ed with the SrcList.a[].colUsed mask 21321fe3ac73Sdrh ** to determine if the index is covering index. 21331fe3ac73Sdrh */ 21341fe3ac73Sdrh static void recomputeColumnsNotIndexed(Index *pIdx){ 21351fe3ac73Sdrh Bitmask m = 0; 21361fe3ac73Sdrh int j; 2137c7476735Sdrh Table *pTab = pIdx->pTable; 21381fe3ac73Sdrh for(j=pIdx->nColumn-1; j>=0; j--){ 21391fe3ac73Sdrh int x = pIdx->aiColumn[j]; 2140c7476735Sdrh if( x>=0 && (pTab->aCol[x].colFlags & COLFLAG_VIRTUAL)==0 ){ 21411fe3ac73Sdrh testcase( x==BMS-1 ); 21421fe3ac73Sdrh testcase( x==BMS-2 ); 21431fe3ac73Sdrh if( x<BMS-1 ) m |= MASKBIT(x); 21441fe3ac73Sdrh } 21451fe3ac73Sdrh } 21461fe3ac73Sdrh pIdx->colNotIdxed = ~m; 21471fe3ac73Sdrh assert( (pIdx->colNotIdxed>>63)==1 ); 21481fe3ac73Sdrh } 21491fe3ac73Sdrh 21507f9c5dbfSdrh /* 2151c6bd4e4aSdrh ** This routine runs at the end of parsing a CREATE TABLE statement that 2152c6bd4e4aSdrh ** has a WITHOUT ROWID clause. The job of this routine is to convert both 2153c6bd4e4aSdrh ** internal schema data structures and the generated VDBE code so that they 2154c6bd4e4aSdrh ** are appropriate for a WITHOUT ROWID table instead of a rowid table. 2155c6bd4e4aSdrh ** Changes include: 21567f9c5dbfSdrh ** 215762340f84Sdrh ** (1) Set all columns of the PRIMARY KEY schema object to be NOT NULL. 21580f3f7664Sdrh ** (2) Convert P3 parameter of the OP_CreateBtree from BTREE_INTKEY 21590f3f7664Sdrh ** into BTREE_BLOBKEY. 21601e32bed3Sdrh ** (3) Bypass the creation of the sqlite_schema table entry 216160ec914cSpeter.d.reid ** for the PRIMARY KEY as the primary key index is now 21621e32bed3Sdrh ** identified by the sqlite_schema table entry of the table itself. 216362340f84Sdrh ** (4) Set the Index.tnum of the PRIMARY KEY Index object in the 2164c6bd4e4aSdrh ** schema to the rootpage from the main table. 2165c6bd4e4aSdrh ** (5) Add all table columns to the PRIMARY KEY Index object 2166c6bd4e4aSdrh ** so that the PRIMARY KEY is a covering index. The surplus 2167a485ad19Sdrh ** columns are part of KeyInfo.nAllField and are not used for 2168c6bd4e4aSdrh ** sorting or lookup or uniqueness checks. 2169c6bd4e4aSdrh ** (6) Replace the rowid tail on all automatically generated UNIQUE 2170c6bd4e4aSdrh ** indices with the PRIMARY KEY columns. 217162340f84Sdrh ** 217262340f84Sdrh ** For virtual tables, only (1) is performed. 21737f9c5dbfSdrh */ 21747f9c5dbfSdrh static void convertToWithoutRowidTable(Parse *pParse, Table *pTab){ 21757f9c5dbfSdrh Index *pIdx; 21767f9c5dbfSdrh Index *pPk; 21777f9c5dbfSdrh int nPk; 21781ff94071Sdan int nExtra; 21797f9c5dbfSdrh int i, j; 21807f9c5dbfSdrh sqlite3 *db = pParse->db; 2181c6bd4e4aSdrh Vdbe *v = pParse->pVdbe; 21827f9c5dbfSdrh 218362340f84Sdrh /* Mark every PRIMARY KEY column as NOT NULL (except for imposter tables) 218462340f84Sdrh */ 218562340f84Sdrh if( !db->init.imposterTable ){ 218662340f84Sdrh for(i=0; i<pTab->nCol; i++){ 218762340f84Sdrh if( (pTab->aCol[i].colFlags & COLFLAG_PRIMKEY)!=0 ){ 218862340f84Sdrh pTab->aCol[i].notNull = OE_Abort; 218962340f84Sdrh } 219062340f84Sdrh } 2191cbda9c7aSdrh pTab->tabFlags |= TF_HasNotNull; 219262340f84Sdrh } 219362340f84Sdrh 21940f3f7664Sdrh /* Convert the P3 operand of the OP_CreateBtree opcode from BTREE_INTKEY 21950f3f7664Sdrh ** into BTREE_BLOBKEY. 21967f9c5dbfSdrh */ 2197381bdaccSdrh assert( !pParse->bReturning ); 2198381bdaccSdrh if( pParse->u1.addrCrTab ){ 2199c6bd4e4aSdrh assert( v ); 2200381bdaccSdrh sqlite3VdbeChangeP3(v, pParse->u1.addrCrTab, BTREE_BLOBKEY); 2201c6bd4e4aSdrh } 2202c6bd4e4aSdrh 22037f9c5dbfSdrh /* Locate the PRIMARY KEY index. Or, if this table was originally 22047f9c5dbfSdrh ** an INTEGER PRIMARY KEY table, create a new PRIMARY KEY index. 22057f9c5dbfSdrh */ 22067f9c5dbfSdrh if( pTab->iPKey>=0 ){ 22077f9c5dbfSdrh ExprList *pList; 2208108aa00aSdrh Token ipkToken; 220940aced5cSdrh sqlite3TokenInit(&ipkToken, pTab->aCol[pTab->iPKey].zName); 2210108aa00aSdrh pList = sqlite3ExprListAppend(pParse, 0, 2211108aa00aSdrh sqlite3ExprAlloc(db, TK_ID, &ipkToken, 0)); 22121bb89e9cSdrh if( pList==0 ){ 22131bb89e9cSdrh pTab->tabFlags &= ~TF_WithoutRowid; 22141bb89e9cSdrh return; 22151bb89e9cSdrh } 2216f9b0c451Sdan if( IN_RENAME_OBJECT ){ 2217f9b0c451Sdan sqlite3RenameTokenRemap(pParse, pList->a[0].pExpr, &pTab->iPKey); 2218f9b0c451Sdan } 22196e11892dSdan pList->a[0].sortFlags = pParse->iPkSortOrder; 22207f9c5dbfSdrh assert( pParse->pNewTable==pTab ); 2221f9b0c451Sdan pTab->iPKey = -1; 222262340f84Sdrh sqlite3CreateIndex(pParse, 0, 0, 0, pList, pTab->keyConf, 0, 0, 0, 0, 222362340f84Sdrh SQLITE_IDXTYPE_PRIMARYKEY); 22243bb9d75aSdrh if( db->mallocFailed || pParse->nErr ){ 22253bb9d75aSdrh pTab->tabFlags &= ~TF_WithoutRowid; 22263bb9d75aSdrh return; 22273bb9d75aSdrh } 222862340f84Sdrh pPk = sqlite3PrimaryKeyIndex(pTab); 22291ff94071Sdan assert( pPk->nKeyCol==1 ); 22304415628aSdrh }else{ 22314415628aSdrh pPk = sqlite3PrimaryKeyIndex(pTab); 2232f0c48b1cSdrh assert( pPk!=0 ); 2233c5b73585Sdan 2234e385d887Sdrh /* 2235e385d887Sdrh ** Remove all redundant columns from the PRIMARY KEY. For example, change 2236e385d887Sdrh ** "PRIMARY KEY(a,b,a,b,c,b,c,d)" into just "PRIMARY KEY(a,b,c,d)". Later 2237e385d887Sdrh ** code assumes the PRIMARY KEY contains no repeated columns. 2238e385d887Sdrh */ 2239e385d887Sdrh for(i=j=1; i<pPk->nKeyCol; i++){ 2240f78d0f42Sdrh if( isDupColumn(pPk, j, pPk, i) ){ 2241e385d887Sdrh pPk->nColumn--; 2242e385d887Sdrh }else{ 2243f78d0f42Sdrh testcase( hasColumn(pPk->aiColumn, j, pPk->aiColumn[i]) ); 22441ff94071Sdan pPk->azColl[j] = pPk->azColl[i]; 22451ff94071Sdan pPk->aSortOrder[j] = pPk->aSortOrder[i]; 2246e385d887Sdrh pPk->aiColumn[j++] = pPk->aiColumn[i]; 2247e385d887Sdrh } 2248e385d887Sdrh } 2249e385d887Sdrh pPk->nKeyCol = j; 22507f9c5dbfSdrh } 22517f9c5dbfSdrh assert( pPk!=0 ); 225262340f84Sdrh pPk->isCovering = 1; 225362340f84Sdrh if( !db->init.imposterTable ) pPk->uniqNotNull = 1; 22541ff94071Sdan nPk = pPk->nColumn = pPk->nKeyCol; 22557f9c5dbfSdrh 22561e32bed3Sdrh /* Bypass the creation of the PRIMARY KEY btree and the sqlite_schema 2257df94966cSdrh ** table entry. This is only required if currently generating VDBE 2258df94966cSdrh ** code for a CREATE TABLE (not when parsing one as part of reading 2259df94966cSdrh ** a database schema). */ 2260df94966cSdrh if( v && pPk->tnum>0 ){ 2261df94966cSdrh assert( db->init.busy==0 ); 2262abc38158Sdrh sqlite3VdbeChangeOpcode(v, (int)pPk->tnum, OP_Goto); 2263df94966cSdrh } 2264df94966cSdrh 2265c6bd4e4aSdrh /* The root page of the PRIMARY KEY is the table root page */ 2266c6bd4e4aSdrh pPk->tnum = pTab->tnum; 2267c6bd4e4aSdrh 22687f9c5dbfSdrh /* Update the in-memory representation of all UNIQUE indices by converting 22697f9c5dbfSdrh ** the final rowid column into one or more columns of the PRIMARY KEY. 22707f9c5dbfSdrh */ 22717f9c5dbfSdrh for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ 22727f9c5dbfSdrh int n; 227348dd1d8eSdrh if( IsPrimaryKeyIndex(pIdx) ) continue; 22747f9c5dbfSdrh for(i=n=0; i<nPk; i++){ 2275f78d0f42Sdrh if( !isDupColumn(pIdx, pIdx->nKeyCol, pPk, i) ){ 2276f78d0f42Sdrh testcase( hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) ); 2277f78d0f42Sdrh n++; 2278f78d0f42Sdrh } 22797f9c5dbfSdrh } 22805a9a37b7Sdrh if( n==0 ){ 22815a9a37b7Sdrh /* This index is a superset of the primary key */ 22825a9a37b7Sdrh pIdx->nColumn = pIdx->nKeyCol; 22835a9a37b7Sdrh continue; 22845a9a37b7Sdrh } 22857f9c5dbfSdrh if( resizeIndexObject(db, pIdx, pIdx->nKeyCol+n) ) return; 22867f9c5dbfSdrh for(i=0, j=pIdx->nKeyCol; i<nPk; i++){ 2287f78d0f42Sdrh if( !isDupColumn(pIdx, pIdx->nKeyCol, pPk, i) ){ 2288f78d0f42Sdrh testcase( hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) ); 22897f9c5dbfSdrh pIdx->aiColumn[j] = pPk->aiColumn[i]; 22907f9c5dbfSdrh pIdx->azColl[j] = pPk->azColl[i]; 2291bf9ff256Sdrh if( pPk->aSortOrder[i] ){ 2292bf9ff256Sdrh /* See ticket https://www.sqlite.org/src/info/bba7b69f9849b5bf */ 2293bf9ff256Sdrh pIdx->bAscKeyBug = 1; 2294bf9ff256Sdrh } 22957f9c5dbfSdrh j++; 22967f9c5dbfSdrh } 22977f9c5dbfSdrh } 229800012df4Sdrh assert( pIdx->nColumn>=pIdx->nKeyCol+n ); 229900012df4Sdrh assert( pIdx->nColumn>=j ); 23007f9c5dbfSdrh } 23017f9c5dbfSdrh 23027f9c5dbfSdrh /* Add all table columns to the PRIMARY KEY index 23037f9c5dbfSdrh */ 23041ff94071Sdan nExtra = 0; 23051ff94071Sdan for(i=0; i<pTab->nCol; i++){ 23068e10d74bSdrh if( !hasColumn(pPk->aiColumn, nPk, i) 23078e10d74bSdrh && (pTab->aCol[i].colFlags & COLFLAG_VIRTUAL)==0 ) nExtra++; 23081ff94071Sdan } 23091ff94071Sdan if( resizeIndexObject(db, pPk, nPk+nExtra) ) return; 23107f9c5dbfSdrh for(i=0, j=nPk; i<pTab->nCol; i++){ 23118e10d74bSdrh if( !hasColumn(pPk->aiColumn, j, i) 23128e10d74bSdrh && (pTab->aCol[i].colFlags & COLFLAG_VIRTUAL)==0 23138e10d74bSdrh ){ 23147f9c5dbfSdrh assert( j<pPk->nColumn ); 23157f9c5dbfSdrh pPk->aiColumn[j] = i; 2316f19aa5faSdrh pPk->azColl[j] = sqlite3StrBINARY; 23177f9c5dbfSdrh j++; 23187f9c5dbfSdrh } 23197f9c5dbfSdrh } 23207f9c5dbfSdrh assert( pPk->nColumn==j ); 23218e10d74bSdrh assert( pTab->nNVCol<=j ); 23221fe3ac73Sdrh recomputeColumnsNotIndexed(pPk); 23237f9c5dbfSdrh } 23247f9c5dbfSdrh 23253d863b5eSdrh 23263d863b5eSdrh #ifndef SQLITE_OMIT_VIRTUALTABLE 23273d863b5eSdrh /* 23283d863b5eSdrh ** Return true if pTab is a virtual table and zName is a shadow table name 23293d863b5eSdrh ** for that virtual table. 23303d863b5eSdrh */ 23313d863b5eSdrh int sqlite3IsShadowTableOf(sqlite3 *db, Table *pTab, const char *zName){ 23323d863b5eSdrh int nName; /* Length of zName */ 23333d863b5eSdrh Module *pMod; /* Module for the virtual table */ 23343d863b5eSdrh 23353d863b5eSdrh if( !IsVirtual(pTab) ) return 0; 23363d863b5eSdrh nName = sqlite3Strlen30(pTab->zName); 23373d863b5eSdrh if( sqlite3_strnicmp(zName, pTab->zName, nName)!=0 ) return 0; 23383d863b5eSdrh if( zName[nName]!='_' ) return 0; 23393d863b5eSdrh pMod = (Module*)sqlite3HashFind(&db->aModule, pTab->azModuleArg[0]); 23403d863b5eSdrh if( pMod==0 ) return 0; 23413d863b5eSdrh if( pMod->pModule->iVersion<3 ) return 0; 23423d863b5eSdrh if( pMod->pModule->xShadowName==0 ) return 0; 23433d863b5eSdrh return pMod->pModule->xShadowName(zName+nName+1); 23443d863b5eSdrh } 23453d863b5eSdrh #endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */ 23463d863b5eSdrh 2347f6e015faSdan #ifndef SQLITE_OMIT_VIRTUALTABLE 2348fdaac671Sdrh /* 234984c501baSdrh ** Return true if zName is a shadow table name in the current database 235084c501baSdrh ** connection. 235184c501baSdrh ** 235284c501baSdrh ** zName is temporarily modified while this routine is running, but is 235384c501baSdrh ** restored to its original value prior to this routine returning. 235484c501baSdrh */ 2355527cbd4aSdrh int sqlite3ShadowTableName(sqlite3 *db, const char *zName){ 235684c501baSdrh char *zTail; /* Pointer to the last "_" in zName */ 235784c501baSdrh Table *pTab; /* Table that zName is a shadow of */ 235884c501baSdrh zTail = strrchr(zName, '_'); 235984c501baSdrh if( zTail==0 ) return 0; 236084c501baSdrh *zTail = 0; 236184c501baSdrh pTab = sqlite3FindTable(db, zName, 0); 236284c501baSdrh *zTail = '_'; 236384c501baSdrh if( pTab==0 ) return 0; 236484c501baSdrh if( !IsVirtual(pTab) ) return 0; 23653d863b5eSdrh return sqlite3IsShadowTableOf(db, pTab, zName); 236684c501baSdrh } 2367f6e015faSdan #endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */ 236884c501baSdrh 23693d863b5eSdrh 2370e7375bfaSdrh #ifdef SQLITE_DEBUG 2371e7375bfaSdrh /* 2372e7375bfaSdrh ** Mark all nodes of an expression as EP_Immutable, indicating that 2373e7375bfaSdrh ** they should not be changed. Expressions attached to a table or 2374e7375bfaSdrh ** index definition are tagged this way to help ensure that we do 2375e7375bfaSdrh ** not pass them into code generator routines by mistake. 2376e7375bfaSdrh */ 2377e7375bfaSdrh static int markImmutableExprStep(Walker *pWalker, Expr *pExpr){ 2378e7375bfaSdrh ExprSetVVAProperty(pExpr, EP_Immutable); 2379e7375bfaSdrh return WRC_Continue; 2380e7375bfaSdrh } 2381e7375bfaSdrh static void markExprListImmutable(ExprList *pList){ 2382e7375bfaSdrh if( pList ){ 2383e7375bfaSdrh Walker w; 2384e7375bfaSdrh memset(&w, 0, sizeof(w)); 2385e7375bfaSdrh w.xExprCallback = markImmutableExprStep; 2386e7375bfaSdrh w.xSelectCallback = sqlite3SelectWalkNoop; 2387e7375bfaSdrh w.xSelectCallback2 = 0; 2388e7375bfaSdrh sqlite3WalkExprList(&w, pList); 2389e7375bfaSdrh } 2390e7375bfaSdrh } 2391e7375bfaSdrh #else 2392e7375bfaSdrh #define markExprListImmutable(X) /* no-op */ 2393e7375bfaSdrh #endif /* SQLITE_DEBUG */ 2394e7375bfaSdrh 2395e7375bfaSdrh 239684c501baSdrh /* 239775897234Sdrh ** This routine is called to report the final ")" that terminates 239875897234Sdrh ** a CREATE TABLE statement. 239975897234Sdrh ** 2400f57b3399Sdrh ** The table structure that other action routines have been building 2401f57b3399Sdrh ** is added to the internal hash tables, assuming no errors have 2402f57b3399Sdrh ** occurred. 240375897234Sdrh ** 2404067b92baSdrh ** An entry for the table is made in the schema table on disk, unless 24051d85d931Sdrh ** this is a temporary table or db->init.busy==1. When db->init.busy==1 24061e32bed3Sdrh ** it means we are reading the sqlite_schema table because we just 24071e32bed3Sdrh ** connected to the database or because the sqlite_schema table has 2408ddba9e54Sdrh ** recently changed, so the entry for this table already exists in 24091e32bed3Sdrh ** the sqlite_schema table. We do not want to create it again. 2410969fa7c1Sdrh ** 2411969fa7c1Sdrh ** If the pSelect argument is not NULL, it means that this routine 2412969fa7c1Sdrh ** was called to create a table generated from a 2413969fa7c1Sdrh ** "CREATE TABLE ... AS SELECT ..." statement. The column names of 2414969fa7c1Sdrh ** the new table will match the result set of the SELECT. 241575897234Sdrh */ 241619a8e7e8Sdanielk1977 void sqlite3EndTable( 241719a8e7e8Sdanielk1977 Parse *pParse, /* Parse context */ 241819a8e7e8Sdanielk1977 Token *pCons, /* The ',' token after the last column defn. */ 24195969da4aSdrh Token *pEnd, /* The ')' before options in the CREATE TABLE */ 24205969da4aSdrh u8 tabOpts, /* Extra table options. Usually 0. */ 242119a8e7e8Sdanielk1977 Select *pSelect /* Select from a "CREATE ... AS SELECT" */ 242219a8e7e8Sdanielk1977 ){ 2423fdaac671Sdrh Table *p; /* The new table */ 2424fdaac671Sdrh sqlite3 *db = pParse->db; /* The database connection */ 2425fdaac671Sdrh int iDb; /* Database in which the table lives */ 2426fdaac671Sdrh Index *pIdx; /* An implied index of the table */ 242775897234Sdrh 2428027616d4Sdrh if( pEnd==0 && pSelect==0 ){ 24295969da4aSdrh return; 2430261919ccSdanielk1977 } 24312803757aSdrh p = pParse->pNewTable; 24325969da4aSdrh if( p==0 ) return; 243375897234Sdrh 2434527cbd4aSdrh if( pSelect==0 && sqlite3ShadowTableName(db, p->zName) ){ 243584c501baSdrh p->tabFlags |= TF_Shadow; 243684c501baSdrh } 243784c501baSdrh 2438c6bd4e4aSdrh /* If the db->init.busy is 1 it means we are reading the SQL off the 24391e32bed3Sdrh ** "sqlite_schema" or "sqlite_temp_schema" table on the disk. 2440c6bd4e4aSdrh ** So do not write to the disk again. Extract the root page number 2441c6bd4e4aSdrh ** for the table from the db->init.newTnum field. (The page number 2442c6bd4e4aSdrh ** should have been put there by the sqliteOpenCb routine.) 2443055f298aSdrh ** 24441e32bed3Sdrh ** If the root page number is 1, that means this is the sqlite_schema 2445055f298aSdrh ** table itself. So mark it read-only. 2446c6bd4e4aSdrh */ 2447c6bd4e4aSdrh if( db->init.busy ){ 24481e9c47beSdrh if( pSelect ){ 24491e9c47beSdrh sqlite3ErrorMsg(pParse, ""); 24501e9c47beSdrh return; 24511e9c47beSdrh } 2452c6bd4e4aSdrh p->tnum = db->init.newTnum; 2453055f298aSdrh if( p->tnum==1 ) p->tabFlags |= TF_Readonly; 2454c6bd4e4aSdrh } 2455c6bd4e4aSdrh 24563cbd2b72Sdrh assert( (p->tabFlags & TF_HasPrimaryKey)==0 24573cbd2b72Sdrh || p->iPKey>=0 || sqlite3PrimaryKeyIndex(p)!=0 ); 24583cbd2b72Sdrh assert( (p->tabFlags & TF_HasPrimaryKey)!=0 24593cbd2b72Sdrh || (p->iPKey<0 && sqlite3PrimaryKeyIndex(p)==0) ); 24603cbd2b72Sdrh 2461c6bd4e4aSdrh /* Special processing for WITHOUT ROWID Tables */ 24625969da4aSdrh if( tabOpts & TF_WithoutRowid ){ 2463d2fe3358Sdrh if( (p->tabFlags & TF_Autoincrement) ){ 2464d2fe3358Sdrh sqlite3ErrorMsg(pParse, 2465d2fe3358Sdrh "AUTOINCREMENT not allowed on WITHOUT ROWID tables"); 2466d2fe3358Sdrh return; 2467d2fe3358Sdrh } 246881eba73eSdrh if( (p->tabFlags & TF_HasPrimaryKey)==0 ){ 2469d2fe3358Sdrh sqlite3ErrorMsg(pParse, "PRIMARY KEY missing on table %s", p->zName); 24708e10d74bSdrh return; 24718e10d74bSdrh } 2472fccda8a1Sdrh p->tabFlags |= TF_WithoutRowid | TF_NoVisibleRowid; 24737f9c5dbfSdrh convertToWithoutRowidTable(pParse, p); 24747f9c5dbfSdrh } 2475b9bb7c18Sdrh iDb = sqlite3SchemaToIndex(db, p->pSchema); 2476da184236Sdanielk1977 2477ffe07b2dSdrh #ifndef SQLITE_OMIT_CHECK 2478ffe07b2dSdrh /* Resolve names in all CHECK constraint expressions. 2479ffe07b2dSdrh */ 2480ffe07b2dSdrh if( p->pCheck ){ 24813780be11Sdrh sqlite3ResolveSelfReference(pParse, p, NC_IsCheck, 0, p->pCheck); 24829524a7eaSdrh if( pParse->nErr ){ 24839524a7eaSdrh /* If errors are seen, delete the CHECK constraints now, else they might 24849524a7eaSdrh ** actually be used if PRAGMA writable_schema=ON is set. */ 24859524a7eaSdrh sqlite3ExprListDelete(db, p->pCheck); 24869524a7eaSdrh p->pCheck = 0; 2487e7375bfaSdrh }else{ 2488e7375bfaSdrh markExprListImmutable(p->pCheck); 24899524a7eaSdrh } 24902938f924Sdrh } 2491ffe07b2dSdrh #endif /* !defined(SQLITE_OMIT_CHECK) */ 249281f7b372Sdrh #ifndef SQLITE_OMIT_GENERATED_COLUMNS 2493427b96aeSdrh if( p->tabFlags & TF_HasGenerated ){ 2494f4658b68Sdrh int ii, nNG = 0; 2495427b96aeSdrh testcase( p->tabFlags & TF_HasVirtual ); 2496427b96aeSdrh testcase( p->tabFlags & TF_HasStored ); 249781f7b372Sdrh for(ii=0; ii<p->nCol; ii++){ 24980b0b3a95Sdrh u32 colFlags = p->aCol[ii].colFlags; 2499427b96aeSdrh if( (colFlags & COLFLAG_GENERATED)!=0 ){ 25007e3f135cSdrh Expr *pX = p->aCol[ii].pDflt; 2501427b96aeSdrh testcase( colFlags & COLFLAG_VIRTUAL ); 2502427b96aeSdrh testcase( colFlags & COLFLAG_STORED ); 25037e3f135cSdrh if( sqlite3ResolveSelfReference(pParse, p, NC_GenCol, pX, 0) ){ 25047e3f135cSdrh /* If there are errors in resolving the expression, change the 25057e3f135cSdrh ** expression to a NULL. This prevents code generators that operate 25067e3f135cSdrh ** on the expression from inserting extra parts into the expression 25077e3f135cSdrh ** tree that have been allocated from lookaside memory, which is 25082d58b7f4Sdrh ** illegal in a schema and will lead to errors or heap corruption 25092d58b7f4Sdrh ** when the database connection closes. */ 25107e3f135cSdrh sqlite3ExprDelete(db, pX); 25117e3f135cSdrh p->aCol[ii].pDflt = sqlite3ExprAlloc(db, TK_NULL, 0, 0); 25127e3f135cSdrh } 2513f4658b68Sdrh }else{ 2514f4658b68Sdrh nNG++; 251581f7b372Sdrh } 25162c40a3ebSdrh } 2517f4658b68Sdrh if( nNG==0 ){ 2518f4658b68Sdrh sqlite3ErrorMsg(pParse, "must have at least one non-generated column"); 25192c40a3ebSdrh return; 252081f7b372Sdrh } 252181f7b372Sdrh } 252281f7b372Sdrh #endif 2523ffe07b2dSdrh 2524e13e9f54Sdrh /* Estimate the average row size for the table and for all implied indices */ 2525e13e9f54Sdrh estimateTableWidth(p); 2526fdaac671Sdrh for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){ 2527e13e9f54Sdrh estimateIndexWidth(pIdx); 2528fdaac671Sdrh } 2529fdaac671Sdrh 2530e3c41372Sdrh /* If not initializing, then create a record for the new table 2531346a70caSdrh ** in the schema table of the database. 2532f57b3399Sdrh ** 2533e0bc4048Sdrh ** If this is a TEMPORARY table, write the entry into the auxiliary 2534e0bc4048Sdrh ** file instead of into the main database file. 253575897234Sdrh */ 25361d85d931Sdrh if( !db->init.busy ){ 25374ff6dfa7Sdrh int n; 2538d8bc7086Sdrh Vdbe *v; 25394794f735Sdrh char *zType; /* "view" or "table" */ 25404794f735Sdrh char *zType2; /* "VIEW" or "TABLE" */ 25414794f735Sdrh char *zStmt; /* Text of the CREATE TABLE or CREATE VIEW statement */ 254275897234Sdrh 25434adee20fSdanielk1977 v = sqlite3GetVdbe(pParse); 25445969da4aSdrh if( NEVER(v==0) ) return; 2545517eb646Sdanielk1977 254666a5167bSdrh sqlite3VdbeAddOp1(v, OP_Close, 0); 2547e6efa74bSdanielk1977 25480fa991b9Sdrh /* 25490fa991b9Sdrh ** Initialize zType for the new view or table. 25504794f735Sdrh */ 25514ff6dfa7Sdrh if( p->pSelect==0 ){ 25524ff6dfa7Sdrh /* A regular table */ 25534794f735Sdrh zType = "table"; 25544794f735Sdrh zType2 = "TABLE"; 2555576ec6b3Sdanielk1977 #ifndef SQLITE_OMIT_VIEW 25564ff6dfa7Sdrh }else{ 25574ff6dfa7Sdrh /* A view */ 25584794f735Sdrh zType = "view"; 25594794f735Sdrh zType2 = "VIEW"; 2560576ec6b3Sdanielk1977 #endif 25614ff6dfa7Sdrh } 2562517eb646Sdanielk1977 2563517eb646Sdanielk1977 /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT 2564517eb646Sdanielk1977 ** statement to populate the new table. The root-page number for the 25650fa991b9Sdrh ** new table is in register pParse->regRoot. 2566517eb646Sdanielk1977 ** 2567517eb646Sdanielk1977 ** Once the SELECT has been coded by sqlite3Select(), it is in a 2568517eb646Sdanielk1977 ** suitable state to query for the column names and types to be used 2569517eb646Sdanielk1977 ** by the new table. 2570c00da105Sdanielk1977 ** 2571c00da105Sdanielk1977 ** A shared-cache write-lock is not required to write to the new table, 2572c00da105Sdanielk1977 ** as a schema-lock must have already been obtained to create it. Since 2573c00da105Sdanielk1977 ** a schema-lock excludes all other database users, the write-lock would 2574c00da105Sdanielk1977 ** be redundant. 2575517eb646Sdanielk1977 */ 2576517eb646Sdanielk1977 if( pSelect ){ 257792632204Sdrh SelectDest dest; /* Where the SELECT should store results */ 25789df25c47Sdrh int regYield; /* Register holding co-routine entry-point */ 25799df25c47Sdrh int addrTop; /* Top of the co-routine */ 258092632204Sdrh int regRec; /* A record to be insert into the new table */ 258192632204Sdrh int regRowid; /* Rowid of the next row to insert */ 258292632204Sdrh int addrInsLoop; /* Top of the loop for inserting rows */ 258392632204Sdrh Table *pSelTab; /* A table that describes the SELECT results */ 25841013c932Sdrh 25859df25c47Sdrh regYield = ++pParse->nMem; 258692632204Sdrh regRec = ++pParse->nMem; 258792632204Sdrh regRowid = ++pParse->nMem; 25886ab3a2ecSdanielk1977 assert(pParse->nTab==1); 25890dd5cdaeSdrh sqlite3MayAbort(pParse); 2590b7654111Sdrh sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb); 2591428c218cSdan sqlite3VdbeChangeP5(v, OPFLAG_P2ISREG); 2592517eb646Sdanielk1977 pParse->nTab = 2; 25939df25c47Sdrh addrTop = sqlite3VdbeCurrentAddr(v) + 1; 25949df25c47Sdrh sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, addrTop); 2595512795dfSdrh if( pParse->nErr ) return; 259681506b88Sdrh pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect, SQLITE_AFF_BLOB); 25975969da4aSdrh if( pSelTab==0 ) return; 2598517eb646Sdanielk1977 assert( p->aCol==0 ); 2599f5f1915dSdrh p->nCol = p->nNVCol = pSelTab->nCol; 2600517eb646Sdanielk1977 p->aCol = pSelTab->aCol; 2601517eb646Sdanielk1977 pSelTab->nCol = 0; 2602517eb646Sdanielk1977 pSelTab->aCol = 0; 26031feeaed2Sdan sqlite3DeleteTable(db, pSelTab); 2604755b0fd3Sdrh sqlite3SelectDestInit(&dest, SRT_Coroutine, regYield); 2605755b0fd3Sdrh sqlite3Select(pParse, pSelect, &dest); 26065060a67cSdrh if( pParse->nErr ) return; 2607755b0fd3Sdrh sqlite3VdbeEndCoroutine(v, regYield); 2608755b0fd3Sdrh sqlite3VdbeJumpHere(v, addrTop - 1); 26099df25c47Sdrh addrInsLoop = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm); 26109df25c47Sdrh VdbeCoverage(v); 26119df25c47Sdrh sqlite3VdbeAddOp3(v, OP_MakeRecord, dest.iSdst, dest.nSdst, regRec); 26129df25c47Sdrh sqlite3TableAffinity(v, p, 0); 26139df25c47Sdrh sqlite3VdbeAddOp2(v, OP_NewRowid, 1, regRowid); 26149df25c47Sdrh sqlite3VdbeAddOp3(v, OP_Insert, 1, regRec, regRowid); 2615076e85f5Sdrh sqlite3VdbeGoto(v, addrInsLoop); 26169df25c47Sdrh sqlite3VdbeJumpHere(v, addrInsLoop); 26179df25c47Sdrh sqlite3VdbeAddOp1(v, OP_Close, 1); 2618517eb646Sdanielk1977 } 2619517eb646Sdanielk1977 26204794f735Sdrh /* Compute the complete text of the CREATE statement */ 26214794f735Sdrh if( pSelect ){ 26221d34fdecSdrh zStmt = createTableStmt(db, p); 26234794f735Sdrh }else{ 26248ea30bfcSdrh Token *pEnd2 = tabOpts ? &pParse->sLastToken : pEnd; 26258ea30bfcSdrh n = (int)(pEnd2->z - pParse->sNameToken.z); 26268ea30bfcSdrh if( pEnd2->z[0]!=';' ) n += pEnd2->n; 26271e536953Sdanielk1977 zStmt = sqlite3MPrintf(db, 26281e536953Sdanielk1977 "CREATE %s %.*s", zType2, n, pParse->sNameToken.z 26291e536953Sdanielk1977 ); 26304794f735Sdrh } 26314794f735Sdrh 26324794f735Sdrh /* A slot for the record has already been allocated in the 2633346a70caSdrh ** schema table. We just need to update that slot with all 26340fa991b9Sdrh ** the information we've collected. 26354794f735Sdrh */ 26364794f735Sdrh sqlite3NestedParse(pParse, 2637346a70caSdrh "UPDATE %Q." DFLT_SCHEMA_TABLE 2638b7654111Sdrh " SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q" 2639b7654111Sdrh " WHERE rowid=#%d", 2640346a70caSdrh db->aDb[iDb].zDbSName, 26414794f735Sdrh zType, 26424794f735Sdrh p->zName, 26434794f735Sdrh p->zName, 2644b7654111Sdrh pParse->regRoot, 2645b7654111Sdrh zStmt, 2646b7654111Sdrh pParse->regRowid 26474794f735Sdrh ); 2648633e6d57Sdrh sqlite3DbFree(db, zStmt); 26499cbf3425Sdrh sqlite3ChangeCookie(pParse, iDb); 26502958a4e6Sdrh 26512958a4e6Sdrh #ifndef SQLITE_OMIT_AUTOINCREMENT 26522958a4e6Sdrh /* Check to see if we need to create an sqlite_sequence table for 26532958a4e6Sdrh ** keeping track of autoincrement keys. 26542958a4e6Sdrh */ 2655755ed41fSdan if( (p->tabFlags & TF_Autoincrement)!=0 && !IN_SPECIAL_PARSE ){ 2656da184236Sdanielk1977 Db *pDb = &db->aDb[iDb]; 26572120608eSdrh assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); 2658da184236Sdanielk1977 if( pDb->pSchema->pSeqTab==0 ){ 26592958a4e6Sdrh sqlite3NestedParse(pParse, 2660f3388144Sdrh "CREATE TABLE %Q.sqlite_sequence(name,seq)", 266169c33826Sdrh pDb->zDbSName 26622958a4e6Sdrh ); 26632958a4e6Sdrh } 26642958a4e6Sdrh } 26652958a4e6Sdrh #endif 26664794f735Sdrh 26674794f735Sdrh /* Reparse everything to update our internal data structures */ 26685d9c9da6Sdrh sqlite3VdbeAddParseSchemaOp(v, iDb, 26696a5a13dfSdan sqlite3MPrintf(db, "tbl_name='%q' AND type!='trigger'", p->zName),0); 267075897234Sdrh } 267117e9e29dSdrh 267217e9e29dSdrh /* Add the table to the in-memory representation of the database. 267317e9e29dSdrh */ 26748af73d41Sdrh if( db->init.busy ){ 267517e9e29dSdrh Table *pOld; 2676e501b89aSdanielk1977 Schema *pSchema = p->pSchema; 26772120608eSdrh assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); 26781bb89e9cSdrh assert( HasRowid(p) || p->iPKey<0 ); 2679acbcb7e0Sdrh pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName, p); 268017e9e29dSdrh if( pOld ){ 268117e9e29dSdrh assert( p==pOld ); /* Malloc must have failed inside HashInsert() */ 26824a642b60Sdrh sqlite3OomFault(db); 26835969da4aSdrh return; 268417e9e29dSdrh } 268517e9e29dSdrh pParse->pNewTable = 0; 26868257aa8dSdrh db->mDbFlags |= DBFLAG_SchemaChange; 2687d4b64699Sdan 2688d4b64699Sdan /* If this is the magic sqlite_sequence table used by autoincrement, 2689d4b64699Sdan ** then record a pointer to this table in the main database structure 2690d4b64699Sdan ** so that INSERT can find the table easily. */ 2691d4b64699Sdan assert( !pParse->nested ); 2692d4b64699Sdan #ifndef SQLITE_OMIT_AUTOINCREMENT 2693d4b64699Sdan if( strcmp(p->zName, "sqlite_sequence")==0 ){ 2694d4b64699Sdan assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); 2695d4b64699Sdan p->pSchema->pSeqTab = p; 2696d4b64699Sdan } 2697d4b64699Sdan #endif 2698578277c2Sdan } 269919a8e7e8Sdanielk1977 270019a8e7e8Sdanielk1977 #ifndef SQLITE_OMIT_ALTERTABLE 2701578277c2Sdan if( !pSelect && !p->pSelect ){ 2702578277c2Sdan assert( pCons && pEnd ); 2703bab45c64Sdanielk1977 if( pCons->z==0 ){ 27045969da4aSdrh pCons = pEnd; 2705bab45c64Sdanielk1977 } 2706578277c2Sdan p->addColOffset = 13 + (int)(pCons->z - pParse->sNameToken.z); 270719a8e7e8Sdanielk1977 } 270819a8e7e8Sdanielk1977 #endif 270917e9e29dSdrh } 271075897234Sdrh 2711b7f9164eSdrh #ifndef SQLITE_OMIT_VIEW 271275897234Sdrh /* 2713a76b5dfcSdrh ** The parser calls this routine in order to create a new VIEW 2714a76b5dfcSdrh */ 27154adee20fSdanielk1977 void sqlite3CreateView( 2716a76b5dfcSdrh Parse *pParse, /* The parsing context */ 2717a76b5dfcSdrh Token *pBegin, /* The CREATE token that begins the statement */ 271848dec7e2Sdanielk1977 Token *pName1, /* The token that holds the name of the view */ 271948dec7e2Sdanielk1977 Token *pName2, /* The token that holds the name of the view */ 27208981b904Sdrh ExprList *pCNames, /* Optional list of view column names */ 27216276c1cbSdrh Select *pSelect, /* A SELECT statement that will become the new view */ 2722fdd48a76Sdrh int isTemp, /* TRUE for a TEMPORARY view */ 2723fdd48a76Sdrh int noErr /* Suppress error messages if VIEW already exists */ 2724a76b5dfcSdrh ){ 2725a76b5dfcSdrh Table *p; 27264b59ab5eSdrh int n; 2727b7916a78Sdrh const char *z; 27284b59ab5eSdrh Token sEnd; 2729f26e09c8Sdrh DbFixer sFix; 273088caeac7Sdrh Token *pName = 0; 2731da184236Sdanielk1977 int iDb; 273217435752Sdrh sqlite3 *db = pParse->db; 2733a76b5dfcSdrh 27347c3d64f1Sdrh if( pParse->nVar>0 ){ 27357c3d64f1Sdrh sqlite3ErrorMsg(pParse, "parameters are not allowed in views"); 273632498f13Sdrh goto create_view_fail; 27377c3d64f1Sdrh } 2738fdd48a76Sdrh sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr); 2739a76b5dfcSdrh p = pParse->pNewTable; 27408981b904Sdrh if( p==0 || pParse->nErr ) goto create_view_fail; 27416e5020e8Sdrh 27426e5020e8Sdrh /* Legacy versions of SQLite allowed the use of the magic "rowid" column 27436e5020e8Sdrh ** on a view, even though views do not have rowids. The following flag 27446e5020e8Sdrh ** setting fixes this problem. But the fix can be disabled by compiling 27456e5020e8Sdrh ** with -DSQLITE_ALLOW_ROWID_IN_VIEW in case there are legacy apps that 27466e5020e8Sdrh ** depend upon the old buggy behavior. */ 27476e5020e8Sdrh #ifndef SQLITE_ALLOW_ROWID_IN_VIEW 2748a6c54defSdrh p->tabFlags |= TF_NoVisibleRowid; 27496e5020e8Sdrh #endif 27506e5020e8Sdrh 2751ef2cb63eSdanielk1977 sqlite3TwoPartName(pParse, pName1, pName2, &pName); 275217435752Sdrh iDb = sqlite3SchemaToIndex(db, p->pSchema); 2753d100f691Sdrh sqlite3FixInit(&sFix, pParse, iDb, "view", pName); 27548981b904Sdrh if( sqlite3FixSelect(&sFix, pSelect) ) goto create_view_fail; 2755174b6195Sdrh 27564b59ab5eSdrh /* Make a copy of the entire SELECT statement that defines the view. 27574b59ab5eSdrh ** This will force all the Expr.token.z values to be dynamically 27584b59ab5eSdrh ** allocated rather than point to the input string - which means that 275924b03fd0Sdanielk1977 ** they will persist after the current sqlite3_exec() call returns. 27604b59ab5eSdrh */ 276138096961Sdan pSelect->selFlags |= SF_View; 2762c9461eccSdan if( IN_RENAME_OBJECT ){ 2763987db767Sdan p->pSelect = pSelect; 2764987db767Sdan pSelect = 0; 2765987db767Sdan }else{ 27666ab3a2ecSdanielk1977 p->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE); 2767987db767Sdan } 27688981b904Sdrh p->pCheck = sqlite3ExprListDup(db, pCNames, EXPRDUP_REDUCE); 27698981b904Sdrh if( db->mallocFailed ) goto create_view_fail; 27704b59ab5eSdrh 27714b59ab5eSdrh /* Locate the end of the CREATE VIEW statement. Make sEnd point to 27724b59ab5eSdrh ** the end. 27734b59ab5eSdrh */ 2774a76b5dfcSdrh sEnd = pParse->sLastToken; 27756116ee4eSdrh assert( sEnd.z[0]!=0 || sEnd.n==0 ); 27768981b904Sdrh if( sEnd.z[0]!=';' ){ 2777a76b5dfcSdrh sEnd.z += sEnd.n; 2778a76b5dfcSdrh } 2779a76b5dfcSdrh sEnd.n = 0; 27801bd10f8aSdrh n = (int)(sEnd.z - pBegin->z); 27818981b904Sdrh assert( n>0 ); 2782b7916a78Sdrh z = pBegin->z; 27838981b904Sdrh while( sqlite3Isspace(z[n-1]) ){ n--; } 27844ff6dfa7Sdrh sEnd.z = &z[n-1]; 27854ff6dfa7Sdrh sEnd.n = 1; 27864b59ab5eSdrh 2787346a70caSdrh /* Use sqlite3EndTable() to add the view to the schema table */ 27885969da4aSdrh sqlite3EndTable(pParse, 0, &sEnd, 0, 0); 27898981b904Sdrh 27908981b904Sdrh create_view_fail: 27918981b904Sdrh sqlite3SelectDelete(db, pSelect); 2792e8ab40d2Sdan if( IN_RENAME_OBJECT ){ 2793e8ab40d2Sdan sqlite3RenameExprlistUnmap(pParse, pCNames); 2794e8ab40d2Sdan } 27958981b904Sdrh sqlite3ExprListDelete(db, pCNames); 2796a76b5dfcSdrh return; 2797417be79cSdrh } 2798b7f9164eSdrh #endif /* SQLITE_OMIT_VIEW */ 2799a76b5dfcSdrh 2800fe3fcbe2Sdanielk1977 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) 2801417be79cSdrh /* 2802417be79cSdrh ** The Table structure pTable is really a VIEW. Fill in the names of 2803417be79cSdrh ** the columns of the view in the pTable structure. Return the number 2804cfa5684dSjplyon ** of errors. If an error is seen leave an error message in pParse->zErrMsg. 2805417be79cSdrh */ 28064adee20fSdanielk1977 int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){ 28079b3187e1Sdrh Table *pSelTab; /* A fake table from which we get the result set */ 28089b3187e1Sdrh Select *pSel; /* Copy of the SELECT that implements the view */ 28099b3187e1Sdrh int nErr = 0; /* Number of errors encountered */ 28109b3187e1Sdrh int n; /* Temporarily holds the number of cursors assigned */ 281117435752Sdrh sqlite3 *db = pParse->db; /* Database connection for malloc errors */ 2812dc6b41edSdrh #ifndef SQLITE_OMIT_VIRTUALTABLE 2813dc6b41edSdrh int rc; 2814dc6b41edSdrh #endif 2815a0daa751Sdrh #ifndef SQLITE_OMIT_AUTHORIZATION 281632c6a48bSdrh sqlite3_xauth xAuth; /* Saved xAuth pointer */ 2817a0daa751Sdrh #endif 2818417be79cSdrh 2819417be79cSdrh assert( pTable ); 2820417be79cSdrh 2821fe3fcbe2Sdanielk1977 #ifndef SQLITE_OMIT_VIRTUALTABLE 2822dc6b41edSdrh db->nSchemaLock++; 2823dc6b41edSdrh rc = sqlite3VtabCallConnect(pParse, pTable); 2824dc6b41edSdrh db->nSchemaLock--; 2825dc6b41edSdrh if( rc ){ 2826efaffb64Sdrh return 1; 2827fe3fcbe2Sdanielk1977 } 28284cbdda9eSdrh if( IsVirtual(pTable) ) return 0; 2829fe3fcbe2Sdanielk1977 #endif 2830fe3fcbe2Sdanielk1977 2831fe3fcbe2Sdanielk1977 #ifndef SQLITE_OMIT_VIEW 2832417be79cSdrh /* A positive nCol means the columns names for this view are 2833417be79cSdrh ** already known. 2834417be79cSdrh */ 2835417be79cSdrh if( pTable->nCol>0 ) return 0; 2836417be79cSdrh 2837417be79cSdrh /* A negative nCol is a special marker meaning that we are currently 2838417be79cSdrh ** trying to compute the column names. If we enter this routine with 2839417be79cSdrh ** a negative nCol, it means two or more views form a loop, like this: 2840417be79cSdrh ** 2841417be79cSdrh ** CREATE VIEW one AS SELECT * FROM two; 2842417be79cSdrh ** CREATE VIEW two AS SELECT * FROM one; 28433b167c75Sdrh ** 2844768578eeSdrh ** Actually, the error above is now caught prior to reaching this point. 2845768578eeSdrh ** But the following test is still important as it does come up 2846768578eeSdrh ** in the following: 2847768578eeSdrh ** 2848768578eeSdrh ** CREATE TABLE main.ex1(a); 2849768578eeSdrh ** CREATE TEMP VIEW ex1 AS SELECT a FROM ex1; 2850768578eeSdrh ** SELECT * FROM temp.ex1; 2851417be79cSdrh */ 2852417be79cSdrh if( pTable->nCol<0 ){ 28534adee20fSdanielk1977 sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName); 2854417be79cSdrh return 1; 2855417be79cSdrh } 285685c23c61Sdrh assert( pTable->nCol>=0 ); 2857417be79cSdrh 2858417be79cSdrh /* If we get this far, it means we need to compute the table names. 28599b3187e1Sdrh ** Note that the call to sqlite3ResultSetOfSelect() will expand any 28609b3187e1Sdrh ** "*" elements in the results set of the view and will assign cursors 28619b3187e1Sdrh ** to the elements of the FROM clause. But we do not want these changes 28629b3187e1Sdrh ** to be permanent. So the computation is done on a copy of the SELECT 28639b3187e1Sdrh ** statement that defines the view. 2864417be79cSdrh */ 28659b3187e1Sdrh assert( pTable->pSelect ); 28666ab3a2ecSdanielk1977 pSel = sqlite3SelectDup(db, pTable->pSelect, 0); 2867261919ccSdanielk1977 if( pSel ){ 28680208337cSdan u8 eParseMode = pParse->eParseMode; 28690208337cSdan pParse->eParseMode = PARSE_MODE_NORMAL; 28709b3187e1Sdrh n = pParse->nTab; 28719b3187e1Sdrh sqlite3SrcListAssignCursors(pParse, pSel->pSrc); 2872417be79cSdrh pTable->nCol = -1; 287331f69626Sdrh DisableLookaside; 2874db2d286bSdanielk1977 #ifndef SQLITE_OMIT_AUTHORIZATION 2875a6d0ffc3Sdrh xAuth = db->xAuth; 2876a6d0ffc3Sdrh db->xAuth = 0; 287796fb16eeSdrh pSelTab = sqlite3ResultSetOfSelect(pParse, pSel, SQLITE_AFF_NONE); 2878a6d0ffc3Sdrh db->xAuth = xAuth; 2879db2d286bSdanielk1977 #else 288096fb16eeSdrh pSelTab = sqlite3ResultSetOfSelect(pParse, pSel, SQLITE_AFF_NONE); 2881db2d286bSdanielk1977 #endif 28829b3187e1Sdrh pParse->nTab = n; 28835d59102aSdan if( pSelTab==0 ){ 28845d59102aSdan pTable->nCol = 0; 28855d59102aSdan nErr++; 28865d59102aSdan }else if( pTable->pCheck ){ 2887ed06a131Sdrh /* CREATE VIEW name(arglist) AS ... 2888ed06a131Sdrh ** The names of the columns in the table are taken from 2889ed06a131Sdrh ** arglist which is stored in pTable->pCheck. The pCheck field 2890ed06a131Sdrh ** normally holds CHECK constraints on an ordinary table, but for 2891ed06a131Sdrh ** a VIEW it holds the list of column names. 2892ed06a131Sdrh */ 2893ed06a131Sdrh sqlite3ColumnsFromExprList(pParse, pTable->pCheck, 2894ed06a131Sdrh &pTable->nCol, &pTable->aCol); 2895ed06a131Sdrh if( db->mallocFailed==0 28964c983b2fSdrh && pParse->nErr==0 2897ed06a131Sdrh && pTable->nCol==pSel->pEList->nExpr 2898ed06a131Sdrh ){ 289996fb16eeSdrh sqlite3SelectAddColumnTypeAndCollation(pParse, pTable, pSel, 290096fb16eeSdrh SQLITE_AFF_NONE); 2901ed06a131Sdrh } 29025d59102aSdan }else{ 2903ed06a131Sdrh /* CREATE VIEW name AS... without an argument list. Construct 2904ed06a131Sdrh ** the column names from the SELECT statement that defines the view. 2905ed06a131Sdrh */ 2906417be79cSdrh assert( pTable->aCol==0 ); 290703836614Sdrh pTable->nCol = pSelTab->nCol; 2908417be79cSdrh pTable->aCol = pSelTab->aCol; 29093dc864b5Sdan pTable->tabFlags |= (pSelTab->tabFlags & COLFLAG_NOINSERT); 2910417be79cSdrh pSelTab->nCol = 0; 2911417be79cSdrh pSelTab->aCol = 0; 29122120608eSdrh assert( sqlite3SchemaMutexHeld(db, 0, pTable->pSchema) ); 2913417be79cSdrh } 291403836614Sdrh pTable->nNVCol = pTable->nCol; 2915e8da01c1Sdrh sqlite3DeleteTable(db, pSelTab); 2916633e6d57Sdrh sqlite3SelectDelete(db, pSel); 291731f69626Sdrh EnableLookaside; 29180208337cSdan pParse->eParseMode = eParseMode; 2919261919ccSdanielk1977 } else { 2920261919ccSdanielk1977 nErr++; 2921261919ccSdanielk1977 } 29228981b904Sdrh pTable->pSchema->schemaFlags |= DB_UnresetViews; 292377f3f402Sdan if( db->mallocFailed ){ 292477f3f402Sdan sqlite3DeleteColumnNames(db, pTable); 292577f3f402Sdan pTable->aCol = 0; 292677f3f402Sdan pTable->nCol = 0; 292777f3f402Sdan } 2928b7f9164eSdrh #endif /* SQLITE_OMIT_VIEW */ 29294b2688abSdanielk1977 return nErr; 2930fe3fcbe2Sdanielk1977 } 2931fe3fcbe2Sdanielk1977 #endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */ 2932417be79cSdrh 2933b7f9164eSdrh #ifndef SQLITE_OMIT_VIEW 2934417be79cSdrh /* 29358bf8dc92Sdrh ** Clear the column names from every VIEW in database idx. 2936417be79cSdrh */ 29379bb575fdSdrh static void sqliteViewResetAll(sqlite3 *db, int idx){ 2938417be79cSdrh HashElem *i; 29392120608eSdrh assert( sqlite3SchemaMutexHeld(db, idx, 0) ); 29408bf8dc92Sdrh if( !DbHasProperty(db, idx, DB_UnresetViews) ) return; 2941da184236Sdanielk1977 for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){ 2942417be79cSdrh Table *pTab = sqliteHashData(i); 2943417be79cSdrh if( pTab->pSelect ){ 294451be3873Sdrh sqlite3DeleteColumnNames(db, pTab); 2945d46def77Sdan pTab->aCol = 0; 2946d46def77Sdan pTab->nCol = 0; 2947417be79cSdrh } 2948417be79cSdrh } 29498bf8dc92Sdrh DbClearProperty(db, idx, DB_UnresetViews); 2950a76b5dfcSdrh } 2951b7f9164eSdrh #else 2952b7f9164eSdrh # define sqliteViewResetAll(A,B) 2953b7f9164eSdrh #endif /* SQLITE_OMIT_VIEW */ 2954a76b5dfcSdrh 295575897234Sdrh /* 2956a0bf2652Sdanielk1977 ** This function is called by the VDBE to adjust the internal schema 2957a0bf2652Sdanielk1977 ** used by SQLite when the btree layer moves a table root page. The 2958a0bf2652Sdanielk1977 ** root-page of a table or index in database iDb has changed from iFrom 2959a0bf2652Sdanielk1977 ** to iTo. 29606205d4a4Sdrh ** 29616205d4a4Sdrh ** Ticket #1728: The symbol table might still contain information 29626205d4a4Sdrh ** on tables and/or indices that are the process of being deleted. 29636205d4a4Sdrh ** If you are unlucky, one of those deleted indices or tables might 29646205d4a4Sdrh ** have the same rootpage number as the real table or index that is 29656205d4a4Sdrh ** being moved. So we cannot stop searching after the first match 29666205d4a4Sdrh ** because the first match might be for one of the deleted indices 29676205d4a4Sdrh ** or tables and not the table/index that is actually being moved. 29686205d4a4Sdrh ** We must continue looping until all tables and indices with 29696205d4a4Sdrh ** rootpage==iFrom have been converted to have a rootpage of iTo 29706205d4a4Sdrh ** in order to be certain that we got the right one. 2971a0bf2652Sdanielk1977 */ 2972a0bf2652Sdanielk1977 #ifndef SQLITE_OMIT_AUTOVACUUM 2973abc38158Sdrh void sqlite3RootPageMoved(sqlite3 *db, int iDb, Pgno iFrom, Pgno iTo){ 2974a0bf2652Sdanielk1977 HashElem *pElem; 2975da184236Sdanielk1977 Hash *pHash; 2976cdf011dcSdrh Db *pDb; 2977a0bf2652Sdanielk1977 2978cdf011dcSdrh assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); 2979cdf011dcSdrh pDb = &db->aDb[iDb]; 2980da184236Sdanielk1977 pHash = &pDb->pSchema->tblHash; 2981da184236Sdanielk1977 for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){ 2982a0bf2652Sdanielk1977 Table *pTab = sqliteHashData(pElem); 2983a0bf2652Sdanielk1977 if( pTab->tnum==iFrom ){ 2984a0bf2652Sdanielk1977 pTab->tnum = iTo; 2985a0bf2652Sdanielk1977 } 2986a0bf2652Sdanielk1977 } 2987da184236Sdanielk1977 pHash = &pDb->pSchema->idxHash; 2988da184236Sdanielk1977 for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){ 2989a0bf2652Sdanielk1977 Index *pIdx = sqliteHashData(pElem); 2990a0bf2652Sdanielk1977 if( pIdx->tnum==iFrom ){ 2991a0bf2652Sdanielk1977 pIdx->tnum = iTo; 2992a0bf2652Sdanielk1977 } 2993a0bf2652Sdanielk1977 } 2994a0bf2652Sdanielk1977 } 2995a0bf2652Sdanielk1977 #endif 2996a0bf2652Sdanielk1977 2997a0bf2652Sdanielk1977 /* 2998a0bf2652Sdanielk1977 ** Write code to erase the table with root-page iTable from database iDb. 29991e32bed3Sdrh ** Also write code to modify the sqlite_schema table and internal schema 3000a0bf2652Sdanielk1977 ** if a root-page of another table is moved by the btree-layer whilst 3001a0bf2652Sdanielk1977 ** erasing iTable (this can happen with an auto-vacuum database). 3002a0bf2652Sdanielk1977 */ 30034e0cff60Sdrh static void destroyRootPage(Parse *pParse, int iTable, int iDb){ 30044e0cff60Sdrh Vdbe *v = sqlite3GetVdbe(pParse); 3005b7654111Sdrh int r1 = sqlite3GetTempReg(pParse); 300619918882Sdrh if( iTable<2 ) sqlite3ErrorMsg(pParse, "corrupt schema"); 3007b7654111Sdrh sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb); 3008e0af83acSdan sqlite3MayAbort(pParse); 300940e016e4Sdrh #ifndef SQLITE_OMIT_AUTOVACUUM 3010b7654111Sdrh /* OP_Destroy stores an in integer r1. If this integer 30114e0cff60Sdrh ** is non-zero, then it is the root page number of a table moved to 30121e32bed3Sdrh ** location iTable. The following code modifies the sqlite_schema table to 30134e0cff60Sdrh ** reflect this. 30144e0cff60Sdrh ** 30150fa991b9Sdrh ** The "#NNN" in the SQL is a special constant that means whatever value 3016b74b1017Sdrh ** is in register NNN. See grammar rules associated with the TK_REGISTER 3017b74b1017Sdrh ** token for additional information. 30184e0cff60Sdrh */ 301963e3e9f8Sdanielk1977 sqlite3NestedParse(pParse, 3020346a70caSdrh "UPDATE %Q." DFLT_SCHEMA_TABLE 3021346a70caSdrh " SET rootpage=%d WHERE #%d AND rootpage=#%d", 3022346a70caSdrh pParse->db->aDb[iDb].zDbSName, iTable, r1, r1); 3023a0bf2652Sdanielk1977 #endif 3024b7654111Sdrh sqlite3ReleaseTempReg(pParse, r1); 3025a0bf2652Sdanielk1977 } 3026a0bf2652Sdanielk1977 3027a0bf2652Sdanielk1977 /* 3028a0bf2652Sdanielk1977 ** Write VDBE code to erase table pTab and all associated indices on disk. 30291e32bed3Sdrh ** Code to update the sqlite_schema tables and internal schema definitions 3030a0bf2652Sdanielk1977 ** in case a root-page belonging to another table is moved by the btree layer 3031a0bf2652Sdanielk1977 ** is also added (this can happen with an auto-vacuum database). 3032a0bf2652Sdanielk1977 */ 30334e0cff60Sdrh static void destroyTable(Parse *pParse, Table *pTab){ 3034a0bf2652Sdanielk1977 /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM 3035a0bf2652Sdanielk1977 ** is not defined), then it is important to call OP_Destroy on the 3036a0bf2652Sdanielk1977 ** table and index root-pages in order, starting with the numerically 3037a0bf2652Sdanielk1977 ** largest root-page number. This guarantees that none of the root-pages 3038a0bf2652Sdanielk1977 ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the 3039a0bf2652Sdanielk1977 ** following were coded: 3040a0bf2652Sdanielk1977 ** 3041a0bf2652Sdanielk1977 ** OP_Destroy 4 0 3042a0bf2652Sdanielk1977 ** ... 3043a0bf2652Sdanielk1977 ** OP_Destroy 5 0 3044a0bf2652Sdanielk1977 ** 3045a0bf2652Sdanielk1977 ** and root page 5 happened to be the largest root-page number in the 3046a0bf2652Sdanielk1977 ** database, then root page 5 would be moved to page 4 by the 3047a0bf2652Sdanielk1977 ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit 3048a0bf2652Sdanielk1977 ** a free-list page. 3049a0bf2652Sdanielk1977 */ 3050abc38158Sdrh Pgno iTab = pTab->tnum; 30518deae5adSdrh Pgno iDestroyed = 0; 3052a0bf2652Sdanielk1977 3053a0bf2652Sdanielk1977 while( 1 ){ 3054a0bf2652Sdanielk1977 Index *pIdx; 30558deae5adSdrh Pgno iLargest = 0; 3056a0bf2652Sdanielk1977 3057a0bf2652Sdanielk1977 if( iDestroyed==0 || iTab<iDestroyed ){ 3058a0bf2652Sdanielk1977 iLargest = iTab; 3059a0bf2652Sdanielk1977 } 3060a0bf2652Sdanielk1977 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ 3061abc38158Sdrh Pgno iIdx = pIdx->tnum; 3062da184236Sdanielk1977 assert( pIdx->pSchema==pTab->pSchema ); 3063a0bf2652Sdanielk1977 if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){ 3064a0bf2652Sdanielk1977 iLargest = iIdx; 3065a0bf2652Sdanielk1977 } 3066a0bf2652Sdanielk1977 } 3067da184236Sdanielk1977 if( iLargest==0 ){ 3068da184236Sdanielk1977 return; 3069da184236Sdanielk1977 }else{ 3070da184236Sdanielk1977 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema); 30715a05be1bSdrh assert( iDb>=0 && iDb<pParse->db->nDb ); 3072da184236Sdanielk1977 destroyRootPage(pParse, iLargest, iDb); 3073a0bf2652Sdanielk1977 iDestroyed = iLargest; 3074a0bf2652Sdanielk1977 } 3075da184236Sdanielk1977 } 3076a0bf2652Sdanielk1977 } 3077a0bf2652Sdanielk1977 3078a0bf2652Sdanielk1977 /* 307974e7c8f5Sdrh ** Remove entries from the sqlite_statN tables (for N in (1,2,3)) 3080a5ae4c33Sdrh ** after a DROP INDEX or DROP TABLE command. 3081a5ae4c33Sdrh */ 3082a5ae4c33Sdrh static void sqlite3ClearStatTables( 3083a5ae4c33Sdrh Parse *pParse, /* The parsing context */ 3084a5ae4c33Sdrh int iDb, /* The database number */ 3085a5ae4c33Sdrh const char *zType, /* "idx" or "tbl" */ 3086a5ae4c33Sdrh const char *zName /* Name of index or table */ 3087a5ae4c33Sdrh ){ 3088a5ae4c33Sdrh int i; 308969c33826Sdrh const char *zDbName = pParse->db->aDb[iDb].zDbSName; 3090f52bb8d3Sdan for(i=1; i<=4; i++){ 309174e7c8f5Sdrh char zTab[24]; 309274e7c8f5Sdrh sqlite3_snprintf(sizeof(zTab),zTab,"sqlite_stat%d",i); 309374e7c8f5Sdrh if( sqlite3FindTable(pParse->db, zTab, zDbName) ){ 3094a5ae4c33Sdrh sqlite3NestedParse(pParse, 3095a5ae4c33Sdrh "DELETE FROM %Q.%s WHERE %s=%Q", 309674e7c8f5Sdrh zDbName, zTab, zType, zName 3097a5ae4c33Sdrh ); 3098a5ae4c33Sdrh } 3099a5ae4c33Sdrh } 3100a5ae4c33Sdrh } 3101a5ae4c33Sdrh 3102a5ae4c33Sdrh /* 3103faacf17cSdrh ** Generate code to drop a table. 3104faacf17cSdrh */ 3105faacf17cSdrh void sqlite3CodeDropTable(Parse *pParse, Table *pTab, int iDb, int isView){ 3106faacf17cSdrh Vdbe *v; 3107faacf17cSdrh sqlite3 *db = pParse->db; 3108faacf17cSdrh Trigger *pTrigger; 3109faacf17cSdrh Db *pDb = &db->aDb[iDb]; 3110faacf17cSdrh 3111faacf17cSdrh v = sqlite3GetVdbe(pParse); 3112faacf17cSdrh assert( v!=0 ); 3113faacf17cSdrh sqlite3BeginWriteOperation(pParse, 1, iDb); 3114faacf17cSdrh 3115faacf17cSdrh #ifndef SQLITE_OMIT_VIRTUALTABLE 3116faacf17cSdrh if( IsVirtual(pTab) ){ 3117faacf17cSdrh sqlite3VdbeAddOp0(v, OP_VBegin); 3118faacf17cSdrh } 3119faacf17cSdrh #endif 3120faacf17cSdrh 3121faacf17cSdrh /* Drop all triggers associated with the table being dropped. Code 31221e32bed3Sdrh ** is generated to remove entries from sqlite_schema and/or 31231e32bed3Sdrh ** sqlite_temp_schema if required. 3124faacf17cSdrh */ 3125faacf17cSdrh pTrigger = sqlite3TriggerList(pParse, pTab); 3126faacf17cSdrh while( pTrigger ){ 3127faacf17cSdrh assert( pTrigger->pSchema==pTab->pSchema || 3128faacf17cSdrh pTrigger->pSchema==db->aDb[1].pSchema ); 3129faacf17cSdrh sqlite3DropTriggerPtr(pParse, pTrigger); 3130faacf17cSdrh pTrigger = pTrigger->pNext; 3131faacf17cSdrh } 3132faacf17cSdrh 3133faacf17cSdrh #ifndef SQLITE_OMIT_AUTOINCREMENT 3134faacf17cSdrh /* Remove any entries of the sqlite_sequence table associated with 3135faacf17cSdrh ** the table being dropped. This is done before the table is dropped 3136faacf17cSdrh ** at the btree level, in case the sqlite_sequence table needs to 3137faacf17cSdrh ** move as a result of the drop (can happen in auto-vacuum mode). 3138faacf17cSdrh */ 3139faacf17cSdrh if( pTab->tabFlags & TF_Autoincrement ){ 3140faacf17cSdrh sqlite3NestedParse(pParse, 3141faacf17cSdrh "DELETE FROM %Q.sqlite_sequence WHERE name=%Q", 314269c33826Sdrh pDb->zDbSName, pTab->zName 3143faacf17cSdrh ); 3144faacf17cSdrh } 3145faacf17cSdrh #endif 3146faacf17cSdrh 3147346a70caSdrh /* Drop all entries in the schema table that refer to the 3148067b92baSdrh ** table. The program name loops through the schema table and deletes 3149faacf17cSdrh ** every row that refers to a table of the same name as the one being 315048864df9Smistachkin ** dropped. Triggers are handled separately because a trigger can be 3151faacf17cSdrh ** created in the temp database that refers to a table in another 3152faacf17cSdrh ** database. 3153faacf17cSdrh */ 3154faacf17cSdrh sqlite3NestedParse(pParse, 3155346a70caSdrh "DELETE FROM %Q." DFLT_SCHEMA_TABLE 3156346a70caSdrh " WHERE tbl_name=%Q and type!='trigger'", 3157346a70caSdrh pDb->zDbSName, pTab->zName); 3158faacf17cSdrh if( !isView && !IsVirtual(pTab) ){ 3159faacf17cSdrh destroyTable(pParse, pTab); 3160faacf17cSdrh } 3161faacf17cSdrh 3162faacf17cSdrh /* Remove the table entry from SQLite's internal schema and modify 3163faacf17cSdrh ** the schema cookie. 3164faacf17cSdrh */ 3165faacf17cSdrh if( IsVirtual(pTab) ){ 3166faacf17cSdrh sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0); 31671d4b1640Sdan sqlite3MayAbort(pParse); 3168faacf17cSdrh } 3169faacf17cSdrh sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0); 3170faacf17cSdrh sqlite3ChangeCookie(pParse, iDb); 3171faacf17cSdrh sqliteViewResetAll(db, iDb); 3172faacf17cSdrh } 3173faacf17cSdrh 3174faacf17cSdrh /* 3175070ae3beSdrh ** Return TRUE if shadow tables should be read-only in the current 3176070ae3beSdrh ** context. 3177070ae3beSdrh */ 3178070ae3beSdrh int sqlite3ReadOnlyShadowTables(sqlite3 *db){ 3179070ae3beSdrh #ifndef SQLITE_OMIT_VIRTUALTABLE 3180070ae3beSdrh if( (db->flags & SQLITE_Defensive)!=0 3181070ae3beSdrh && db->pVtabCtx==0 3182070ae3beSdrh && db->nVdbeExec==0 318373983658Sdan && !sqlite3VtabInSync(db) 3184070ae3beSdrh ){ 3185070ae3beSdrh return 1; 3186070ae3beSdrh } 3187070ae3beSdrh #endif 3188070ae3beSdrh return 0; 3189070ae3beSdrh } 3190070ae3beSdrh 3191070ae3beSdrh /* 3192d0c51d1aSdrh ** Return true if it is not allowed to drop the given table 3193d0c51d1aSdrh */ 3194070ae3beSdrh static int tableMayNotBeDropped(sqlite3 *db, Table *pTab){ 3195d0c51d1aSdrh if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){ 3196d0c51d1aSdrh if( sqlite3StrNICmp(pTab->zName+7, "stat", 4)==0 ) return 0; 3197d0c51d1aSdrh if( sqlite3StrNICmp(pTab->zName+7, "parameters", 10)==0 ) return 0; 3198d0c51d1aSdrh return 1; 3199d0c51d1aSdrh } 3200070ae3beSdrh if( (pTab->tabFlags & TF_Shadow)!=0 && sqlite3ReadOnlyShadowTables(db) ){ 3201070ae3beSdrh return 1; 3202d0c51d1aSdrh } 3203d0c51d1aSdrh return 0; 3204d0c51d1aSdrh } 3205d0c51d1aSdrh 3206d0c51d1aSdrh /* 320775897234Sdrh ** This routine is called to do the work of a DROP TABLE statement. 3208d9b0257aSdrh ** pName is the name of the table to be dropped. 320975897234Sdrh */ 3210a073384fSdrh void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){ 3211a8858103Sdanielk1977 Table *pTab; 321275897234Sdrh Vdbe *v; 32139bb575fdSdrh sqlite3 *db = pParse->db; 3214d24cc427Sdrh int iDb; 321575897234Sdrh 32168af73d41Sdrh if( db->mallocFailed ){ 32176f7adc8aSdrh goto exit_drop_table; 32186f7adc8aSdrh } 32198af73d41Sdrh assert( pParse->nErr==0 ); 3220a8858103Sdanielk1977 assert( pName->nSrc==1 ); 322175209969Sdrh if( sqlite3ReadSchema(pParse) ) goto exit_drop_table; 3222a7564663Sdrh if( noErr ) db->suppressErr++; 32234d249e61Sdrh assert( isView==0 || isView==LOCATE_VIEW ); 322441fb5cd1Sdan pTab = sqlite3LocateTableItem(pParse, isView, &pName->a[0]); 3225a7564663Sdrh if( noErr ) db->suppressErr--; 3226a8858103Sdanielk1977 3227a073384fSdrh if( pTab==0 ){ 322831da7be9Sdrh if( noErr ){ 322931da7be9Sdrh sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase); 323031da7be9Sdrh sqlite3ForceNotReadOnly(pParse); 323131da7be9Sdrh } 3232a073384fSdrh goto exit_drop_table; 3233a073384fSdrh } 3234da184236Sdanielk1977 iDb = sqlite3SchemaToIndex(db, pTab->pSchema); 3235e22a334bSdrh assert( iDb>=0 && iDb<db->nDb ); 3236b5258c3dSdanielk1977 3237b5258c3dSdanielk1977 /* If pTab is a virtual table, call ViewGetColumnNames() to ensure 3238b5258c3dSdanielk1977 ** it is initialized. 3239b5258c3dSdanielk1977 */ 3240b5258c3dSdanielk1977 if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){ 3241b5258c3dSdanielk1977 goto exit_drop_table; 3242b5258c3dSdanielk1977 } 3243e5f9c644Sdrh #ifndef SQLITE_OMIT_AUTHORIZATION 3244e5f9c644Sdrh { 3245e5f9c644Sdrh int code; 3246da184236Sdanielk1977 const char *zTab = SCHEMA_TABLE(iDb); 324769c33826Sdrh const char *zDb = db->aDb[iDb].zDbSName; 3248f1a381e7Sdanielk1977 const char *zArg2 = 0; 32494adee20fSdanielk1977 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){ 3250a8858103Sdanielk1977 goto exit_drop_table; 3251e22a334bSdrh } 3252e5f9c644Sdrh if( isView ){ 325353c0f748Sdanielk1977 if( !OMIT_TEMPDB && iDb==1 ){ 3254e5f9c644Sdrh code = SQLITE_DROP_TEMP_VIEW; 3255e5f9c644Sdrh }else{ 3256e5f9c644Sdrh code = SQLITE_DROP_VIEW; 3257e5f9c644Sdrh } 32584b2688abSdanielk1977 #ifndef SQLITE_OMIT_VIRTUALTABLE 3259f1a381e7Sdanielk1977 }else if( IsVirtual(pTab) ){ 3260f1a381e7Sdanielk1977 code = SQLITE_DROP_VTABLE; 3261595a523aSdanielk1977 zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName; 32624b2688abSdanielk1977 #endif 3263e5f9c644Sdrh }else{ 326453c0f748Sdanielk1977 if( !OMIT_TEMPDB && iDb==1 ){ 3265e5f9c644Sdrh code = SQLITE_DROP_TEMP_TABLE; 3266e5f9c644Sdrh }else{ 3267e5f9c644Sdrh code = SQLITE_DROP_TABLE; 3268e5f9c644Sdrh } 3269e5f9c644Sdrh } 3270f1a381e7Sdanielk1977 if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){ 3271a8858103Sdanielk1977 goto exit_drop_table; 3272e5f9c644Sdrh } 3273a8858103Sdanielk1977 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){ 3274a8858103Sdanielk1977 goto exit_drop_table; 327577ad4e41Sdrh } 3276e5f9c644Sdrh } 3277e5f9c644Sdrh #endif 3278070ae3beSdrh if( tableMayNotBeDropped(db, pTab) ){ 3279a8858103Sdanielk1977 sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName); 3280a8858103Sdanielk1977 goto exit_drop_table; 328175897234Sdrh } 3282576ec6b3Sdanielk1977 3283576ec6b3Sdanielk1977 #ifndef SQLITE_OMIT_VIEW 3284576ec6b3Sdanielk1977 /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used 3285576ec6b3Sdanielk1977 ** on a table. 3286576ec6b3Sdanielk1977 */ 3287a8858103Sdanielk1977 if( isView && pTab->pSelect==0 ){ 3288a8858103Sdanielk1977 sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName); 3289a8858103Sdanielk1977 goto exit_drop_table; 32904ff6dfa7Sdrh } 3291a8858103Sdanielk1977 if( !isView && pTab->pSelect ){ 3292a8858103Sdanielk1977 sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName); 3293a8858103Sdanielk1977 goto exit_drop_table; 32944ff6dfa7Sdrh } 3295576ec6b3Sdanielk1977 #endif 329675897234Sdrh 3297067b92baSdrh /* Generate code to remove the table from the schema table 32981ccde15dSdrh ** on disk. 32991ccde15dSdrh */ 33004adee20fSdanielk1977 v = sqlite3GetVdbe(pParse); 330175897234Sdrh if( v ){ 330277658e2fSdrh sqlite3BeginWriteOperation(pParse, 1, iDb); 33030fc2da3fSmistachkin if( !isView ){ 3304a5ae4c33Sdrh sqlite3ClearStatTables(pParse, iDb, "tbl", pTab->zName); 3305e0bc4048Sdrh sqlite3FkDropTable(pParse, pName, pTab); 33060fc2da3fSmistachkin } 3307faacf17cSdrh sqlite3CodeDropTable(pParse, pTab, iDb, isView); 33084ff6dfa7Sdrh } 33092958a4e6Sdrh 3310a8858103Sdanielk1977 exit_drop_table: 3311633e6d57Sdrh sqlite3SrcListDelete(db, pName); 331275897234Sdrh } 331375897234Sdrh 331475897234Sdrh /* 3315c2eef3b3Sdrh ** This routine is called to create a new foreign key on the table 3316c2eef3b3Sdrh ** currently under construction. pFromCol determines which columns 3317c2eef3b3Sdrh ** in the current table point to the foreign key. If pFromCol==0 then 3318c2eef3b3Sdrh ** connect the key to the last column inserted. pTo is the name of 3319bd50a926Sdrh ** the table referred to (a.k.a the "parent" table). pToCol is a list 3320bd50a926Sdrh ** of tables in the parent pTo table. flags contains all 3321c2eef3b3Sdrh ** information about the conflict resolution algorithms specified 3322c2eef3b3Sdrh ** in the ON DELETE, ON UPDATE and ON INSERT clauses. 3323c2eef3b3Sdrh ** 3324c2eef3b3Sdrh ** An FKey structure is created and added to the table currently 3325e61922a6Sdrh ** under construction in the pParse->pNewTable field. 3326c2eef3b3Sdrh ** 3327c2eef3b3Sdrh ** The foreign key is set for IMMEDIATE processing. A subsequent call 33284adee20fSdanielk1977 ** to sqlite3DeferForeignKey() might change this to DEFERRED. 3329c2eef3b3Sdrh */ 33304adee20fSdanielk1977 void sqlite3CreateForeignKey( 3331c2eef3b3Sdrh Parse *pParse, /* Parsing context */ 33320202b29eSdanielk1977 ExprList *pFromCol, /* Columns in this table that point to other table */ 3333c2eef3b3Sdrh Token *pTo, /* Name of the other table */ 33340202b29eSdanielk1977 ExprList *pToCol, /* Columns in the other table */ 3335c2eef3b3Sdrh int flags /* Conflict resolution algorithms. */ 3336c2eef3b3Sdrh ){ 33371857693dSdanielk1977 sqlite3 *db = pParse->db; 3338b7f9164eSdrh #ifndef SQLITE_OMIT_FOREIGN_KEY 333940e016e4Sdrh FKey *pFKey = 0; 33401da40a38Sdan FKey *pNextTo; 3341c2eef3b3Sdrh Table *p = pParse->pNewTable; 3342c2eef3b3Sdrh int nByte; 3343c2eef3b3Sdrh int i; 3344c2eef3b3Sdrh int nCol; 3345c2eef3b3Sdrh char *z; 3346c2eef3b3Sdrh 3347c2eef3b3Sdrh assert( pTo!=0 ); 33488af73d41Sdrh if( p==0 || IN_DECLARE_VTAB ) goto fk_end; 3349c2eef3b3Sdrh if( pFromCol==0 ){ 3350c2eef3b3Sdrh int iCol = p->nCol-1; 3351d3001711Sdrh if( NEVER(iCol<0) ) goto fk_end; 33520202b29eSdanielk1977 if( pToCol && pToCol->nExpr!=1 ){ 33534adee20fSdanielk1977 sqlite3ErrorMsg(pParse, "foreign key on %s" 3354f7a9e1acSdrh " should reference only one column of table %T", 3355f7a9e1acSdrh p->aCol[iCol].zName, pTo); 3356c2eef3b3Sdrh goto fk_end; 3357c2eef3b3Sdrh } 3358c2eef3b3Sdrh nCol = 1; 33590202b29eSdanielk1977 }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){ 33604adee20fSdanielk1977 sqlite3ErrorMsg(pParse, 3361c2eef3b3Sdrh "number of columns in foreign key does not match the number of " 3362f7a9e1acSdrh "columns in the referenced table"); 3363c2eef3b3Sdrh goto fk_end; 3364c2eef3b3Sdrh }else{ 33650202b29eSdanielk1977 nCol = pFromCol->nExpr; 3366c2eef3b3Sdrh } 3367e61922a6Sdrh nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1; 3368c2eef3b3Sdrh if( pToCol ){ 33690202b29eSdanielk1977 for(i=0; i<pToCol->nExpr; i++){ 337041cee668Sdrh nByte += sqlite3Strlen30(pToCol->a[i].zEName) + 1; 3371c2eef3b3Sdrh } 3372c2eef3b3Sdrh } 3373633e6d57Sdrh pFKey = sqlite3DbMallocZero(db, nByte ); 337417435752Sdrh if( pFKey==0 ){ 337517435752Sdrh goto fk_end; 337617435752Sdrh } 3377c2eef3b3Sdrh pFKey->pFrom = p; 3378c2eef3b3Sdrh pFKey->pNextFrom = p->pFKey; 3379e61922a6Sdrh z = (char*)&pFKey->aCol[nCol]; 3380df68f6b7Sdrh pFKey->zTo = z; 3381c9461eccSdan if( IN_RENAME_OBJECT ){ 3382c9461eccSdan sqlite3RenameTokenMap(pParse, (void*)z, pTo); 3383c9461eccSdan } 3384c2eef3b3Sdrh memcpy(z, pTo->z, pTo->n); 3385c2eef3b3Sdrh z[pTo->n] = 0; 338670d9e9ccSdanielk1977 sqlite3Dequote(z); 3387c2eef3b3Sdrh z += pTo->n+1; 3388c2eef3b3Sdrh pFKey->nCol = nCol; 3389c2eef3b3Sdrh if( pFromCol==0 ){ 3390c2eef3b3Sdrh pFKey->aCol[0].iFrom = p->nCol-1; 3391c2eef3b3Sdrh }else{ 3392c2eef3b3Sdrh for(i=0; i<nCol; i++){ 3393c2eef3b3Sdrh int j; 3394c2eef3b3Sdrh for(j=0; j<p->nCol; j++){ 339541cee668Sdrh if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zEName)==0 ){ 3396c2eef3b3Sdrh pFKey->aCol[i].iFrom = j; 3397c2eef3b3Sdrh break; 3398c2eef3b3Sdrh } 3399c2eef3b3Sdrh } 3400c2eef3b3Sdrh if( j>=p->nCol ){ 34014adee20fSdanielk1977 sqlite3ErrorMsg(pParse, 3402f7a9e1acSdrh "unknown column \"%s\" in foreign key definition", 340341cee668Sdrh pFromCol->a[i].zEName); 3404c2eef3b3Sdrh goto fk_end; 3405c2eef3b3Sdrh } 3406c9461eccSdan if( IN_RENAME_OBJECT ){ 340741cee668Sdrh sqlite3RenameTokenRemap(pParse, &pFKey->aCol[i], pFromCol->a[i].zEName); 3408cf8f2895Sdan } 3409c2eef3b3Sdrh } 3410c2eef3b3Sdrh } 3411c2eef3b3Sdrh if( pToCol ){ 3412c2eef3b3Sdrh for(i=0; i<nCol; i++){ 341341cee668Sdrh int n = sqlite3Strlen30(pToCol->a[i].zEName); 3414c2eef3b3Sdrh pFKey->aCol[i].zCol = z; 3415c9461eccSdan if( IN_RENAME_OBJECT ){ 341641cee668Sdrh sqlite3RenameTokenRemap(pParse, z, pToCol->a[i].zEName); 34176fe7f23fSdan } 341841cee668Sdrh memcpy(z, pToCol->a[i].zEName, n); 3419c2eef3b3Sdrh z[n] = 0; 3420c2eef3b3Sdrh z += n+1; 3421c2eef3b3Sdrh } 3422c2eef3b3Sdrh } 3423c2eef3b3Sdrh pFKey->isDeferred = 0; 34248099ce6fSdan pFKey->aAction[0] = (u8)(flags & 0xff); /* ON DELETE action */ 34258099ce6fSdan pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff); /* ON UPDATE action */ 3426c2eef3b3Sdrh 34272120608eSdrh assert( sqlite3SchemaMutexHeld(db, 0, p->pSchema) ); 34281da40a38Sdan pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash, 3429acbcb7e0Sdrh pFKey->zTo, (void *)pFKey 34301da40a38Sdan ); 3431f59c5cacSdan if( pNextTo==pFKey ){ 34324a642b60Sdrh sqlite3OomFault(db); 3433f59c5cacSdan goto fk_end; 3434f59c5cacSdan } 34351da40a38Sdan if( pNextTo ){ 34361da40a38Sdan assert( pNextTo->pPrevTo==0 ); 34371da40a38Sdan pFKey->pNextTo = pNextTo; 34381da40a38Sdan pNextTo->pPrevTo = pFKey; 34391da40a38Sdan } 34401da40a38Sdan 3441c2eef3b3Sdrh /* Link the foreign key to the table as the last step. 3442c2eef3b3Sdrh */ 3443c2eef3b3Sdrh p->pFKey = pFKey; 3444c2eef3b3Sdrh pFKey = 0; 3445c2eef3b3Sdrh 3446c2eef3b3Sdrh fk_end: 3447633e6d57Sdrh sqlite3DbFree(db, pFKey); 3448b7f9164eSdrh #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */ 3449633e6d57Sdrh sqlite3ExprListDelete(db, pFromCol); 3450633e6d57Sdrh sqlite3ExprListDelete(db, pToCol); 3451c2eef3b3Sdrh } 3452c2eef3b3Sdrh 3453c2eef3b3Sdrh /* 3454c2eef3b3Sdrh ** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED 3455c2eef3b3Sdrh ** clause is seen as part of a foreign key definition. The isDeferred 3456c2eef3b3Sdrh ** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE. 3457c2eef3b3Sdrh ** The behavior of the most recently created foreign key is adjusted 3458c2eef3b3Sdrh ** accordingly. 3459c2eef3b3Sdrh */ 34604adee20fSdanielk1977 void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){ 3461b7f9164eSdrh #ifndef SQLITE_OMIT_FOREIGN_KEY 3462c2eef3b3Sdrh Table *pTab; 3463c2eef3b3Sdrh FKey *pFKey; 3464c2eef3b3Sdrh if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return; 34654c429839Sdrh assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */ 34661bd10f8aSdrh pFKey->isDeferred = (u8)isDeferred; 3467b7f9164eSdrh #endif 3468c2eef3b3Sdrh } 3469c2eef3b3Sdrh 3470c2eef3b3Sdrh /* 3471063336a5Sdrh ** Generate code that will erase and refill index *pIdx. This is 3472063336a5Sdrh ** used to initialize a newly created index or to recompute the 3473063336a5Sdrh ** content of an index in response to a REINDEX command. 3474063336a5Sdrh ** 3475063336a5Sdrh ** if memRootPage is not negative, it means that the index is newly 34761db639ceSdrh ** created. The register specified by memRootPage contains the 3477063336a5Sdrh ** root page number of the index. If memRootPage is negative, then 3478063336a5Sdrh ** the index already exists and must be cleared before being refilled and 3479063336a5Sdrh ** the root page number of the index is taken from pIndex->tnum. 3480063336a5Sdrh */ 3481063336a5Sdrh static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){ 3482063336a5Sdrh Table *pTab = pIndex->pTable; /* The table that is indexed */ 34836ab3a2ecSdanielk1977 int iTab = pParse->nTab++; /* Btree cursor used for pTab */ 34846ab3a2ecSdanielk1977 int iIdx = pParse->nTab++; /* Btree cursor used for pIndex */ 3485b07028f7Sdrh int iSorter; /* Cursor opened by OpenSorter (if in use) */ 3486063336a5Sdrh int addr1; /* Address of top of loop */ 34875134d135Sdan int addr2; /* Address to jump to for next iteration */ 3488abc38158Sdrh Pgno tnum; /* Root page of index */ 3489b2b9d3d7Sdrh int iPartIdxLabel; /* Jump to this label to skip a row */ 3490063336a5Sdrh Vdbe *v; /* Generate code into this virtual machine */ 3491b3bf556eSdanielk1977 KeyInfo *pKey; /* KeyInfo for index */ 349260ec914cSpeter.d.reid int regRecord; /* Register holding assembled index record */ 349317435752Sdrh sqlite3 *db = pParse->db; /* The database connection */ 349417435752Sdrh int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema); 3495063336a5Sdrh 34961d54df88Sdanielk1977 #ifndef SQLITE_OMIT_AUTHORIZATION 34971d54df88Sdanielk1977 if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0, 349869c33826Sdrh db->aDb[iDb].zDbSName ) ){ 34991d54df88Sdanielk1977 return; 35001d54df88Sdanielk1977 } 35011d54df88Sdanielk1977 #endif 35021d54df88Sdanielk1977 3503c00da105Sdanielk1977 /* Require a write-lock on the table to perform this operation */ 3504c00da105Sdanielk1977 sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName); 3505c00da105Sdanielk1977 3506063336a5Sdrh v = sqlite3GetVdbe(pParse); 3507063336a5Sdrh if( v==0 ) return; 3508063336a5Sdrh if( memRootPage>=0 ){ 3509abc38158Sdrh tnum = (Pgno)memRootPage; 3510063336a5Sdrh }else{ 3511063336a5Sdrh tnum = pIndex->tnum; 3512063336a5Sdrh } 35132ec2fb22Sdrh pKey = sqlite3KeyInfoOfIndex(pParse, pIndex); 351460de73e8Sdrh assert( pKey!=0 || db->mallocFailed || pParse->nErr ); 3515a20fde64Sdan 3516689ab897Sdan /* Open the sorter cursor if we are to use one. */ 3517689ab897Sdan iSorter = pParse->nTab++; 3518fad9f9a8Sdan sqlite3VdbeAddOp4(v, OP_SorterOpen, iSorter, 0, pIndex->nKeyCol, (char*) 35192ec2fb22Sdrh sqlite3KeyInfoRef(pKey), P4_KEYINFO); 3520a20fde64Sdan 3521a20fde64Sdan /* Open the table. Loop through all rows of the table, inserting index 3522a20fde64Sdan ** records into the sorter. */ 3523c00da105Sdanielk1977 sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead); 3524688852abSdrh addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0); VdbeCoverage(v); 35252d401ab8Sdrh regRecord = sqlite3GetTempReg(pParse); 35264031bafaSdrh sqlite3MultiWrite(pParse); 3527689ab897Sdan 35281c2c0b77Sdrh sqlite3GenerateIndexKey(pParse,pIndex,iTab,regRecord,0,&iPartIdxLabel,0,0); 35295134d135Sdan sqlite3VdbeAddOp2(v, OP_SorterInsert, iSorter, regRecord); 353087744513Sdrh sqlite3ResolvePartIdxLabel(pParse, iPartIdxLabel); 3531688852abSdrh sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1); VdbeCoverage(v); 3532a20fde64Sdan sqlite3VdbeJumpHere(v, addr1); 35334415628aSdrh if( memRootPage<0 ) sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb); 3534abc38158Sdrh sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, (int)tnum, iDb, 35352ec2fb22Sdrh (char *)pKey, P4_KEYINFO); 35364415628aSdrh sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR|((memRootPage>=0)?OPFLAG_P2ISREG:0)); 35374415628aSdrh 3538688852abSdrh addr1 = sqlite3VdbeAddOp2(v, OP_SorterSort, iSorter, 0); VdbeCoverage(v); 353960de73e8Sdrh if( IsUniqueIndex(pIndex) ){ 35404031bafaSdrh int j2 = sqlite3VdbeGoto(v, 1); 35415134d135Sdan addr2 = sqlite3VdbeCurrentAddr(v); 35424031bafaSdrh sqlite3VdbeVerifyAbortable(v, OE_Abort); 35431153c7b2Sdrh sqlite3VdbeAddOp4Int(v, OP_SorterCompare, iSorter, j2, regRecord, 3544ac50232dSdrh pIndex->nKeyCol); VdbeCoverage(v); 3545f9c8ce3cSdrh sqlite3UniqueConstraint(pParse, OE_Abort, pIndex); 35464031bafaSdrh sqlite3VdbeJumpHere(v, j2); 35475134d135Sdan }else{ 35487ed6c068Sdan /* Most CREATE INDEX and REINDEX statements that are not UNIQUE can not 35497ed6c068Sdan ** abort. The exception is if one of the indexed expressions contains a 35507ed6c068Sdan ** user function that throws an exception when it is evaluated. But the 35517ed6c068Sdan ** overhead of adding a statement journal to a CREATE INDEX statement is 35527ed6c068Sdan ** very small (since most of the pages written do not contain content that 35537ed6c068Sdan ** needs to be restored if the statement aborts), so we call 35547ed6c068Sdan ** sqlite3MayAbort() for all CREATE INDEX statements. */ 3555ef14abbfSdan sqlite3MayAbort(pParse); 35565134d135Sdan addr2 = sqlite3VdbeCurrentAddr(v); 3557689ab897Sdan } 35586cf4a7dfSdrh sqlite3VdbeAddOp3(v, OP_SorterData, iSorter, regRecord, iIdx); 3559bf9ff256Sdrh if( !pIndex->bAscKeyBug ){ 3560bf9ff256Sdrh /* This OP_SeekEnd opcode makes index insert for a REINDEX go much 3561bf9ff256Sdrh ** faster by avoiding unnecessary seeks. But the optimization does 3562bf9ff256Sdrh ** not work for UNIQUE constraint indexes on WITHOUT ROWID tables 3563bf9ff256Sdrh ** with DESC primary keys, since those indexes have there keys in 3564bf9ff256Sdrh ** a different order from the main table. 3565bf9ff256Sdrh ** See ticket: https://www.sqlite.org/src/info/bba7b69f9849b5bf 3566bf9ff256Sdrh */ 356786b40dfdSdrh sqlite3VdbeAddOp1(v, OP_SeekEnd, iIdx); 3568bf9ff256Sdrh } 35699b4eaebcSdrh sqlite3VdbeAddOp2(v, OP_IdxInsert, iIdx, regRecord); 3570ca892a72Sdrh sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT); 35712d401ab8Sdrh sqlite3ReleaseTempReg(pParse, regRecord); 3572688852abSdrh sqlite3VdbeAddOp2(v, OP_SorterNext, iSorter, addr2); VdbeCoverage(v); 3573d654be80Sdrh sqlite3VdbeJumpHere(v, addr1); 3574a20fde64Sdan 357566a5167bSdrh sqlite3VdbeAddOp1(v, OP_Close, iTab); 357666a5167bSdrh sqlite3VdbeAddOp1(v, OP_Close, iIdx); 3577689ab897Sdan sqlite3VdbeAddOp1(v, OP_Close, iSorter); 3578063336a5Sdrh } 3579063336a5Sdrh 3580063336a5Sdrh /* 358177e57dfbSdrh ** Allocate heap space to hold an Index object with nCol columns. 358277e57dfbSdrh ** 358377e57dfbSdrh ** Increase the allocation size to provide an extra nExtra bytes 358477e57dfbSdrh ** of 8-byte aligned space after the Index object and return a 358577e57dfbSdrh ** pointer to this extra space in *ppExtra. 358677e57dfbSdrh */ 358777e57dfbSdrh Index *sqlite3AllocateIndexObject( 358877e57dfbSdrh sqlite3 *db, /* Database connection */ 3589bbbdc83bSdrh i16 nCol, /* Total number of columns in the index */ 359077e57dfbSdrh int nExtra, /* Number of bytes of extra space to alloc */ 359177e57dfbSdrh char **ppExtra /* Pointer to the "extra" space */ 359277e57dfbSdrh ){ 359377e57dfbSdrh Index *p; /* Allocated index object */ 359477e57dfbSdrh int nByte; /* Bytes of space for Index object + arrays */ 359577e57dfbSdrh 359677e57dfbSdrh nByte = ROUND8(sizeof(Index)) + /* Index structure */ 359777e57dfbSdrh ROUND8(sizeof(char*)*nCol) + /* Index.azColl */ 3598cfc9df76Sdan ROUND8(sizeof(LogEst)*(nCol+1) + /* Index.aiRowLogEst */ 3599bbbdc83bSdrh sizeof(i16)*nCol + /* Index.aiColumn */ 360077e57dfbSdrh sizeof(u8)*nCol); /* Index.aSortOrder */ 360177e57dfbSdrh p = sqlite3DbMallocZero(db, nByte + nExtra); 360277e57dfbSdrh if( p ){ 360377e57dfbSdrh char *pExtra = ((char*)p)+ROUND8(sizeof(Index)); 3604f19aa5faSdrh p->azColl = (const char**)pExtra; pExtra += ROUND8(sizeof(char*)*nCol); 3605cfc9df76Sdan p->aiRowLogEst = (LogEst*)pExtra; pExtra += sizeof(LogEst)*(nCol+1); 3606bbbdc83bSdrh p->aiColumn = (i16*)pExtra; pExtra += sizeof(i16)*nCol; 360777e57dfbSdrh p->aSortOrder = (u8*)pExtra; 360877e57dfbSdrh p->nColumn = nCol; 3609bbbdc83bSdrh p->nKeyCol = nCol - 1; 361077e57dfbSdrh *ppExtra = ((char*)p) + nByte; 361177e57dfbSdrh } 361277e57dfbSdrh return p; 361377e57dfbSdrh } 361477e57dfbSdrh 361577e57dfbSdrh /* 36169105fd51Sdan ** If expression list pList contains an expression that was parsed with 36179105fd51Sdan ** an explicit "NULLS FIRST" or "NULLS LAST" clause, leave an error in 36189105fd51Sdan ** pParse and return non-zero. Otherwise, return zero. 36199105fd51Sdan */ 36209105fd51Sdan int sqlite3HasExplicitNulls(Parse *pParse, ExprList *pList){ 36219105fd51Sdan if( pList ){ 36229105fd51Sdan int i; 36239105fd51Sdan for(i=0; i<pList->nExpr; i++){ 36249105fd51Sdan if( pList->a[i].bNulls ){ 36259105fd51Sdan u8 sf = pList->a[i].sortFlags; 36269105fd51Sdan sqlite3ErrorMsg(pParse, "unsupported use of NULLS %s", 36279105fd51Sdan (sf==0 || sf==3) ? "FIRST" : "LAST" 36289105fd51Sdan ); 36299105fd51Sdan return 1; 36309105fd51Sdan } 36319105fd51Sdan } 36329105fd51Sdan } 36339105fd51Sdan return 0; 36349105fd51Sdan } 36359105fd51Sdan 36369105fd51Sdan /* 363723bf66d6Sdrh ** Create a new index for an SQL table. pName1.pName2 is the name of the index 363823bf66d6Sdrh ** and pTblList is the name of the table that is to be indexed. Both will 3639adbca9cfSdrh ** be NULL for a primary key or an index that is created to satisfy a 3640adbca9cfSdrh ** UNIQUE constraint. If pTable and pIndex are NULL, use pParse->pNewTable 3641382c0247Sdrh ** as the table to be indexed. pParse->pNewTable is a table that is 3642382c0247Sdrh ** currently being constructed by a CREATE TABLE statement. 364375897234Sdrh ** 3644382c0247Sdrh ** pList is a list of columns to be indexed. pList will be NULL if this 3645382c0247Sdrh ** is a primary key or unique-constraint on the most recent column added 3646382c0247Sdrh ** to the table currently under construction. 364775897234Sdrh */ 364862340f84Sdrh void sqlite3CreateIndex( 364975897234Sdrh Parse *pParse, /* All information about this parse */ 3650cbb18d22Sdanielk1977 Token *pName1, /* First part of index name. May be NULL */ 3651cbb18d22Sdanielk1977 Token *pName2, /* Second part of index name. May be NULL */ 36520202b29eSdanielk1977 SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */ 36530202b29eSdanielk1977 ExprList *pList, /* A list of columns to be indexed */ 36549cfcf5d4Sdrh int onError, /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */ 36551c55ba09Sdrh Token *pStart, /* The CREATE token that begins this statement */ 36561fe0537eSdrh Expr *pPIWhere, /* WHERE clause for partial indices */ 36574d91a701Sdrh int sortOrder, /* Sort order of primary key when pList==NULL */ 365862340f84Sdrh int ifNotExist, /* Omit error if index already exists */ 365962340f84Sdrh u8 idxType /* The index type */ 366075897234Sdrh ){ 3661cbb18d22Sdanielk1977 Table *pTab = 0; /* Table to be indexed */ 3662d8123366Sdanielk1977 Index *pIndex = 0; /* The index to be created */ 3663fdd6e85aSdrh char *zName = 0; /* Name of the index */ 3664fdd6e85aSdrh int nName; /* Number of characters in zName */ 3665beae3194Sdrh int i, j; 3666f26e09c8Sdrh DbFixer sFix; /* For assigning database names to pTable */ 3667fdd6e85aSdrh int sortOrderMask; /* 1 to honor DESC in index. 0 to ignore. */ 36689bb575fdSdrh sqlite3 *db = pParse->db; 3669fdd6e85aSdrh Db *pDb; /* The specific table containing the indexed database */ 3670cbb18d22Sdanielk1977 int iDb; /* Index of the database that is being written */ 3671cbb18d22Sdanielk1977 Token *pName = 0; /* Unqualified name of the index to create */ 3672fdd6e85aSdrh struct ExprList_item *pListItem; /* For looping over pList */ 3673c28c4e50Sdrh int nExtra = 0; /* Space allocated for zExtra[] */ 36744415628aSdrh int nExtraCol; /* Number of extra columns needed */ 367547b927d2Sdrh char *zExtra = 0; /* Extra space after the Index object */ 36764415628aSdrh Index *pPk = 0; /* PRIMARY KEY index for WITHOUT ROWID tables */ 3677cbb18d22Sdanielk1977 367862340f84Sdrh if( db->mallocFailed || pParse->nErr>0 ){ 367962340f84Sdrh goto exit_create_index; 368062340f84Sdrh } 368162340f84Sdrh if( IN_DECLARE_VTAB && idxType!=SQLITE_IDXTYPE_PRIMARYKEY ){ 3682d3001711Sdrh goto exit_create_index; 3683d3001711Sdrh } 3684d3001711Sdrh if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){ 3685e501b89aSdanielk1977 goto exit_create_index; 3686e501b89aSdanielk1977 } 36879105fd51Sdan if( sqlite3HasExplicitNulls(pParse, pList) ){ 36889105fd51Sdan goto exit_create_index; 36899105fd51Sdan } 3690daffd0e5Sdrh 369175897234Sdrh /* 369275897234Sdrh ** Find the table that is to be indexed. Return early if not found. 369375897234Sdrh */ 3694cbb18d22Sdanielk1977 if( pTblName!=0 ){ 3695cbb18d22Sdanielk1977 3696cbb18d22Sdanielk1977 /* Use the two-part index name to determine the database 3697ef2cb63eSdanielk1977 ** to search for the table. 'Fix' the table name to this db 3698ef2cb63eSdanielk1977 ** before looking up the table. 3699cbb18d22Sdanielk1977 */ 3700cbb18d22Sdanielk1977 assert( pName1 && pName2 ); 3701ef2cb63eSdanielk1977 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName); 3702cbb18d22Sdanielk1977 if( iDb<0 ) goto exit_create_index; 3703b07028f7Sdrh assert( pName && pName->z ); 3704cbb18d22Sdanielk1977 370553c0f748Sdanielk1977 #ifndef SQLITE_OMIT_TEMPDB 3706d5578433Smistachkin /* If the index name was unqualified, check if the table 3707fe910339Sdanielk1977 ** is a temp table. If so, set the database to 1. Do not do this 3708fe910339Sdanielk1977 ** if initialising a database schema. 3709cbb18d22Sdanielk1977 */ 3710fe910339Sdanielk1977 if( !db->init.busy ){ 3711ef2cb63eSdanielk1977 pTab = sqlite3SrcListLookup(pParse, pTblName); 3712d3001711Sdrh if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){ 3713ef2cb63eSdanielk1977 iDb = 1; 3714ef2cb63eSdanielk1977 } 3715fe910339Sdanielk1977 } 371653c0f748Sdanielk1977 #endif 3717ef2cb63eSdanielk1977 3718d100f691Sdrh sqlite3FixInit(&sFix, pParse, iDb, "index", pName); 3719d100f691Sdrh if( sqlite3FixSrcList(&sFix, pTblName) ){ 372085c23c61Sdrh /* Because the parser constructs pTblName from a single identifier, 372185c23c61Sdrh ** sqlite3FixSrcList can never fail. */ 372285c23c61Sdrh assert(0); 3723cbb18d22Sdanielk1977 } 372441fb5cd1Sdan pTab = sqlite3LocateTableItem(pParse, 0, &pTblName->a[0]); 3725c31c7c1cSdrh assert( db->mallocFailed==0 || pTab==0 ); 3726c31c7c1cSdrh if( pTab==0 ) goto exit_create_index; 3727989b116aSdrh if( iDb==1 && db->aDb[iDb].pSchema!=pTab->pSchema ){ 3728989b116aSdrh sqlite3ErrorMsg(pParse, 3729989b116aSdrh "cannot create a TEMP index on non-TEMP table \"%s\"", 3730989b116aSdrh pTab->zName); 3731989b116aSdrh goto exit_create_index; 3732989b116aSdrh } 37334415628aSdrh if( !HasRowid(pTab) ) pPk = sqlite3PrimaryKeyIndex(pTab); 373475897234Sdrh }else{ 3735e3c41372Sdrh assert( pName==0 ); 3736b07028f7Sdrh assert( pStart==0 ); 373775897234Sdrh pTab = pParse->pNewTable; 3738a6370df1Sdrh if( !pTab ) goto exit_create_index; 3739da184236Sdanielk1977 iDb = sqlite3SchemaToIndex(db, pTab->pSchema); 374075897234Sdrh } 3741fdd6e85aSdrh pDb = &db->aDb[iDb]; 3742cbb18d22Sdanielk1977 3743d3001711Sdrh assert( pTab!=0 ); 3744d3001711Sdrh assert( pParse->nErr==0 ); 37450388123fSdrh if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 37463a3a03f2Sdrh && db->init.busy==0 3747346f4e26Sdrh && pTblName!=0 3748d4530979Sdrh #if SQLITE_USER_AUTHENTICATION 3749d4530979Sdrh && sqlite3UserAuthTable(pTab->zName)==0 3750d4530979Sdrh #endif 37518c2e6c5fSdrh ){ 37524adee20fSdanielk1977 sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName); 37530be9df07Sdrh goto exit_create_index; 37540be9df07Sdrh } 3755576ec6b3Sdanielk1977 #ifndef SQLITE_OMIT_VIEW 3756a76b5dfcSdrh if( pTab->pSelect ){ 37574adee20fSdanielk1977 sqlite3ErrorMsg(pParse, "views may not be indexed"); 3758a76b5dfcSdrh goto exit_create_index; 3759a76b5dfcSdrh } 3760576ec6b3Sdanielk1977 #endif 37615ee9d697Sdanielk1977 #ifndef SQLITE_OMIT_VIRTUALTABLE 37625ee9d697Sdanielk1977 if( IsVirtual(pTab) ){ 37635ee9d697Sdanielk1977 sqlite3ErrorMsg(pParse, "virtual tables may not be indexed"); 37645ee9d697Sdanielk1977 goto exit_create_index; 37655ee9d697Sdanielk1977 } 37665ee9d697Sdanielk1977 #endif 376775897234Sdrh 376875897234Sdrh /* 376975897234Sdrh ** Find the name of the index. Make sure there is not already another 3770f57b3399Sdrh ** index or table with the same name. 3771f57b3399Sdrh ** 3772f57b3399Sdrh ** Exception: If we are reading the names of permanent indices from the 37731e32bed3Sdrh ** sqlite_schema table (because some other process changed the schema) and 3774f57b3399Sdrh ** one of the index names collides with the name of a temporary table or 3775d24cc427Sdrh ** index, then we will continue to process this index. 3776f57b3399Sdrh ** 3777f57b3399Sdrh ** If pName==0 it means that we are 3778adbca9cfSdrh ** dealing with a primary key or UNIQUE constraint. We have to invent our 3779adbca9cfSdrh ** own name. 378075897234Sdrh */ 3781d8123366Sdanielk1977 if( pName ){ 378217435752Sdrh zName = sqlite3NameFromToken(db, pName); 3783d8123366Sdanielk1977 if( zName==0 ) goto exit_create_index; 3784b07028f7Sdrh assert( pName->z!=0 ); 3785c5a93d4cSdrh if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName,"index",pTab->zName) ){ 3786d8123366Sdanielk1977 goto exit_create_index; 3787d8123366Sdanielk1977 } 3788c9461eccSdan if( !IN_RENAME_OBJECT ){ 3789d8123366Sdanielk1977 if( !db->init.busy ){ 3790d45a0315Sdanielk1977 if( sqlite3FindTable(db, zName, 0)!=0 ){ 3791d45a0315Sdanielk1977 sqlite3ErrorMsg(pParse, "there is already a table named %s", zName); 3792d45a0315Sdanielk1977 goto exit_create_index; 3793d45a0315Sdanielk1977 } 3794d45a0315Sdanielk1977 } 379569c33826Sdrh if( sqlite3FindIndex(db, zName, pDb->zDbSName)!=0 ){ 37964d91a701Sdrh if( !ifNotExist ){ 37974adee20fSdanielk1977 sqlite3ErrorMsg(pParse, "index %s already exists", zName); 37987687c83dSdan }else{ 37997687c83dSdan assert( !db->init.busy ); 38007687c83dSdan sqlite3CodeVerifySchema(pParse, iDb); 380131da7be9Sdrh sqlite3ForceNotReadOnly(pParse); 38024d91a701Sdrh } 380375897234Sdrh goto exit_create_index; 380475897234Sdrh } 3805cf8f2895Sdan } 3806a21c6b6fSdanielk1977 }else{ 3807adbca9cfSdrh int n; 3808adbca9cfSdrh Index *pLoop; 3809adbca9cfSdrh for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){} 3810f089aa45Sdrh zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n); 3811a1644fd8Sdanielk1977 if( zName==0 ){ 3812a1644fd8Sdanielk1977 goto exit_create_index; 3813a1644fd8Sdanielk1977 } 38140aafa9c8Sdrh 38150aafa9c8Sdrh /* Automatic index names generated from within sqlite3_declare_vtab() 38160aafa9c8Sdrh ** must have names that are distinct from normal automatic index names. 38170aafa9c8Sdrh ** The following statement converts "sqlite3_autoindex..." into 38180aafa9c8Sdrh ** "sqlite3_butoindex..." in order to make the names distinct. 38190aafa9c8Sdrh ** The "vtab_err.test" test demonstrates the need of this statement. */ 3820cf8f2895Sdan if( IN_SPECIAL_PARSE ) zName[7]++; 3821e3c41372Sdrh } 382275897234Sdrh 3823e5f9c644Sdrh /* Check for authorization to create an index. 3824e5f9c644Sdrh */ 3825e5f9c644Sdrh #ifndef SQLITE_OMIT_AUTHORIZATION 3826c9461eccSdan if( !IN_RENAME_OBJECT ){ 382769c33826Sdrh const char *zDb = pDb->zDbSName; 382853c0f748Sdanielk1977 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){ 3829e5f9c644Sdrh goto exit_create_index; 3830e5f9c644Sdrh } 3831e5f9c644Sdrh i = SQLITE_CREATE_INDEX; 383253c0f748Sdanielk1977 if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX; 38334adee20fSdanielk1977 if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){ 3834e5f9c644Sdrh goto exit_create_index; 3835e5f9c644Sdrh } 3836e22a334bSdrh } 3837e5f9c644Sdrh #endif 3838e5f9c644Sdrh 383975897234Sdrh /* If pList==0, it means this routine was called to make a primary 38401ccde15dSdrh ** key out of the last column added to the table under construction. 384175897234Sdrh ** So create a fake list to simulate this. 384275897234Sdrh */ 384375897234Sdrh if( pList==0 ){ 3844108aa00aSdrh Token prevCol; 384526e731ccSdan Column *pCol = &pTab->aCol[pTab->nCol-1]; 384626e731ccSdan pCol->colFlags |= COLFLAG_UNIQUE; 384726e731ccSdan sqlite3TokenInit(&prevCol, pCol->zName); 3848108aa00aSdrh pList = sqlite3ExprListAppend(pParse, 0, 3849108aa00aSdrh sqlite3ExprAlloc(db, TK_ID, &prevCol, 0)); 385075897234Sdrh if( pList==0 ) goto exit_create_index; 3851bc622bc0Sdrh assert( pList->nExpr==1 ); 38525b32bdffSdan sqlite3ExprListSetSortOrder(pList, sortOrder, SQLITE_SO_UNDEFINED); 3853108aa00aSdrh }else{ 3854108aa00aSdrh sqlite3ExprListCheckLength(pParse, pList, "index"); 38558fe25c64Sdrh if( pParse->nErr ) goto exit_create_index; 385675897234Sdrh } 385775897234Sdrh 3858b3bf556eSdanielk1977 /* Figure out how many bytes of space are required to store explicitly 3859b3bf556eSdanielk1977 ** specified collation sequence names. 3860b3bf556eSdanielk1977 */ 3861b3bf556eSdanielk1977 for(i=0; i<pList->nExpr; i++){ 3862d3001711Sdrh Expr *pExpr = pList->a[i].pExpr; 38637d3d9daeSdrh assert( pExpr!=0 ); 38647d3d9daeSdrh if( pExpr->op==TK_COLLATE ){ 3865911ce418Sdan nExtra += (1 + sqlite3Strlen30(pExpr->u.zToken)); 3866b3bf556eSdanielk1977 } 3867d3001711Sdrh } 3868b3bf556eSdanielk1977 386975897234Sdrh /* 387075897234Sdrh ** Allocate the index structure. 387175897234Sdrh */ 3872ea678832Sdrh nName = sqlite3Strlen30(zName); 38734415628aSdrh nExtraCol = pPk ? pPk->nKeyCol : 1; 38748fe25c64Sdrh assert( pList->nExpr + nExtraCol <= 32767 /* Fits in i16 */ ); 38754415628aSdrh pIndex = sqlite3AllocateIndexObject(db, pList->nExpr + nExtraCol, 387677e57dfbSdrh nName + nExtra + 1, &zExtra); 387717435752Sdrh if( db->mallocFailed ){ 387817435752Sdrh goto exit_create_index; 387917435752Sdrh } 3880cfc9df76Sdan assert( EIGHT_BYTE_ALIGNMENT(pIndex->aiRowLogEst) ); 3881e09b84c5Sdrh assert( EIGHT_BYTE_ALIGNMENT(pIndex->azColl) ); 388277e57dfbSdrh pIndex->zName = zExtra; 388377e57dfbSdrh zExtra += nName + 1; 38845bb3eb9bSdrh memcpy(pIndex->zName, zName, nName+1); 388575897234Sdrh pIndex->pTable = pTab; 38861bd10f8aSdrh pIndex->onError = (u8)onError; 38879eade087Sdrh pIndex->uniqNotNull = onError!=OE_None; 388862340f84Sdrh pIndex->idxType = idxType; 3889da184236Sdanielk1977 pIndex->pSchema = db->aDb[iDb].pSchema; 389072ffd091Sdrh pIndex->nKeyCol = pList->nExpr; 38913780be11Sdrh if( pPIWhere ){ 38923780be11Sdrh sqlite3ResolveSelfReference(pParse, pTab, NC_PartIdx, pPIWhere, 0); 38931fe0537eSdrh pIndex->pPartIdxWhere = pPIWhere; 38941fe0537eSdrh pPIWhere = 0; 38953780be11Sdrh } 38962120608eSdrh assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); 389775897234Sdrh 3898fdd6e85aSdrh /* Check to see if we should honor DESC requests on index columns 3899fdd6e85aSdrh */ 3900da184236Sdanielk1977 if( pDb->pSchema->file_format>=4 ){ 3901fdd6e85aSdrh sortOrderMask = -1; /* Honor DESC */ 3902fdd6e85aSdrh }else{ 3903fdd6e85aSdrh sortOrderMask = 0; /* Ignore DESC */ 3904fdd6e85aSdrh } 3905fdd6e85aSdrh 39061f9ca2c8Sdrh /* Analyze the list of expressions that form the terms of the index and 39071f9ca2c8Sdrh ** report any errors. In the common case where the expression is exactly 39081f9ca2c8Sdrh ** a table column, store that column in aiColumn[]. For general expressions, 39094b92f98cSdrh ** populate pIndex->aColExpr and store XN_EXPR (-2) in aiColumn[]. 3910d3001711Sdrh ** 39111f9ca2c8Sdrh ** TODO: Issue a warning if two or more columns of the index are identical. 39121f9ca2c8Sdrh ** TODO: Issue a warning if the table primary key is used as part of the 39131f9ca2c8Sdrh ** index key. 391475897234Sdrh */ 3915cf8f2895Sdan pListItem = pList->a; 3916c9461eccSdan if( IN_RENAME_OBJECT ){ 3917cf8f2895Sdan pIndex->aColExpr = pList; 3918cf8f2895Sdan pList = 0; 3919cf8f2895Sdan } 3920cf8f2895Sdan for(i=0; i<pIndex->nKeyCol; i++, pListItem++){ 39211f9ca2c8Sdrh Expr *pCExpr; /* The i-th index expression */ 39221f9ca2c8Sdrh int requestedSortOrder; /* ASC or DESC on the i-th expression */ 3923f19aa5faSdrh const char *zColl; /* Collation sequence name */ 3924b3bf556eSdanielk1977 3925edb04ed9Sdrh sqlite3StringToId(pListItem->pExpr); 3926a514b8ebSdrh sqlite3ResolveSelfReference(pParse, pTab, NC_IdxExpr, pListItem->pExpr, 0); 3927a514b8ebSdrh if( pParse->nErr ) goto exit_create_index; 3928108aa00aSdrh pCExpr = sqlite3ExprSkipCollate(pListItem->pExpr); 3929a514b8ebSdrh if( pCExpr->op!=TK_COLUMN ){ 39301f9ca2c8Sdrh if( pTab==pParse->pNewTable ){ 39311f9ca2c8Sdrh sqlite3ErrorMsg(pParse, "expressions prohibited in PRIMARY KEY and " 39321f9ca2c8Sdrh "UNIQUE constraints"); 39331f9ca2c8Sdrh goto exit_create_index; 3934108aa00aSdrh } 39351f9ca2c8Sdrh if( pIndex->aColExpr==0 ){ 3936cf8f2895Sdan pIndex->aColExpr = pList; 3937cf8f2895Sdan pList = 0; 39381f9ca2c8Sdrh } 39394b92f98cSdrh j = XN_EXPR; 39404b92f98cSdrh pIndex->aiColumn[i] = XN_EXPR; 39418492653cSdrh pIndex->uniqNotNull = 0; 39421f9ca2c8Sdrh }else{ 3943a514b8ebSdrh j = pCExpr->iColumn; 3944bf20a35dSdrh assert( j<=0x7fff ); 39451f9ca2c8Sdrh if( j<0 ){ 39461f9ca2c8Sdrh j = pTab->iPKey; 3947c7476735Sdrh }else{ 3948c7476735Sdrh if( pTab->aCol[j].notNull==0 ){ 39491f9ca2c8Sdrh pIndex->uniqNotNull = 0; 39501f9ca2c8Sdrh } 3951c7476735Sdrh if( pTab->aCol[j].colFlags & COLFLAG_VIRTUAL ){ 3952c7476735Sdrh pIndex->bHasVCol = 1; 3953c7476735Sdrh } 3954c7476735Sdrh } 3955bbbdc83bSdrh pIndex->aiColumn[i] = (i16)j; 39561f9ca2c8Sdrh } 3957a514b8ebSdrh zColl = 0; 3958108aa00aSdrh if( pListItem->pExpr->op==TK_COLLATE ){ 3959d3001711Sdrh int nColl; 3960911ce418Sdan zColl = pListItem->pExpr->u.zToken; 3961d3001711Sdrh nColl = sqlite3Strlen30(zColl) + 1; 3962d3001711Sdrh assert( nExtra>=nColl ); 3963d3001711Sdrh memcpy(zExtra, zColl, nColl); 3964b3bf556eSdanielk1977 zColl = zExtra; 3965d3001711Sdrh zExtra += nColl; 3966d3001711Sdrh nExtra -= nColl; 3967a514b8ebSdrh }else if( j>=0 ){ 3968b3bf556eSdanielk1977 zColl = pTab->aCol[j].zColl; 3969b3bf556eSdanielk1977 } 3970f19aa5faSdrh if( !zColl ) zColl = sqlite3StrBINARY; 3971b7f24de2Sdrh if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){ 39727cedc8d4Sdanielk1977 goto exit_create_index; 39737cedc8d4Sdanielk1977 } 3974b3bf556eSdanielk1977 pIndex->azColl[i] = zColl; 39756e11892dSdan requestedSortOrder = pListItem->sortFlags & sortOrderMask; 39761bd10f8aSdrh pIndex->aSortOrder[i] = (u8)requestedSortOrder; 39770202b29eSdanielk1977 } 39781f9ca2c8Sdrh 39791f9ca2c8Sdrh /* Append the table key to the end of the index. For WITHOUT ROWID 39801f9ca2c8Sdrh ** tables (when pPk!=0) this will be the declared PRIMARY KEY. For 39811f9ca2c8Sdrh ** normal tables (when pPk==0) this will be the rowid. 39821f9ca2c8Sdrh */ 39834415628aSdrh if( pPk ){ 39847913e41fSdrh for(j=0; j<pPk->nKeyCol; j++){ 39857913e41fSdrh int x = pPk->aiColumn[j]; 39861f9ca2c8Sdrh assert( x>=0 ); 3987f78d0f42Sdrh if( isDupColumn(pIndex, pIndex->nKeyCol, pPk, j) ){ 39887913e41fSdrh pIndex->nColumn--; 39897913e41fSdrh }else{ 3990f78d0f42Sdrh testcase( hasColumn(pIndex->aiColumn,pIndex->nKeyCol,x) ); 39917913e41fSdrh pIndex->aiColumn[i] = x; 39924415628aSdrh pIndex->azColl[i] = pPk->azColl[j]; 39934415628aSdrh pIndex->aSortOrder[i] = pPk->aSortOrder[j]; 39947913e41fSdrh i++; 39954415628aSdrh } 39967913e41fSdrh } 39977913e41fSdrh assert( i==pIndex->nColumn ); 39984415628aSdrh }else{ 39994b92f98cSdrh pIndex->aiColumn[i] = XN_ROWID; 4000f19aa5faSdrh pIndex->azColl[i] = sqlite3StrBINARY; 4001f769cd61Sdan } 4002f769cd61Sdan sqlite3DefaultRowEst(pIndex); 4003f769cd61Sdan if( pParse->pNewTable==0 ) estimateIndexWidth(pIndex); 4004f769cd61Sdan 4005e1dd0608Sdrh /* If this index contains every column of its table, then mark 4006e1dd0608Sdrh ** it as a covering index */ 4007f769cd61Sdan assert( HasRowid(pTab) 4008b9bcf7caSdrh || pTab->iPKey<0 || sqlite3TableColumnToIndex(pIndex, pTab->iPKey)>=0 ); 40091fe3ac73Sdrh recomputeColumnsNotIndexed(pIndex); 4010e1dd0608Sdrh if( pTblName!=0 && pIndex->nColumn>=pTab->nCol ){ 4011e1dd0608Sdrh pIndex->isCovering = 1; 4012e1dd0608Sdrh for(j=0; j<pTab->nCol; j++){ 4013e1dd0608Sdrh if( j==pTab->iPKey ) continue; 4014b9bcf7caSdrh if( sqlite3TableColumnToIndex(pIndex,j)>=0 ) continue; 4015e1dd0608Sdrh pIndex->isCovering = 0; 4016e1dd0608Sdrh break; 4017e1dd0608Sdrh } 4018e1dd0608Sdrh } 401975897234Sdrh 4020d8123366Sdanielk1977 if( pTab==pParse->pNewTable ){ 4021d8123366Sdanielk1977 /* This routine has been called to create an automatic index as a 4022d8123366Sdanielk1977 ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or 4023d8123366Sdanielk1977 ** a PRIMARY KEY or UNIQUE clause following the column definitions. 4024d8123366Sdanielk1977 ** i.e. one of: 4025d8123366Sdanielk1977 ** 4026d8123366Sdanielk1977 ** CREATE TABLE t(x PRIMARY KEY, y); 4027d8123366Sdanielk1977 ** CREATE TABLE t(x, y, UNIQUE(x, y)); 4028d8123366Sdanielk1977 ** 4029d8123366Sdanielk1977 ** Either way, check to see if the table already has such an index. If 4030d8123366Sdanielk1977 ** so, don't bother creating this one. This only applies to 4031d8123366Sdanielk1977 ** automatically created indices. Users can do as they wish with 4032d8123366Sdanielk1977 ** explicit indices. 4033d3001711Sdrh ** 4034d3001711Sdrh ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent 4035d3001711Sdrh ** (and thus suppressing the second one) even if they have different 4036d3001711Sdrh ** sort orders. 4037d3001711Sdrh ** 4038d3001711Sdrh ** If there are different collating sequences or if the columns of 4039d3001711Sdrh ** the constraint occur in different orders, then the constraints are 4040d3001711Sdrh ** considered distinct and both result in separate indices. 4041d8123366Sdanielk1977 */ 4042d8123366Sdanielk1977 Index *pIdx; 4043d8123366Sdanielk1977 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ 4044d8123366Sdanielk1977 int k; 40455f1d1d9cSdrh assert( IsUniqueIndex(pIdx) ); 404648dd1d8eSdrh assert( pIdx->idxType!=SQLITE_IDXTYPE_APPDEF ); 40475f1d1d9cSdrh assert( IsUniqueIndex(pIndex) ); 4048d8123366Sdanielk1977 4049bbbdc83bSdrh if( pIdx->nKeyCol!=pIndex->nKeyCol ) continue; 4050bbbdc83bSdrh for(k=0; k<pIdx->nKeyCol; k++){ 4051d3001711Sdrh const char *z1; 4052d3001711Sdrh const char *z2; 40531f9ca2c8Sdrh assert( pIdx->aiColumn[k]>=0 ); 4054d8123366Sdanielk1977 if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break; 4055d3001711Sdrh z1 = pIdx->azColl[k]; 4056d3001711Sdrh z2 = pIndex->azColl[k]; 4057c41c132cSdrh if( sqlite3StrICmp(z1, z2) ) break; 4058d8123366Sdanielk1977 } 4059bbbdc83bSdrh if( k==pIdx->nKeyCol ){ 4060f736b771Sdanielk1977 if( pIdx->onError!=pIndex->onError ){ 4061f736b771Sdanielk1977 /* This constraint creates the same index as a previous 4062f736b771Sdanielk1977 ** constraint specified somewhere in the CREATE TABLE statement. 4063f736b771Sdanielk1977 ** However the ON CONFLICT clauses are different. If both this 4064f736b771Sdanielk1977 ** constraint and the previous equivalent constraint have explicit 4065f736b771Sdanielk1977 ** ON CONFLICT clauses this is an error. Otherwise, use the 406648864df9Smistachkin ** explicitly specified behavior for the index. 4067d8123366Sdanielk1977 */ 4068f736b771Sdanielk1977 if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){ 4069f736b771Sdanielk1977 sqlite3ErrorMsg(pParse, 4070f736b771Sdanielk1977 "conflicting ON CONFLICT clauses specified", 0); 4071f736b771Sdanielk1977 } 4072f736b771Sdanielk1977 if( pIdx->onError==OE_Default ){ 4073f736b771Sdanielk1977 pIdx->onError = pIndex->onError; 4074f736b771Sdanielk1977 } 4075f736b771Sdanielk1977 } 4076273bfe9fSdrh if( idxType==SQLITE_IDXTYPE_PRIMARYKEY ) pIdx->idxType = idxType; 4077885eeb67Sdrh if( IN_RENAME_OBJECT ){ 4078885eeb67Sdrh pIndex->pNext = pParse->pNewIndex; 4079885eeb67Sdrh pParse->pNewIndex = pIndex; 4080885eeb67Sdrh pIndex = 0; 4081885eeb67Sdrh } 4082d8123366Sdanielk1977 goto exit_create_index; 4083d8123366Sdanielk1977 } 4084d8123366Sdanielk1977 } 4085d8123366Sdanielk1977 } 4086d8123366Sdanielk1977 4087c9461eccSdan if( !IN_RENAME_OBJECT ){ 4088cf8f2895Sdan 408975897234Sdrh /* Link the new Index structure to its table and to the other 4090adbca9cfSdrh ** in-memory database structures. 409175897234Sdrh */ 40927d3d9daeSdrh assert( pParse->nErr==0 ); 4093cc971738Sdrh if( db->init.busy ){ 40946d4abfbeSdrh Index *p; 4095cf8f2895Sdan assert( !IN_SPECIAL_PARSE ); 40962120608eSdrh assert( sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) ); 4097234c39dfSdrh if( pTblName!=0 ){ 40981d85d931Sdrh pIndex->tnum = db->init.newTnum; 40998d40673cSdrh if( sqlite3IndexHasDuplicateRootPage(pIndex) ){ 41008d40673cSdrh sqlite3ErrorMsg(pParse, "invalid rootpage"); 41018d40673cSdrh pParse->rc = SQLITE_CORRUPT_BKPT; 41028d40673cSdrh goto exit_create_index; 41038d40673cSdrh } 4104d78eeee1Sdrh } 4105da7a4c0fSdan p = sqlite3HashInsert(&pIndex->pSchema->idxHash, 4106da7a4c0fSdan pIndex->zName, pIndex); 4107da7a4c0fSdan if( p ){ 4108da7a4c0fSdan assert( p==pIndex ); /* Malloc must have failed */ 4109da7a4c0fSdan sqlite3OomFault(db); 4110da7a4c0fSdan goto exit_create_index; 4111da7a4c0fSdan } 4112da7a4c0fSdan db->mDbFlags |= DBFLAG_SchemaChange; 4113234c39dfSdrh } 4114d78eeee1Sdrh 41155838340bSdrh /* If this is the initial CREATE INDEX statement (or CREATE TABLE if the 41165838340bSdrh ** index is an implied index for a UNIQUE or PRIMARY KEY constraint) then 41175838340bSdrh ** emit code to allocate the index rootpage on disk and make an entry for 41181e32bed3Sdrh ** the index in the sqlite_schema table and populate the index with 41191e32bed3Sdrh ** content. But, do not do this if we are simply reading the sqlite_schema 41205838340bSdrh ** table to parse the schema, or if this index is the PRIMARY KEY index 41215838340bSdrh ** of a WITHOUT ROWID table. 412275897234Sdrh ** 41235838340bSdrh ** If pTblName==0 it means this index is generated as an implied PRIMARY KEY 41245838340bSdrh ** or UNIQUE index in a CREATE TABLE statement. Since the table 4125382c0247Sdrh ** has just been created, it contains no data and the index initialization 4126382c0247Sdrh ** step can be skipped. 412775897234Sdrh */ 41287d3d9daeSdrh else if( HasRowid(pTab) || pTblName!=0 ){ 4129adbca9cfSdrh Vdbe *v; 4130063336a5Sdrh char *zStmt; 41310a07c107Sdrh int iMem = ++pParse->nMem; 413275897234Sdrh 41334adee20fSdanielk1977 v = sqlite3GetVdbe(pParse); 413475897234Sdrh if( v==0 ) goto exit_create_index; 4135063336a5Sdrh 4136aee128dcSdrh sqlite3BeginWriteOperation(pParse, 1, iDb); 4137c5b73585Sdan 4138c5b73585Sdan /* Create the rootpage for the index using CreateIndex. But before 4139c5b73585Sdan ** doing so, code a Noop instruction and store its address in 4140c5b73585Sdan ** Index.tnum. This is required in case this index is actually a 4141c5b73585Sdan ** PRIMARY KEY and the table is actually a WITHOUT ROWID table. In 4142c5b73585Sdan ** that case the convertToWithoutRowidTable() routine will replace 4143c5b73585Sdan ** the Noop with a Goto to jump over the VDBE code generated below. */ 4144abc38158Sdrh pIndex->tnum = (Pgno)sqlite3VdbeAddOp0(v, OP_Noop); 41450f3f7664Sdrh sqlite3VdbeAddOp3(v, OP_CreateBtree, iDb, iMem, BTREE_BLOBKEY); 4146063336a5Sdrh 4147063336a5Sdrh /* Gather the complete text of the CREATE INDEX statement into 4148063336a5Sdrh ** the zStmt variable 4149063336a5Sdrh */ 415055f66b34Sdrh assert( pName!=0 || pStart==0 ); 4151d3001711Sdrh if( pStart ){ 415277dfd5bbSdrh int n = (int)(pParse->sLastToken.z - pName->z) + pParse->sLastToken.n; 41538a9789b6Sdrh if( pName->z[n-1]==';' ) n--; 4154063336a5Sdrh /* A named index with an explicit CREATE INDEX statement */ 41551e536953Sdanielk1977 zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s", 41568a9789b6Sdrh onError==OE_None ? "" : " UNIQUE", n, pName->z); 41570202b29eSdanielk1977 }else{ 4158063336a5Sdrh /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */ 4159e497f005Sdrh /* zStmt = sqlite3MPrintf(""); */ 4160e497f005Sdrh zStmt = 0; 41610202b29eSdanielk1977 } 4162063336a5Sdrh 41631e32bed3Sdrh /* Add an entry in sqlite_schema for this index 4164063336a5Sdrh */ 4165063336a5Sdrh sqlite3NestedParse(pParse, 4166346a70caSdrh "INSERT INTO %Q." DFLT_SCHEMA_TABLE " VALUES('index',%Q,%Q,#%d,%Q);", 4167346a70caSdrh db->aDb[iDb].zDbSName, 4168063336a5Sdrh pIndex->zName, 4169063336a5Sdrh pTab->zName, 4170b7654111Sdrh iMem, 4171063336a5Sdrh zStmt 4172063336a5Sdrh ); 4173633e6d57Sdrh sqlite3DbFree(db, zStmt); 4174063336a5Sdrh 4175a21c6b6fSdanielk1977 /* Fill the index with data and reparse the schema. Code an OP_Expire 4176a21c6b6fSdanielk1977 ** to invalidate all pre-compiled statements. 4177063336a5Sdrh */ 4178cbb18d22Sdanielk1977 if( pTblName ){ 4179063336a5Sdrh sqlite3RefillIndex(pParse, pIndex, iMem); 41809cbf3425Sdrh sqlite3ChangeCookie(pParse, iDb); 41815d9c9da6Sdrh sqlite3VdbeAddParseSchemaOp(v, iDb, 41826a5a13dfSdan sqlite3MPrintf(db, "name='%q' AND type='index'", pIndex->zName), 0); 4183ba968dbfSdrh sqlite3VdbeAddOp2(v, OP_Expire, 0, 1); 418475897234Sdrh } 4185c5b73585Sdan 4186abc38158Sdrh sqlite3VdbeJumpHere(v, (int)pIndex->tnum); 418775897234Sdrh } 4188cf8f2895Sdan } 4189234c39dfSdrh if( db->init.busy || pTblName==0 ){ 4190d8123366Sdanielk1977 pIndex->pNext = pTab->pIndex; 4191d8123366Sdanielk1977 pTab->pIndex = pIndex; 4192d8123366Sdanielk1977 pIndex = 0; 4193234c39dfSdrh } 4194c9461eccSdan else if( IN_RENAME_OBJECT ){ 4195cf8f2895Sdan assert( pParse->pNewIndex==0 ); 4196cf8f2895Sdan pParse->pNewIndex = pIndex; 4197cf8f2895Sdan pIndex = 0; 4198cf8f2895Sdan } 4199d8123366Sdanielk1977 420075897234Sdrh /* Clean up before exiting */ 420175897234Sdrh exit_create_index: 4202cf8f2895Sdan if( pIndex ) sqlite3FreeIndex(db, pIndex); 420397060e5aSdrh if( pTab ){ 420497060e5aSdrh /* Ensure all REPLACE indexes on pTab are at the end of the pIndex list. 420597060e5aSdrh ** The list was already ordered when this routine was entered, so at this 420697060e5aSdrh ** point at most a single index (the newly added index) will be out of 420797060e5aSdrh ** order. So we have to reorder at most one index. */ 4208d35bdd6cSdrh Index **ppFrom = &pTab->pIndex; 4209d35bdd6cSdrh Index *pThis; 4210d35bdd6cSdrh for(ppFrom=&pTab->pIndex; (pThis = *ppFrom)!=0; ppFrom=&pThis->pNext){ 4211d35bdd6cSdrh Index *pNext; 4212d35bdd6cSdrh if( pThis->onError!=OE_Replace ) continue; 4213d35bdd6cSdrh while( (pNext = pThis->pNext)!=0 && pNext->onError!=OE_Replace ){ 4214d35bdd6cSdrh *ppFrom = pNext; 4215d35bdd6cSdrh pThis->pNext = pNext->pNext; 4216d35bdd6cSdrh pNext->pNext = pThis; 4217d35bdd6cSdrh ppFrom = &pNext->pNext; 4218d35bdd6cSdrh } 4219d35bdd6cSdrh break; 4220d35bdd6cSdrh } 422197060e5aSdrh #ifdef SQLITE_DEBUG 422297060e5aSdrh /* Verify that all REPLACE indexes really are now at the end 422397060e5aSdrh ** of the index list. In other words, no other index type ever 422497060e5aSdrh ** comes after a REPLACE index on the list. */ 422597060e5aSdrh for(pThis = pTab->pIndex; pThis; pThis=pThis->pNext){ 422697060e5aSdrh assert( pThis->onError!=OE_Replace 422797060e5aSdrh || pThis->pNext==0 422897060e5aSdrh || pThis->pNext->onError==OE_Replace ); 422997060e5aSdrh } 423097060e5aSdrh #endif 4231d35bdd6cSdrh } 42321fe0537eSdrh sqlite3ExprDelete(db, pPIWhere); 4233633e6d57Sdrh sqlite3ExprListDelete(db, pList); 4234633e6d57Sdrh sqlite3SrcListDelete(db, pTblName); 4235633e6d57Sdrh sqlite3DbFree(db, zName); 423675897234Sdrh } 423775897234Sdrh 423875897234Sdrh /* 423951147baaSdrh ** Fill the Index.aiRowEst[] array with default information - information 424091124b35Sdrh ** to be used when we have not run the ANALYZE command. 424128c4cf42Sdrh ** 424260ec914cSpeter.d.reid ** aiRowEst[0] is supposed to contain the number of elements in the index. 424328c4cf42Sdrh ** Since we do not know, guess 1 million. aiRowEst[1] is an estimate of the 424428c4cf42Sdrh ** number of rows in the table that match any particular value of the 424528c4cf42Sdrh ** first column of the index. aiRowEst[2] is an estimate of the number 4246cfc9df76Sdan ** of rows that match any particular combination of the first 2 columns 424728c4cf42Sdrh ** of the index. And so forth. It must always be the case that 424828c4cf42Sdrh * 424928c4cf42Sdrh ** aiRowEst[N]<=aiRowEst[N-1] 425028c4cf42Sdrh ** aiRowEst[N]>=1 425128c4cf42Sdrh ** 425228c4cf42Sdrh ** Apart from that, we have little to go on besides intuition as to 425328c4cf42Sdrh ** how aiRowEst[] should be initialized. The numbers generated here 425428c4cf42Sdrh ** are based on typical values found in actual indices. 425551147baaSdrh */ 425651147baaSdrh void sqlite3DefaultRowEst(Index *pIdx){ 4257264d2b97Sdan /* 10, 9, 8, 7, 6 */ 425856c65c92Sdrh static const LogEst aVal[] = { 33, 32, 30, 28, 26 }; 4259cfc9df76Sdan LogEst *a = pIdx->aiRowLogEst; 426056c65c92Sdrh LogEst x; 4261cfc9df76Sdan int nCopy = MIN(ArraySize(aVal), pIdx->nKeyCol); 426251147baaSdrh int i; 4263cfc9df76Sdan 426433bec3f5Sdrh /* Indexes with default row estimates should not have stat1 data */ 426533bec3f5Sdrh assert( !pIdx->hasStat1 ); 426633bec3f5Sdrh 4267264d2b97Sdan /* Set the first entry (number of rows in the index) to the estimated 42688dc570b6Sdrh ** number of rows in the table, or half the number of rows in the table 426956c65c92Sdrh ** for a partial index. 427056c65c92Sdrh ** 427156c65c92Sdrh ** 2020-05-27: If some of the stat data is coming from the sqlite_stat1 427256c65c92Sdrh ** table but other parts we are having to guess at, then do not let the 427356c65c92Sdrh ** estimated number of rows in the table be less than 1000 (LogEst 99). 427456c65c92Sdrh ** Failure to do this can cause the indexes for which we do not have 42758c1fbe81Sdrh ** stat1 data to be ignored by the query planner. 427656c65c92Sdrh */ 427756c65c92Sdrh x = pIdx->pTable->nRowLogEst; 427856c65c92Sdrh assert( 99==sqlite3LogEst(1000) ); 427956c65c92Sdrh if( x<99 ){ 428056c65c92Sdrh pIdx->pTable->nRowLogEst = x = 99; 428156c65c92Sdrh } 42825f086ddeSdrh if( pIdx->pPartIdxWhere!=0 ){ x -= 10; assert( 10==sqlite3LogEst(2) ); } 428356c65c92Sdrh a[0] = x; 4284264d2b97Sdan 4285264d2b97Sdan /* Estimate that a[1] is 10, a[2] is 9, a[3] is 8, a[4] is 7, a[5] is 4286264d2b97Sdan ** 6 and each subsequent value (if any) is 5. */ 4287cfc9df76Sdan memcpy(&a[1], aVal, nCopy*sizeof(LogEst)); 4288264d2b97Sdan for(i=nCopy+1; i<=pIdx->nKeyCol; i++){ 4289264d2b97Sdan a[i] = 23; assert( 23==sqlite3LogEst(5) ); 429028c4cf42Sdrh } 4291264d2b97Sdan 4292264d2b97Sdan assert( 0==sqlite3LogEst(1) ); 42935f1d1d9cSdrh if( IsUniqueIndex(pIdx) ) a[pIdx->nKeyCol] = 0; 429451147baaSdrh } 429551147baaSdrh 429651147baaSdrh /* 429774e24cd0Sdrh ** This routine will drop an existing named index. This routine 429874e24cd0Sdrh ** implements the DROP INDEX statement. 429975897234Sdrh */ 43004d91a701Sdrh void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){ 430175897234Sdrh Index *pIndex; 430275897234Sdrh Vdbe *v; 43039bb575fdSdrh sqlite3 *db = pParse->db; 4304da184236Sdanielk1977 int iDb; 430575897234Sdrh 43068af73d41Sdrh assert( pParse->nErr==0 ); /* Never called with prior errors */ 43078af73d41Sdrh if( db->mallocFailed ){ 4308d5d56523Sdanielk1977 goto exit_drop_index; 4309d5d56523Sdanielk1977 } 4310d24cc427Sdrh assert( pName->nSrc==1 ); 4311d5d56523Sdanielk1977 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){ 4312d5d56523Sdanielk1977 goto exit_drop_index; 4313d5d56523Sdanielk1977 } 43144adee20fSdanielk1977 pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase); 431575897234Sdrh if( pIndex==0 ){ 43164d91a701Sdrh if( !ifExists ){ 4317a979993bSdrh sqlite3ErrorMsg(pParse, "no such index: %S", pName->a); 431857966753Sdan }else{ 431957966753Sdan sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase); 432031da7be9Sdrh sqlite3ForceNotReadOnly(pParse); 43214d91a701Sdrh } 4322a6ecd338Sdrh pParse->checkSchema = 1; 4323d24cc427Sdrh goto exit_drop_index; 432475897234Sdrh } 432548dd1d8eSdrh if( pIndex->idxType!=SQLITE_IDXTYPE_APPDEF ){ 43264adee20fSdanielk1977 sqlite3ErrorMsg(pParse, "index associated with UNIQUE " 4327485b39b4Sdrh "or PRIMARY KEY constraint cannot be dropped", 0); 4328d24cc427Sdrh goto exit_drop_index; 4329d24cc427Sdrh } 4330da184236Sdanielk1977 iDb = sqlite3SchemaToIndex(db, pIndex->pSchema); 4331e5f9c644Sdrh #ifndef SQLITE_OMIT_AUTHORIZATION 4332e5f9c644Sdrh { 4333e5f9c644Sdrh int code = SQLITE_DROP_INDEX; 4334e5f9c644Sdrh Table *pTab = pIndex->pTable; 433569c33826Sdrh const char *zDb = db->aDb[iDb].zDbSName; 4336da184236Sdanielk1977 const char *zTab = SCHEMA_TABLE(iDb); 43374adee20fSdanielk1977 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){ 4338d24cc427Sdrh goto exit_drop_index; 4339ed6c8671Sdrh } 434093fd5420Sdrh if( !OMIT_TEMPDB && iDb==1 ) code = SQLITE_DROP_TEMP_INDEX; 43414adee20fSdanielk1977 if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){ 4342d24cc427Sdrh goto exit_drop_index; 4343e5f9c644Sdrh } 4344e5f9c644Sdrh } 4345e5f9c644Sdrh #endif 434675897234Sdrh 4347067b92baSdrh /* Generate code to remove the index and from the schema table */ 43484adee20fSdanielk1977 v = sqlite3GetVdbe(pParse); 434975897234Sdrh if( v ){ 435077658e2fSdrh sqlite3BeginWriteOperation(pParse, 1, iDb); 4351b17131a0Sdrh sqlite3NestedParse(pParse, 4352346a70caSdrh "DELETE FROM %Q." DFLT_SCHEMA_TABLE " WHERE name=%Q AND type='index'", 4353346a70caSdrh db->aDb[iDb].zDbSName, pIndex->zName 4354b17131a0Sdrh ); 4355a5ae4c33Sdrh sqlite3ClearStatTables(pParse, iDb, "idx", pIndex->zName); 43569cbf3425Sdrh sqlite3ChangeCookie(pParse, iDb); 4357b17131a0Sdrh destroyRootPage(pParse, pIndex->tnum, iDb); 435866a5167bSdrh sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0); 435975897234Sdrh } 436075897234Sdrh 4361d24cc427Sdrh exit_drop_index: 4362633e6d57Sdrh sqlite3SrcListDelete(db, pName); 436375897234Sdrh } 436475897234Sdrh 436575897234Sdrh /* 4366cf643729Sdrh ** pArray is a pointer to an array of objects. Each object in the 43679ace112cSdan ** array is szEntry bytes in size. This routine uses sqlite3DbRealloc() 43689ace112cSdan ** to extend the array so that there is space for a new object at the end. 436913449892Sdrh ** 43709ace112cSdan ** When this function is called, *pnEntry contains the current size of 43719ace112cSdan ** the array (in entries - so the allocation is ((*pnEntry) * szEntry) bytes 43729ace112cSdan ** in total). 437313449892Sdrh ** 43749ace112cSdan ** If the realloc() is successful (i.e. if no OOM condition occurs), the 43759ace112cSdan ** space allocated for the new object is zeroed, *pnEntry updated to 43769ace112cSdan ** reflect the new size of the array and a pointer to the new allocation 43779ace112cSdan ** returned. *pIdx is set to the index of the new array entry in this case. 437813449892Sdrh ** 43799ace112cSdan ** Otherwise, if the realloc() fails, *pIdx is set to -1, *pnEntry remains 43809ace112cSdan ** unchanged and a copy of pArray returned. 438113449892Sdrh */ 4382cf643729Sdrh void *sqlite3ArrayAllocate( 438317435752Sdrh sqlite3 *db, /* Connection to notify of malloc failures */ 4384cf643729Sdrh void *pArray, /* Array of objects. Might be reallocated */ 4385cf643729Sdrh int szEntry, /* Size of each object in the array */ 4386cf643729Sdrh int *pnEntry, /* Number of objects currently in use */ 4387cf643729Sdrh int *pIdx /* Write the index of a new slot here */ 4388cf643729Sdrh ){ 4389cf643729Sdrh char *z; 4390f6ad201aSdrh sqlite3_int64 n = *pIdx = *pnEntry; 43916c535158Sdrh if( (n & (n-1))==0 ){ 43920aa3231fSdrh sqlite3_int64 sz = (n==0) ? 1 : 2*n; 43936c535158Sdrh void *pNew = sqlite3DbRealloc(db, pArray, sz*szEntry); 439413449892Sdrh if( pNew==0 ){ 4395cf643729Sdrh *pIdx = -1; 4396cf643729Sdrh return pArray; 439713449892Sdrh } 4398cf643729Sdrh pArray = pNew; 439913449892Sdrh } 4400cf643729Sdrh z = (char*)pArray; 44016c535158Sdrh memset(&z[n * szEntry], 0, szEntry); 4402cf643729Sdrh ++*pnEntry; 4403cf643729Sdrh return pArray; 440413449892Sdrh } 440513449892Sdrh 440613449892Sdrh /* 440775897234Sdrh ** Append a new element to the given IdList. Create a new IdList if 440875897234Sdrh ** need be. 4409daffd0e5Sdrh ** 4410daffd0e5Sdrh ** A new IdList is returned, or NULL if malloc() fails. 441175897234Sdrh */ 44125496d6a2Sdan IdList *sqlite3IdListAppend(Parse *pParse, IdList *pList, Token *pToken){ 44135496d6a2Sdan sqlite3 *db = pParse->db; 441413449892Sdrh int i; 441575897234Sdrh if( pList==0 ){ 441617435752Sdrh pList = sqlite3DbMallocZero(db, sizeof(IdList) ); 441775897234Sdrh if( pList==0 ) return 0; 441875897234Sdrh } 4419cf643729Sdrh pList->a = sqlite3ArrayAllocate( 442017435752Sdrh db, 4421cf643729Sdrh pList->a, 4422cf643729Sdrh sizeof(pList->a[0]), 4423cf643729Sdrh &pList->nId, 4424cf643729Sdrh &i 4425cf643729Sdrh ); 442613449892Sdrh if( i<0 ){ 4427633e6d57Sdrh sqlite3IdListDelete(db, pList); 4428daffd0e5Sdrh return 0; 442975897234Sdrh } 443017435752Sdrh pList->a[i].zName = sqlite3NameFromToken(db, pToken); 4431c9461eccSdan if( IN_RENAME_OBJECT && pList->a[i].zName ){ 443207e95233Sdan sqlite3RenameTokenMap(pParse, (void*)pList->a[i].zName, pToken); 44335496d6a2Sdan } 443475897234Sdrh return pList; 443575897234Sdrh } 443675897234Sdrh 443775897234Sdrh /* 4438fe05af87Sdrh ** Delete an IdList. 4439fe05af87Sdrh */ 4440633e6d57Sdrh void sqlite3IdListDelete(sqlite3 *db, IdList *pList){ 4441fe05af87Sdrh int i; 4442fe05af87Sdrh if( pList==0 ) return; 4443fe05af87Sdrh for(i=0; i<pList->nId; i++){ 4444633e6d57Sdrh sqlite3DbFree(db, pList->a[i].zName); 4445fe05af87Sdrh } 4446633e6d57Sdrh sqlite3DbFree(db, pList->a); 4447dbd6a7dcSdrh sqlite3DbFreeNN(db, pList); 4448fe05af87Sdrh } 4449fe05af87Sdrh 4450fe05af87Sdrh /* 4451fe05af87Sdrh ** Return the index in pList of the identifier named zId. Return -1 4452fe05af87Sdrh ** if not found. 4453fe05af87Sdrh */ 4454fe05af87Sdrh int sqlite3IdListIndex(IdList *pList, const char *zName){ 4455fe05af87Sdrh int i; 4456fe05af87Sdrh if( pList==0 ) return -1; 4457fe05af87Sdrh for(i=0; i<pList->nId; i++){ 4458fe05af87Sdrh if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i; 4459fe05af87Sdrh } 4460fe05af87Sdrh return -1; 4461fe05af87Sdrh } 4462fe05af87Sdrh 4463fe05af87Sdrh /* 44640ad7aa81Sdrh ** Maximum size of a SrcList object. 44650ad7aa81Sdrh ** The SrcList object is used to represent the FROM clause of a 44660ad7aa81Sdrh ** SELECT statement, and the query planner cannot deal with more 44670ad7aa81Sdrh ** than 64 tables in a join. So any value larger than 64 here 44680ad7aa81Sdrh ** is sufficient for most uses. Smaller values, like say 10, are 44690ad7aa81Sdrh ** appropriate for small and memory-limited applications. 44700ad7aa81Sdrh */ 44710ad7aa81Sdrh #ifndef SQLITE_MAX_SRCLIST 44720ad7aa81Sdrh # define SQLITE_MAX_SRCLIST 200 44730ad7aa81Sdrh #endif 44740ad7aa81Sdrh 44750ad7aa81Sdrh /* 4476a78c22c4Sdrh ** Expand the space allocated for the given SrcList object by 4477a78c22c4Sdrh ** creating nExtra new slots beginning at iStart. iStart is zero based. 4478a78c22c4Sdrh ** New slots are zeroed. 4479a78c22c4Sdrh ** 4480a78c22c4Sdrh ** For example, suppose a SrcList initially contains two entries: A,B. 4481a78c22c4Sdrh ** To append 3 new entries onto the end, do this: 4482a78c22c4Sdrh ** 4483a78c22c4Sdrh ** sqlite3SrcListEnlarge(db, pSrclist, 3, 2); 4484a78c22c4Sdrh ** 4485a78c22c4Sdrh ** After the call above it would contain: A, B, nil, nil, nil. 4486a78c22c4Sdrh ** If the iStart argument had been 1 instead of 2, then the result 4487a78c22c4Sdrh ** would have been: A, nil, nil, nil, B. To prepend the new slots, 4488a78c22c4Sdrh ** the iStart value would be 0. The result then would 4489a78c22c4Sdrh ** be: nil, nil, nil, A, B. 4490a78c22c4Sdrh ** 449129c992cbSdrh ** If a memory allocation fails or the SrcList becomes too large, leave 449229c992cbSdrh ** the original SrcList unchanged, return NULL, and leave an error message 449329c992cbSdrh ** in pParse. 4494a78c22c4Sdrh */ 4495a78c22c4Sdrh SrcList *sqlite3SrcListEnlarge( 449629c992cbSdrh Parse *pParse, /* Parsing context into which errors are reported */ 4497a78c22c4Sdrh SrcList *pSrc, /* The SrcList to be enlarged */ 4498a78c22c4Sdrh int nExtra, /* Number of new slots to add to pSrc->a[] */ 4499a78c22c4Sdrh int iStart /* Index in pSrc->a[] of first new slot */ 4500a78c22c4Sdrh ){ 4501a78c22c4Sdrh int i; 4502a78c22c4Sdrh 4503a78c22c4Sdrh /* Sanity checking on calling parameters */ 4504a78c22c4Sdrh assert( iStart>=0 ); 4505a78c22c4Sdrh assert( nExtra>=1 ); 45068af73d41Sdrh assert( pSrc!=0 ); 45078af73d41Sdrh assert( iStart<=pSrc->nSrc ); 4508a78c22c4Sdrh 4509a78c22c4Sdrh /* Allocate additional space if needed */ 4510fc5717ccSdrh if( (u32)pSrc->nSrc+nExtra>pSrc->nAlloc ){ 4511a78c22c4Sdrh SrcList *pNew; 45120aa3231fSdrh sqlite3_int64 nAlloc = 2*(sqlite3_int64)pSrc->nSrc+nExtra; 451329c992cbSdrh sqlite3 *db = pParse->db; 45140ad7aa81Sdrh 45150ad7aa81Sdrh if( pSrc->nSrc+nExtra>=SQLITE_MAX_SRCLIST ){ 451629c992cbSdrh sqlite3ErrorMsg(pParse, "too many FROM clause terms, max: %d", 451729c992cbSdrh SQLITE_MAX_SRCLIST); 451829c992cbSdrh return 0; 45190ad7aa81Sdrh } 45200ad7aa81Sdrh if( nAlloc>SQLITE_MAX_SRCLIST ) nAlloc = SQLITE_MAX_SRCLIST; 4521a78c22c4Sdrh pNew = sqlite3DbRealloc(db, pSrc, 4522a78c22c4Sdrh sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) ); 4523a78c22c4Sdrh if( pNew==0 ){ 4524a78c22c4Sdrh assert( db->mallocFailed ); 452529c992cbSdrh return 0; 4526a78c22c4Sdrh } 4527a78c22c4Sdrh pSrc = pNew; 4528d0ee3a1eSdrh pSrc->nAlloc = nAlloc; 4529a78c22c4Sdrh } 4530a78c22c4Sdrh 4531a78c22c4Sdrh /* Move existing slots that come after the newly inserted slots 4532a78c22c4Sdrh ** out of the way */ 4533a78c22c4Sdrh for(i=pSrc->nSrc-1; i>=iStart; i--){ 4534a78c22c4Sdrh pSrc->a[i+nExtra] = pSrc->a[i]; 4535a78c22c4Sdrh } 45366d1626ebSdrh pSrc->nSrc += nExtra; 4537a78c22c4Sdrh 4538a78c22c4Sdrh /* Zero the newly allocated slots */ 4539a78c22c4Sdrh memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra); 4540a78c22c4Sdrh for(i=iStart; i<iStart+nExtra; i++){ 4541a78c22c4Sdrh pSrc->a[i].iCursor = -1; 4542a78c22c4Sdrh } 4543a78c22c4Sdrh 4544a78c22c4Sdrh /* Return a pointer to the enlarged SrcList */ 4545a78c22c4Sdrh return pSrc; 4546a78c22c4Sdrh } 4547a78c22c4Sdrh 4548a78c22c4Sdrh 4549a78c22c4Sdrh /* 4550ad3cab52Sdrh ** Append a new table name to the given SrcList. Create a new SrcList if 4551b7916a78Sdrh ** need be. A new entry is created in the SrcList even if pTable is NULL. 4552ad3cab52Sdrh ** 455329c992cbSdrh ** A SrcList is returned, or NULL if there is an OOM error or if the 455429c992cbSdrh ** SrcList grows to large. The returned 4555a78c22c4Sdrh ** SrcList might be the same as the SrcList that was input or it might be 4556a78c22c4Sdrh ** a new one. If an OOM error does occurs, then the prior value of pList 4557a78c22c4Sdrh ** that is input to this routine is automatically freed. 4558113088ecSdrh ** 4559113088ecSdrh ** If pDatabase is not null, it means that the table has an optional 4560113088ecSdrh ** database name prefix. Like this: "database.table". The pDatabase 4561113088ecSdrh ** points to the table name and the pTable points to the database name. 4562113088ecSdrh ** The SrcList.a[].zName field is filled with the table name which might 4563113088ecSdrh ** come from pTable (if pDatabase is NULL) or from pDatabase. 4564113088ecSdrh ** SrcList.a[].zDatabase is filled with the database name from pTable, 4565113088ecSdrh ** or with NULL if no database is specified. 4566113088ecSdrh ** 4567113088ecSdrh ** In other words, if call like this: 4568113088ecSdrh ** 456917435752Sdrh ** sqlite3SrcListAppend(D,A,B,0); 4570113088ecSdrh ** 4571113088ecSdrh ** Then B is a table name and the database name is unspecified. If called 4572113088ecSdrh ** like this: 4573113088ecSdrh ** 457417435752Sdrh ** sqlite3SrcListAppend(D,A,B,C); 4575113088ecSdrh ** 4576d3001711Sdrh ** Then C is the table name and B is the database name. If C is defined 4577d3001711Sdrh ** then so is B. In other words, we never have a case where: 4578d3001711Sdrh ** 4579d3001711Sdrh ** sqlite3SrcListAppend(D,A,0,C); 4580b7916a78Sdrh ** 4581b7916a78Sdrh ** Both pTable and pDatabase are assumed to be quoted. They are dequoted 4582b7916a78Sdrh ** before being added to the SrcList. 4583ad3cab52Sdrh */ 458417435752Sdrh SrcList *sqlite3SrcListAppend( 458529c992cbSdrh Parse *pParse, /* Parsing context, in which errors are reported */ 458617435752Sdrh SrcList *pList, /* Append to this SrcList. NULL creates a new SrcList */ 458717435752Sdrh Token *pTable, /* Table to append */ 458817435752Sdrh Token *pDatabase /* Database of the table */ 458917435752Sdrh ){ 45907601294aSdrh SrcItem *pItem; 459129c992cbSdrh sqlite3 *db; 4592d3001711Sdrh assert( pDatabase==0 || pTable!=0 ); /* Cannot have C without B */ 459329c992cbSdrh assert( pParse!=0 ); 459429c992cbSdrh assert( pParse->db!=0 ); 459529c992cbSdrh db = pParse->db; 4596ad3cab52Sdrh if( pList==0 ){ 459729c992cbSdrh pList = sqlite3DbMallocRawNN(pParse->db, sizeof(SrcList) ); 4598ad3cab52Sdrh if( pList==0 ) return 0; 45994305d103Sdrh pList->nAlloc = 1; 4600ac178b3dSdrh pList->nSrc = 1; 4601ac178b3dSdrh memset(&pList->a[0], 0, sizeof(pList->a[0])); 4602ac178b3dSdrh pList->a[0].iCursor = -1; 4603ac178b3dSdrh }else{ 460429c992cbSdrh SrcList *pNew = sqlite3SrcListEnlarge(pParse, pList, 1, pList->nSrc); 460529c992cbSdrh if( pNew==0 ){ 4606633e6d57Sdrh sqlite3SrcListDelete(db, pList); 4607ad3cab52Sdrh return 0; 460829c992cbSdrh }else{ 460929c992cbSdrh pList = pNew; 461029c992cbSdrh } 4611ad3cab52Sdrh } 4612a78c22c4Sdrh pItem = &pList->a[pList->nSrc-1]; 4613113088ecSdrh if( pDatabase && pDatabase->z==0 ){ 4614113088ecSdrh pDatabase = 0; 4615113088ecSdrh } 4616d3001711Sdrh if( pDatabase ){ 4617169a689fSdrh pItem->zName = sqlite3NameFromToken(db, pDatabase); 4618169a689fSdrh pItem->zDatabase = sqlite3NameFromToken(db, pTable); 4619169a689fSdrh }else{ 462017435752Sdrh pItem->zName = sqlite3NameFromToken(db, pTable); 4621169a689fSdrh pItem->zDatabase = 0; 4622169a689fSdrh } 4623ad3cab52Sdrh return pList; 4624ad3cab52Sdrh } 4625ad3cab52Sdrh 4626ad3cab52Sdrh /* 4627dfe88eceSdrh ** Assign VdbeCursor index numbers to all tables in a SrcList 462863eb5f29Sdrh */ 46294adee20fSdanielk1977 void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){ 463063eb5f29Sdrh int i; 46317601294aSdrh SrcItem *pItem; 463292a2824cSdrh assert( pList || pParse->db->mallocFailed ); 46339da977f1Sdrh if( ALWAYS(pList) ){ 46349b3187e1Sdrh for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){ 463534055854Sdrh if( pItem->iCursor>=0 ) continue; 46369b3187e1Sdrh pItem->iCursor = pParse->nTab++; 46379b3187e1Sdrh if( pItem->pSelect ){ 46389b3187e1Sdrh sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc); 463963eb5f29Sdrh } 464063eb5f29Sdrh } 464163eb5f29Sdrh } 4642261919ccSdanielk1977 } 464363eb5f29Sdrh 464463eb5f29Sdrh /* 4645ad3cab52Sdrh ** Delete an entire SrcList including all its substructure. 4646ad3cab52Sdrh */ 4647633e6d57Sdrh void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){ 4648ad3cab52Sdrh int i; 46497601294aSdrh SrcItem *pItem; 4650ad3cab52Sdrh if( pList==0 ) return; 4651be5c89acSdrh for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){ 465245d827cbSdrh if( pItem->zDatabase ) sqlite3DbFreeNN(db, pItem->zDatabase); 4653633e6d57Sdrh sqlite3DbFree(db, pItem->zName); 465445d827cbSdrh if( pItem->zAlias ) sqlite3DbFreeNN(db, pItem->zAlias); 46558a48b9c0Sdrh if( pItem->fg.isIndexedBy ) sqlite3DbFree(db, pItem->u1.zIndexedBy); 46568a48b9c0Sdrh if( pItem->fg.isTabFunc ) sqlite3ExprListDelete(db, pItem->u1.pFuncArg); 46571feeaed2Sdan sqlite3DeleteTable(db, pItem->pTab); 465845d827cbSdrh if( pItem->pSelect ) sqlite3SelectDelete(db, pItem->pSelect); 465945d827cbSdrh if( pItem->pOn ) sqlite3ExprDelete(db, pItem->pOn); 466045d827cbSdrh if( pItem->pUsing ) sqlite3IdListDelete(db, pItem->pUsing); 466175897234Sdrh } 4662dbd6a7dcSdrh sqlite3DbFreeNN(db, pList); 466375897234Sdrh } 466475897234Sdrh 4665982cef7eSdrh /* 466661dfc31dSdrh ** This routine is called by the parser to add a new term to the 466761dfc31dSdrh ** end of a growing FROM clause. The "p" parameter is the part of 466861dfc31dSdrh ** the FROM clause that has already been constructed. "p" is NULL 466961dfc31dSdrh ** if this is the first term of the FROM clause. pTable and pDatabase 467061dfc31dSdrh ** are the name of the table and database named in the FROM clause term. 467161dfc31dSdrh ** pDatabase is NULL if the database name qualifier is missing - the 467260ec914cSpeter.d.reid ** usual case. If the term has an alias, then pAlias points to the 467361dfc31dSdrh ** alias token. If the term is a subquery, then pSubquery is the 467461dfc31dSdrh ** SELECT statement that the subquery encodes. The pTable and 467561dfc31dSdrh ** pDatabase parameters are NULL for subqueries. The pOn and pUsing 467661dfc31dSdrh ** parameters are the content of the ON and USING clauses. 467761dfc31dSdrh ** 467861dfc31dSdrh ** Return a new SrcList which encodes is the FROM with the new 467961dfc31dSdrh ** term added. 468061dfc31dSdrh */ 468161dfc31dSdrh SrcList *sqlite3SrcListAppendFromTerm( 468217435752Sdrh Parse *pParse, /* Parsing context */ 468361dfc31dSdrh SrcList *p, /* The left part of the FROM clause already seen */ 468461dfc31dSdrh Token *pTable, /* Name of the table to add to the FROM clause */ 468561dfc31dSdrh Token *pDatabase, /* Name of the database containing pTable */ 468661dfc31dSdrh Token *pAlias, /* The right-hand side of the AS subexpression */ 468761dfc31dSdrh Select *pSubquery, /* A subquery used in place of a table name */ 468861dfc31dSdrh Expr *pOn, /* The ON clause of a join */ 468961dfc31dSdrh IdList *pUsing /* The USING clause of a join */ 469061dfc31dSdrh ){ 46917601294aSdrh SrcItem *pItem; 469217435752Sdrh sqlite3 *db = pParse->db; 4693bd1a0a4fSdanielk1977 if( !p && (pOn || pUsing) ){ 4694bd1a0a4fSdanielk1977 sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s", 4695bd1a0a4fSdanielk1977 (pOn ? "ON" : "USING") 4696bd1a0a4fSdanielk1977 ); 4697bd1a0a4fSdanielk1977 goto append_from_error; 4698bd1a0a4fSdanielk1977 } 469929c992cbSdrh p = sqlite3SrcListAppend(pParse, p, pTable, pDatabase); 47009d9c41e2Sdrh if( p==0 ){ 4701bd1a0a4fSdanielk1977 goto append_from_error; 470261dfc31dSdrh } 47039d9c41e2Sdrh assert( p->nSrc>0 ); 470461dfc31dSdrh pItem = &p->a[p->nSrc-1]; 4705a488ec9fSdrh assert( (pTable==0)==(pDatabase==0) ); 4706a488ec9fSdrh assert( pItem->zName==0 || pDatabase!=0 ); 4707c9461eccSdan if( IN_RENAME_OBJECT && pItem->zName ){ 4708a488ec9fSdrh Token *pToken = (ALWAYS(pDatabase) && pDatabase->z) ? pDatabase : pTable; 4709c9461eccSdan sqlite3RenameTokenMap(pParse, pItem->zName, pToken); 4710c9461eccSdan } 47118af73d41Sdrh assert( pAlias!=0 ); 47128af73d41Sdrh if( pAlias->n ){ 471317435752Sdrh pItem->zAlias = sqlite3NameFromToken(db, pAlias); 471461dfc31dSdrh } 471561dfc31dSdrh pItem->pSelect = pSubquery; 471661dfc31dSdrh pItem->pOn = pOn; 471761dfc31dSdrh pItem->pUsing = pUsing; 4718bd1a0a4fSdanielk1977 return p; 4719bd1a0a4fSdanielk1977 4720bd1a0a4fSdanielk1977 append_from_error: 4721bd1a0a4fSdanielk1977 assert( p==0 ); 47229b87d7b9Sdanielk1977 sqlite3ExprDelete(db, pOn); 47239b87d7b9Sdanielk1977 sqlite3IdListDelete(db, pUsing); 4724bd1a0a4fSdanielk1977 sqlite3SelectDelete(db, pSubquery); 4725bd1a0a4fSdanielk1977 return 0; 472661dfc31dSdrh } 472761dfc31dSdrh 472861dfc31dSdrh /* 4729b1c685b0Sdanielk1977 ** Add an INDEXED BY or NOT INDEXED clause to the most recently added 4730b1c685b0Sdanielk1977 ** element of the source-list passed as the second argument. 4731b1c685b0Sdanielk1977 */ 4732b1c685b0Sdanielk1977 void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){ 47338af73d41Sdrh assert( pIndexedBy!=0 ); 47348abc80b2Sdrh if( p && pIndexedBy->n>0 ){ 47357601294aSdrh SrcItem *pItem; 47368abc80b2Sdrh assert( p->nSrc>0 ); 47378abc80b2Sdrh pItem = &p->a[p->nSrc-1]; 47388a48b9c0Sdrh assert( pItem->fg.notIndexed==0 ); 47398a48b9c0Sdrh assert( pItem->fg.isIndexedBy==0 ); 47408a48b9c0Sdrh assert( pItem->fg.isTabFunc==0 ); 4741b1c685b0Sdanielk1977 if( pIndexedBy->n==1 && !pIndexedBy->z ){ 4742b1c685b0Sdanielk1977 /* A "NOT INDEXED" clause was supplied. See parse.y 4743b1c685b0Sdanielk1977 ** construct "indexed_opt" for details. */ 47448a48b9c0Sdrh pItem->fg.notIndexed = 1; 4745b1c685b0Sdanielk1977 }else{ 47468a48b9c0Sdrh pItem->u1.zIndexedBy = sqlite3NameFromToken(pParse->db, pIndexedBy); 47478abc80b2Sdrh pItem->fg.isIndexedBy = 1; 4748b1c685b0Sdanielk1977 } 4749b1c685b0Sdanielk1977 } 4750b1c685b0Sdanielk1977 } 4751b1c685b0Sdanielk1977 4752b1c685b0Sdanielk1977 /* 475369887c99Sdan ** Append the contents of SrcList p2 to SrcList p1 and return the resulting 475469887c99Sdan ** SrcList. Or, if an error occurs, return NULL. In all cases, p1 and p2 475569887c99Sdan ** are deleted by this function. 475669887c99Sdan */ 475769887c99Sdan SrcList *sqlite3SrcListAppendList(Parse *pParse, SrcList *p1, SrcList *p2){ 47588b023cf5Sdan assert( p1 && p1->nSrc==1 ); 47598b023cf5Sdan if( p2 ){ 47608b023cf5Sdan SrcList *pNew = sqlite3SrcListEnlarge(pParse, p1, p2->nSrc, 1); 47618b023cf5Sdan if( pNew==0 ){ 47628b023cf5Sdan sqlite3SrcListDelete(pParse->db, p2); 47638b023cf5Sdan }else{ 47648b023cf5Sdan p1 = pNew; 47657601294aSdrh memcpy(&p1->a[1], p2->a, p2->nSrc*sizeof(SrcItem)); 4766525326efSdrh sqlite3DbFree(pParse->db, p2); 476769887c99Sdan } 476869887c99Sdan } 476969887c99Sdan return p1; 477069887c99Sdan } 477169887c99Sdan 477269887c99Sdan /* 477301d230ceSdrh ** Add the list of function arguments to the SrcList entry for a 477401d230ceSdrh ** table-valued-function. 477501d230ceSdrh */ 477601d230ceSdrh void sqlite3SrcListFuncArgs(Parse *pParse, SrcList *p, ExprList *pList){ 477720292310Sdrh if( p ){ 47787601294aSdrh SrcItem *pItem = &p->a[p->nSrc-1]; 477901d230ceSdrh assert( pItem->fg.notIndexed==0 ); 478001d230ceSdrh assert( pItem->fg.isIndexedBy==0 ); 478101d230ceSdrh assert( pItem->fg.isTabFunc==0 ); 478201d230ceSdrh pItem->u1.pFuncArg = pList; 478301d230ceSdrh pItem->fg.isTabFunc = 1; 4784d8b1bfc6Sdrh }else{ 4785d8b1bfc6Sdrh sqlite3ExprListDelete(pParse->db, pList); 478601d230ceSdrh } 478701d230ceSdrh } 478801d230ceSdrh 478901d230ceSdrh /* 479061dfc31dSdrh ** When building up a FROM clause in the parser, the join operator 479161dfc31dSdrh ** is initially attached to the left operand. But the code generator 479261dfc31dSdrh ** expects the join operator to be on the right operand. This routine 479361dfc31dSdrh ** Shifts all join operators from left to right for an entire FROM 479461dfc31dSdrh ** clause. 479561dfc31dSdrh ** 479661dfc31dSdrh ** Example: Suppose the join is like this: 479761dfc31dSdrh ** 479861dfc31dSdrh ** A natural cross join B 479961dfc31dSdrh ** 480061dfc31dSdrh ** The operator is "natural cross join". The A and B operands are stored 480161dfc31dSdrh ** in p->a[0] and p->a[1], respectively. The parser initially stores the 480261dfc31dSdrh ** operator with A. This routine shifts that operator over to B. 480361dfc31dSdrh */ 480461dfc31dSdrh void sqlite3SrcListShiftJoinType(SrcList *p){ 4805d017ab99Sdrh if( p ){ 480661dfc31dSdrh int i; 480761dfc31dSdrh for(i=p->nSrc-1; i>0; i--){ 48088a48b9c0Sdrh p->a[i].fg.jointype = p->a[i-1].fg.jointype; 480961dfc31dSdrh } 48108a48b9c0Sdrh p->a[0].fg.jointype = 0; 481161dfc31dSdrh } 481261dfc31dSdrh } 481361dfc31dSdrh 481461dfc31dSdrh /* 4815b0c88651Sdrh ** Generate VDBE code for a BEGIN statement. 4816c4a3c779Sdrh */ 4817684917c2Sdrh void sqlite3BeginTransaction(Parse *pParse, int type){ 48189bb575fdSdrh sqlite3 *db; 48191d850a72Sdanielk1977 Vdbe *v; 4820684917c2Sdrh int i; 48215e00f6c7Sdrh 4822d3001711Sdrh assert( pParse!=0 ); 4823d3001711Sdrh db = pParse->db; 4824d3001711Sdrh assert( db!=0 ); 4825d3001711Sdrh if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){ 4826d3001711Sdrh return; 4827d3001711Sdrh } 48281d850a72Sdanielk1977 v = sqlite3GetVdbe(pParse); 48291d850a72Sdanielk1977 if( !v ) return; 4830684917c2Sdrh if( type!=TK_DEFERRED ){ 4831684917c2Sdrh for(i=0; i<db->nDb; i++){ 48321ca037f4Sdrh int eTxnType; 48331ca037f4Sdrh Btree *pBt = db->aDb[i].pBt; 48341ca037f4Sdrh if( pBt && sqlite3BtreeIsReadonly(pBt) ){ 48351ca037f4Sdrh eTxnType = 0; /* Read txn */ 48361ca037f4Sdrh }else if( type==TK_EXCLUSIVE ){ 48371ca037f4Sdrh eTxnType = 2; /* Exclusive txn */ 48381ca037f4Sdrh }else{ 48391ca037f4Sdrh eTxnType = 1; /* Write txn */ 48401ca037f4Sdrh } 48411ca037f4Sdrh sqlite3VdbeAddOp2(v, OP_Transaction, i, eTxnType); 4842fb98264aSdrh sqlite3VdbeUsesBtree(v, i); 4843684917c2Sdrh } 4844684917c2Sdrh } 4845b0c88651Sdrh sqlite3VdbeAddOp0(v, OP_AutoCommit); 484602f75f19Sdrh } 4847c4a3c779Sdrh 4848c4a3c779Sdrh /* 484907a3b11aSdrh ** Generate VDBE code for a COMMIT or ROLLBACK statement. 485007a3b11aSdrh ** Code for ROLLBACK is generated if eType==TK_ROLLBACK. Otherwise 485107a3b11aSdrh ** code is generated for a COMMIT. 4852c4a3c779Sdrh */ 485307a3b11aSdrh void sqlite3EndTransaction(Parse *pParse, int eType){ 48541d850a72Sdanielk1977 Vdbe *v; 485507a3b11aSdrh int isRollback; 48565e00f6c7Sdrh 4857d3001711Sdrh assert( pParse!=0 ); 4858b07028f7Sdrh assert( pParse->db!=0 ); 485907a3b11aSdrh assert( eType==TK_COMMIT || eType==TK_END || eType==TK_ROLLBACK ); 486007a3b11aSdrh isRollback = eType==TK_ROLLBACK; 486107a3b11aSdrh if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, 486207a3b11aSdrh isRollback ? "ROLLBACK" : "COMMIT", 0, 0) ){ 4863d3001711Sdrh return; 4864d3001711Sdrh } 48651d850a72Sdanielk1977 v = sqlite3GetVdbe(pParse); 48661d850a72Sdanielk1977 if( v ){ 486707a3b11aSdrh sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, isRollback); 4868c4a3c779Sdrh } 486902f75f19Sdrh } 4870f57b14a6Sdrh 4871f57b14a6Sdrh /* 4872fd7f0452Sdanielk1977 ** This function is called by the parser when it parses a command to create, 4873fd7f0452Sdanielk1977 ** release or rollback an SQL savepoint. 4874fd7f0452Sdanielk1977 */ 4875fd7f0452Sdanielk1977 void sqlite3Savepoint(Parse *pParse, int op, Token *pName){ 4876ab9b703fSdanielk1977 char *zName = sqlite3NameFromToken(pParse->db, pName); 4877ab9b703fSdanielk1977 if( zName ){ 4878ab9b703fSdanielk1977 Vdbe *v = sqlite3GetVdbe(pParse); 4879ab9b703fSdanielk1977 #ifndef SQLITE_OMIT_AUTHORIZATION 4880558814f8Sdan static const char * const az[] = { "BEGIN", "RELEASE", "ROLLBACK" }; 4881ab9b703fSdanielk1977 assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 ); 4882ab9b703fSdanielk1977 #endif 4883ab9b703fSdanielk1977 if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){ 4884ab9b703fSdanielk1977 sqlite3DbFree(pParse->db, zName); 4885ab9b703fSdanielk1977 return; 4886ab9b703fSdanielk1977 } 4887ab9b703fSdanielk1977 sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC); 4888fd7f0452Sdanielk1977 } 4889fd7f0452Sdanielk1977 } 4890fd7f0452Sdanielk1977 4891fd7f0452Sdanielk1977 /* 4892dc3ff9c3Sdrh ** Make sure the TEMP database is open and available for use. Return 4893dc3ff9c3Sdrh ** the number of errors. Leave any error messages in the pParse structure. 4894dc3ff9c3Sdrh */ 4895ddfb2f03Sdanielk1977 int sqlite3OpenTempDatabase(Parse *pParse){ 4896dc3ff9c3Sdrh sqlite3 *db = pParse->db; 4897dc3ff9c3Sdrh if( db->aDb[1].pBt==0 && !pParse->explain ){ 489833f4e02aSdrh int rc; 489910a76c90Sdrh Btree *pBt; 490033f4e02aSdrh static const int flags = 490133f4e02aSdrh SQLITE_OPEN_READWRITE | 490233f4e02aSdrh SQLITE_OPEN_CREATE | 490333f4e02aSdrh SQLITE_OPEN_EXCLUSIVE | 490433f4e02aSdrh SQLITE_OPEN_DELETEONCLOSE | 490533f4e02aSdrh SQLITE_OPEN_TEMP_DB; 490633f4e02aSdrh 49073a6d8aecSdan rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pBt, 0, flags); 4908dc3ff9c3Sdrh if( rc!=SQLITE_OK ){ 4909dc3ff9c3Sdrh sqlite3ErrorMsg(pParse, "unable to open a temporary database " 4910dc3ff9c3Sdrh "file for storing temporary tables"); 4911dc3ff9c3Sdrh pParse->rc = rc; 4912dc3ff9c3Sdrh return 1; 4913dc3ff9c3Sdrh } 491410a76c90Sdrh db->aDb[1].pBt = pBt; 491514db2665Sdanielk1977 assert( db->aDb[1].pSchema ); 4916e937df81Sdrh if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, 0, 0) ){ 49174a642b60Sdrh sqlite3OomFault(db); 49187c9c9868Sdrh return 1; 491910a76c90Sdrh } 4920dc3ff9c3Sdrh } 4921dc3ff9c3Sdrh return 0; 4922dc3ff9c3Sdrh } 4923dc3ff9c3Sdrh 4924dc3ff9c3Sdrh /* 4925aceb31b1Sdrh ** Record the fact that the schema cookie will need to be verified 4926aceb31b1Sdrh ** for database iDb. The code to actually verify the schema cookie 4927aceb31b1Sdrh ** will occur at the end of the top-level VDBE and will be generated 4928aceb31b1Sdrh ** later, by sqlite3FinishCoding(). 4929001bbcbbSdrh */ 49301d8f892aSdrh static void sqlite3CodeVerifySchemaAtToplevel(Parse *pToplevel, int iDb){ 49311d8f892aSdrh assert( iDb>=0 && iDb<pToplevel->db->nDb ); 49321d8f892aSdrh assert( pToplevel->db->aDb[iDb].pBt!=0 || iDb==1 ); 4933099b385dSdrh assert( iDb<SQLITE_MAX_DB ); 49341d8f892aSdrh assert( sqlite3SchemaMutexHeld(pToplevel->db, iDb, 0) ); 4935a7ab6d81Sdrh if( DbMaskTest(pToplevel->cookieMask, iDb)==0 ){ 4936a7ab6d81Sdrh DbMaskSet(pToplevel->cookieMask, iDb); 493753c0f748Sdanielk1977 if( !OMIT_TEMPDB && iDb==1 ){ 493865a7cd16Sdan sqlite3OpenTempDatabase(pToplevel); 4939dc3ff9c3Sdrh } 4940001bbcbbSdrh } 4941c275b4eaSdrh } 49421d8f892aSdrh void sqlite3CodeVerifySchema(Parse *pParse, int iDb){ 49431d8f892aSdrh sqlite3CodeVerifySchemaAtToplevel(sqlite3ParseToplevel(pParse), iDb); 49441d8f892aSdrh } 49451d8f892aSdrh 4946001bbcbbSdrh 4947001bbcbbSdrh /* 494857966753Sdan ** If argument zDb is NULL, then call sqlite3CodeVerifySchema() for each 494957966753Sdan ** attached database. Otherwise, invoke it for the database named zDb only. 495057966753Sdan */ 495157966753Sdan void sqlite3CodeVerifyNamedSchema(Parse *pParse, const char *zDb){ 495257966753Sdan sqlite3 *db = pParse->db; 495357966753Sdan int i; 495457966753Sdan for(i=0; i<db->nDb; i++){ 495557966753Sdan Db *pDb = &db->aDb[i]; 495669c33826Sdrh if( pDb->pBt && (!zDb || 0==sqlite3StrICmp(zDb, pDb->zDbSName)) ){ 495757966753Sdan sqlite3CodeVerifySchema(pParse, i); 495857966753Sdan } 495957966753Sdan } 496057966753Sdan } 496157966753Sdan 496257966753Sdan /* 49631c92853dSdrh ** Generate VDBE code that prepares for doing an operation that 4964c977f7f5Sdrh ** might change the database. 4965c977f7f5Sdrh ** 4966c977f7f5Sdrh ** This routine starts a new transaction if we are not already within 4967c977f7f5Sdrh ** a transaction. If we are already within a transaction, then a checkpoint 49687f0f12e3Sdrh ** is set if the setStatement parameter is true. A checkpoint should 4969c977f7f5Sdrh ** be set for operations that might fail (due to a constraint) part of 4970c977f7f5Sdrh ** the way through and which will need to undo some writes without having to 4971c977f7f5Sdrh ** rollback the whole transaction. For operations where all constraints 4972c977f7f5Sdrh ** can be checked before any changes are made to the database, it is never 4973c977f7f5Sdrh ** necessary to undo a write and the checkpoint should not be set. 49741c92853dSdrh */ 49757f0f12e3Sdrh void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){ 497665a7cd16Sdan Parse *pToplevel = sqlite3ParseToplevel(pParse); 49771d8f892aSdrh sqlite3CodeVerifySchemaAtToplevel(pToplevel, iDb); 4978a7ab6d81Sdrh DbMaskSet(pToplevel->writeMask, iDb); 4979e0af83acSdan pToplevel->isMultiWrite |= setStatement; 49801d850a72Sdanielk1977 } 4981e0af83acSdan 4982e0af83acSdan /* 4983ff738bceSdrh ** Indicate that the statement currently under construction might write 4984ff738bceSdrh ** more than one entry (example: deleting one row then inserting another, 4985ff738bceSdrh ** inserting multiple rows in a table, or inserting a row and index entries.) 4986ff738bceSdrh ** If an abort occurs after some of these writes have completed, then it will 4987ff738bceSdrh ** be necessary to undo the completed writes. 4988ff738bceSdrh */ 4989ff738bceSdrh void sqlite3MultiWrite(Parse *pParse){ 4990ff738bceSdrh Parse *pToplevel = sqlite3ParseToplevel(pParse); 4991ff738bceSdrh pToplevel->isMultiWrite = 1; 4992ff738bceSdrh } 4993ff738bceSdrh 4994ff738bceSdrh /* 4995ff738bceSdrh ** The code generator calls this routine if is discovers that it is 4996ff738bceSdrh ** possible to abort a statement prior to completion. In order to 4997ff738bceSdrh ** perform this abort without corrupting the database, we need to make 4998ff738bceSdrh ** sure that the statement is protected by a statement transaction. 4999ff738bceSdrh ** 5000ff738bceSdrh ** Technically, we only need to set the mayAbort flag if the 5001ff738bceSdrh ** isMultiWrite flag was previously set. There is a time dependency 5002ff738bceSdrh ** such that the abort must occur after the multiwrite. This makes 5003ff738bceSdrh ** some statements involving the REPLACE conflict resolution algorithm 5004ff738bceSdrh ** go a little faster. But taking advantage of this time dependency 5005ff738bceSdrh ** makes it more difficult to prove that the code is correct (in 5006ff738bceSdrh ** particular, it prevents us from writing an effective 5007ff738bceSdrh ** implementation of sqlite3AssertMayAbort()) and so we have chosen 5008ff738bceSdrh ** to take the safe route and skip the optimization. 5009e0af83acSdan */ 5010e0af83acSdan void sqlite3MayAbort(Parse *pParse){ 5011e0af83acSdan Parse *pToplevel = sqlite3ParseToplevel(pParse); 5012e0af83acSdan pToplevel->mayAbort = 1; 5013e0af83acSdan } 5014e0af83acSdan 5015e0af83acSdan /* 5016e0af83acSdan ** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT 5017e0af83acSdan ** error. The onError parameter determines which (if any) of the statement 5018e0af83acSdan ** and/or current transaction is rolled back. 5019e0af83acSdan */ 5020d91c1a17Sdrh void sqlite3HaltConstraint( 5021d91c1a17Sdrh Parse *pParse, /* Parsing context */ 5022d91c1a17Sdrh int errCode, /* extended error code */ 5023d91c1a17Sdrh int onError, /* Constraint type */ 5024d91c1a17Sdrh char *p4, /* Error message */ 5025f9c8ce3cSdrh i8 p4type, /* P4_STATIC or P4_TRANSIENT */ 5026f9c8ce3cSdrh u8 p5Errmsg /* P5_ErrMsg type */ 5027d91c1a17Sdrh ){ 5028289a0c84Sdrh Vdbe *v; 5029289a0c84Sdrh assert( pParse->pVdbe!=0 ); 5030289a0c84Sdrh v = sqlite3GetVdbe(pParse); 50319e5fdc41Sdrh assert( (errCode&0xff)==SQLITE_CONSTRAINT || pParse->nested ); 5032e0af83acSdan if( onError==OE_Abort ){ 5033e0af83acSdan sqlite3MayAbort(pParse); 5034e0af83acSdan } 5035d91c1a17Sdrh sqlite3VdbeAddOp4(v, OP_Halt, errCode, onError, 0, p4, p4type); 50369b34abeeSdrh sqlite3VdbeChangeP5(v, p5Errmsg); 5037f9c8ce3cSdrh } 5038f9c8ce3cSdrh 5039f9c8ce3cSdrh /* 5040f9c8ce3cSdrh ** Code an OP_Halt due to UNIQUE or PRIMARY KEY constraint violation. 5041f9c8ce3cSdrh */ 5042f9c8ce3cSdrh void sqlite3UniqueConstraint( 5043f9c8ce3cSdrh Parse *pParse, /* Parsing context */ 5044f9c8ce3cSdrh int onError, /* Constraint type */ 5045f9c8ce3cSdrh Index *pIdx /* The index that triggers the constraint */ 5046f9c8ce3cSdrh ){ 5047f9c8ce3cSdrh char *zErr; 5048f9c8ce3cSdrh int j; 5049f9c8ce3cSdrh StrAccum errMsg; 5050f9c8ce3cSdrh Table *pTab = pIdx->pTable; 5051f9c8ce3cSdrh 505286ec1eddSdrh sqlite3StrAccumInit(&errMsg, pParse->db, 0, 0, 505386ec1eddSdrh pParse->db->aLimit[SQLITE_LIMIT_LENGTH]); 50548b576422Sdrh if( pIdx->aColExpr ){ 50550cdbe1aeSdrh sqlite3_str_appendf(&errMsg, "index '%q'", pIdx->zName); 50568b576422Sdrh }else{ 5057f9c8ce3cSdrh for(j=0; j<pIdx->nKeyCol; j++){ 50581f9ca2c8Sdrh char *zCol; 50591f9ca2c8Sdrh assert( pIdx->aiColumn[j]>=0 ); 50601f9ca2c8Sdrh zCol = pTab->aCol[pIdx->aiColumn[j]].zName; 50610cdbe1aeSdrh if( j ) sqlite3_str_append(&errMsg, ", ", 2); 50620cdbe1aeSdrh sqlite3_str_appendall(&errMsg, pTab->zName); 50630cdbe1aeSdrh sqlite3_str_append(&errMsg, ".", 1); 50640cdbe1aeSdrh sqlite3_str_appendall(&errMsg, zCol); 50658b576422Sdrh } 5066f9c8ce3cSdrh } 5067f9c8ce3cSdrh zErr = sqlite3StrAccumFinish(&errMsg); 5068f9c8ce3cSdrh sqlite3HaltConstraint(pParse, 506948dd1d8eSdrh IsPrimaryKeyIndex(pIdx) ? SQLITE_CONSTRAINT_PRIMARYKEY 507048dd1d8eSdrh : SQLITE_CONSTRAINT_UNIQUE, 507193889d93Sdan onError, zErr, P4_DYNAMIC, P5_ConstraintUnique); 5072f9c8ce3cSdrh } 5073f9c8ce3cSdrh 5074f9c8ce3cSdrh 5075f9c8ce3cSdrh /* 5076f9c8ce3cSdrh ** Code an OP_Halt due to non-unique rowid. 5077f9c8ce3cSdrh */ 5078f9c8ce3cSdrh void sqlite3RowidConstraint( 5079f9c8ce3cSdrh Parse *pParse, /* Parsing context */ 5080f9c8ce3cSdrh int onError, /* Conflict resolution algorithm */ 5081f9c8ce3cSdrh Table *pTab /* The table with the non-unique rowid */ 5082f9c8ce3cSdrh ){ 5083f9c8ce3cSdrh char *zMsg; 5084f9c8ce3cSdrh int rc; 5085f9c8ce3cSdrh if( pTab->iPKey>=0 ){ 5086f9c8ce3cSdrh zMsg = sqlite3MPrintf(pParse->db, "%s.%s", pTab->zName, 5087f9c8ce3cSdrh pTab->aCol[pTab->iPKey].zName); 5088f9c8ce3cSdrh rc = SQLITE_CONSTRAINT_PRIMARYKEY; 5089f9c8ce3cSdrh }else{ 5090f9c8ce3cSdrh zMsg = sqlite3MPrintf(pParse->db, "%s.rowid", pTab->zName); 5091f9c8ce3cSdrh rc = SQLITE_CONSTRAINT_ROWID; 5092f9c8ce3cSdrh } 5093f9c8ce3cSdrh sqlite3HaltConstraint(pParse, rc, onError, zMsg, P4_DYNAMIC, 5094f9c8ce3cSdrh P5_ConstraintUnique); 5095663fc63aSdrh } 5096663fc63aSdrh 50974343fea2Sdrh /* 50984343fea2Sdrh ** Check to see if pIndex uses the collating sequence pColl. Return 50994343fea2Sdrh ** true if it does and false if it does not. 51004343fea2Sdrh */ 51014343fea2Sdrh #ifndef SQLITE_OMIT_REINDEX 5102b3bf556eSdanielk1977 static int collationMatch(const char *zColl, Index *pIndex){ 5103b3bf556eSdanielk1977 int i; 51040449171eSdrh assert( zColl!=0 ); 5105b3bf556eSdanielk1977 for(i=0; i<pIndex->nColumn; i++){ 5106b3bf556eSdanielk1977 const char *z = pIndex->azColl[i]; 5107bbbdc83bSdrh assert( z!=0 || pIndex->aiColumn[i]<0 ); 5108bbbdc83bSdrh if( pIndex->aiColumn[i]>=0 && 0==sqlite3StrICmp(z, zColl) ){ 5109b3bf556eSdanielk1977 return 1; 5110b3bf556eSdanielk1977 } 51114343fea2Sdrh } 51124343fea2Sdrh return 0; 51134343fea2Sdrh } 51144343fea2Sdrh #endif 51154343fea2Sdrh 51164343fea2Sdrh /* 51174343fea2Sdrh ** Recompute all indices of pTab that use the collating sequence pColl. 51184343fea2Sdrh ** If pColl==0 then recompute all indices of pTab. 51194343fea2Sdrh */ 51204343fea2Sdrh #ifndef SQLITE_OMIT_REINDEX 5121b3bf556eSdanielk1977 static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){ 5122e6370e9cSdan if( !IsVirtual(pTab) ){ 51234343fea2Sdrh Index *pIndex; /* An index associated with pTab */ 51244343fea2Sdrh 51254343fea2Sdrh for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){ 5126b3bf556eSdanielk1977 if( zColl==0 || collationMatch(zColl, pIndex) ){ 5127da184236Sdanielk1977 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema); 5128da184236Sdanielk1977 sqlite3BeginWriteOperation(pParse, 0, iDb); 51294343fea2Sdrh sqlite3RefillIndex(pParse, pIndex, -1); 51304343fea2Sdrh } 51314343fea2Sdrh } 51324343fea2Sdrh } 5133e6370e9cSdan } 51344343fea2Sdrh #endif 51354343fea2Sdrh 51364343fea2Sdrh /* 51374343fea2Sdrh ** Recompute all indices of all tables in all databases where the 51384343fea2Sdrh ** indices use the collating sequence pColl. If pColl==0 then recompute 51394343fea2Sdrh ** all indices everywhere. 51404343fea2Sdrh */ 51414343fea2Sdrh #ifndef SQLITE_OMIT_REINDEX 5142b3bf556eSdanielk1977 static void reindexDatabases(Parse *pParse, char const *zColl){ 51434343fea2Sdrh Db *pDb; /* A single database */ 51444343fea2Sdrh int iDb; /* The database index number */ 51454343fea2Sdrh sqlite3 *db = pParse->db; /* The database connection */ 51464343fea2Sdrh HashElem *k; /* For looping over tables in pDb */ 51474343fea2Sdrh Table *pTab; /* A table in the database */ 51484343fea2Sdrh 51492120608eSdrh assert( sqlite3BtreeHoldsAllMutexes(db) ); /* Needed for schema access */ 51504343fea2Sdrh for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){ 515143617e9aSdrh assert( pDb!=0 ); 5152da184236Sdanielk1977 for(k=sqliteHashFirst(&pDb->pSchema->tblHash); k; k=sqliteHashNext(k)){ 51534343fea2Sdrh pTab = (Table*)sqliteHashData(k); 5154b3bf556eSdanielk1977 reindexTable(pParse, pTab, zColl); 51554343fea2Sdrh } 51564343fea2Sdrh } 51574343fea2Sdrh } 51584343fea2Sdrh #endif 51594343fea2Sdrh 51604343fea2Sdrh /* 5161eee46cf3Sdrh ** Generate code for the REINDEX command. 5162eee46cf3Sdrh ** 5163eee46cf3Sdrh ** REINDEX -- 1 5164eee46cf3Sdrh ** REINDEX <collation> -- 2 5165eee46cf3Sdrh ** REINDEX ?<database>.?<tablename> -- 3 5166eee46cf3Sdrh ** REINDEX ?<database>.?<indexname> -- 4 5167eee46cf3Sdrh ** 5168eee46cf3Sdrh ** Form 1 causes all indices in all attached databases to be rebuilt. 5169eee46cf3Sdrh ** Form 2 rebuilds all indices in all databases that use the named 5170eee46cf3Sdrh ** collating function. Forms 3 and 4 rebuild the named index or all 5171eee46cf3Sdrh ** indices associated with the named table. 51724343fea2Sdrh */ 51734343fea2Sdrh #ifndef SQLITE_OMIT_REINDEX 51744343fea2Sdrh void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){ 51754343fea2Sdrh CollSeq *pColl; /* Collating sequence to be reindexed, or NULL */ 51764343fea2Sdrh char *z; /* Name of a table or index */ 51774343fea2Sdrh const char *zDb; /* Name of the database */ 51784343fea2Sdrh Table *pTab; /* A table in the database */ 51794343fea2Sdrh Index *pIndex; /* An index associated with pTab */ 51804343fea2Sdrh int iDb; /* The database index number */ 51814343fea2Sdrh sqlite3 *db = pParse->db; /* The database connection */ 51824343fea2Sdrh Token *pObjName; /* Name of the table or index to be reindexed */ 51834343fea2Sdrh 518433a5edc3Sdanielk1977 /* Read the database schema. If an error occurs, leave an error message 518533a5edc3Sdanielk1977 ** and code in pParse and return NULL. */ 518633a5edc3Sdanielk1977 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){ 5187e63739a8Sdanielk1977 return; 518833a5edc3Sdanielk1977 } 518933a5edc3Sdanielk1977 51908af73d41Sdrh if( pName1==0 ){ 51914343fea2Sdrh reindexDatabases(pParse, 0); 51924343fea2Sdrh return; 5193d3001711Sdrh }else if( NEVER(pName2==0) || pName2->z==0 ){ 519439002505Sdanielk1977 char *zColl; 5195b3bf556eSdanielk1977 assert( pName1->z ); 519639002505Sdanielk1977 zColl = sqlite3NameFromToken(pParse->db, pName1); 519739002505Sdanielk1977 if( !zColl ) return; 5198c4a64facSdrh pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0); 51994343fea2Sdrh if( pColl ){ 5200f0113000Sdanielk1977 reindexDatabases(pParse, zColl); 5201633e6d57Sdrh sqlite3DbFree(db, zColl); 52024343fea2Sdrh return; 52034343fea2Sdrh } 5204633e6d57Sdrh sqlite3DbFree(db, zColl); 52054343fea2Sdrh } 52064343fea2Sdrh iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName); 52074343fea2Sdrh if( iDb<0 ) return; 520817435752Sdrh z = sqlite3NameFromToken(db, pObjName); 520984f31128Sdrh if( z==0 ) return; 521069c33826Sdrh zDb = db->aDb[iDb].zDbSName; 52114343fea2Sdrh pTab = sqlite3FindTable(db, z, zDb); 52124343fea2Sdrh if( pTab ){ 52134343fea2Sdrh reindexTable(pParse, pTab, 0); 5214633e6d57Sdrh sqlite3DbFree(db, z); 52154343fea2Sdrh return; 52164343fea2Sdrh } 52174343fea2Sdrh pIndex = sqlite3FindIndex(db, z, zDb); 5218633e6d57Sdrh sqlite3DbFree(db, z); 52194343fea2Sdrh if( pIndex ){ 52204343fea2Sdrh sqlite3BeginWriteOperation(pParse, 0, iDb); 52214343fea2Sdrh sqlite3RefillIndex(pParse, pIndex, -1); 52224343fea2Sdrh return; 52234343fea2Sdrh } 52244343fea2Sdrh sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed"); 52254343fea2Sdrh } 52264343fea2Sdrh #endif 5227b3bf556eSdanielk1977 5228b3bf556eSdanielk1977 /* 52292ec2fb22Sdrh ** Return a KeyInfo structure that is appropriate for the given Index. 5230b3bf556eSdanielk1977 ** 52312ec2fb22Sdrh ** The caller should invoke sqlite3KeyInfoUnref() on the returned object 52322ec2fb22Sdrh ** when it has finished using it. 5233b3bf556eSdanielk1977 */ 52342ec2fb22Sdrh KeyInfo *sqlite3KeyInfoOfIndex(Parse *pParse, Index *pIdx){ 5235b3bf556eSdanielk1977 int i; 5236ad124329Sdrh int nCol = pIdx->nColumn; 5237ad124329Sdrh int nKey = pIdx->nKeyCol; 5238323df790Sdrh KeyInfo *pKey; 523918b67f3fSdrh if( pParse->nErr ) return 0; 52401153c7b2Sdrh if( pIdx->uniqNotNull ){ 5241ad124329Sdrh pKey = sqlite3KeyInfoAlloc(pParse->db, nKey, nCol-nKey); 52421153c7b2Sdrh }else{ 52431153c7b2Sdrh pKey = sqlite3KeyInfoAlloc(pParse->db, nCol, 0); 52441153c7b2Sdrh } 5245b3bf556eSdanielk1977 if( pKey ){ 52462ec2fb22Sdrh assert( sqlite3KeyInfoIsWriteable(pKey) ); 5247b3bf556eSdanielk1977 for(i=0; i<nCol; i++){ 5248f19aa5faSdrh const char *zColl = pIdx->azColl[i]; 5249f19aa5faSdrh pKey->aColl[i] = zColl==sqlite3StrBINARY ? 0 : 5250b8a9bb4fSdrh sqlite3LocateCollSeq(pParse, zColl); 52516e11892dSdan pKey->aSortFlags[i] = pIdx->aSortOrder[i]; 52526e11892dSdan assert( 0==(pKey->aSortFlags[i] & KEYINFO_ORDER_BIGNULL) ); 5253b3bf556eSdanielk1977 } 5254b3bf556eSdanielk1977 if( pParse->nErr ){ 52557e8515d8Sdrh assert( pParse->rc==SQLITE_ERROR_MISSING_COLLSEQ ); 52567e8515d8Sdrh if( pIdx->bNoQuery==0 ){ 52577e8515d8Sdrh /* Deactivate the index because it contains an unknown collating 52587e8515d8Sdrh ** sequence. The only way to reactive the index is to reload the 52597e8515d8Sdrh ** schema. Adding the missing collating sequence later does not 52607e8515d8Sdrh ** reactive the index. The application had the chance to register 52617e8515d8Sdrh ** the missing index using the collation-needed callback. For 52627e8515d8Sdrh ** simplicity, SQLite will not give the application a second chance. 52637e8515d8Sdrh */ 52647e8515d8Sdrh pIdx->bNoQuery = 1; 52657e8515d8Sdrh pParse->rc = SQLITE_ERROR_RETRY; 52667e8515d8Sdrh } 52672ec2fb22Sdrh sqlite3KeyInfoUnref(pKey); 526818b67f3fSdrh pKey = 0; 5269b3bf556eSdanielk1977 } 52702ec2fb22Sdrh } 527118b67f3fSdrh return pKey; 5272b3bf556eSdanielk1977 } 52738b471863Sdrh 52748b471863Sdrh #ifndef SQLITE_OMIT_CTE 52757d562dbeSdan /* 5276f824b41eSdrh ** Create a new CTE object 5277f824b41eSdrh */ 5278f824b41eSdrh Cte *sqlite3CteNew( 5279f824b41eSdrh Parse *pParse, /* Parsing context */ 5280f824b41eSdrh Token *pName, /* Name of the common-table */ 5281f824b41eSdrh ExprList *pArglist, /* Optional column name list for the table */ 5282745912efSdrh Select *pQuery, /* Query used to initialize the table */ 5283745912efSdrh u8 eM10d /* The MATERIALIZED flag */ 5284f824b41eSdrh ){ 5285f824b41eSdrh Cte *pNew; 5286f824b41eSdrh sqlite3 *db = pParse->db; 5287f824b41eSdrh 5288f824b41eSdrh pNew = sqlite3DbMallocZero(db, sizeof(*pNew)); 5289f824b41eSdrh assert( pNew!=0 || db->mallocFailed ); 5290f824b41eSdrh 5291f824b41eSdrh if( db->mallocFailed ){ 5292f824b41eSdrh sqlite3ExprListDelete(db, pArglist); 5293f824b41eSdrh sqlite3SelectDelete(db, pQuery); 5294f824b41eSdrh }else{ 5295f824b41eSdrh pNew->pSelect = pQuery; 5296f824b41eSdrh pNew->pCols = pArglist; 5297f824b41eSdrh pNew->zName = sqlite3NameFromToken(pParse->db, pName); 5298745912efSdrh pNew->eM10d = eM10d; 5299f824b41eSdrh } 5300f824b41eSdrh return pNew; 5301f824b41eSdrh } 5302f824b41eSdrh 5303f824b41eSdrh /* 5304f824b41eSdrh ** Clear information from a Cte object, but do not deallocate storage 5305f824b41eSdrh ** for the object itself. 5306f824b41eSdrh */ 5307f824b41eSdrh static void cteClear(sqlite3 *db, Cte *pCte){ 5308f824b41eSdrh assert( pCte!=0 ); 5309f824b41eSdrh sqlite3ExprListDelete(db, pCte->pCols); 5310f824b41eSdrh sqlite3SelectDelete(db, pCte->pSelect); 5311f824b41eSdrh sqlite3DbFree(db, pCte->zName); 5312f824b41eSdrh } 5313f824b41eSdrh 5314f824b41eSdrh /* 5315f824b41eSdrh ** Free the contents of the CTE object passed as the second argument. 5316f824b41eSdrh */ 5317f824b41eSdrh void sqlite3CteDelete(sqlite3 *db, Cte *pCte){ 5318f824b41eSdrh assert( pCte!=0 ); 5319f824b41eSdrh cteClear(db, pCte); 5320f824b41eSdrh sqlite3DbFree(db, pCte); 5321f824b41eSdrh } 5322f824b41eSdrh 5323f824b41eSdrh /* 53247d562dbeSdan ** This routine is invoked once per CTE by the parser while parsing a 5325f824b41eSdrh ** WITH clause. The CTE described by teh third argument is added to 5326f824b41eSdrh ** the WITH clause of the second argument. If the second argument is 5327f824b41eSdrh ** NULL, then a new WITH argument is created. 53288b471863Sdrh */ 53297d562dbeSdan With *sqlite3WithAdd( 53308b471863Sdrh Parse *pParse, /* Parsing context */ 53317d562dbeSdan With *pWith, /* Existing WITH clause, or NULL */ 5332f824b41eSdrh Cte *pCte /* CTE to add to the WITH clause */ 53338b471863Sdrh ){ 53344e9119d9Sdan sqlite3 *db = pParse->db; 53354e9119d9Sdan With *pNew; 53364e9119d9Sdan char *zName; 53374e9119d9Sdan 5338f824b41eSdrh if( pCte==0 ){ 5339f824b41eSdrh return pWith; 5340f824b41eSdrh } 5341f824b41eSdrh 53424e9119d9Sdan /* Check that the CTE name is unique within this WITH clause. If 53434e9119d9Sdan ** not, store an error in the Parse structure. */ 5344f824b41eSdrh zName = pCte->zName; 53454e9119d9Sdan if( zName && pWith ){ 53464e9119d9Sdan int i; 53474e9119d9Sdan for(i=0; i<pWith->nCte; i++){ 53484e9119d9Sdan if( sqlite3StrICmp(zName, pWith->a[i].zName)==0 ){ 5349727a99f1Sdrh sqlite3ErrorMsg(pParse, "duplicate WITH table name: %s", zName); 53504e9119d9Sdan } 53514e9119d9Sdan } 53524e9119d9Sdan } 53534e9119d9Sdan 53544e9119d9Sdan if( pWith ){ 53550aa3231fSdrh sqlite3_int64 nByte = sizeof(*pWith) + (sizeof(pWith->a[1]) * pWith->nCte); 53564e9119d9Sdan pNew = sqlite3DbRealloc(db, pWith, nByte); 53574e9119d9Sdan }else{ 53584e9119d9Sdan pNew = sqlite3DbMallocZero(db, sizeof(*pWith)); 53594e9119d9Sdan } 5360b84e574cSdrh assert( (pNew!=0 && zName!=0) || db->mallocFailed ); 53614e9119d9Sdan 5362b84e574cSdrh if( db->mallocFailed ){ 5363f824b41eSdrh sqlite3CteDelete(db, pCte); 5364a9f5c13dSdan pNew = pWith; 53654e9119d9Sdan }else{ 5366f824b41eSdrh pNew->a[pNew->nCte++] = *pCte; 5367f824b41eSdrh sqlite3DbFree(db, pCte); 53684e9119d9Sdan } 53694e9119d9Sdan 53704e9119d9Sdan return pNew; 53718b471863Sdrh } 53728b471863Sdrh 53737d562dbeSdan /* 53747d562dbeSdan ** Free the contents of the With object passed as the second argument. 53758b471863Sdrh */ 53767d562dbeSdan void sqlite3WithDelete(sqlite3 *db, With *pWith){ 53774e9119d9Sdan if( pWith ){ 53784e9119d9Sdan int i; 53794e9119d9Sdan for(i=0; i<pWith->nCte; i++){ 5380f824b41eSdrh cteClear(db, &pWith->a[i]); 53814e9119d9Sdan } 53824e9119d9Sdan sqlite3DbFree(db, pWith); 53834e9119d9Sdan } 53848b471863Sdrh } 53858b471863Sdrh #endif /* !defined(SQLITE_OMIT_CTE) */ 5386