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 1737132f436Sdrh if( pReturning->nRetCol==0 ){ 1747132f436Sdrh assert( CORRUPT_DB ); 1757132f436Sdrh }else{ 176381bdaccSdrh addrRewind = 177381bdaccSdrh sqlite3VdbeAddOp1(v, OP_Rewind, pReturning->iRetCur); 1786859d324Sdrh VdbeCoverage(v); 179552562c4Sdrh reg = pReturning->iRetReg; 180381bdaccSdrh for(i=0; i<pReturning->nRetCol; i++){ 181381bdaccSdrh sqlite3VdbeAddOp3(v, OP_Column, pReturning->iRetCur, i, reg+i); 182381bdaccSdrh } 183381bdaccSdrh sqlite3VdbeAddOp2(v, OP_ResultRow, reg, i); 184381bdaccSdrh sqlite3VdbeAddOp2(v, OP_Next, pReturning->iRetCur, addrRewind+1); 1856859d324Sdrh VdbeCoverage(v); 186381bdaccSdrh sqlite3VdbeJumpHere(v, addrRewind); 187381bdaccSdrh } 1887132f436Sdrh } 18966a5167bSdrh sqlite3VdbeAddOp0(v, OP_Halt); 1900e3d7476Sdrh 191b2445d5eSdrh #if SQLITE_USER_AUTHENTICATION 192b2445d5eSdrh if( pParse->nTableLock>0 && db->init.busy==0 ){ 1937883ecfcSdrh sqlite3UserAuthInit(db); 194b2445d5eSdrh if( db->auth.authLevel<UAUTH_User ){ 195b2445d5eSdrh sqlite3ErrorMsg(pParse, "user not authenticated"); 1966ae3ab00Sdrh pParse->rc = SQLITE_AUTH_USER; 197b2445d5eSdrh return; 198b2445d5eSdrh } 199b2445d5eSdrh } 200b2445d5eSdrh #endif 201b2445d5eSdrh 2020e3d7476Sdrh /* The cookie mask contains one bit for each database file open. 2030e3d7476Sdrh ** (Bit 0 is for main, bit 1 is for temp, and so forth.) Bits are 2040e3d7476Sdrh ** set for each database that is used. Generate code to start a 2050e3d7476Sdrh ** transaction on each used database and to verify the schema cookie 2060e3d7476Sdrh ** on each used database. 2070e3d7476Sdrh */ 208a7ab6d81Sdrh if( db->mallocFailed==0 209a7ab6d81Sdrh && (DbMaskNonZero(pParse->cookieMask) || pParse->pConstExpr) 210a7ab6d81Sdrh ){ 211aceb31b1Sdrh int iDb, i; 212aceb31b1Sdrh assert( sqlite3VdbeGetOp(v, 0)->opcode==OP_Init ); 213aceb31b1Sdrh sqlite3VdbeJumpHere(v, 0); 214a7ab6d81Sdrh for(iDb=0; iDb<db->nDb; iDb++){ 2151d96cc60Sdrh Schema *pSchema; 216a7ab6d81Sdrh if( DbMaskTest(pParse->cookieMask, iDb)==0 ) continue; 217fb98264aSdrh sqlite3VdbeUsesBtree(v, iDb); 2181d96cc60Sdrh pSchema = db->aDb[iDb].pSchema; 219b22f7c83Sdrh sqlite3VdbeAddOp4Int(v, 220b22f7c83Sdrh OP_Transaction, /* Opcode */ 221b22f7c83Sdrh iDb, /* P1 */ 222a7ab6d81Sdrh DbMaskTest(pParse->writeMask,iDb), /* P2 */ 2231d96cc60Sdrh pSchema->schema_cookie, /* P3 */ 2241d96cc60Sdrh pSchema->iGeneration /* P4 */ 225b22f7c83Sdrh ); 226b22f7c83Sdrh if( db->init.busy==0 ) sqlite3VdbeChangeP5(v, 1); 227076e0f96Sdan VdbeComment((v, 228076e0f96Sdan "usesStmtJournal=%d", pParse->mayAbort && pParse->isMultiWrite)); 2298a939190Sdrh } 230f9e7dda7Sdanielk1977 #ifndef SQLITE_OMIT_VIRTUALTABLE 2314f3dd150Sdrh for(i=0; i<pParse->nVtabLock; i++){ 232595a523aSdanielk1977 char *vtab = (char *)sqlite3GetVTable(db, pParse->apVtabLock[i]); 23366a5167bSdrh sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB); 234f9e7dda7Sdanielk1977 } 2354f3dd150Sdrh pParse->nVtabLock = 0; 236f9e7dda7Sdanielk1977 #endif 237c00da105Sdanielk1977 238c00da105Sdanielk1977 /* Once all the cookies have been verified and transactions opened, 239c00da105Sdanielk1977 ** obtain the required table-locks. This is a no-op unless the 240c00da105Sdanielk1977 ** shared-cache feature is enabled. 241c00da105Sdanielk1977 */ 242c00da105Sdanielk1977 codeTableLocks(pParse); 2430b9f50d8Sdrh 2440b9f50d8Sdrh /* Initialize any AUTOINCREMENT data structures required. 2450b9f50d8Sdrh */ 2460b9f50d8Sdrh sqlite3AutoincrementBegin(pParse); 2470b9f50d8Sdrh 24889636628Sdrh /* Code constant expressions that where factored out of inner loops. 24989636628Sdrh ** 25089636628Sdrh ** The pConstExpr list might also contain expressions that we simply 25189636628Sdrh ** want to keep around until the Parse object is deleted. Such 25289636628Sdrh ** expressions have iConstExprReg==0. Do not generate code for 25389636628Sdrh ** those expressions, of course. 25489636628Sdrh */ 255f30a969bSdrh if( pParse->pConstExpr ){ 256f30a969bSdrh ExprList *pEL = pParse->pConstExpr; 257aceb31b1Sdrh pParse->okConstFactor = 0; 258f30a969bSdrh for(i=0; i<pEL->nExpr; i++){ 25989636628Sdrh int iReg = pEL->a[i].u.iConstExprReg; 26089636628Sdrh if( iReg>0 ){ 26189636628Sdrh sqlite3ExprCode(pParse, pEL->a[i].pExpr, iReg); 26289636628Sdrh } 263f30a969bSdrh } 264f30a969bSdrh } 265f30a969bSdrh 266381bdaccSdrh if( pParse->bReturning ){ 267381bdaccSdrh Returning *pRet = pParse->u1.pReturning; 2687132f436Sdrh if( pRet->nRetCol==0 ){ 2697132f436Sdrh assert( CORRUPT_DB ); 2707132f436Sdrh }else{ 271381bdaccSdrh sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pRet->iRetCur, pRet->nRetCol); 272381bdaccSdrh } 2737132f436Sdrh } 274381bdaccSdrh 2750b9f50d8Sdrh /* Finally, jump back to the beginning of the executable code. */ 276076e85f5Sdrh sqlite3VdbeGoto(v, 1); 27780242055Sdrh } 27871c697efSdrh } 27971c697efSdrh 28080242055Sdrh /* Get the VDBE program ready for execution 28180242055Sdrh */ 282126a6e26Sdrh if( v && pParse->nErr==0 && !db->mallocFailed ){ 2833492dd71Sdrh /* A minimum of one cursor is required if autoincrement is used 2843492dd71Sdrh * See ticket [a696379c1f08866] */ 28504ab586bSdrh assert( pParse->pAinc==0 || pParse->nTab>0 ); 286124c0b49Sdrh sqlite3VdbeMakeReady(v, pParse); 287441daf68Sdanielk1977 pParse->rc = SQLITE_DONE; 288e294da02Sdrh }else{ 289483750baSdrh pParse->rc = SQLITE_ERROR; 29075897234Sdrh } 29175897234Sdrh } 29275897234Sdrh 29375897234Sdrh /* 294205f48e6Sdrh ** Run the parser and code generator recursively in order to generate 295205f48e6Sdrh ** code for the SQL statement given onto the end of the pParse context 2963edc927eSdrh ** currently under construction. Notes: 2973edc927eSdrh ** 2983edc927eSdrh ** * The final OP_Halt is not appended and other initialization 299205f48e6Sdrh ** and finalization steps are omitted because those are handling by the 300205f48e6Sdrh ** outermost parser. 301205f48e6Sdrh ** 3023edc927eSdrh ** * Built-in SQL functions always take precedence over application-defined 3033edc927eSdrh ** SQL functions. In other words, it is not possible to override a 3043edc927eSdrh ** built-in function. 305205f48e6Sdrh */ 306205f48e6Sdrh void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){ 307205f48e6Sdrh va_list ap; 308205f48e6Sdrh char *zSql; 309fb45d8c5Sdrh char *zErrMsg = 0; 310633e6d57Sdrh sqlite3 *db = pParse->db; 3113edc927eSdrh u32 savedDbFlags = db->mDbFlags; 312cd9af608Sdrh char saveBuf[PARSE_TAIL_SZ]; 313f1974846Sdrh 314205f48e6Sdrh if( pParse->nErr ) return; 315205f48e6Sdrh assert( pParse->nested<10 ); /* Nesting should only be of limited depth */ 316205f48e6Sdrh va_start(ap, zFormat); 317633e6d57Sdrh zSql = sqlite3VMPrintf(db, zFormat, ap); 318205f48e6Sdrh va_end(ap); 31973c42a13Sdrh if( zSql==0 ){ 320480c572fSdrh /* This can result either from an OOM or because the formatted string 321480c572fSdrh ** exceeds SQLITE_LIMIT_LENGTH. In the latter case, we need to set 322480c572fSdrh ** an error */ 323480c572fSdrh if( !db->mallocFailed ) pParse->rc = SQLITE_TOOBIG; 324a2b6806bSdrh pParse->nErr++; 325480c572fSdrh return; 32673c42a13Sdrh } 327205f48e6Sdrh pParse->nested++; 328cd9af608Sdrh memcpy(saveBuf, PARSE_TAIL(pParse), PARSE_TAIL_SZ); 329cd9af608Sdrh memset(PARSE_TAIL(pParse), 0, PARSE_TAIL_SZ); 3303edc927eSdrh db->mDbFlags |= DBFLAG_PreferBuiltin; 331fb45d8c5Sdrh sqlite3RunParser(pParse, zSql, &zErrMsg); 3323edc927eSdrh db->mDbFlags = savedDbFlags; 333633e6d57Sdrh sqlite3DbFree(db, zErrMsg); 334633e6d57Sdrh sqlite3DbFree(db, zSql); 335cd9af608Sdrh memcpy(PARSE_TAIL(pParse), saveBuf, PARSE_TAIL_SZ); 336205f48e6Sdrh pParse->nested--; 337205f48e6Sdrh } 338205f48e6Sdrh 339d4530979Sdrh #if SQLITE_USER_AUTHENTICATION 340d4530979Sdrh /* 341d4530979Sdrh ** Return TRUE if zTable is the name of the system table that stores the 342d4530979Sdrh ** list of users and their access credentials. 343d4530979Sdrh */ 344d4530979Sdrh int sqlite3UserAuthTable(const char *zTable){ 345d4530979Sdrh return sqlite3_stricmp(zTable, "sqlite_user")==0; 346d4530979Sdrh } 347d4530979Sdrh #endif 348d4530979Sdrh 349205f48e6Sdrh /* 3508a41449eSdanielk1977 ** Locate the in-memory structure that describes a particular database 3518a41449eSdanielk1977 ** table given the name of that table and (optionally) the name of the 3528a41449eSdanielk1977 ** database containing the table. Return NULL if not found. 353a69d9168Sdrh ** 3548a41449eSdanielk1977 ** If zDatabase is 0, all databases are searched for the table and the 3558a41449eSdanielk1977 ** first matching table is returned. (No checking for duplicate table 3568a41449eSdanielk1977 ** names is done.) The search order is TEMP first, then MAIN, then any 3578a41449eSdanielk1977 ** auxiliary databases added using the ATTACH command. 358f26e09c8Sdrh ** 3594adee20fSdanielk1977 ** See also sqlite3LocateTable(). 36075897234Sdrh */ 3619bb575fdSdrh Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){ 362d24cc427Sdrh Table *p = 0; 363d24cc427Sdrh int i; 3649ca95730Sdrh 3652120608eSdrh /* All mutexes are required for schema access. Make sure we hold them. */ 3662120608eSdrh assert( zDatabase!=0 || sqlite3BtreeHoldsAllMutexes(db) ); 367d4530979Sdrh #if SQLITE_USER_AUTHENTICATION 368d4530979Sdrh /* Only the admin user is allowed to know that the sqlite_user table 369d4530979Sdrh ** exists */ 370e933b83fSdrh if( db->auth.authLevel<UAUTH_Admin && sqlite3UserAuthTable(zName)!=0 ){ 371e933b83fSdrh return 0; 372e933b83fSdrh } 373d4530979Sdrh #endif 374b2eb7e46Sdrh if( zDatabase ){ 375b2eb7e46Sdrh for(i=0; i<db->nDb; i++){ 376b2eb7e46Sdrh if( sqlite3StrICmp(zDatabase, db->aDb[i].zDbSName)==0 ) break; 377d24cc427Sdrh } 378b2eb7e46Sdrh if( i>=db->nDb ){ 379b2eb7e46Sdrh /* No match against the official names. But always match "main" 380b2eb7e46Sdrh ** to schema 0 as a legacy fallback. */ 381b2eb7e46Sdrh if( sqlite3StrICmp(zDatabase,"main")==0 ){ 382b2eb7e46Sdrh i = 0; 383b2eb7e46Sdrh }else{ 384e0a04a36Sdrh return 0; 38575897234Sdrh } 386b2eb7e46Sdrh } 387b2eb7e46Sdrh p = sqlite3HashFind(&db->aDb[i].pSchema->tblHash, zName); 388346a70caSdrh if( p==0 && sqlite3StrNICmp(zName, "sqlite_", 7)==0 ){ 389346a70caSdrh if( i==1 ){ 390a764709bSdrh if( sqlite3StrICmp(zName+7, &ALT_TEMP_SCHEMA_TABLE[7])==0 391a764709bSdrh || sqlite3StrICmp(zName+7, &ALT_SCHEMA_TABLE[7])==0 392a764709bSdrh || sqlite3StrICmp(zName+7, &DFLT_SCHEMA_TABLE[7])==0 393346a70caSdrh ){ 394346a70caSdrh p = sqlite3HashFind(&db->aDb[1].pSchema->tblHash, 395346a70caSdrh DFLT_TEMP_SCHEMA_TABLE); 396346a70caSdrh } 397346a70caSdrh }else{ 398a764709bSdrh if( sqlite3StrICmp(zName+7, &ALT_SCHEMA_TABLE[7])==0 ){ 399346a70caSdrh p = sqlite3HashFind(&db->aDb[i].pSchema->tblHash, 400346a70caSdrh DFLT_SCHEMA_TABLE); 401346a70caSdrh } 402346a70caSdrh } 403b2eb7e46Sdrh } 404b2eb7e46Sdrh }else{ 405b2eb7e46Sdrh /* Match against TEMP first */ 406b2eb7e46Sdrh p = sqlite3HashFind(&db->aDb[1].pSchema->tblHash, zName); 407b2eb7e46Sdrh if( p ) return p; 408b2eb7e46Sdrh /* The main database is second */ 409b2eb7e46Sdrh p = sqlite3HashFind(&db->aDb[0].pSchema->tblHash, zName); 410b2eb7e46Sdrh if( p ) return p; 411b2eb7e46Sdrh /* Attached databases are in order of attachment */ 412b2eb7e46Sdrh for(i=2; i<db->nDb; i++){ 413b2eb7e46Sdrh assert( sqlite3SchemaMutexHeld(db, i, 0) ); 414b2eb7e46Sdrh p = sqlite3HashFind(&db->aDb[i].pSchema->tblHash, zName); 415b2eb7e46Sdrh if( p ) break; 416b2eb7e46Sdrh } 417346a70caSdrh if( p==0 && sqlite3StrNICmp(zName, "sqlite_", 7)==0 ){ 418a764709bSdrh if( sqlite3StrICmp(zName+7, &ALT_SCHEMA_TABLE[7])==0 ){ 419346a70caSdrh p = sqlite3HashFind(&db->aDb[0].pSchema->tblHash, DFLT_SCHEMA_TABLE); 420a764709bSdrh }else if( sqlite3StrICmp(zName+7, &ALT_TEMP_SCHEMA_TABLE[7])==0 ){ 421346a70caSdrh p = sqlite3HashFind(&db->aDb[1].pSchema->tblHash, 422346a70caSdrh DFLT_TEMP_SCHEMA_TABLE); 423346a70caSdrh } 424346a70caSdrh } 425b2eb7e46Sdrh } 426b2eb7e46Sdrh return p; 427b2eb7e46Sdrh } 42875897234Sdrh 42975897234Sdrh /* 4308a41449eSdanielk1977 ** Locate the in-memory structure that describes a particular database 4318a41449eSdanielk1977 ** table given the name of that table and (optionally) the name of the 4328a41449eSdanielk1977 ** database containing the table. Return NULL if not found. Also leave an 4338a41449eSdanielk1977 ** error message in pParse->zErrMsg. 434a69d9168Sdrh ** 4358a41449eSdanielk1977 ** The difference between this routine and sqlite3FindTable() is that this 4368a41449eSdanielk1977 ** routine leaves an error message in pParse->zErrMsg where 4378a41449eSdanielk1977 ** sqlite3FindTable() does not. 438a69d9168Sdrh */ 439ca424114Sdrh Table *sqlite3LocateTable( 440ca424114Sdrh Parse *pParse, /* context in which to report errors */ 4414d249e61Sdrh u32 flags, /* LOCATE_VIEW or LOCATE_NOERR */ 442ca424114Sdrh const char *zName, /* Name of the table we are looking for */ 443ca424114Sdrh const char *zDbase /* Name of the database. Might be NULL */ 444ca424114Sdrh ){ 445a69d9168Sdrh Table *p; 446b2c8559fSdrh sqlite3 *db = pParse->db; 447f26e09c8Sdrh 4488a41449eSdanielk1977 /* Read the database schema. If an error occurs, leave an error message 4498a41449eSdanielk1977 ** and code in pParse and return NULL. */ 450b2c8559fSdrh if( (db->mDbFlags & DBFLAG_SchemaKnownOk)==0 451b2c8559fSdrh && SQLITE_OK!=sqlite3ReadSchema(pParse) 452b2c8559fSdrh ){ 4538a41449eSdanielk1977 return 0; 4548a41449eSdanielk1977 } 4558a41449eSdanielk1977 456b2c8559fSdrh p = sqlite3FindTable(db, zName, zDbase); 457a69d9168Sdrh if( p==0 ){ 458d2975928Sdrh #ifndef SQLITE_OMIT_VIRTUALTABLE 45951be3873Sdrh /* If zName is the not the name of a table in the schema created using 46051be3873Sdrh ** CREATE, then check to see if it is the name of an virtual table that 46151be3873Sdrh ** can be an eponymous virtual table. */ 462bb0eec43Sdan if( pParse->disableVtab==0 && db->init.busy==0 ){ 463b2c8559fSdrh Module *pMod = (Module*)sqlite3HashFind(&db->aModule, zName); 4642fcc1590Sdrh if( pMod==0 && sqlite3_strnicmp(zName, "pragma_", 7)==0 ){ 465b2c8559fSdrh pMod = sqlite3PragmaVtabRegister(db, zName); 4662fcc1590Sdrh } 46751be3873Sdrh if( pMod && sqlite3VtabEponymousTableInit(pParse, pMod) ){ 468bd24e8faSdan testcase( pMod->pEpoTab==0 ); 46951be3873Sdrh return pMod->pEpoTab; 47051be3873Sdrh } 4711ea0443cSdan } 47251be3873Sdrh #endif 4731ea0443cSdan if( flags & LOCATE_NOERR ) return 0; 4741ea0443cSdan pParse->checkSchema = 1; 4751ea0443cSdan }else if( IsVirtual(p) && pParse->disableVtab ){ 4761ea0443cSdan p = 0; 4771ea0443cSdan } 4781ea0443cSdan 4791ea0443cSdan if( p==0 ){ 4801ea0443cSdan const char *zMsg = flags & LOCATE_VIEW ? "no such view" : "no such table"; 4818a41449eSdanielk1977 if( zDbase ){ 482ca424114Sdrh sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName); 483a69d9168Sdrh }else{ 484ca424114Sdrh sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName); 485a69d9168Sdrh } 4861bb89e9cSdrh }else{ 4871bb89e9cSdrh assert( HasRowid(p) || p->iPKey<0 ); 4884d249e61Sdrh } 489fab1d401Sdan 490a69d9168Sdrh return p; 491a69d9168Sdrh } 492a69d9168Sdrh 493a69d9168Sdrh /* 49441fb5cd1Sdan ** Locate the table identified by *p. 49541fb5cd1Sdan ** 49641fb5cd1Sdan ** This is a wrapper around sqlite3LocateTable(). The difference between 49741fb5cd1Sdan ** sqlite3LocateTable() and this function is that this function restricts 49841fb5cd1Sdan ** the search to schema (p->pSchema) if it is not NULL. p->pSchema may be 49941fb5cd1Sdan ** non-NULL if it is part of a view or trigger program definition. See 50041fb5cd1Sdan ** sqlite3FixSrcList() for details. 50141fb5cd1Sdan */ 50241fb5cd1Sdan Table *sqlite3LocateTableItem( 50341fb5cd1Sdan Parse *pParse, 5044d249e61Sdrh u32 flags, 5057601294aSdrh SrcItem *p 50641fb5cd1Sdan ){ 50741fb5cd1Sdan const char *zDb; 508cd1499f4Sdrh assert( p->pSchema==0 || p->zDatabase==0 ); 50941fb5cd1Sdan if( p->pSchema ){ 51041fb5cd1Sdan int iDb = sqlite3SchemaToIndex(pParse->db, p->pSchema); 51169c33826Sdrh zDb = pParse->db->aDb[iDb].zDbSName; 51241fb5cd1Sdan }else{ 51341fb5cd1Sdan zDb = p->zDatabase; 51441fb5cd1Sdan } 5154d249e61Sdrh return sqlite3LocateTable(pParse, flags, p->zName, zDb); 51641fb5cd1Sdan } 51741fb5cd1Sdan 51841fb5cd1Sdan /* 519a69d9168Sdrh ** Locate the in-memory structure that describes 520a69d9168Sdrh ** a particular index given the name of that index 521a69d9168Sdrh ** and the name of the database that contains the index. 522f57b3399Sdrh ** Return NULL if not found. 523f26e09c8Sdrh ** 524f26e09c8Sdrh ** If zDatabase is 0, all databases are searched for the 525f26e09c8Sdrh ** table and the first matching index is returned. (No checking 526f26e09c8Sdrh ** for duplicate index names is done.) The search order is 527f26e09c8Sdrh ** TEMP first, then MAIN, then any auxiliary databases added 528f26e09c8Sdrh ** using the ATTACH command. 52975897234Sdrh */ 5309bb575fdSdrh Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){ 531d24cc427Sdrh Index *p = 0; 532d24cc427Sdrh int i; 5332120608eSdrh /* All mutexes are required for schema access. Make sure we hold them. */ 5342120608eSdrh assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) ); 53553c0f748Sdanielk1977 for(i=OMIT_TEMPDB; i<db->nDb; i++){ 536812d7a21Sdrh int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */ 537e501b89aSdanielk1977 Schema *pSchema = db->aDb[j].pSchema; 5380449171eSdrh assert( pSchema ); 539465c2b89Sdan if( zDb && sqlite3DbIsNamed(db, j, zDb)==0 ) continue; 5402120608eSdrh assert( sqlite3SchemaMutexHeld(db, j, 0) ); 541acbcb7e0Sdrh p = sqlite3HashFind(&pSchema->idxHash, zName); 542d24cc427Sdrh if( p ) break; 543d24cc427Sdrh } 54474e24cd0Sdrh return p; 54575897234Sdrh } 54675897234Sdrh 54775897234Sdrh /* 548956bc92cSdrh ** Reclaim the memory used by an index 549956bc92cSdrh */ 550cf8f2895Sdan void sqlite3FreeIndex(sqlite3 *db, Index *p){ 55192aa5eacSdrh #ifndef SQLITE_OMIT_ANALYZE 552d46def77Sdan sqlite3DeleteIndexSamples(db, p); 55392aa5eacSdrh #endif 5541fe0537eSdrh sqlite3ExprDelete(db, p->pPartIdxWhere); 5551f9ca2c8Sdrh sqlite3ExprListDelete(db, p->aColExpr); 556633e6d57Sdrh sqlite3DbFree(db, p->zColAff); 5575905f86bSmistachkin if( p->isResized ) sqlite3DbFree(db, (void *)p->azColl); 558175b8f06Sdrh #ifdef SQLITE_ENABLE_STAT4 55975b170b1Sdrh sqlite3_free(p->aiRowEst); 56075b170b1Sdrh #endif 561633e6d57Sdrh sqlite3DbFree(db, p); 562956bc92cSdrh } 563956bc92cSdrh 564956bc92cSdrh /* 565c96d8530Sdrh ** For the index called zIdxName which is found in the database iDb, 566c96d8530Sdrh ** unlike that index from its Table then remove the index from 567c96d8530Sdrh ** the index hash table and free all memory structures associated 568c96d8530Sdrh ** with the index. 5695e00f6c7Sdrh */ 5709bb575fdSdrh void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){ 571956bc92cSdrh Index *pIndex; 5722120608eSdrh Hash *pHash; 573956bc92cSdrh 5742120608eSdrh assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); 5752120608eSdrh pHash = &db->aDb[iDb].pSchema->idxHash; 576acbcb7e0Sdrh pIndex = sqlite3HashInsert(pHash, zIdxName, 0); 57722645842Sdrh if( ALWAYS(pIndex) ){ 5785e00f6c7Sdrh if( pIndex->pTable->pIndex==pIndex ){ 5795e00f6c7Sdrh pIndex->pTable->pIndex = pIndex->pNext; 5805e00f6c7Sdrh }else{ 5815e00f6c7Sdrh Index *p; 5820449171eSdrh /* Justification of ALWAYS(); The index must be on the list of 5830449171eSdrh ** indices. */ 5840449171eSdrh p = pIndex->pTable->pIndex; 5850449171eSdrh while( ALWAYS(p) && p->pNext!=pIndex ){ p = p->pNext; } 5860449171eSdrh if( ALWAYS(p && p->pNext==pIndex) ){ 5875e00f6c7Sdrh p->pNext = pIndex->pNext; 5885e00f6c7Sdrh } 5895e00f6c7Sdrh } 590cf8f2895Sdan sqlite3FreeIndex(db, pIndex); 591956bc92cSdrh } 5928257aa8dSdrh db->mDbFlags |= DBFLAG_SchemaChange; 5935e00f6c7Sdrh } 5945e00f6c7Sdrh 5955e00f6c7Sdrh /* 59681028a45Sdrh ** Look through the list of open database files in db->aDb[] and if 59781028a45Sdrh ** any have been closed, remove them from the list. Reallocate the 59881028a45Sdrh ** db->aDb[] structure to a smaller size, if possible. 5991c2d8414Sdrh ** 60081028a45Sdrh ** Entry 0 (the "main" database) and entry 1 (the "temp" database) 60181028a45Sdrh ** are never candidates for being collapsed. 60274e24cd0Sdrh */ 60381028a45Sdrh void sqlite3CollapseDatabaseArray(sqlite3 *db){ 6041c2d8414Sdrh int i, j; 6051c2d8414Sdrh for(i=j=2; i<db->nDb; i++){ 6064d189ca4Sdrh struct Db *pDb = &db->aDb[i]; 6074d189ca4Sdrh if( pDb->pBt==0 ){ 60869c33826Sdrh sqlite3DbFree(db, pDb->zDbSName); 60969c33826Sdrh pDb->zDbSName = 0; 6101c2d8414Sdrh continue; 6111c2d8414Sdrh } 6121c2d8414Sdrh if( j<i ){ 6138bf8dc92Sdrh db->aDb[j] = db->aDb[i]; 6141c2d8414Sdrh } 6158bf8dc92Sdrh j++; 6161c2d8414Sdrh } 6171c2d8414Sdrh db->nDb = j; 6181c2d8414Sdrh if( db->nDb<=2 && db->aDb!=db->aDbStatic ){ 6191c2d8414Sdrh memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0])); 620633e6d57Sdrh sqlite3DbFree(db, db->aDb); 6211c2d8414Sdrh db->aDb = db->aDbStatic; 6221c2d8414Sdrh } 623e0bc4048Sdrh } 624e0bc4048Sdrh 625e0bc4048Sdrh /* 62681028a45Sdrh ** Reset the schema for the database at index iDb. Also reset the 627dc6b41edSdrh ** TEMP schema. The reset is deferred if db->nSchemaLock is not zero. 628dc6b41edSdrh ** Deferred resets may be run by calling with iDb<0. 62981028a45Sdrh */ 63081028a45Sdrh void sqlite3ResetOneSchema(sqlite3 *db, int iDb){ 631dc6b41edSdrh int i; 63281028a45Sdrh assert( iDb<db->nDb ); 63381028a45Sdrh 634dc6b41edSdrh if( iDb>=0 ){ 63581028a45Sdrh assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); 636dc6b41edSdrh DbSetProperty(db, iDb, DB_ResetWanted); 637dc6b41edSdrh DbSetProperty(db, 1, DB_ResetWanted); 638b2c8559fSdrh db->mDbFlags &= ~DBFLAG_SchemaKnownOk; 63981028a45Sdrh } 640dc6b41edSdrh 641dc6b41edSdrh if( db->nSchemaLock==0 ){ 642dc6b41edSdrh for(i=0; i<db->nDb; i++){ 643dc6b41edSdrh if( DbHasProperty(db, i, DB_ResetWanted) ){ 644dc6b41edSdrh sqlite3SchemaClear(db->aDb[i].pSchema); 645dc6b41edSdrh } 646dc6b41edSdrh } 647dc6b41edSdrh } 64881028a45Sdrh } 64981028a45Sdrh 65081028a45Sdrh /* 65181028a45Sdrh ** Erase all schema information from all attached databases (including 65281028a45Sdrh ** "main" and "temp") for a single database connection. 65381028a45Sdrh */ 65481028a45Sdrh void sqlite3ResetAllSchemasOfConnection(sqlite3 *db){ 65581028a45Sdrh int i; 65681028a45Sdrh sqlite3BtreeEnterAll(db); 65781028a45Sdrh for(i=0; i<db->nDb; i++){ 65881028a45Sdrh Db *pDb = &db->aDb[i]; 65981028a45Sdrh if( pDb->pSchema ){ 66063e50b9eSdan if( db->nSchemaLock==0 ){ 66181028a45Sdrh sqlite3SchemaClear(pDb->pSchema); 66263e50b9eSdan }else{ 66363e50b9eSdan DbSetProperty(db, i, DB_ResetWanted); 66463e50b9eSdan } 66581028a45Sdrh } 66681028a45Sdrh } 667b2c8559fSdrh db->mDbFlags &= ~(DBFLAG_SchemaChange|DBFLAG_SchemaKnownOk); 66881028a45Sdrh sqlite3VtabUnlockList(db); 66981028a45Sdrh sqlite3BtreeLeaveAll(db); 67063e50b9eSdan if( db->nSchemaLock==0 ){ 67181028a45Sdrh sqlite3CollapseDatabaseArray(db); 67281028a45Sdrh } 67363e50b9eSdan } 67481028a45Sdrh 67581028a45Sdrh /* 676e0bc4048Sdrh ** This routine is called when a commit occurs. 677e0bc4048Sdrh */ 6789bb575fdSdrh void sqlite3CommitInternalChanges(sqlite3 *db){ 6798257aa8dSdrh db->mDbFlags &= ~DBFLAG_SchemaChange; 68074e24cd0Sdrh } 68174e24cd0Sdrh 68274e24cd0Sdrh /* 68379cf2b71Sdrh ** Set the expression associated with a column. This is usually 68479cf2b71Sdrh ** the DEFAULT value, but might also be the expression that computes 68579cf2b71Sdrh ** the value for a generated column. 68679cf2b71Sdrh */ 68779cf2b71Sdrh void sqlite3ColumnSetExpr( 68879cf2b71Sdrh Parse *pParse, /* Parsing context */ 68979cf2b71Sdrh Table *pTab, /* The table containing the column */ 69079cf2b71Sdrh Column *pCol, /* The column to receive the new DEFAULT expression */ 69179cf2b71Sdrh Expr *pExpr /* The new default expression */ 69279cf2b71Sdrh ){ 693f38524d2Sdrh ExprList *pList; 69478b2fa86Sdrh assert( IsOrdinaryTable(pTab) ); 695f38524d2Sdrh pList = pTab->u.tab.pDfltList; 69679cf2b71Sdrh if( pCol->iDflt==0 697324f91a5Sdrh || NEVER(pList==0) 698324f91a5Sdrh || NEVER(pList->nExpr<pCol->iDflt) 69979cf2b71Sdrh ){ 70079cf2b71Sdrh pCol->iDflt = pList==0 ? 1 : pList->nExpr+1; 701f38524d2Sdrh pTab->u.tab.pDfltList = sqlite3ExprListAppend(pParse, pList, pExpr); 70279cf2b71Sdrh }else{ 70379cf2b71Sdrh sqlite3ExprDelete(pParse->db, pList->a[pCol->iDflt-1].pExpr); 70479cf2b71Sdrh pList->a[pCol->iDflt-1].pExpr = pExpr; 70579cf2b71Sdrh } 70679cf2b71Sdrh } 70779cf2b71Sdrh 70879cf2b71Sdrh /* 70979cf2b71Sdrh ** Return the expression associated with a column. The expression might be 71079cf2b71Sdrh ** the DEFAULT clause or the AS clause of a generated column. 71179cf2b71Sdrh ** Return NULL if the column has no associated expression. 71279cf2b71Sdrh */ 71379cf2b71Sdrh Expr *sqlite3ColumnExpr(Table *pTab, Column *pCol){ 71479cf2b71Sdrh if( pCol->iDflt==0 ) return 0; 71578b2fa86Sdrh if( NEVER(!IsOrdinaryTable(pTab)) ) return 0; 716324f91a5Sdrh if( NEVER(pTab->u.tab.pDfltList==0) ) return 0; 717324f91a5Sdrh if( NEVER(pTab->u.tab.pDfltList->nExpr<pCol->iDflt) ) return 0; 718f38524d2Sdrh return pTab->u.tab.pDfltList->a[pCol->iDflt-1].pExpr; 71979cf2b71Sdrh } 72079cf2b71Sdrh 72179cf2b71Sdrh /* 72265b40093Sdrh ** Set the collating sequence name for a column. 72365b40093Sdrh */ 72465b40093Sdrh void sqlite3ColumnSetColl( 72565b40093Sdrh sqlite3 *db, 72665b40093Sdrh Column *pCol, 72765b40093Sdrh const char *zColl 72865b40093Sdrh ){ 72965b40093Sdrh int nColl; 73065b40093Sdrh int n; 73165b40093Sdrh char *zNew; 73265b40093Sdrh assert( zColl!=0 ); 73365b40093Sdrh n = sqlite3Strlen30(pCol->zCnName) + 1; 73465b40093Sdrh if( pCol->colFlags & COLFLAG_HASTYPE ){ 73565b40093Sdrh n += sqlite3Strlen30(pCol->zCnName+n) + 1; 73665b40093Sdrh } 73765b40093Sdrh nColl = sqlite3Strlen30(zColl) + 1; 73865b40093Sdrh zNew = sqlite3DbRealloc(db, pCol->zCnName, nColl+n); 73965b40093Sdrh if( zNew ){ 74065b40093Sdrh pCol->zCnName = zNew; 74165b40093Sdrh memcpy(pCol->zCnName + n, zColl, nColl); 74265b40093Sdrh pCol->colFlags |= COLFLAG_HASCOLL; 74365b40093Sdrh } 74465b40093Sdrh } 74565b40093Sdrh 74665b40093Sdrh /* 74765b40093Sdrh ** Return the collating squence name for a column 74865b40093Sdrh */ 74965b40093Sdrh const char *sqlite3ColumnColl(Column *pCol){ 75065b40093Sdrh const char *z; 75165b40093Sdrh if( (pCol->colFlags & COLFLAG_HASCOLL)==0 ) return 0; 75265b40093Sdrh z = pCol->zCnName; 75365b40093Sdrh while( *z ){ z++; } 75465b40093Sdrh if( pCol->colFlags & COLFLAG_HASTYPE ){ 75565b40093Sdrh do{ z++; }while( *z ); 75665b40093Sdrh } 75765b40093Sdrh return z+1; 75865b40093Sdrh } 75965b40093Sdrh 76065b40093Sdrh /* 761d46def77Sdan ** Delete memory allocated for the column names of a table or view (the 762d46def77Sdan ** Table.aCol[] array). 763956bc92cSdrh */ 76451be3873Sdrh void sqlite3DeleteColumnNames(sqlite3 *db, Table *pTable){ 765956bc92cSdrh int i; 766956bc92cSdrh Column *pCol; 767956bc92cSdrh assert( pTable!=0 ); 768dd5b2fa5Sdrh if( (pCol = pTable->aCol)!=0 ){ 769dd5b2fa5Sdrh for(i=0; i<pTable->nCol; i++, pCol++){ 770cf9d36d1Sdrh assert( pCol->zCnName==0 || pCol->hName==sqlite3StrIHash(pCol->zCnName) ); 771cf9d36d1Sdrh sqlite3DbFree(db, pCol->zCnName); 772956bc92cSdrh } 773633e6d57Sdrh sqlite3DbFree(db, pTable->aCol); 77478b2fa86Sdrh if( IsOrdinaryTable(pTable) ){ 775f38524d2Sdrh sqlite3ExprListDelete(db, pTable->u.tab.pDfltList); 776f38524d2Sdrh } 77779cf2b71Sdrh if( db==0 || db->pnBytesFreed==0 ){ 77879cf2b71Sdrh pTable->aCol = 0; 77979cf2b71Sdrh pTable->nCol = 0; 78078b2fa86Sdrh if( IsOrdinaryTable(pTable) ){ 781f38524d2Sdrh pTable->u.tab.pDfltList = 0; 782f38524d2Sdrh } 78379cf2b71Sdrh } 784dd5b2fa5Sdrh } 785956bc92cSdrh } 786956bc92cSdrh 787956bc92cSdrh /* 78875897234Sdrh ** Remove the memory data structures associated with the given 789967e8b73Sdrh ** Table. No changes are made to disk by this routine. 79075897234Sdrh ** 79175897234Sdrh ** This routine just deletes the data structure. It does not unlink 792e61922a6Sdrh ** the table data structure from the hash table. But it does destroy 793c2eef3b3Sdrh ** memory structures of the indices and foreign keys associated with 794c2eef3b3Sdrh ** the table. 79529ddd3acSdrh ** 79629ddd3acSdrh ** The db parameter is optional. It is needed if the Table object 79729ddd3acSdrh ** contains lookaside memory. (Table objects in the schema do not use 79829ddd3acSdrh ** lookaside memory, but some ephemeral Table objects do.) Or the 79929ddd3acSdrh ** db parameter can be used with db->pnBytesFreed to measure the memory 80029ddd3acSdrh ** used by the Table object. 80175897234Sdrh */ 802e8da01c1Sdrh static void SQLITE_NOINLINE deleteTable(sqlite3 *db, Table *pTable){ 80375897234Sdrh Index *pIndex, *pNext; 804c2eef3b3Sdrh 80552fb8e19Sdrh #ifdef SQLITE_DEBUG 80629ddd3acSdrh /* Record the number of outstanding lookaside allocations in schema Tables 80729ddd3acSdrh ** prior to doing any free() operations. Since schema Tables do not use 808bedf84c1Sdan ** lookaside, this number should not change. 809bedf84c1Sdan ** 810bedf84c1Sdan ** If malloc has already failed, it may be that it failed while allocating 811bedf84c1Sdan ** a Table object that was going to be marked ephemeral. So do not check 812bedf84c1Sdan ** that no lookaside memory is used in this case either. */ 81352fb8e19Sdrh int nLookaside = 0; 814bedf84c1Sdan if( db && !db->mallocFailed && (pTable->tabFlags & TF_Ephemeral)==0 ){ 81552fb8e19Sdrh nLookaside = sqlite3LookasideUsed(db, 0); 81652fb8e19Sdrh } 81752fb8e19Sdrh #endif 81829ddd3acSdrh 819d46def77Sdan /* Delete all indices associated with this table. */ 820c2eef3b3Sdrh for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){ 821c2eef3b3Sdrh pNext = pIndex->pNext; 82262340f84Sdrh assert( pIndex->pSchema==pTable->pSchema 82362340f84Sdrh || (IsVirtual(pTable) && pIndex->idxType!=SQLITE_IDXTYPE_APPDEF) ); 824273bfe9fSdrh if( (db==0 || db->pnBytesFreed==0) && !IsVirtual(pTable) ){ 825d46def77Sdan char *zName = pIndex->zName; 826d46def77Sdan TESTONLY ( Index *pOld = ) sqlite3HashInsert( 827acbcb7e0Sdrh &pIndex->pSchema->idxHash, zName, 0 828d46def77Sdan ); 8292120608eSdrh assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) ); 830d46def77Sdan assert( pOld==pIndex || pOld==0 ); 831d46def77Sdan } 832cf8f2895Sdan sqlite3FreeIndex(db, pIndex); 833c2eef3b3Sdrh } 834c2eef3b3Sdrh 835f38524d2Sdrh if( IsOrdinaryTable(pTable) ){ 8361feeaed2Sdan sqlite3FkDelete(db, pTable); 837f38524d2Sdrh } 838f38524d2Sdrh #ifndef SQLITE_OMIT_VIRTUAL_TABLE 839f38524d2Sdrh else if( IsVirtual(pTable) ){ 840f38524d2Sdrh sqlite3VtabClear(db, pTable); 841f38524d2Sdrh } 842f38524d2Sdrh #endif 843f38524d2Sdrh else{ 844f38524d2Sdrh assert( IsView(pTable) ); 845f38524d2Sdrh sqlite3SelectDelete(db, pTable->u.view.pSelect); 846f38524d2Sdrh } 847c2eef3b3Sdrh 848c2eef3b3Sdrh /* Delete the Table structure itself. 849c2eef3b3Sdrh */ 85051be3873Sdrh sqlite3DeleteColumnNames(db, pTable); 851633e6d57Sdrh sqlite3DbFree(db, pTable->zName); 852633e6d57Sdrh sqlite3DbFree(db, pTable->zColAff); 8532938f924Sdrh sqlite3ExprListDelete(db, pTable->pCheck); 854633e6d57Sdrh sqlite3DbFree(db, pTable); 85529ddd3acSdrh 85629ddd3acSdrh /* Verify that no lookaside memory was used by schema tables */ 85752fb8e19Sdrh assert( nLookaside==0 || nLookaside==sqlite3LookasideUsed(db,0) ); 85875897234Sdrh } 859e8da01c1Sdrh void sqlite3DeleteTable(sqlite3 *db, Table *pTable){ 860e8da01c1Sdrh /* Do not delete the table until the reference count reaches zero. */ 861e8da01c1Sdrh if( !pTable ) return; 86279df7782Sdrh if( ((!db || db->pnBytesFreed==0) && (--pTable->nTabRef)>0) ) return; 863e8da01c1Sdrh deleteTable(db, pTable); 864e8da01c1Sdrh } 865e8da01c1Sdrh 86675897234Sdrh 86775897234Sdrh /* 8685edc3124Sdrh ** Unlink the given table from the hash tables and the delete the 869c2eef3b3Sdrh ** table structure with all its indices and foreign keys. 8705edc3124Sdrh */ 8719bb575fdSdrh void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){ 872956bc92cSdrh Table *p; 873956bc92cSdrh Db *pDb; 874956bc92cSdrh 875d229ca94Sdrh assert( db!=0 ); 876956bc92cSdrh assert( iDb>=0 && iDb<db->nDb ); 877972a2311Sdrh assert( zTabName ); 8782120608eSdrh assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); 879972a2311Sdrh testcase( zTabName[0]==0 ); /* Zero-length table names are allowed */ 880956bc92cSdrh pDb = &db->aDb[iDb]; 881acbcb7e0Sdrh p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName, 0); 8821feeaed2Sdan sqlite3DeleteTable(db, p); 8838257aa8dSdrh db->mDbFlags |= DBFLAG_SchemaChange; 884956bc92cSdrh } 88574e24cd0Sdrh 88674e24cd0Sdrh /* 887a99db3b6Sdrh ** Given a token, return a string that consists of the text of that 88824fb627aSdrh ** token. Space to hold the returned string 889a99db3b6Sdrh ** is obtained from sqliteMalloc() and must be freed by the calling 890a99db3b6Sdrh ** function. 89175897234Sdrh ** 89224fb627aSdrh ** Any quotation marks (ex: "name", 'name', [name], or `name`) that 89324fb627aSdrh ** surround the body of the token are removed. 89424fb627aSdrh ** 895c96d8530Sdrh ** Tokens are often just pointers into the original SQL text and so 896a99db3b6Sdrh ** are not \000 terminated and are not persistent. The returned string 897a99db3b6Sdrh ** is \000 terminated and is persistent. 89875897234Sdrh */ 899b6dad520Sdrh char *sqlite3NameFromToken(sqlite3 *db, const Token *pName){ 900a99db3b6Sdrh char *zName; 901a99db3b6Sdrh if( pName ){ 902b6dad520Sdrh zName = sqlite3DbStrNDup(db, (const char*)pName->z, pName->n); 903b7916a78Sdrh sqlite3Dequote(zName); 904a99db3b6Sdrh }else{ 905a99db3b6Sdrh zName = 0; 906a99db3b6Sdrh } 90775897234Sdrh return zName; 90875897234Sdrh } 90975897234Sdrh 91075897234Sdrh /* 9111e32bed3Sdrh ** Open the sqlite_schema table stored in database number iDb for 912cbb18d22Sdanielk1977 ** writing. The table is opened using cursor 0. 913e0bc4048Sdrh */ 914346a70caSdrh void sqlite3OpenSchemaTable(Parse *p, int iDb){ 915c00da105Sdanielk1977 Vdbe *v = sqlite3GetVdbe(p); 916346a70caSdrh sqlite3TableLock(p, iDb, SCHEMA_ROOT, 1, DFLT_SCHEMA_TABLE); 917346a70caSdrh sqlite3VdbeAddOp4Int(v, OP_OpenWrite, 0, SCHEMA_ROOT, iDb, 5); 9186ab3a2ecSdanielk1977 if( p->nTab==0 ){ 9196ab3a2ecSdanielk1977 p->nTab = 1; 9206ab3a2ecSdanielk1977 } 921e0bc4048Sdrh } 922e0bc4048Sdrh 923e0bc4048Sdrh /* 9240410302eSdanielk1977 ** Parameter zName points to a nul-terminated buffer containing the name 9250410302eSdanielk1977 ** of a database ("main", "temp" or the name of an attached db). This 9260410302eSdanielk1977 ** function returns the index of the named database in db->aDb[], or 9270410302eSdanielk1977 ** -1 if the named db cannot be found. 928cbb18d22Sdanielk1977 */ 9290410302eSdanielk1977 int sqlite3FindDbName(sqlite3 *db, const char *zName){ 930576ec6b3Sdanielk1977 int i = -1; /* Database number */ 93173c42a13Sdrh if( zName ){ 9320410302eSdanielk1977 Db *pDb; 933576ec6b3Sdanielk1977 for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){ 9342951809eSdrh if( 0==sqlite3_stricmp(pDb->zDbSName, zName) ) break; 9352951809eSdrh /* "main" is always an acceptable alias for the primary database 9362951809eSdrh ** even if it has been renamed using SQLITE_DBCONFIG_MAINDBNAME. */ 9372951809eSdrh if( i==0 && 0==sqlite3_stricmp("main", zName) ) break; 938576ec6b3Sdanielk1977 } 939576ec6b3Sdanielk1977 } 940cbb18d22Sdanielk1977 return i; 941cbb18d22Sdanielk1977 } 942cbb18d22Sdanielk1977 9430410302eSdanielk1977 /* 9440410302eSdanielk1977 ** The token *pName contains the name of a database (either "main" or 9450410302eSdanielk1977 ** "temp" or the name of an attached db). This routine returns the 9460410302eSdanielk1977 ** index of the named database in db->aDb[], or -1 if the named db 9470410302eSdanielk1977 ** does not exist. 9480410302eSdanielk1977 */ 9490410302eSdanielk1977 int sqlite3FindDb(sqlite3 *db, Token *pName){ 9500410302eSdanielk1977 int i; /* Database number */ 9510410302eSdanielk1977 char *zName; /* Name we are searching for */ 9520410302eSdanielk1977 zName = sqlite3NameFromToken(db, pName); 9530410302eSdanielk1977 i = sqlite3FindDbName(db, zName); 9540410302eSdanielk1977 sqlite3DbFree(db, zName); 9550410302eSdanielk1977 return i; 9560410302eSdanielk1977 } 9570410302eSdanielk1977 9580e3d7476Sdrh /* The table or view or trigger name is passed to this routine via tokens 9590e3d7476Sdrh ** pName1 and pName2. If the table name was fully qualified, for example: 9600e3d7476Sdrh ** 9610e3d7476Sdrh ** CREATE TABLE xxx.yyy (...); 9620e3d7476Sdrh ** 9630e3d7476Sdrh ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if 9640e3d7476Sdrh ** the table name is not fully qualified, i.e.: 9650e3d7476Sdrh ** 9660e3d7476Sdrh ** CREATE TABLE yyy(...); 9670e3d7476Sdrh ** 9680e3d7476Sdrh ** Then pName1 is set to "yyy" and pName2 is "". 9690e3d7476Sdrh ** 9700e3d7476Sdrh ** This routine sets the *ppUnqual pointer to point at the token (pName1 or 9710e3d7476Sdrh ** pName2) that stores the unqualified table name. The index of the 9720e3d7476Sdrh ** database "xxx" is returned. 9730e3d7476Sdrh */ 974ef2cb63eSdanielk1977 int sqlite3TwoPartName( 9750e3d7476Sdrh Parse *pParse, /* Parsing and code generating context */ 97690f5ecb3Sdrh Token *pName1, /* The "xxx" in the name "xxx.yyy" or "xxx" */ 9770e3d7476Sdrh Token *pName2, /* The "yyy" in the name "xxx.yyy" */ 9780e3d7476Sdrh Token **pUnqual /* Write the unqualified object name here */ 979cbb18d22Sdanielk1977 ){ 9800e3d7476Sdrh int iDb; /* Database holding the object */ 981cbb18d22Sdanielk1977 sqlite3 *db = pParse->db; 982cbb18d22Sdanielk1977 983055f298aSdrh assert( pName2!=0 ); 984055f298aSdrh if( pName2->n>0 ){ 985dcc50b74Sshane if( db->init.busy ) { 986dcc50b74Sshane sqlite3ErrorMsg(pParse, "corrupt database"); 987dcc50b74Sshane return -1; 988dcc50b74Sshane } 989cbb18d22Sdanielk1977 *pUnqual = pName2; 990ff2d5ea4Sdrh iDb = sqlite3FindDb(db, pName1); 991cbb18d22Sdanielk1977 if( iDb<0 ){ 992cbb18d22Sdanielk1977 sqlite3ErrorMsg(pParse, "unknown database %T", pName1); 993cbb18d22Sdanielk1977 return -1; 994cbb18d22Sdanielk1977 } 995cbb18d22Sdanielk1977 }else{ 996d36bcec9Sdrh assert( db->init.iDb==0 || db->init.busy || IN_SPECIAL_PARSE 9978257aa8dSdrh || (db->mDbFlags & DBFLAG_Vacuum)!=0); 998cbb18d22Sdanielk1977 iDb = db->init.iDb; 999cbb18d22Sdanielk1977 *pUnqual = pName1; 1000cbb18d22Sdanielk1977 } 1001cbb18d22Sdanielk1977 return iDb; 1002cbb18d22Sdanielk1977 } 1003cbb18d22Sdanielk1977 1004cbb18d22Sdanielk1977 /* 10050f1c2eb5Sdrh ** True if PRAGMA writable_schema is ON 10060f1c2eb5Sdrh */ 10070f1c2eb5Sdrh int sqlite3WritableSchema(sqlite3 *db){ 10080f1c2eb5Sdrh testcase( (db->flags&(SQLITE_WriteSchema|SQLITE_Defensive))==0 ); 10090f1c2eb5Sdrh testcase( (db->flags&(SQLITE_WriteSchema|SQLITE_Defensive))== 10100f1c2eb5Sdrh SQLITE_WriteSchema ); 10110f1c2eb5Sdrh testcase( (db->flags&(SQLITE_WriteSchema|SQLITE_Defensive))== 10120f1c2eb5Sdrh SQLITE_Defensive ); 10130f1c2eb5Sdrh testcase( (db->flags&(SQLITE_WriteSchema|SQLITE_Defensive))== 10140f1c2eb5Sdrh (SQLITE_WriteSchema|SQLITE_Defensive) ); 10150f1c2eb5Sdrh return (db->flags&(SQLITE_WriteSchema|SQLITE_Defensive))==SQLITE_WriteSchema; 10160f1c2eb5Sdrh } 10170f1c2eb5Sdrh 10180f1c2eb5Sdrh /* 1019d8123366Sdanielk1977 ** This routine is used to check if the UTF-8 string zName is a legal 1020d8123366Sdanielk1977 ** unqualified name for a new schema object (table, index, view or 1021d8123366Sdanielk1977 ** trigger). All names are legal except those that begin with the string 1022d8123366Sdanielk1977 ** "sqlite_" (in upper, lower or mixed case). This portion of the namespace 1023d8123366Sdanielk1977 ** is reserved for internal use. 1024c5a93d4cSdrh ** 10251e32bed3Sdrh ** When parsing the sqlite_schema table, this routine also checks to 1026c5a93d4cSdrh ** make sure the "type", "name", and "tbl_name" columns are consistent 1027c5a93d4cSdrh ** with the SQL. 1028d8123366Sdanielk1977 */ 1029c5a93d4cSdrh int sqlite3CheckObjectName( 1030c5a93d4cSdrh Parse *pParse, /* Parsing context */ 1031c5a93d4cSdrh const char *zName, /* Name of the object to check */ 1032c5a93d4cSdrh const char *zType, /* Type of this object */ 1033c5a93d4cSdrh const char *zTblName /* Parent table name for triggers and indexes */ 1034c5a93d4cSdrh ){ 1035c5a93d4cSdrh sqlite3 *db = pParse->db; 1036ca439a49Sdrh if( sqlite3WritableSchema(db) 1037ca439a49Sdrh || db->init.imposterTable 1038ca439a49Sdrh || !sqlite3Config.bExtraSchemaChecks 1039ca439a49Sdrh ){ 1040c5a93d4cSdrh /* Skip these error checks for writable_schema=ON */ 1041c5a93d4cSdrh return SQLITE_OK; 1042c5a93d4cSdrh } 1043c5a93d4cSdrh if( db->init.busy ){ 1044c5a93d4cSdrh if( sqlite3_stricmp(zType, db->init.azInit[0]) 1045c5a93d4cSdrh || sqlite3_stricmp(zName, db->init.azInit[1]) 1046c5a93d4cSdrh || sqlite3_stricmp(zTblName, db->init.azInit[2]) 1047c5a93d4cSdrh ){ 1048c5a93d4cSdrh sqlite3ErrorMsg(pParse, ""); /* corruptSchema() will supply the error */ 1049d8123366Sdanielk1977 return SQLITE_ERROR; 1050d8123366Sdanielk1977 } 1051c5a93d4cSdrh }else{ 1052527cbd4aSdrh if( (pParse->nested==0 && 0==sqlite3StrNICmp(zName, "sqlite_", 7)) 1053527cbd4aSdrh || (sqlite3ReadOnlyShadowTables(db) && sqlite3ShadowTableName(db, zName)) 1054c5a93d4cSdrh ){ 1055c5a93d4cSdrh sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", 1056c5a93d4cSdrh zName); 1057c5a93d4cSdrh return SQLITE_ERROR; 1058c5a93d4cSdrh } 1059527cbd4aSdrh 1060c5a93d4cSdrh } 1061d8123366Sdanielk1977 return SQLITE_OK; 1062d8123366Sdanielk1977 } 1063d8123366Sdanielk1977 1064d8123366Sdanielk1977 /* 10654415628aSdrh ** Return the PRIMARY KEY index of a table 10664415628aSdrh */ 10674415628aSdrh Index *sqlite3PrimaryKeyIndex(Table *pTab){ 10684415628aSdrh Index *p; 106948dd1d8eSdrh for(p=pTab->pIndex; p && !IsPrimaryKeyIndex(p); p=p->pNext){} 10704415628aSdrh return p; 10714415628aSdrh } 10724415628aSdrh 10734415628aSdrh /* 1074b9bcf7caSdrh ** Convert an table column number into a index column number. That is, 1075b9bcf7caSdrh ** for the column iCol in the table (as defined by the CREATE TABLE statement) 1076b9bcf7caSdrh ** find the (first) offset of that column in index pIdx. Or return -1 1077b9bcf7caSdrh ** if column iCol is not used in index pIdx. 10784415628aSdrh */ 1079b9bcf7caSdrh i16 sqlite3TableColumnToIndex(Index *pIdx, i16 iCol){ 10804415628aSdrh int i; 10814415628aSdrh for(i=0; i<pIdx->nColumn; i++){ 10824415628aSdrh if( iCol==pIdx->aiColumn[i] ) return i; 10834415628aSdrh } 10844415628aSdrh return -1; 10854415628aSdrh } 10864415628aSdrh 108781f7b372Sdrh #ifndef SQLITE_OMIT_GENERATED_COLUMNS 1088b9bcf7caSdrh /* Convert a storage column number into a table column number. 108981f7b372Sdrh ** 10908e10d74bSdrh ** The storage column number (0,1,2,....) is the index of the value 10918e10d74bSdrh ** as it appears in the record on disk. The true column number 10928e10d74bSdrh ** is the index (0,1,2,...) of the column in the CREATE TABLE statement. 10938e10d74bSdrh ** 1094b9bcf7caSdrh ** The storage column number is less than the table column number if 1095b9bcf7caSdrh ** and only there are VIRTUAL columns to the left. 10968e10d74bSdrh ** 10978e10d74bSdrh ** If SQLITE_OMIT_GENERATED_COLUMNS, this routine is a no-op macro. 10988e10d74bSdrh */ 1099b9bcf7caSdrh i16 sqlite3StorageColumnToTable(Table *pTab, i16 iCol){ 11008e10d74bSdrh if( pTab->tabFlags & TF_HasVirtual ){ 11018e10d74bSdrh int i; 11028e10d74bSdrh for(i=0; i<=iCol; i++){ 11038e10d74bSdrh if( pTab->aCol[i].colFlags & COLFLAG_VIRTUAL ) iCol++; 11048e10d74bSdrh } 11058e10d74bSdrh } 11068e10d74bSdrh return iCol; 11078e10d74bSdrh } 11088e10d74bSdrh #endif 11098e10d74bSdrh 11108e10d74bSdrh #ifndef SQLITE_OMIT_GENERATED_COLUMNS 1111b9bcf7caSdrh /* Convert a table column number into a storage column number. 11128e10d74bSdrh ** 11138e10d74bSdrh ** The storage column number (0,1,2,....) is the index of the value 1114dd6cc9b5Sdrh ** as it appears in the record on disk. Or, if the input column is 1115dd6cc9b5Sdrh ** the N-th virtual column (zero-based) then the storage number is 1116dd6cc9b5Sdrh ** the number of non-virtual columns in the table plus N. 11178e10d74bSdrh ** 1118dd6cc9b5Sdrh ** The true column number is the index (0,1,2,...) of the column in 1119dd6cc9b5Sdrh ** the CREATE TABLE statement. 11208e10d74bSdrh ** 1121dd6cc9b5Sdrh ** If the input column is a VIRTUAL column, then it should not appear 1122dd6cc9b5Sdrh ** in storage. But the value sometimes is cached in registers that 1123dd6cc9b5Sdrh ** follow the range of registers used to construct storage. This 1124dd6cc9b5Sdrh ** avoids computing the same VIRTUAL column multiple times, and provides 1125dd6cc9b5Sdrh ** values for use by OP_Param opcodes in triggers. Hence, if the 1126dd6cc9b5Sdrh ** input column is a VIRTUAL table, put it after all the other columns. 1127dd6cc9b5Sdrh ** 1128dd6cc9b5Sdrh ** In the following, N means "normal column", S means STORED, and 1129dd6cc9b5Sdrh ** V means VIRTUAL. Suppose the CREATE TABLE has columns like this: 1130dd6cc9b5Sdrh ** 1131dd6cc9b5Sdrh ** CREATE TABLE ex(N,S,V,N,S,V,N,S,V); 1132dd6cc9b5Sdrh ** -- 0 1 2 3 4 5 6 7 8 1133dd6cc9b5Sdrh ** 1134dd6cc9b5Sdrh ** Then the mapping from this function is as follows: 1135dd6cc9b5Sdrh ** 1136dd6cc9b5Sdrh ** INPUTS: 0 1 2 3 4 5 6 7 8 1137dd6cc9b5Sdrh ** OUTPUTS: 0 1 6 2 3 7 4 5 8 1138dd6cc9b5Sdrh ** 1139dd6cc9b5Sdrh ** So, in other words, this routine shifts all the virtual columns to 1140dd6cc9b5Sdrh ** the end. 1141dd6cc9b5Sdrh ** 1142dd6cc9b5Sdrh ** If SQLITE_OMIT_GENERATED_COLUMNS then there are no virtual columns and 11437fe2fc0dSdrh ** this routine is a no-op macro. If the pTab does not have any virtual 11447fe2fc0dSdrh ** columns, then this routine is no-op that always return iCol. If iCol 11457fe2fc0dSdrh ** is negative (indicating the ROWID column) then this routine return iCol. 114681f7b372Sdrh */ 1147b9bcf7caSdrh i16 sqlite3TableColumnToStorage(Table *pTab, i16 iCol){ 114881f7b372Sdrh int i; 114981f7b372Sdrh i16 n; 115081f7b372Sdrh assert( iCol<pTab->nCol ); 11517fe2fc0dSdrh if( (pTab->tabFlags & TF_HasVirtual)==0 || iCol<0 ) return iCol; 115281f7b372Sdrh for(i=0, n=0; i<iCol; i++){ 115381f7b372Sdrh if( (pTab->aCol[i].colFlags & COLFLAG_VIRTUAL)==0 ) n++; 115481f7b372Sdrh } 1155dd6cc9b5Sdrh if( pTab->aCol[i].colFlags & COLFLAG_VIRTUAL ){ 1156dd6cc9b5Sdrh /* iCol is a virtual column itself */ 1157dd6cc9b5Sdrh return pTab->nNVCol + i - n; 1158dd6cc9b5Sdrh }else{ 1159dd6cc9b5Sdrh /* iCol is a normal or stored column */ 116081f7b372Sdrh return n; 116181f7b372Sdrh } 1162dd6cc9b5Sdrh } 116381f7b372Sdrh #endif 116481f7b372Sdrh 11654415628aSdrh /* 116631da7be9Sdrh ** Insert a single OP_JournalMode query opcode in order to force the 116731da7be9Sdrh ** prepared statement to return false for sqlite3_stmt_readonly(). This 116831da7be9Sdrh ** is used by CREATE TABLE IF NOT EXISTS and similar if the table already 116931da7be9Sdrh ** exists, so that the prepared statement for CREATE TABLE IF NOT EXISTS 117031da7be9Sdrh ** will return false for sqlite3_stmt_readonly() even if that statement 117131da7be9Sdrh ** is a read-only no-op. 117231da7be9Sdrh */ 117331da7be9Sdrh static void sqlite3ForceNotReadOnly(Parse *pParse){ 117431da7be9Sdrh int iReg = ++pParse->nMem; 117531da7be9Sdrh Vdbe *v = sqlite3GetVdbe(pParse); 117631da7be9Sdrh if( v ){ 117731da7be9Sdrh sqlite3VdbeAddOp3(v, OP_JournalMode, 0, iReg, PAGER_JOURNALMODE_QUERY); 1178a8f249f1Sdan sqlite3VdbeUsesBtree(v, 0); 117931da7be9Sdrh } 118031da7be9Sdrh } 118131da7be9Sdrh 118231da7be9Sdrh /* 118375897234Sdrh ** Begin constructing a new table representation in memory. This is 118475897234Sdrh ** the first of several action routines that get called in response 1185d9b0257aSdrh ** to a CREATE TABLE statement. In particular, this routine is called 118674161705Sdrh ** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp 1187e0bc4048Sdrh ** flag is true if the table should be stored in the auxiliary database 1188e0bc4048Sdrh ** file instead of in the main database file. This is normally the case 1189e0bc4048Sdrh ** when the "TEMP" or "TEMPORARY" keyword occurs in between 1190f57b3399Sdrh ** CREATE and TABLE. 1191d9b0257aSdrh ** 1192f57b3399Sdrh ** The new table record is initialized and put in pParse->pNewTable. 1193f57b3399Sdrh ** As more of the CREATE TABLE statement is parsed, additional action 1194f57b3399Sdrh ** routines will be called to add more information to this record. 11954adee20fSdanielk1977 ** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine 1196f57b3399Sdrh ** is called to complete the construction of the new table record. 119775897234Sdrh */ 11984adee20fSdanielk1977 void sqlite3StartTable( 1199e5f9c644Sdrh Parse *pParse, /* Parser context */ 1200cbb18d22Sdanielk1977 Token *pName1, /* First part of the name of the table or view */ 1201cbb18d22Sdanielk1977 Token *pName2, /* Second part of the name of the table or view */ 1202e5f9c644Sdrh int isTemp, /* True if this is a TEMP table */ 1203faa59554Sdrh int isView, /* True if this is a VIEW */ 1204f1a381e7Sdanielk1977 int isVirtual, /* True if this is a VIRTUAL table */ 1205faa59554Sdrh int noErr /* Do nothing if table already exists */ 1206e5f9c644Sdrh ){ 120775897234Sdrh Table *pTable; 120823bf66d6Sdrh char *zName = 0; /* The name of the new table */ 12099bb575fdSdrh sqlite3 *db = pParse->db; 1210adbca9cfSdrh Vdbe *v; 1211cbb18d22Sdanielk1977 int iDb; /* Database number to create the table in */ 1212cbb18d22Sdanielk1977 Token *pName; /* Unqualified name of the table to create */ 121375897234Sdrh 1214055f298aSdrh if( db->init.busy && db->init.newTnum==1 ){ 12151e32bed3Sdrh /* Special case: Parsing the sqlite_schema or sqlite_temp_schema schema */ 1216055f298aSdrh iDb = db->init.iDb; 1217055f298aSdrh zName = sqlite3DbStrDup(db, SCHEMA_TABLE(iDb)); 1218055f298aSdrh pName = pName1; 1219055f298aSdrh }else{ 1220055f298aSdrh /* The common case */ 1221ef2cb63eSdanielk1977 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName); 1222cbb18d22Sdanielk1977 if( iDb<0 ) return; 122372c5ea32Sdan if( !OMIT_TEMPDB && isTemp && pName2->n>0 && iDb!=1 ){ 122472c5ea32Sdan /* If creating a temp table, the name may not be qualified. Unless 122572c5ea32Sdan ** the database name is "temp" anyway. */ 1226cbb18d22Sdanielk1977 sqlite3ErrorMsg(pParse, "temporary table name must be unqualified"); 1227cbb18d22Sdanielk1977 return; 1228cbb18d22Sdanielk1977 } 122953c0f748Sdanielk1977 if( !OMIT_TEMPDB && isTemp ) iDb = 1; 123017435752Sdrh zName = sqlite3NameFromToken(db, pName); 1231c9461eccSdan if( IN_RENAME_OBJECT ){ 1232c9461eccSdan sqlite3RenameTokenMap(pParse, (void*)zName, pName); 1233c9461eccSdan } 1234055f298aSdrh } 1235055f298aSdrh pParse->sNameToken = *pName; 1236e0048400Sdanielk1977 if( zName==0 ) return; 1237c5a93d4cSdrh if( sqlite3CheckObjectName(pParse, zName, isView?"view":"table", zName) ){ 123823bf66d6Sdrh goto begin_table_error; 1239d8123366Sdanielk1977 } 12401d85d931Sdrh if( db->init.iDb==1 ) isTemp = 1; 1241e5f9c644Sdrh #ifndef SQLITE_OMIT_AUTHORIZATION 1242055f298aSdrh assert( isTemp==0 || isTemp==1 ); 1243055f298aSdrh assert( isView==0 || isView==1 ); 1244e22a334bSdrh { 1245055f298aSdrh static const u8 aCode[] = { 1246055f298aSdrh SQLITE_CREATE_TABLE, 1247055f298aSdrh SQLITE_CREATE_TEMP_TABLE, 1248055f298aSdrh SQLITE_CREATE_VIEW, 1249055f298aSdrh SQLITE_CREATE_TEMP_VIEW 1250055f298aSdrh }; 125169c33826Sdrh char *zDb = db->aDb[iDb].zDbSName; 12524adee20fSdanielk1977 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){ 125323bf66d6Sdrh goto begin_table_error; 1254ed6c8671Sdrh } 1255055f298aSdrh if( !isVirtual && sqlite3AuthCheck(pParse, (int)aCode[isTemp+2*isView], 1256055f298aSdrh zName, 0, zDb) ){ 125723bf66d6Sdrh goto begin_table_error; 1258e5f9c644Sdrh } 1259e5f9c644Sdrh } 1260e5f9c644Sdrh #endif 1261e5f9c644Sdrh 1262f57b3399Sdrh /* Make sure the new table name does not collide with an existing 12633df6b257Sdanielk1977 ** index or table name in the same database. Issue an error message if 12647e6ebfb2Sdanielk1977 ** it does. The exception is if the statement being parsed was passed 12657e6ebfb2Sdanielk1977 ** to an sqlite3_declare_vtab() call. In that case only the column names 12667e6ebfb2Sdanielk1977 ** and types will be used, so there is no need to test for namespace 12677e6ebfb2Sdanielk1977 ** collisions. 1268f57b3399Sdrh */ 1269cf8f2895Sdan if( !IN_SPECIAL_PARSE ){ 127069c33826Sdrh char *zDb = db->aDb[iDb].zDbSName; 12715558a8a6Sdanielk1977 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){ 12725558a8a6Sdanielk1977 goto begin_table_error; 12735558a8a6Sdanielk1977 } 1274a16d1060Sdan pTable = sqlite3FindTable(db, zName, zDb); 12753df6b257Sdanielk1977 if( pTable ){ 1276faa59554Sdrh if( !noErr ){ 12774adee20fSdanielk1977 sqlite3ErrorMsg(pParse, "table %T already exists", pName); 12787687c83dSdan }else{ 127933c59ecaSdrh assert( !db->init.busy || CORRUPT_DB ); 12807687c83dSdan sqlite3CodeVerifySchema(pParse, iDb); 128131da7be9Sdrh sqlite3ForceNotReadOnly(pParse); 1282faa59554Sdrh } 128323bf66d6Sdrh goto begin_table_error; 128475897234Sdrh } 12858a8a0d1dSdrh if( sqlite3FindIndex(db, zName, zDb)!=0 ){ 12864adee20fSdanielk1977 sqlite3ErrorMsg(pParse, "there is already an index named %s", zName); 128723bf66d6Sdrh goto begin_table_error; 128875897234Sdrh } 12897e6ebfb2Sdanielk1977 } 12907e6ebfb2Sdanielk1977 129126783a58Sdanielk1977 pTable = sqlite3DbMallocZero(db, sizeof(Table)); 12926d4abfbeSdrh if( pTable==0 ){ 12934df86af3Sdrh assert( db->mallocFailed ); 1294fad3039cSmistachkin pParse->rc = SQLITE_NOMEM_BKPT; 1295e0048400Sdanielk1977 pParse->nErr++; 129623bf66d6Sdrh goto begin_table_error; 12976d4abfbeSdrh } 129875897234Sdrh pTable->zName = zName; 12994a32431cSdrh pTable->iPKey = -1; 1300da184236Sdanielk1977 pTable->pSchema = db->aDb[iDb].pSchema; 130179df7782Sdrh pTable->nTabRef = 1; 1302d1417ee1Sdrh #ifdef SQLITE_DEFAULT_ROWEST 1303d1417ee1Sdrh pTable->nRowLogEst = sqlite3LogEst(SQLITE_DEFAULT_ROWEST); 1304d1417ee1Sdrh #else 1305cfc9df76Sdan pTable->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) ); 1306d1417ee1Sdrh #endif 1307c4a64facSdrh assert( pParse->pNewTable==0 ); 130875897234Sdrh pParse->pNewTable = pTable; 130917f71934Sdrh 131017f71934Sdrh /* Begin generating the code that will insert the table record into 1311346a70caSdrh ** the schema table. Note in particular that we must go ahead 131217f71934Sdrh ** and allocate the record number for the table entry now. Before any 131317f71934Sdrh ** PRIMARY KEY or UNIQUE keywords are parsed. Those keywords will cause 131417f71934Sdrh ** indices to be created and the table record must come before the 131517f71934Sdrh ** indices. Hence, the record number for the table must be allocated 131617f71934Sdrh ** now. 131717f71934Sdrh */ 13184adee20fSdanielk1977 if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){ 1319728e0f91Sdrh int addr1; 1320e321c29aSdrh int fileFormat; 1321b7654111Sdrh int reg1, reg2, reg3; 13223c03afd3Sdrh /* nullRow[] is an OP_Record encoding of a row containing 5 NULLs */ 13233c03afd3Sdrh static const char nullRow[] = { 6, 0, 0, 0, 0, 0 }; 13240dd5cdaeSdrh sqlite3BeginWriteOperation(pParse, 1, iDb); 1325b17131a0Sdrh 132620b1eaffSdanielk1977 #ifndef SQLITE_OMIT_VIRTUALTABLE 132720b1eaffSdanielk1977 if( isVirtual ){ 132866a5167bSdrh sqlite3VdbeAddOp0(v, OP_VBegin); 132920b1eaffSdanielk1977 } 133020b1eaffSdanielk1977 #endif 133120b1eaffSdanielk1977 133236963fdcSdanielk1977 /* If the file format and encoding in the database have not been set, 133336963fdcSdanielk1977 ** set them now. 1334cbb18d22Sdanielk1977 */ 1335b7654111Sdrh reg1 = pParse->regRowid = ++pParse->nMem; 1336b7654111Sdrh reg2 = pParse->regRoot = ++pParse->nMem; 1337b7654111Sdrh reg3 = ++pParse->nMem; 13380d19f7acSdanielk1977 sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT); 1339fb98264aSdrh sqlite3VdbeUsesBtree(v, iDb); 1340728e0f91Sdrh addr1 = sqlite3VdbeAddOp1(v, OP_If, reg3); VdbeCoverage(v); 1341e321c29aSdrh fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ? 134276fe8032Sdrh 1 : SQLITE_MAX_FILE_FORMAT; 13431861afcdSdrh sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, fileFormat); 13441861afcdSdrh sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, ENC(db)); 1345728e0f91Sdrh sqlite3VdbeJumpHere(v, addr1); 1346d008cfe3Sdanielk1977 13471e32bed3Sdrh /* This just creates a place-holder record in the sqlite_schema table. 13484794f735Sdrh ** The record created does not contain anything yet. It will be replaced 13494794f735Sdrh ** by the real entry in code generated at sqlite3EndTable(). 1350b17131a0Sdrh ** 13510fa991b9Sdrh ** The rowid for the new entry is left in register pParse->regRowid. 13520fa991b9Sdrh ** The root page number of the new table is left in reg pParse->regRoot. 13530fa991b9Sdrh ** The rowid and root page number values are needed by the code that 13540fa991b9Sdrh ** sqlite3EndTable will generate. 13554794f735Sdrh */ 1356f1a381e7Sdanielk1977 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) 1357f1a381e7Sdanielk1977 if( isView || isVirtual ){ 1358b7654111Sdrh sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2); 1359a21c6b6fSdanielk1977 }else 1360a21c6b6fSdanielk1977 #endif 1361a21c6b6fSdanielk1977 { 1362381bdaccSdrh assert( !pParse->bReturning ); 1363381bdaccSdrh pParse->u1.addrCrTab = 13640f3f7664Sdrh sqlite3VdbeAddOp3(v, OP_CreateBtree, iDb, reg2, BTREE_INTKEY); 1365a21c6b6fSdanielk1977 } 1366346a70caSdrh sqlite3OpenSchemaTable(pParse, iDb); 1367b7654111Sdrh sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1); 13683c03afd3Sdrh sqlite3VdbeAddOp4(v, OP_Blob, 6, reg3, 0, nullRow, P4_STATIC); 1369b7654111Sdrh sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1); 1370b7654111Sdrh sqlite3VdbeChangeP5(v, OPFLAG_APPEND); 137166a5167bSdrh sqlite3VdbeAddOp0(v, OP_Close); 13725e00f6c7Sdrh } 137323bf66d6Sdrh 137423bf66d6Sdrh /* Normal (non-error) return. */ 137523bf66d6Sdrh return; 137623bf66d6Sdrh 137723bf66d6Sdrh /* If an error occurs, we jump here */ 137823bf66d6Sdrh begin_table_error: 1379c0495e8cSdrh pParse->checkSchema = 1; 1380633e6d57Sdrh sqlite3DbFree(db, zName); 138123bf66d6Sdrh return; 138275897234Sdrh } 138375897234Sdrh 138403d69a68Sdrh /* Set properties of a table column based on the (magical) 138503d69a68Sdrh ** name of the column. 138603d69a68Sdrh */ 138703d69a68Sdrh #if SQLITE_ENABLE_HIDDEN_COLUMNS 1388e6110505Sdrh void sqlite3ColumnPropertiesFromName(Table *pTab, Column *pCol){ 1389cf9d36d1Sdrh if( sqlite3_strnicmp(pCol->zCnName, "__hidden__", 10)==0 ){ 139003d69a68Sdrh pCol->colFlags |= COLFLAG_HIDDEN; 13916f6e60ddSdrh if( pTab ) pTab->tabFlags |= TF_HasHidden; 1392ba68f8f3Sdan }else if( pTab && pCol!=pTab->aCol && (pCol[-1].colFlags & COLFLAG_HIDDEN) ){ 1393ba68f8f3Sdan pTab->tabFlags |= TF_OOOHidden; 139403d69a68Sdrh } 139503d69a68Sdrh } 1396e6110505Sdrh #endif 139703d69a68Sdrh 13982053f313Sdrh /* 139928828c55Sdrh ** Name of the special TEMP trigger used to implement RETURNING. The 140028828c55Sdrh ** name begins with "sqlite_" so that it is guaranteed not to collide 140128828c55Sdrh ** with any application-generated triggers. 1402b8352479Sdrh */ 140328828c55Sdrh #define RETURNING_TRIGGER_NAME "sqlite_returning" 1404b8352479Sdrh 1405b8352479Sdrh /* 140628828c55Sdrh ** Clean up the data structures associated with the RETURNING clause. 1407b8352479Sdrh */ 1408b8352479Sdrh static void sqlite3DeleteReturning(sqlite3 *db, Returning *pRet){ 1409b8352479Sdrh Hash *pHash; 1410b8352479Sdrh pHash = &(db->aDb[1].pSchema->trigHash); 141128828c55Sdrh sqlite3HashInsert(pHash, RETURNING_TRIGGER_NAME, 0); 1412b8352479Sdrh sqlite3ExprListDelete(db, pRet->pReturnEL); 1413b8352479Sdrh sqlite3DbFree(db, pRet); 1414b8352479Sdrh } 1415b8352479Sdrh 1416b8352479Sdrh /* 141728828c55Sdrh ** Add the RETURNING clause to the parse currently underway. 141828828c55Sdrh ** 141928828c55Sdrh ** This routine creates a special TEMP trigger that will fire for each row 142028828c55Sdrh ** of the DML statement. That TEMP trigger contains a single SELECT 142128828c55Sdrh ** statement with a result set that is the argument of the RETURNING clause. 142228828c55Sdrh ** The trigger has the Trigger.bReturning flag and an opcode of 142328828c55Sdrh ** TK_RETURNING instead of TK_SELECT, so that the trigger code generator 142428828c55Sdrh ** knows to handle it specially. The TEMP trigger is automatically 142528828c55Sdrh ** removed at the end of the parse. 142628828c55Sdrh ** 142728828c55Sdrh ** When this routine is called, we do not yet know if the RETURNING clause 142828828c55Sdrh ** is attached to a DELETE, INSERT, or UPDATE, so construct it as a 142928828c55Sdrh ** RETURNING trigger instead. It will then be converted into the appropriate 143028828c55Sdrh ** type on the first call to sqlite3TriggersExist(). 14312053f313Sdrh */ 14322053f313Sdrh void sqlite3AddReturning(Parse *pParse, ExprList *pList){ 1433b8352479Sdrh Returning *pRet; 1434b8352479Sdrh Hash *pHash; 1435b8352479Sdrh sqlite3 *db = pParse->db; 1436e1c9a4ebSdrh if( pParse->pNewTrigger ){ 1437e1c9a4ebSdrh sqlite3ErrorMsg(pParse, "cannot use RETURNING in a trigger"); 1438e1c9a4ebSdrh }else{ 1439e1c9a4ebSdrh assert( pParse->bReturning==0 ); 1440e1c9a4ebSdrh } 1441d086aa0aSdrh pParse->bReturning = 1; 1442b8352479Sdrh pRet = sqlite3DbMallocZero(db, sizeof(*pRet)); 1443b8352479Sdrh if( pRet==0 ){ 1444b8352479Sdrh sqlite3ExprListDelete(db, pList); 1445b8352479Sdrh return; 1446b8352479Sdrh } 1447381bdaccSdrh pParse->u1.pReturning = pRet; 1448b8352479Sdrh pRet->pParse = pParse; 1449b8352479Sdrh pRet->pReturnEL = pList; 14502053f313Sdrh sqlite3ParserAddCleanup(pParse, 1451b8352479Sdrh (void(*)(sqlite3*,void*))sqlite3DeleteReturning, pRet); 14526d0053cfSdrh testcase( pParse->earlyCleanup ); 1453cf4108bbSdrh if( db->mallocFailed ) return; 145428828c55Sdrh pRet->retTrig.zName = RETURNING_TRIGGER_NAME; 1455b8352479Sdrh pRet->retTrig.op = TK_RETURNING; 1456b8352479Sdrh pRet->retTrig.tr_tm = TRIGGER_AFTER; 1457b8352479Sdrh pRet->retTrig.bReturning = 1; 1458b8352479Sdrh pRet->retTrig.pSchema = db->aDb[1].pSchema; 1459a4767683Sdrh pRet->retTrig.pTabSchema = db->aDb[1].pSchema; 1460b8352479Sdrh pRet->retTrig.step_list = &pRet->retTStep; 1461dac9a5f7Sdrh pRet->retTStep.op = TK_RETURNING; 1462b8352479Sdrh pRet->retTStep.pTrig = &pRet->retTrig; 1463381bdaccSdrh pRet->retTStep.pExprList = pList; 1464b8352479Sdrh pHash = &(db->aDb[1].pSchema->trigHash); 1465e1c9a4ebSdrh assert( sqlite3HashFind(pHash, RETURNING_TRIGGER_NAME)==0 || pParse->nErr ); 146628828c55Sdrh if( sqlite3HashInsert(pHash, RETURNING_TRIGGER_NAME, &pRet->retTrig) 14670166df0bSdrh ==&pRet->retTrig ){ 14680166df0bSdrh sqlite3OomFault(db); 14690166df0bSdrh } 14702053f313Sdrh } 147103d69a68Sdrh 147275897234Sdrh /* 147375897234Sdrh ** Add a new column to the table currently being constructed. 1474d9b0257aSdrh ** 1475d9b0257aSdrh ** The parser calls this routine once for each column declaration 14764adee20fSdanielk1977 ** in a CREATE TABLE statement. sqlite3StartTable() gets called 1477d9b0257aSdrh ** first to get things going. Then this routine is called for each 1478d9b0257aSdrh ** column. 147975897234Sdrh */ 148077441fafSdrh void sqlite3AddColumn(Parse *pParse, Token sName, Token sType){ 148175897234Sdrh Table *p; 148297fc3d06Sdrh int i; 1483a99db3b6Sdrh char *z; 148494eaafa9Sdrh char *zType; 1485c9b84a1fSdrh Column *pCol; 1486bb4957f8Sdrh sqlite3 *db = pParse->db; 14873e992d1aSdrh u8 hName; 14887b3c514bSdrh Column *aNew; 1489c2df4d6aSdrh u8 eType = COLTYPE_CUSTOM; 1490c2df4d6aSdrh u8 szEst = 1; 1491c2df4d6aSdrh char affinity = SQLITE_AFF_BLOB; 14923e992d1aSdrh 149375897234Sdrh if( (p = pParse->pNewTable)==0 ) return; 1494bb4957f8Sdrh if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){ 1495e5c941b8Sdrh sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName); 1496e5c941b8Sdrh return; 1497e5c941b8Sdrh } 149877441fafSdrh if( !IN_RENAME_OBJECT ) sqlite3DequoteToken(&sName); 1499e48f261eSdrh 1500e48f261eSdrh /* Because keywords GENERATE ALWAYS can be converted into indentifiers 1501e48f261eSdrh ** by the parser, we can sometimes end up with a typename that ends 1502e48f261eSdrh ** with "generated always". Check for this case and omit the surplus 1503e48f261eSdrh ** text. */ 1504e48f261eSdrh if( sType.n>=16 1505e48f261eSdrh && sqlite3_strnicmp(sType.z+(sType.n-6),"always",6)==0 1506e48f261eSdrh ){ 1507e48f261eSdrh sType.n -= 6; 1508e48f261eSdrh while( ALWAYS(sType.n>0) && sqlite3Isspace(sType.z[sType.n-1]) ) sType.n--; 1509e48f261eSdrh if( sType.n>=9 1510e48f261eSdrh && sqlite3_strnicmp(sType.z+(sType.n-9),"generated",9)==0 1511e48f261eSdrh ){ 1512e48f261eSdrh sType.n -= 9; 1513e48f261eSdrh while( sType.n>0 && sqlite3Isspace(sType.z[sType.n-1]) ) sType.n--; 1514e48f261eSdrh } 1515e48f261eSdrh } 1516e48f261eSdrh 1517c2df4d6aSdrh /* Check for standard typenames. For standard typenames we will 1518c2df4d6aSdrh ** set the Column.eType field rather than storing the typename after 1519c2df4d6aSdrh ** the column name, in order to save space. */ 1520c2df4d6aSdrh if( sType.n>=3 ){ 1521c2df4d6aSdrh sqlite3DequoteToken(&sType); 1522c2df4d6aSdrh for(i=0; i<SQLITE_N_STDTYPE; i++){ 1523c2df4d6aSdrh if( sType.n==sqlite3StdTypeLen[i] 1524c2df4d6aSdrh && sqlite3_strnicmp(sType.z, sqlite3StdType[i], sType.n)==0 1525c2df4d6aSdrh ){ 1526c2df4d6aSdrh sType.n = 0; 1527c2df4d6aSdrh eType = i+1; 1528c2df4d6aSdrh affinity = sqlite3StdTypeAffinity[i]; 1529c2df4d6aSdrh if( affinity<=SQLITE_AFF_TEXT ) szEst = 5; 1530c2df4d6aSdrh break; 1531c2df4d6aSdrh } 1532c2df4d6aSdrh } 1533c2df4d6aSdrh } 1534c2df4d6aSdrh 1535c2df4d6aSdrh z = sqlite3DbMallocRaw(db, sName.n + 1 + sType.n + (sType.n>0) ); 153697fc3d06Sdrh if( z==0 ) return; 153777441fafSdrh if( IN_RENAME_OBJECT ) sqlite3RenameTokenMap(pParse, (void*)z, &sName); 153877441fafSdrh memcpy(z, sName.z, sName.n); 153977441fafSdrh z[sName.n] = 0; 154094eaafa9Sdrh sqlite3Dequote(z); 15413e992d1aSdrh hName = sqlite3StrIHash(z); 154297fc3d06Sdrh for(i=0; i<p->nCol; i++){ 1543cf9d36d1Sdrh if( p->aCol[i].hName==hName && sqlite3StrICmp(z, p->aCol[i].zCnName)==0 ){ 15444adee20fSdanielk1977 sqlite3ErrorMsg(pParse, "duplicate column name: %s", z); 1545633e6d57Sdrh sqlite3DbFree(db, z); 154697fc3d06Sdrh return; 154797fc3d06Sdrh } 154897fc3d06Sdrh } 15497b3c514bSdrh aNew = sqlite3DbRealloc(db,p->aCol,(p->nCol+1)*sizeof(p->aCol[0])); 1550d5d56523Sdanielk1977 if( aNew==0 ){ 1551633e6d57Sdrh sqlite3DbFree(db, z); 1552d5d56523Sdanielk1977 return; 1553d5d56523Sdanielk1977 } 15546d4abfbeSdrh p->aCol = aNew; 1555c9b84a1fSdrh pCol = &p->aCol[p->nCol]; 1556c9b84a1fSdrh memset(pCol, 0, sizeof(p->aCol[0])); 1557cf9d36d1Sdrh pCol->zCnName = z; 15583e992d1aSdrh pCol->hName = hName; 1559ba68f8f3Sdan sqlite3ColumnPropertiesFromName(p, pCol); 1560a37cdde0Sdanielk1977 156177441fafSdrh if( sType.n==0 ){ 1562a37cdde0Sdanielk1977 /* If there is no type specified, columns have the default affinity 1563bbade8d1Sdrh ** 'BLOB' with a default size of 4 bytes. */ 1564c2df4d6aSdrh pCol->affinity = affinity; 1565b70f2eabSdrh pCol->eCType = eType; 1566c2df4d6aSdrh pCol->szEst = szEst; 1567bbade8d1Sdrh #ifdef SQLITE_ENABLE_SORTER_REFERENCES 1568c2df4d6aSdrh if( affinity==SQLITE_AFF_BLOB ){ 15692e3a5a81Sdan if( 4>=sqlite3GlobalConfig.szSorterRef ){ 15702e3a5a81Sdan pCol->colFlags |= COLFLAG_SORTERREF; 15712e3a5a81Sdan } 1572c2df4d6aSdrh } 1573bbade8d1Sdrh #endif 15742881ab62Sdrh }else{ 1575ddb2b4a3Sdrh zType = z + sqlite3Strlen30(z) + 1; 157677441fafSdrh memcpy(zType, sType.z, sType.n); 157777441fafSdrh zType[sType.n] = 0; 1578a6dddd9bSdrh sqlite3Dequote(zType); 15792e3a5a81Sdan pCol->affinity = sqlite3AffinityType(zType, pCol); 1580d7564865Sdrh pCol->colFlags |= COLFLAG_HASTYPE; 15812881ab62Sdrh } 1582c9b84a1fSdrh p->nCol++; 1583f95909c7Sdrh p->nNVCol++; 1584986dde70Sdrh pParse->constraintName.n = 0; 158575897234Sdrh } 158675897234Sdrh 158775897234Sdrh /* 1588382c0247Sdrh ** This routine is called by the parser while in the middle of 1589382c0247Sdrh ** parsing a CREATE TABLE statement. A "NOT NULL" constraint has 1590382c0247Sdrh ** been seen on a column. This routine sets the notNull flag on 1591382c0247Sdrh ** the column currently under construction. 1592382c0247Sdrh */ 15934adee20fSdanielk1977 void sqlite3AddNotNull(Parse *pParse, int onError){ 1594382c0247Sdrh Table *p; 159526e731ccSdan Column *pCol; 1596c4a64facSdrh p = pParse->pNewTable; 1597c4a64facSdrh if( p==0 || NEVER(p->nCol<1) ) return; 159826e731ccSdan pCol = &p->aCol[p->nCol-1]; 159926e731ccSdan pCol->notNull = (u8)onError; 16008b174f29Sdrh p->tabFlags |= TF_HasNotNull; 160126e731ccSdan 160226e731ccSdan /* Set the uniqNotNull flag on any UNIQUE or PK indexes already created 160326e731ccSdan ** on this column. */ 160426e731ccSdan if( pCol->colFlags & COLFLAG_UNIQUE ){ 160526e731ccSdan Index *pIdx; 160626e731ccSdan for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){ 160726e731ccSdan assert( pIdx->nKeyCol==1 && pIdx->onError!=OE_None ); 160826e731ccSdan if( pIdx->aiColumn[0]==p->nCol-1 ){ 160926e731ccSdan pIdx->uniqNotNull = 1; 161026e731ccSdan } 161126e731ccSdan } 161226e731ccSdan } 1613382c0247Sdrh } 1614382c0247Sdrh 1615382c0247Sdrh /* 161652a83fbbSdanielk1977 ** Scan the column type name zType (length nType) and return the 161752a83fbbSdanielk1977 ** associated affinity type. 1618b3dff964Sdanielk1977 ** 1619b3dff964Sdanielk1977 ** This routine does a case-independent search of zType for the 1620b3dff964Sdanielk1977 ** substrings in the following table. If one of the substrings is 1621b3dff964Sdanielk1977 ** found, the corresponding affinity is returned. If zType contains 1622b3dff964Sdanielk1977 ** more than one of the substrings, entries toward the top of 1623b3dff964Sdanielk1977 ** the table take priority. For example, if zType is 'BLOBINT', 16248a51256cSdrh ** SQLITE_AFF_INTEGER is returned. 1625b3dff964Sdanielk1977 ** 1626b3dff964Sdanielk1977 ** Substring | Affinity 1627b3dff964Sdanielk1977 ** -------------------------------- 1628b3dff964Sdanielk1977 ** 'INT' | SQLITE_AFF_INTEGER 1629b3dff964Sdanielk1977 ** 'CHAR' | SQLITE_AFF_TEXT 1630b3dff964Sdanielk1977 ** 'CLOB' | SQLITE_AFF_TEXT 1631b3dff964Sdanielk1977 ** 'TEXT' | SQLITE_AFF_TEXT 163205883a34Sdrh ** 'BLOB' | SQLITE_AFF_BLOB 16338a51256cSdrh ** 'REAL' | SQLITE_AFF_REAL 16348a51256cSdrh ** 'FLOA' | SQLITE_AFF_REAL 16358a51256cSdrh ** 'DOUB' | SQLITE_AFF_REAL 1636b3dff964Sdanielk1977 ** 1637b3dff964Sdanielk1977 ** If none of the substrings in the above table are found, 1638b3dff964Sdanielk1977 ** SQLITE_AFF_NUMERIC is returned. 163952a83fbbSdanielk1977 */ 16402e3a5a81Sdan char sqlite3AffinityType(const char *zIn, Column *pCol){ 1641b3dff964Sdanielk1977 u32 h = 0; 1642b3dff964Sdanielk1977 char aff = SQLITE_AFF_NUMERIC; 1643d3037a41Sdrh const char *zChar = 0; 164452a83fbbSdanielk1977 16452f1e02e8Sdrh assert( zIn!=0 ); 1646fdaac671Sdrh while( zIn[0] ){ 1647b7916a78Sdrh h = (h<<8) + sqlite3UpperToLower[(*zIn)&0xff]; 1648b3dff964Sdanielk1977 zIn++; 1649201f7168Sdanielk1977 if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){ /* CHAR */ 1650201f7168Sdanielk1977 aff = SQLITE_AFF_TEXT; 1651fdaac671Sdrh zChar = zIn; 1652201f7168Sdanielk1977 }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){ /* CLOB */ 1653201f7168Sdanielk1977 aff = SQLITE_AFF_TEXT; 1654201f7168Sdanielk1977 }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){ /* TEXT */ 1655201f7168Sdanielk1977 aff = SQLITE_AFF_TEXT; 1656201f7168Sdanielk1977 }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b') /* BLOB */ 16578a51256cSdrh && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){ 165805883a34Sdrh aff = SQLITE_AFF_BLOB; 1659d3037a41Sdrh if( zIn[0]=='(' ) zChar = zIn; 16608a51256cSdrh #ifndef SQLITE_OMIT_FLOATING_POINT 16618a51256cSdrh }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l') /* REAL */ 16628a51256cSdrh && aff==SQLITE_AFF_NUMERIC ){ 16638a51256cSdrh aff = SQLITE_AFF_REAL; 16648a51256cSdrh }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a') /* FLOA */ 16658a51256cSdrh && aff==SQLITE_AFF_NUMERIC ){ 16668a51256cSdrh aff = SQLITE_AFF_REAL; 16678a51256cSdrh }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b') /* DOUB */ 16688a51256cSdrh && aff==SQLITE_AFF_NUMERIC ){ 16698a51256cSdrh aff = SQLITE_AFF_REAL; 16708a51256cSdrh #endif 1671201f7168Sdanielk1977 }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){ /* INT */ 16728a51256cSdrh aff = SQLITE_AFF_INTEGER; 1673b3dff964Sdanielk1977 break; 167452a83fbbSdanielk1977 } 167552a83fbbSdanielk1977 } 1676d3037a41Sdrh 16772e3a5a81Sdan /* If pCol is not NULL, store an estimate of the field size. The 1678d3037a41Sdrh ** estimate is scaled so that the size of an integer is 1. */ 16792e3a5a81Sdan if( pCol ){ 16802e3a5a81Sdan int v = 0; /* default size is approx 4 bytes */ 16817ea31ccbSdrh if( aff<SQLITE_AFF_NUMERIC ){ 1682d3037a41Sdrh if( zChar ){ 1683fdaac671Sdrh while( zChar[0] ){ 1684d3037a41Sdrh if( sqlite3Isdigit(zChar[0]) ){ 16852e3a5a81Sdan /* BLOB(k), VARCHAR(k), CHAR(k) -> r=(k/4+1) */ 1686d3037a41Sdrh sqlite3GetInt32(zChar, &v); 1687fdaac671Sdrh break; 1688fdaac671Sdrh } 1689fdaac671Sdrh zChar++; 1690fdaac671Sdrh } 1691fdaac671Sdrh }else{ 16922e3a5a81Sdan v = 16; /* BLOB, TEXT, CLOB -> r=5 (approx 20 bytes)*/ 1693d3037a41Sdrh } 1694fdaac671Sdrh } 1695bbade8d1Sdrh #ifdef SQLITE_ENABLE_SORTER_REFERENCES 16962e3a5a81Sdan if( v>=sqlite3GlobalConfig.szSorterRef ){ 16972e3a5a81Sdan pCol->colFlags |= COLFLAG_SORTERREF; 16982e3a5a81Sdan } 1699bbade8d1Sdrh #endif 17002e3a5a81Sdan v = v/4 + 1; 17012e3a5a81Sdan if( v>255 ) v = 255; 17022e3a5a81Sdan pCol->szEst = v; 1703fdaac671Sdrh } 1704b3dff964Sdanielk1977 return aff; 170552a83fbbSdanielk1977 } 170652a83fbbSdanielk1977 170752a83fbbSdanielk1977 /* 17087977a17fSdanielk1977 ** The expression is the default value for the most recently added column 17097977a17fSdanielk1977 ** of the table currently under construction. 17107977a17fSdanielk1977 ** 17117977a17fSdanielk1977 ** Default value expressions must be constant. Raise an exception if this 17127977a17fSdanielk1977 ** is not the case. 1713d9b0257aSdrh ** 1714d9b0257aSdrh ** This routine is called by the parser while in the middle of 1715d9b0257aSdrh ** parsing a CREATE TABLE statement. 17167020f651Sdrh */ 17171be266baSdrh void sqlite3AddDefaultValue( 17181be266baSdrh Parse *pParse, /* Parsing context */ 17191be266baSdrh Expr *pExpr, /* The parsed expression of the default value */ 17201be266baSdrh const char *zStart, /* Start of the default value text */ 17211be266baSdrh const char *zEnd /* First character past end of defaut value text */ 17221be266baSdrh ){ 17237020f651Sdrh Table *p; 17247977a17fSdanielk1977 Column *pCol; 1725633e6d57Sdrh sqlite3 *db = pParse->db; 1726c4a64facSdrh p = pParse->pNewTable; 1727c4a64facSdrh if( p!=0 ){ 1728014fff20Sdrh int isInit = db->init.busy && db->init.iDb!=1; 17297977a17fSdanielk1977 pCol = &(p->aCol[p->nCol-1]); 1730014fff20Sdrh if( !sqlite3ExprIsConstantOrFunction(pExpr, isInit) ){ 17317977a17fSdanielk1977 sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant", 1732cf9d36d1Sdrh pCol->zCnName); 17337e7fd73bSdrh #ifndef SQLITE_OMIT_GENERATED_COLUMNS 17347e7fd73bSdrh }else if( pCol->colFlags & COLFLAG_GENERATED ){ 1735ab0992f0Sdrh testcase( pCol->colFlags & COLFLAG_VIRTUAL ); 1736ab0992f0Sdrh testcase( pCol->colFlags & COLFLAG_STORED ); 17377e7fd73bSdrh sqlite3ErrorMsg(pParse, "cannot use DEFAULT on a generated column"); 17387e7fd73bSdrh #endif 17397977a17fSdanielk1977 }else{ 17406ab3a2ecSdanielk1977 /* A copy of pExpr is used instead of the original, as pExpr contains 17411be266baSdrh ** tokens that point to volatile memory. 17426ab3a2ecSdanielk1977 */ 174379cf2b71Sdrh Expr x, *pDfltExpr; 174494fa9c41Sdrh memset(&x, 0, sizeof(x)); 174594fa9c41Sdrh x.op = TK_SPAN; 17469b2e0435Sdrh x.u.zToken = sqlite3DbSpanDup(db, zStart, zEnd); 17471be266baSdrh x.pLeft = pExpr; 174894fa9c41Sdrh x.flags = EP_Skip; 174979cf2b71Sdrh pDfltExpr = sqlite3ExprDup(db, &x, EXPRDUP_REDUCE); 175094fa9c41Sdrh sqlite3DbFree(db, x.u.zToken); 175179cf2b71Sdrh sqlite3ColumnSetExpr(pParse, p, pCol, pDfltExpr); 17527977a17fSdanielk1977 } 175342b9d7c5Sdrh } 17548900a48bSdan if( IN_RENAME_OBJECT ){ 17558900a48bSdan sqlite3RenameExprUnmap(pParse, pExpr); 17568900a48bSdan } 17571be266baSdrh sqlite3ExprDelete(db, pExpr); 17587020f651Sdrh } 17597020f651Sdrh 17607020f651Sdrh /* 1761153110a7Sdrh ** Backwards Compatibility Hack: 1762153110a7Sdrh ** 1763153110a7Sdrh ** Historical versions of SQLite accepted strings as column names in 1764153110a7Sdrh ** indexes and PRIMARY KEY constraints and in UNIQUE constraints. Example: 1765153110a7Sdrh ** 1766153110a7Sdrh ** CREATE TABLE xyz(a,b,c,d,e,PRIMARY KEY('a'),UNIQUE('b','c' COLLATE trim) 1767153110a7Sdrh ** CREATE INDEX abc ON xyz('c','d' DESC,'e' COLLATE nocase DESC); 1768153110a7Sdrh ** 1769153110a7Sdrh ** This is goofy. But to preserve backwards compatibility we continue to 1770153110a7Sdrh ** accept it. This routine does the necessary conversion. It converts 1771153110a7Sdrh ** the expression given in its argument from a TK_STRING into a TK_ID 1772153110a7Sdrh ** if the expression is just a TK_STRING with an optional COLLATE clause. 17736c591364Sdrh ** If the expression is anything other than TK_STRING, the expression is 1774153110a7Sdrh ** unchanged. 1775153110a7Sdrh */ 1776153110a7Sdrh static void sqlite3StringToId(Expr *p){ 1777153110a7Sdrh if( p->op==TK_STRING ){ 1778153110a7Sdrh p->op = TK_ID; 1779153110a7Sdrh }else if( p->op==TK_COLLATE && p->pLeft->op==TK_STRING ){ 1780153110a7Sdrh p->pLeft->op = TK_ID; 1781153110a7Sdrh } 1782153110a7Sdrh } 1783153110a7Sdrh 1784153110a7Sdrh /* 1785f4b1d8dcSdrh ** Tag the given column as being part of the PRIMARY KEY 1786f4b1d8dcSdrh */ 1787f4b1d8dcSdrh static void makeColumnPartOfPrimaryKey(Parse *pParse, Column *pCol){ 1788f4b1d8dcSdrh pCol->colFlags |= COLFLAG_PRIMKEY; 1789f4b1d8dcSdrh #ifndef SQLITE_OMIT_GENERATED_COLUMNS 1790f4b1d8dcSdrh if( pCol->colFlags & COLFLAG_GENERATED ){ 1791f4b1d8dcSdrh testcase( pCol->colFlags & COLFLAG_VIRTUAL ); 1792f4b1d8dcSdrh testcase( pCol->colFlags & COLFLAG_STORED ); 1793f4b1d8dcSdrh sqlite3ErrorMsg(pParse, 1794f4b1d8dcSdrh "generated columns cannot be part of the PRIMARY KEY"); 1795f4b1d8dcSdrh } 1796f4b1d8dcSdrh #endif 1797f4b1d8dcSdrh } 1798f4b1d8dcSdrh 1799f4b1d8dcSdrh /* 18004a32431cSdrh ** Designate the PRIMARY KEY for the table. pList is a list of names 18014a32431cSdrh ** of columns that form the primary key. If pList is NULL, then the 18024a32431cSdrh ** most recently added column of the table is the primary key. 18034a32431cSdrh ** 18044a32431cSdrh ** A table can have at most one primary key. If the table already has 18054a32431cSdrh ** a primary key (and this is the second primary key) then create an 18064a32431cSdrh ** error. 18074a32431cSdrh ** 18084a32431cSdrh ** If the PRIMARY KEY is on a single column whose datatype is INTEGER, 180923bf66d6Sdrh ** then we will try to use that column as the rowid. Set the Table.iPKey 18104a32431cSdrh ** field of the table under construction to be the index of the 18114a32431cSdrh ** INTEGER PRIMARY KEY column. Table.iPKey is set to -1 if there is 18124a32431cSdrh ** no INTEGER PRIMARY KEY. 18134a32431cSdrh ** 18144a32431cSdrh ** If the key is not an INTEGER PRIMARY KEY, then create a unique 18154a32431cSdrh ** index for the key. No index is created for INTEGER PRIMARY KEYs. 18164a32431cSdrh */ 1817205f48e6Sdrh void sqlite3AddPrimaryKey( 1818205f48e6Sdrh Parse *pParse, /* Parsing context */ 1819205f48e6Sdrh ExprList *pList, /* List of field names to be indexed */ 1820205f48e6Sdrh int onError, /* What to do with a uniqueness conflict */ 1821fdd6e85aSdrh int autoInc, /* True if the AUTOINCREMENT keyword is present */ 1822fdd6e85aSdrh int sortOrder /* SQLITE_SO_ASC or SQLITE_SO_DESC */ 1823205f48e6Sdrh ){ 18244a32431cSdrh Table *pTab = pParse->pNewTable; 1825d7564865Sdrh Column *pCol = 0; 182678100cc9Sdrh int iCol = -1, i; 18278ea30bfcSdrh int nTerm; 182862340f84Sdrh if( pTab==0 ) goto primary_key_exit; 18297d10d5a6Sdrh if( pTab->tabFlags & TF_HasPrimaryKey ){ 18304adee20fSdanielk1977 sqlite3ErrorMsg(pParse, 1831f7a9e1acSdrh "table \"%s\" has more than one primary key", pTab->zName); 1832e0194f2bSdrh goto primary_key_exit; 18334a32431cSdrh } 18347d10d5a6Sdrh pTab->tabFlags |= TF_HasPrimaryKey; 18354a32431cSdrh if( pList==0 ){ 18364a32431cSdrh iCol = pTab->nCol - 1; 1837d7564865Sdrh pCol = &pTab->aCol[iCol]; 1838f4b1d8dcSdrh makeColumnPartOfPrimaryKey(pParse, pCol); 18398ea30bfcSdrh nTerm = 1; 184078100cc9Sdrh }else{ 18418ea30bfcSdrh nTerm = pList->nExpr; 18428ea30bfcSdrh for(i=0; i<nTerm; i++){ 1843108aa00aSdrh Expr *pCExpr = sqlite3ExprSkipCollate(pList->a[i].pExpr); 18447d3d9daeSdrh assert( pCExpr!=0 ); 1845153110a7Sdrh sqlite3StringToId(pCExpr); 18467d3d9daeSdrh if( pCExpr->op==TK_ID ){ 1847f9751074Sdrh const char *zCName; 1848f9751074Sdrh assert( !ExprHasProperty(pCExpr, EP_IntValue) ); 1849f9751074Sdrh zCName = pCExpr->u.zToken; 18504a32431cSdrh for(iCol=0; iCol<pTab->nCol; iCol++){ 1851cf9d36d1Sdrh if( sqlite3StrICmp(zCName, pTab->aCol[iCol].zCnName)==0 ){ 1852d7564865Sdrh pCol = &pTab->aCol[iCol]; 1853f4b1d8dcSdrh makeColumnPartOfPrimaryKey(pParse, pCol); 1854d3d39e93Sdrh break; 1855d3d39e93Sdrh } 18564a32431cSdrh } 18576e4fc2caSdrh } 185878100cc9Sdrh } 1859108aa00aSdrh } 18608ea30bfcSdrh if( nTerm==1 1861d7564865Sdrh && pCol 1862b70f2eabSdrh && pCol->eCType==COLTYPE_INTEGER 1863bc622bc0Sdrh && sortOrder!=SQLITE_SO_DESC 18648ea30bfcSdrh ){ 1865c9461eccSdan if( IN_RENAME_OBJECT && pList ){ 18662381f6d7Sdan Expr *pCExpr = sqlite3ExprSkipCollate(pList->a[0].pExpr); 18672381f6d7Sdan sqlite3RenameTokenRemap(pParse, &pTab->iPKey, pCExpr); 1868987db767Sdan } 18694a32431cSdrh pTab->iPKey = iCol; 18701bd10f8aSdrh pTab->keyConf = (u8)onError; 18717d10d5a6Sdrh assert( autoInc==0 || autoInc==1 ); 18727d10d5a6Sdrh pTab->tabFlags |= autoInc*TF_Autoincrement; 18736e11892dSdan if( pList ) pParse->iPkSortOrder = pList->a[0].sortFlags; 187434ab941eSdrh (void)sqlite3HasExplicitNulls(pParse, pList); 1875205f48e6Sdrh }else if( autoInc ){ 18764794f735Sdrh #ifndef SQLITE_OMIT_AUTOINCREMENT 1877205f48e6Sdrh sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an " 1878205f48e6Sdrh "INTEGER PRIMARY KEY"); 18794794f735Sdrh #endif 18804a32431cSdrh }else{ 188162340f84Sdrh sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0, 188262340f84Sdrh 0, sortOrder, 0, SQLITE_IDXTYPE_PRIMARYKEY); 1883e0194f2bSdrh pList = 0; 18844a32431cSdrh } 1885e0194f2bSdrh 1886e0194f2bSdrh primary_key_exit: 1887633e6d57Sdrh sqlite3ExprListDelete(pParse->db, pList); 1888e0194f2bSdrh return; 18894a32431cSdrh } 18904a32431cSdrh 18914a32431cSdrh /* 1892ffe07b2dSdrh ** Add a new CHECK constraint to the table currently under construction. 1893ffe07b2dSdrh */ 1894ffe07b2dSdrh void sqlite3AddCheckConstraint( 1895ffe07b2dSdrh Parse *pParse, /* Parsing context */ 189692e21ef0Sdrh Expr *pCheckExpr, /* The check expression */ 189792e21ef0Sdrh const char *zStart, /* Opening "(" */ 189892e21ef0Sdrh const char *zEnd /* Closing ")" */ 1899ffe07b2dSdrh ){ 1900ffe07b2dSdrh #ifndef SQLITE_OMIT_CHECK 1901ffe07b2dSdrh Table *pTab = pParse->pNewTable; 1902c9bbb011Sdrh sqlite3 *db = pParse->db; 1903c9bbb011Sdrh if( pTab && !IN_DECLARE_VTAB 1904c9bbb011Sdrh && !sqlite3BtreeIsReadonly(db->aDb[db->init.iDb].pBt) 1905c9bbb011Sdrh ){ 19062938f924Sdrh pTab->pCheck = sqlite3ExprListAppend(pParse, pTab->pCheck, pCheckExpr); 19072938f924Sdrh if( pParse->constraintName.n ){ 19082938f924Sdrh sqlite3ExprListSetName(pParse, pTab->pCheck, &pParse->constraintName, 1); 190992e21ef0Sdrh }else{ 191092e21ef0Sdrh Token t; 191192e21ef0Sdrh for(zStart++; sqlite3Isspace(zStart[0]); zStart++){} 191292e21ef0Sdrh while( sqlite3Isspace(zEnd[-1]) ){ zEnd--; } 191392e21ef0Sdrh t.z = zStart; 191492e21ef0Sdrh t.n = (int)(zEnd - t.z); 191592e21ef0Sdrh sqlite3ExprListSetName(pParse, pTab->pCheck, &t, 1); 19162938f924Sdrh } 191733e619fcSdrh }else 1918ffe07b2dSdrh #endif 191933e619fcSdrh { 19202938f924Sdrh sqlite3ExprDelete(pParse->db, pCheckExpr); 1921ffe07b2dSdrh } 192233e619fcSdrh } 1923ffe07b2dSdrh 1924ffe07b2dSdrh /* 1925d3d39e93Sdrh ** Set the collation function of the most recently parsed table column 1926d3d39e93Sdrh ** to the CollSeq given. 19278e2ca029Sdrh */ 192839002505Sdanielk1977 void sqlite3AddCollateType(Parse *pParse, Token *pToken){ 19298e2ca029Sdrh Table *p; 19300202b29eSdanielk1977 int i; 193139002505Sdanielk1977 char *zColl; /* Dequoted name of collation sequence */ 1932633e6d57Sdrh sqlite3 *db; 1933a37cdde0Sdanielk1977 1934936a3059Sdan if( (p = pParse->pNewTable)==0 || IN_RENAME_OBJECT ) return; 19350202b29eSdanielk1977 i = p->nCol-1; 1936633e6d57Sdrh db = pParse->db; 1937633e6d57Sdrh zColl = sqlite3NameFromToken(db, pToken); 193839002505Sdanielk1977 if( !zColl ) return; 193939002505Sdanielk1977 1940c4a64facSdrh if( sqlite3LocateCollSeq(pParse, zColl) ){ 1941b3bf556eSdanielk1977 Index *pIdx; 194265b40093Sdrh sqlite3ColumnSetColl(db, &p->aCol[i], zColl); 19430202b29eSdanielk1977 19440202b29eSdanielk1977 /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>", 19450202b29eSdanielk1977 ** then an index may have been created on this column before the 19460202b29eSdanielk1977 ** collation type was added. Correct this if it is the case. 19470202b29eSdanielk1977 */ 19480202b29eSdanielk1977 for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){ 1949bbbdc83bSdrh assert( pIdx->nKeyCol==1 ); 1950b3bf556eSdanielk1977 if( pIdx->aiColumn[0]==i ){ 195165b40093Sdrh pIdx->azColl[0] = sqlite3ColumnColl(&p->aCol[i]); 19527cedc8d4Sdanielk1977 } 19537cedc8d4Sdanielk1977 } 195465b40093Sdrh } 1955633e6d57Sdrh sqlite3DbFree(db, zColl); 19567cedc8d4Sdanielk1977 } 19577cedc8d4Sdanielk1977 195881f7b372Sdrh /* Change the most recently parsed column to be a GENERATED ALWAYS AS 195981f7b372Sdrh ** column. 196081f7b372Sdrh */ 196181f7b372Sdrh void sqlite3AddGenerated(Parse *pParse, Expr *pExpr, Token *pType){ 196281f7b372Sdrh #ifndef SQLITE_OMIT_GENERATED_COLUMNS 196381f7b372Sdrh u8 eType = COLFLAG_VIRTUAL; 196481f7b372Sdrh Table *pTab = pParse->pNewTable; 196581f7b372Sdrh Column *pCol; 1966f68bf5fbSdrh if( pTab==0 ){ 1967f68bf5fbSdrh /* generated column in an CREATE TABLE IF NOT EXISTS that already exists */ 1968f68bf5fbSdrh goto generated_done; 1969f68bf5fbSdrh } 197081f7b372Sdrh pCol = &(pTab->aCol[pTab->nCol-1]); 1971b9bcf7caSdrh if( IN_DECLARE_VTAB ){ 1972b9bcf7caSdrh sqlite3ErrorMsg(pParse, "virtual tables cannot use computed columns"); 1973b9bcf7caSdrh goto generated_done; 1974b9bcf7caSdrh } 197579cf2b71Sdrh if( pCol->iDflt>0 ) goto generated_error; 197681f7b372Sdrh if( pType ){ 197781f7b372Sdrh if( pType->n==7 && sqlite3StrNICmp("virtual",pType->z,7)==0 ){ 197881f7b372Sdrh /* no-op */ 197981f7b372Sdrh }else if( pType->n==6 && sqlite3StrNICmp("stored",pType->z,6)==0 ){ 198081f7b372Sdrh eType = COLFLAG_STORED; 198181f7b372Sdrh }else{ 198281f7b372Sdrh goto generated_error; 198381f7b372Sdrh } 198481f7b372Sdrh } 1985f95909c7Sdrh if( eType==COLFLAG_VIRTUAL ) pTab->nNVCol--; 198681f7b372Sdrh pCol->colFlags |= eType; 1987c1431144Sdrh assert( TF_HasVirtual==COLFLAG_VIRTUAL ); 1988c1431144Sdrh assert( TF_HasStored==COLFLAG_STORED ); 1989c1431144Sdrh pTab->tabFlags |= eType; 1990a0e16a22Sdrh if( pCol->colFlags & COLFLAG_PRIMKEY ){ 1991a0e16a22Sdrh makeColumnPartOfPrimaryKey(pParse, pCol); /* For the error message */ 1992a0e16a22Sdrh } 199379cf2b71Sdrh sqlite3ColumnSetExpr(pParse, pTab, pCol, pExpr); 1994b9bcf7caSdrh pExpr = 0; 199581f7b372Sdrh goto generated_done; 199681f7b372Sdrh 199781f7b372Sdrh generated_error: 19987e7fd73bSdrh sqlite3ErrorMsg(pParse, "error in generated column \"%s\"", 1999cf9d36d1Sdrh pCol->zCnName); 200081f7b372Sdrh generated_done: 200181f7b372Sdrh sqlite3ExprDelete(pParse->db, pExpr); 200281f7b372Sdrh #else 200381f7b372Sdrh /* Throw and error for the GENERATED ALWAYS AS clause if the 200481f7b372Sdrh ** SQLITE_OMIT_GENERATED_COLUMNS compile-time option is used. */ 20057e7fd73bSdrh sqlite3ErrorMsg(pParse, "generated columns not supported"); 200681f7b372Sdrh sqlite3ExprDelete(pParse->db, pExpr); 200781f7b372Sdrh #endif 200881f7b372Sdrh } 200981f7b372Sdrh 2010466be56bSdanielk1977 /* 20113f7d4e49Sdrh ** Generate code that will increment the schema cookie. 201250e5dadfSdrh ** 201350e5dadfSdrh ** The schema cookie is used to determine when the schema for the 201450e5dadfSdrh ** database changes. After each schema change, the cookie value 201550e5dadfSdrh ** changes. When a process first reads the schema it records the 201650e5dadfSdrh ** cookie. Thereafter, whenever it goes to access the database, 201750e5dadfSdrh ** it checks the cookie to make sure the schema has not changed 201850e5dadfSdrh ** since it was last read. 201950e5dadfSdrh ** 202050e5dadfSdrh ** This plan is not completely bullet-proof. It is possible for 202150e5dadfSdrh ** the schema to change multiple times and for the cookie to be 202250e5dadfSdrh ** set back to prior value. But schema changes are infrequent 202350e5dadfSdrh ** and the probability of hitting the same cookie value is only 202450e5dadfSdrh ** 1 chance in 2^32. So we're safe enough. 202596fdcb40Sdrh ** 202696fdcb40Sdrh ** IMPLEMENTATION-OF: R-34230-56049 SQLite automatically increments 202796fdcb40Sdrh ** the schema-version whenever the schema changes. 202850e5dadfSdrh */ 20299cbf3425Sdrh void sqlite3ChangeCookie(Parse *pParse, int iDb){ 20309cbf3425Sdrh sqlite3 *db = pParse->db; 20319cbf3425Sdrh Vdbe *v = pParse->pVdbe; 20322120608eSdrh assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); 20331861afcdSdrh sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION, 20343517b312Sdrh (int)(1+(unsigned)db->aDb[iDb].pSchema->schema_cookie)); 203550e5dadfSdrh } 203650e5dadfSdrh 203750e5dadfSdrh /* 2038969fa7c1Sdrh ** Measure the number of characters needed to output the given 2039969fa7c1Sdrh ** identifier. The number returned includes any quotes used 2040969fa7c1Sdrh ** but does not include the null terminator. 2041234c39dfSdrh ** 2042234c39dfSdrh ** The estimate is conservative. It might be larger that what is 2043234c39dfSdrh ** really needed. 2044969fa7c1Sdrh */ 2045969fa7c1Sdrh static int identLength(const char *z){ 2046969fa7c1Sdrh int n; 204717f71934Sdrh for(n=0; *z; n++, z++){ 2048234c39dfSdrh if( *z=='"' ){ n++; } 2049969fa7c1Sdrh } 2050234c39dfSdrh return n + 2; 2051969fa7c1Sdrh } 2052969fa7c1Sdrh 2053969fa7c1Sdrh /* 20541b870de6Sdanielk1977 ** The first parameter is a pointer to an output buffer. The second 20551b870de6Sdanielk1977 ** parameter is a pointer to an integer that contains the offset at 20561b870de6Sdanielk1977 ** which to write into the output buffer. This function copies the 20571b870de6Sdanielk1977 ** nul-terminated string pointed to by the third parameter, zSignedIdent, 20581b870de6Sdanielk1977 ** to the specified offset in the buffer and updates *pIdx to refer 20591b870de6Sdanielk1977 ** to the first byte after the last byte written before returning. 20601b870de6Sdanielk1977 ** 20611b870de6Sdanielk1977 ** If the string zSignedIdent consists entirely of alpha-numeric 20621b870de6Sdanielk1977 ** characters, does not begin with a digit and is not an SQL keyword, 20631b870de6Sdanielk1977 ** then it is copied to the output buffer exactly as it is. Otherwise, 20641b870de6Sdanielk1977 ** it is quoted using double-quotes. 20651b870de6Sdanielk1977 */ 2066c4a64facSdrh static void identPut(char *z, int *pIdx, char *zSignedIdent){ 20674c755c0fSdrh unsigned char *zIdent = (unsigned char*)zSignedIdent; 206817f71934Sdrh int i, j, needQuote; 2069969fa7c1Sdrh i = *pIdx; 20701b870de6Sdanielk1977 207117f71934Sdrh for(j=0; zIdent[j]; j++){ 207278ca0e7eSdanielk1977 if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break; 207317f71934Sdrh } 2074c7407524Sdrh needQuote = sqlite3Isdigit(zIdent[0]) 2075c7407524Sdrh || sqlite3KeywordCode(zIdent, j)!=TK_ID 2076c7407524Sdrh || zIdent[j]!=0 2077c7407524Sdrh || j==0; 20781b870de6Sdanielk1977 2079234c39dfSdrh if( needQuote ) z[i++] = '"'; 2080969fa7c1Sdrh for(j=0; zIdent[j]; j++){ 2081969fa7c1Sdrh z[i++] = zIdent[j]; 2082234c39dfSdrh if( zIdent[j]=='"' ) z[i++] = '"'; 2083969fa7c1Sdrh } 2084234c39dfSdrh if( needQuote ) z[i++] = '"'; 2085969fa7c1Sdrh z[i] = 0; 2086969fa7c1Sdrh *pIdx = i; 2087969fa7c1Sdrh } 2088969fa7c1Sdrh 2089969fa7c1Sdrh /* 2090969fa7c1Sdrh ** Generate a CREATE TABLE statement appropriate for the given 2091969fa7c1Sdrh ** table. Memory to hold the text of the statement is obtained 2092969fa7c1Sdrh ** from sqliteMalloc() and must be freed by the calling function. 2093969fa7c1Sdrh */ 20941d34fdecSdrh static char *createTableStmt(sqlite3 *db, Table *p){ 2095969fa7c1Sdrh int i, k, n; 2096969fa7c1Sdrh char *zStmt; 2097c4a64facSdrh char *zSep, *zSep2, *zEnd; 2098234c39dfSdrh Column *pCol; 2099969fa7c1Sdrh n = 0; 2100234c39dfSdrh for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){ 2101cf9d36d1Sdrh n += identLength(pCol->zCnName) + 5; 2102969fa7c1Sdrh } 2103969fa7c1Sdrh n += identLength(p->zName); 2104234c39dfSdrh if( n<50 ){ 2105969fa7c1Sdrh zSep = ""; 2106969fa7c1Sdrh zSep2 = ","; 2107969fa7c1Sdrh zEnd = ")"; 2108969fa7c1Sdrh }else{ 2109969fa7c1Sdrh zSep = "\n "; 2110969fa7c1Sdrh zSep2 = ",\n "; 2111969fa7c1Sdrh zEnd = "\n)"; 2112969fa7c1Sdrh } 2113e0bc4048Sdrh n += 35 + 6*p->nCol; 2114b975598eSdrh zStmt = sqlite3DbMallocRaw(0, n); 2115820a9069Sdrh if( zStmt==0 ){ 21164a642b60Sdrh sqlite3OomFault(db); 2117820a9069Sdrh return 0; 2118820a9069Sdrh } 2119bdb339ffSdrh sqlite3_snprintf(n, zStmt, "CREATE TABLE "); 2120ea678832Sdrh k = sqlite3Strlen30(zStmt); 2121c4a64facSdrh identPut(zStmt, &k, p->zName); 2122969fa7c1Sdrh zStmt[k++] = '('; 2123234c39dfSdrh for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){ 2124c4a64facSdrh static const char * const azType[] = { 212505883a34Sdrh /* SQLITE_AFF_BLOB */ "", 21267ea31ccbSdrh /* SQLITE_AFF_TEXT */ " TEXT", 2127c4a64facSdrh /* SQLITE_AFF_NUMERIC */ " NUM", 2128c4a64facSdrh /* SQLITE_AFF_INTEGER */ " INT", 2129c4a64facSdrh /* SQLITE_AFF_REAL */ " REAL" 2130c4a64facSdrh }; 2131c4a64facSdrh int len; 2132c4a64facSdrh const char *zType; 2133c4a64facSdrh 21345bb3eb9bSdrh sqlite3_snprintf(n-k, &zStmt[k], zSep); 2135ea678832Sdrh k += sqlite3Strlen30(&zStmt[k]); 2136969fa7c1Sdrh zSep = zSep2; 2137cf9d36d1Sdrh identPut(zStmt, &k, pCol->zCnName); 213805883a34Sdrh assert( pCol->affinity-SQLITE_AFF_BLOB >= 0 ); 213905883a34Sdrh assert( pCol->affinity-SQLITE_AFF_BLOB < ArraySize(azType) ); 214005883a34Sdrh testcase( pCol->affinity==SQLITE_AFF_BLOB ); 21417ea31ccbSdrh testcase( pCol->affinity==SQLITE_AFF_TEXT ); 2142c4a64facSdrh testcase( pCol->affinity==SQLITE_AFF_NUMERIC ); 2143c4a64facSdrh testcase( pCol->affinity==SQLITE_AFF_INTEGER ); 2144c4a64facSdrh testcase( pCol->affinity==SQLITE_AFF_REAL ); 2145c4a64facSdrh 214605883a34Sdrh zType = azType[pCol->affinity - SQLITE_AFF_BLOB]; 2147c4a64facSdrh len = sqlite3Strlen30(zType); 214805883a34Sdrh assert( pCol->affinity==SQLITE_AFF_BLOB 2149fdaac671Sdrh || pCol->affinity==sqlite3AffinityType(zType, 0) ); 2150c4a64facSdrh memcpy(&zStmt[k], zType, len); 2151c4a64facSdrh k += len; 2152c4a64facSdrh assert( k<=n ); 2153969fa7c1Sdrh } 21545bb3eb9bSdrh sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd); 2155969fa7c1Sdrh return zStmt; 2156969fa7c1Sdrh } 2157969fa7c1Sdrh 2158969fa7c1Sdrh /* 21597f9c5dbfSdrh ** Resize an Index object to hold N columns total. Return SQLITE_OK 21607f9c5dbfSdrh ** on success and SQLITE_NOMEM on an OOM error. 21617f9c5dbfSdrh */ 21627f9c5dbfSdrh static int resizeIndexObject(sqlite3 *db, Index *pIdx, int N){ 21637f9c5dbfSdrh char *zExtra; 21647f9c5dbfSdrh int nByte; 21657f9c5dbfSdrh if( pIdx->nColumn>=N ) return SQLITE_OK; 21667f9c5dbfSdrh assert( pIdx->isResized==0 ); 2167b5a69238Sdan nByte = (sizeof(char*) + sizeof(LogEst) + sizeof(i16) + 1)*N; 21687f9c5dbfSdrh zExtra = sqlite3DbMallocZero(db, nByte); 2169fad3039cSmistachkin if( zExtra==0 ) return SQLITE_NOMEM_BKPT; 21707f9c5dbfSdrh memcpy(zExtra, pIdx->azColl, sizeof(char*)*pIdx->nColumn); 2171f19aa5faSdrh pIdx->azColl = (const char**)zExtra; 21727f9c5dbfSdrh zExtra += sizeof(char*)*N; 2173b5a69238Sdan memcpy(zExtra, pIdx->aiRowLogEst, sizeof(LogEst)*(pIdx->nKeyCol+1)); 2174b5a69238Sdan pIdx->aiRowLogEst = (LogEst*)zExtra; 2175b5a69238Sdan zExtra += sizeof(LogEst)*N; 21767f9c5dbfSdrh memcpy(zExtra, pIdx->aiColumn, sizeof(i16)*pIdx->nColumn); 21777f9c5dbfSdrh pIdx->aiColumn = (i16*)zExtra; 21787f9c5dbfSdrh zExtra += sizeof(i16)*N; 21797f9c5dbfSdrh memcpy(zExtra, pIdx->aSortOrder, pIdx->nColumn); 21807f9c5dbfSdrh pIdx->aSortOrder = (u8*)zExtra; 21817f9c5dbfSdrh pIdx->nColumn = N; 21827f9c5dbfSdrh pIdx->isResized = 1; 21837f9c5dbfSdrh return SQLITE_OK; 21847f9c5dbfSdrh } 21857f9c5dbfSdrh 21867f9c5dbfSdrh /* 2187fdaac671Sdrh ** Estimate the total row width for a table. 2188fdaac671Sdrh */ 2189e13e9f54Sdrh static void estimateTableWidth(Table *pTab){ 2190fdaac671Sdrh unsigned wTable = 0; 2191fdaac671Sdrh const Column *pTabCol; 2192fdaac671Sdrh int i; 2193fdaac671Sdrh for(i=pTab->nCol, pTabCol=pTab->aCol; i>0; i--, pTabCol++){ 2194fdaac671Sdrh wTable += pTabCol->szEst; 2195fdaac671Sdrh } 2196fdaac671Sdrh if( pTab->iPKey<0 ) wTable++; 2197e13e9f54Sdrh pTab->szTabRow = sqlite3LogEst(wTable*4); 2198fdaac671Sdrh } 2199fdaac671Sdrh 2200fdaac671Sdrh /* 2201e13e9f54Sdrh ** Estimate the average size of a row for an index. 2202fdaac671Sdrh */ 2203e13e9f54Sdrh static void estimateIndexWidth(Index *pIdx){ 2204bbbdc83bSdrh unsigned wIndex = 0; 2205fdaac671Sdrh int i; 2206fdaac671Sdrh const Column *aCol = pIdx->pTable->aCol; 2207fdaac671Sdrh for(i=0; i<pIdx->nColumn; i++){ 2208bbbdc83bSdrh i16 x = pIdx->aiColumn[i]; 2209bbbdc83bSdrh assert( x<pIdx->pTable->nCol ); 2210bbbdc83bSdrh wIndex += x<0 ? 1 : aCol[pIdx->aiColumn[i]].szEst; 2211fdaac671Sdrh } 2212e13e9f54Sdrh pIdx->szIdxRow = sqlite3LogEst(wIndex*4); 2213fdaac671Sdrh } 2214fdaac671Sdrh 2215f78d0f42Sdrh /* Return true if column number x is any of the first nCol entries of aiCol[]. 2216f78d0f42Sdrh ** This is used to determine if the column number x appears in any of the 2217f78d0f42Sdrh ** first nCol entries of an index. 22187f9c5dbfSdrh */ 22197f9c5dbfSdrh static int hasColumn(const i16 *aiCol, int nCol, int x){ 2220f78d0f42Sdrh while( nCol-- > 0 ){ 2221f78d0f42Sdrh if( x==*(aiCol++) ){ 2222f78d0f42Sdrh return 1; 2223f78d0f42Sdrh } 2224f78d0f42Sdrh } 2225f78d0f42Sdrh return 0; 2226f78d0f42Sdrh } 2227f78d0f42Sdrh 2228f78d0f42Sdrh /* 2229c19b63c9Sdrh ** Return true if any of the first nKey entries of index pIdx exactly 2230c19b63c9Sdrh ** match the iCol-th entry of pPk. pPk is always a WITHOUT ROWID 2231c19b63c9Sdrh ** PRIMARY KEY index. pIdx is an index on the same table. pIdx may 2232c19b63c9Sdrh ** or may not be the same index as pPk. 2233f78d0f42Sdrh ** 2234c19b63c9Sdrh ** The first nKey entries of pIdx are guaranteed to be ordinary columns, 2235f78d0f42Sdrh ** not a rowid or expression. 2236f78d0f42Sdrh ** 2237f78d0f42Sdrh ** This routine differs from hasColumn() in that both the column and the 2238f78d0f42Sdrh ** collating sequence must match for this routine, but for hasColumn() only 2239f78d0f42Sdrh ** the column name must match. 2240f78d0f42Sdrh */ 2241c19b63c9Sdrh static int isDupColumn(Index *pIdx, int nKey, Index *pPk, int iCol){ 2242f78d0f42Sdrh int i, j; 2243c19b63c9Sdrh assert( nKey<=pIdx->nColumn ); 2244c19b63c9Sdrh assert( iCol<MAX(pPk->nColumn,pPk->nKeyCol) ); 2245c19b63c9Sdrh assert( pPk->idxType==SQLITE_IDXTYPE_PRIMARYKEY ); 2246c19b63c9Sdrh assert( pPk->pTable->tabFlags & TF_WithoutRowid ); 2247c19b63c9Sdrh assert( pPk->pTable==pIdx->pTable ); 2248c19b63c9Sdrh testcase( pPk==pIdx ); 2249c19b63c9Sdrh j = pPk->aiColumn[iCol]; 2250c19b63c9Sdrh assert( j!=XN_ROWID && j!=XN_EXPR ); 2251f78d0f42Sdrh for(i=0; i<nKey; i++){ 2252c19b63c9Sdrh assert( pIdx->aiColumn[i]>=0 || j>=0 ); 2253c19b63c9Sdrh if( pIdx->aiColumn[i]==j 2254c19b63c9Sdrh && sqlite3StrICmp(pIdx->azColl[i], pPk->azColl[iCol])==0 2255f78d0f42Sdrh ){ 2256f78d0f42Sdrh return 1; 2257f78d0f42Sdrh } 2258f78d0f42Sdrh } 22597f9c5dbfSdrh return 0; 22607f9c5dbfSdrh } 22617f9c5dbfSdrh 22621fe3ac73Sdrh /* Recompute the colNotIdxed field of the Index. 22631fe3ac73Sdrh ** 22641fe3ac73Sdrh ** colNotIdxed is a bitmask that has a 0 bit representing each indexed 22651fe3ac73Sdrh ** columns that are within the first 63 columns of the table. The 22661fe3ac73Sdrh ** high-order bit of colNotIdxed is always 1. All unindexed columns 22671fe3ac73Sdrh ** of the table have a 1. 22681fe3ac73Sdrh ** 2269c7476735Sdrh ** 2019-10-24: For the purpose of this computation, virtual columns are 2270c7476735Sdrh ** not considered to be covered by the index, even if they are in the 2271c7476735Sdrh ** index, because we do not trust the logic in whereIndexExprTrans() to be 2272c7476735Sdrh ** able to find all instances of a reference to the indexed table column 2273c7476735Sdrh ** and convert them into references to the index. Hence we always want 2274c7476735Sdrh ** the actual table at hand in order to recompute the virtual column, if 2275c7476735Sdrh ** necessary. 2276c7476735Sdrh ** 22771fe3ac73Sdrh ** The colNotIdxed mask is AND-ed with the SrcList.a[].colUsed mask 22781fe3ac73Sdrh ** to determine if the index is covering index. 22791fe3ac73Sdrh */ 22801fe3ac73Sdrh static void recomputeColumnsNotIndexed(Index *pIdx){ 22811fe3ac73Sdrh Bitmask m = 0; 22821fe3ac73Sdrh int j; 2283c7476735Sdrh Table *pTab = pIdx->pTable; 22841fe3ac73Sdrh for(j=pIdx->nColumn-1; j>=0; j--){ 22851fe3ac73Sdrh int x = pIdx->aiColumn[j]; 2286c7476735Sdrh if( x>=0 && (pTab->aCol[x].colFlags & COLFLAG_VIRTUAL)==0 ){ 22871fe3ac73Sdrh testcase( x==BMS-1 ); 22881fe3ac73Sdrh testcase( x==BMS-2 ); 22891fe3ac73Sdrh if( x<BMS-1 ) m |= MASKBIT(x); 22901fe3ac73Sdrh } 22911fe3ac73Sdrh } 22921fe3ac73Sdrh pIdx->colNotIdxed = ~m; 22931fe3ac73Sdrh assert( (pIdx->colNotIdxed>>63)==1 ); 22941fe3ac73Sdrh } 22951fe3ac73Sdrh 22967f9c5dbfSdrh /* 2297c6bd4e4aSdrh ** This routine runs at the end of parsing a CREATE TABLE statement that 2298c6bd4e4aSdrh ** has a WITHOUT ROWID clause. The job of this routine is to convert both 2299c6bd4e4aSdrh ** internal schema data structures and the generated VDBE code so that they 2300c6bd4e4aSdrh ** are appropriate for a WITHOUT ROWID table instead of a rowid table. 2301c6bd4e4aSdrh ** Changes include: 23027f9c5dbfSdrh ** 230362340f84Sdrh ** (1) Set all columns of the PRIMARY KEY schema object to be NOT NULL. 23040f3f7664Sdrh ** (2) Convert P3 parameter of the OP_CreateBtree from BTREE_INTKEY 23050f3f7664Sdrh ** into BTREE_BLOBKEY. 23061e32bed3Sdrh ** (3) Bypass the creation of the sqlite_schema table entry 230760ec914cSpeter.d.reid ** for the PRIMARY KEY as the primary key index is now 23081e32bed3Sdrh ** identified by the sqlite_schema table entry of the table itself. 230962340f84Sdrh ** (4) Set the Index.tnum of the PRIMARY KEY Index object in the 2310c6bd4e4aSdrh ** schema to the rootpage from the main table. 2311c6bd4e4aSdrh ** (5) Add all table columns to the PRIMARY KEY Index object 2312c6bd4e4aSdrh ** so that the PRIMARY KEY is a covering index. The surplus 2313a485ad19Sdrh ** columns are part of KeyInfo.nAllField and are not used for 2314c6bd4e4aSdrh ** sorting or lookup or uniqueness checks. 2315c6bd4e4aSdrh ** (6) Replace the rowid tail on all automatically generated UNIQUE 2316c6bd4e4aSdrh ** indices with the PRIMARY KEY columns. 231762340f84Sdrh ** 231862340f84Sdrh ** For virtual tables, only (1) is performed. 23197f9c5dbfSdrh */ 23207f9c5dbfSdrh static void convertToWithoutRowidTable(Parse *pParse, Table *pTab){ 23217f9c5dbfSdrh Index *pIdx; 23227f9c5dbfSdrh Index *pPk; 23237f9c5dbfSdrh int nPk; 23241ff94071Sdan int nExtra; 23257f9c5dbfSdrh int i, j; 23267f9c5dbfSdrh sqlite3 *db = pParse->db; 2327c6bd4e4aSdrh Vdbe *v = pParse->pVdbe; 23287f9c5dbfSdrh 232962340f84Sdrh /* Mark every PRIMARY KEY column as NOT NULL (except for imposter tables) 233062340f84Sdrh */ 233162340f84Sdrh if( !db->init.imposterTable ){ 233262340f84Sdrh for(i=0; i<pTab->nCol; i++){ 2333fd46ec64Sdrh if( (pTab->aCol[i].colFlags & COLFLAG_PRIMKEY)!=0 2334fd46ec64Sdrh && (pTab->aCol[i].notNull==OE_None) 2335fd46ec64Sdrh ){ 233662340f84Sdrh pTab->aCol[i].notNull = OE_Abort; 233762340f84Sdrh } 233862340f84Sdrh } 2339cbda9c7aSdrh pTab->tabFlags |= TF_HasNotNull; 234062340f84Sdrh } 234162340f84Sdrh 23420f3f7664Sdrh /* Convert the P3 operand of the OP_CreateBtree opcode from BTREE_INTKEY 23430f3f7664Sdrh ** into BTREE_BLOBKEY. 23447f9c5dbfSdrh */ 2345381bdaccSdrh assert( !pParse->bReturning ); 2346381bdaccSdrh if( pParse->u1.addrCrTab ){ 2347c6bd4e4aSdrh assert( v ); 2348381bdaccSdrh sqlite3VdbeChangeP3(v, pParse->u1.addrCrTab, BTREE_BLOBKEY); 2349c6bd4e4aSdrh } 2350c6bd4e4aSdrh 23517f9c5dbfSdrh /* Locate the PRIMARY KEY index. Or, if this table was originally 23527f9c5dbfSdrh ** an INTEGER PRIMARY KEY table, create a new PRIMARY KEY index. 23537f9c5dbfSdrh */ 23547f9c5dbfSdrh if( pTab->iPKey>=0 ){ 23557f9c5dbfSdrh ExprList *pList; 2356108aa00aSdrh Token ipkToken; 2357cf9d36d1Sdrh sqlite3TokenInit(&ipkToken, pTab->aCol[pTab->iPKey].zCnName); 2358108aa00aSdrh pList = sqlite3ExprListAppend(pParse, 0, 2359108aa00aSdrh sqlite3ExprAlloc(db, TK_ID, &ipkToken, 0)); 23601bb89e9cSdrh if( pList==0 ){ 23611bb89e9cSdrh pTab->tabFlags &= ~TF_WithoutRowid; 23621bb89e9cSdrh return; 23631bb89e9cSdrh } 2364f9b0c451Sdan if( IN_RENAME_OBJECT ){ 2365f9b0c451Sdan sqlite3RenameTokenRemap(pParse, pList->a[0].pExpr, &pTab->iPKey); 2366f9b0c451Sdan } 23676e11892dSdan pList->a[0].sortFlags = pParse->iPkSortOrder; 23687f9c5dbfSdrh assert( pParse->pNewTable==pTab ); 2369f9b0c451Sdan pTab->iPKey = -1; 237062340f84Sdrh sqlite3CreateIndex(pParse, 0, 0, 0, pList, pTab->keyConf, 0, 0, 0, 0, 237162340f84Sdrh SQLITE_IDXTYPE_PRIMARYKEY); 23723bb9d75aSdrh if( db->mallocFailed || pParse->nErr ){ 23733bb9d75aSdrh pTab->tabFlags &= ~TF_WithoutRowid; 23743bb9d75aSdrh return; 23753bb9d75aSdrh } 237662340f84Sdrh pPk = sqlite3PrimaryKeyIndex(pTab); 23771ff94071Sdan assert( pPk->nKeyCol==1 ); 23784415628aSdrh }else{ 23794415628aSdrh pPk = sqlite3PrimaryKeyIndex(pTab); 2380f0c48b1cSdrh assert( pPk!=0 ); 2381c5b73585Sdan 2382e385d887Sdrh /* 2383e385d887Sdrh ** Remove all redundant columns from the PRIMARY KEY. For example, change 2384e385d887Sdrh ** "PRIMARY KEY(a,b,a,b,c,b,c,d)" into just "PRIMARY KEY(a,b,c,d)". Later 2385e385d887Sdrh ** code assumes the PRIMARY KEY contains no repeated columns. 2386e385d887Sdrh */ 2387e385d887Sdrh for(i=j=1; i<pPk->nKeyCol; i++){ 2388f78d0f42Sdrh if( isDupColumn(pPk, j, pPk, i) ){ 2389e385d887Sdrh pPk->nColumn--; 2390e385d887Sdrh }else{ 2391f78d0f42Sdrh testcase( hasColumn(pPk->aiColumn, j, pPk->aiColumn[i]) ); 23921ff94071Sdan pPk->azColl[j] = pPk->azColl[i]; 23931ff94071Sdan pPk->aSortOrder[j] = pPk->aSortOrder[i]; 2394e385d887Sdrh pPk->aiColumn[j++] = pPk->aiColumn[i]; 2395e385d887Sdrh } 2396e385d887Sdrh } 2397e385d887Sdrh pPk->nKeyCol = j; 23987f9c5dbfSdrh } 23997f9c5dbfSdrh assert( pPk!=0 ); 240062340f84Sdrh pPk->isCovering = 1; 240162340f84Sdrh if( !db->init.imposterTable ) pPk->uniqNotNull = 1; 24021ff94071Sdan nPk = pPk->nColumn = pPk->nKeyCol; 24037f9c5dbfSdrh 24041e32bed3Sdrh /* Bypass the creation of the PRIMARY KEY btree and the sqlite_schema 2405df94966cSdrh ** table entry. This is only required if currently generating VDBE 2406df94966cSdrh ** code for a CREATE TABLE (not when parsing one as part of reading 2407df94966cSdrh ** a database schema). */ 2408df94966cSdrh if( v && pPk->tnum>0 ){ 2409df94966cSdrh assert( db->init.busy==0 ); 2410abc38158Sdrh sqlite3VdbeChangeOpcode(v, (int)pPk->tnum, OP_Goto); 2411df94966cSdrh } 2412df94966cSdrh 2413c6bd4e4aSdrh /* The root page of the PRIMARY KEY is the table root page */ 2414c6bd4e4aSdrh pPk->tnum = pTab->tnum; 2415c6bd4e4aSdrh 24167f9c5dbfSdrh /* Update the in-memory representation of all UNIQUE indices by converting 24177f9c5dbfSdrh ** the final rowid column into one or more columns of the PRIMARY KEY. 24187f9c5dbfSdrh */ 24197f9c5dbfSdrh for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ 24207f9c5dbfSdrh int n; 242148dd1d8eSdrh if( IsPrimaryKeyIndex(pIdx) ) continue; 24227f9c5dbfSdrh for(i=n=0; i<nPk; i++){ 2423f78d0f42Sdrh if( !isDupColumn(pIdx, pIdx->nKeyCol, pPk, i) ){ 2424f78d0f42Sdrh testcase( hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) ); 2425f78d0f42Sdrh n++; 2426f78d0f42Sdrh } 24277f9c5dbfSdrh } 24285a9a37b7Sdrh if( n==0 ){ 24295a9a37b7Sdrh /* This index is a superset of the primary key */ 24305a9a37b7Sdrh pIdx->nColumn = pIdx->nKeyCol; 24315a9a37b7Sdrh continue; 24325a9a37b7Sdrh } 24337f9c5dbfSdrh if( resizeIndexObject(db, pIdx, pIdx->nKeyCol+n) ) return; 24347f9c5dbfSdrh for(i=0, j=pIdx->nKeyCol; i<nPk; i++){ 2435f78d0f42Sdrh if( !isDupColumn(pIdx, pIdx->nKeyCol, pPk, i) ){ 2436f78d0f42Sdrh testcase( hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) ); 24377f9c5dbfSdrh pIdx->aiColumn[j] = pPk->aiColumn[i]; 24387f9c5dbfSdrh pIdx->azColl[j] = pPk->azColl[i]; 2439bf9ff256Sdrh if( pPk->aSortOrder[i] ){ 2440bf9ff256Sdrh /* See ticket https://www.sqlite.org/src/info/bba7b69f9849b5bf */ 2441bf9ff256Sdrh pIdx->bAscKeyBug = 1; 2442bf9ff256Sdrh } 24437f9c5dbfSdrh j++; 24447f9c5dbfSdrh } 24457f9c5dbfSdrh } 244600012df4Sdrh assert( pIdx->nColumn>=pIdx->nKeyCol+n ); 244700012df4Sdrh assert( pIdx->nColumn>=j ); 24487f9c5dbfSdrh } 24497f9c5dbfSdrh 24507f9c5dbfSdrh /* Add all table columns to the PRIMARY KEY index 24517f9c5dbfSdrh */ 24521ff94071Sdan nExtra = 0; 24531ff94071Sdan for(i=0; i<pTab->nCol; i++){ 24548e10d74bSdrh if( !hasColumn(pPk->aiColumn, nPk, i) 24558e10d74bSdrh && (pTab->aCol[i].colFlags & COLFLAG_VIRTUAL)==0 ) nExtra++; 24561ff94071Sdan } 24571ff94071Sdan if( resizeIndexObject(db, pPk, nPk+nExtra) ) return; 24587f9c5dbfSdrh for(i=0, j=nPk; i<pTab->nCol; i++){ 24598e10d74bSdrh if( !hasColumn(pPk->aiColumn, j, i) 24608e10d74bSdrh && (pTab->aCol[i].colFlags & COLFLAG_VIRTUAL)==0 24618e10d74bSdrh ){ 24627f9c5dbfSdrh assert( j<pPk->nColumn ); 24637f9c5dbfSdrh pPk->aiColumn[j] = i; 2464f19aa5faSdrh pPk->azColl[j] = sqlite3StrBINARY; 24657f9c5dbfSdrh j++; 24667f9c5dbfSdrh } 24677f9c5dbfSdrh } 24687f9c5dbfSdrh assert( pPk->nColumn==j ); 24698e10d74bSdrh assert( pTab->nNVCol<=j ); 24701fe3ac73Sdrh recomputeColumnsNotIndexed(pPk); 24717f9c5dbfSdrh } 24727f9c5dbfSdrh 24733d863b5eSdrh 24743d863b5eSdrh #ifndef SQLITE_OMIT_VIRTUALTABLE 24753d863b5eSdrh /* 24763d863b5eSdrh ** Return true if pTab is a virtual table and zName is a shadow table name 24773d863b5eSdrh ** for that virtual table. 24783d863b5eSdrh */ 24793d863b5eSdrh int sqlite3IsShadowTableOf(sqlite3 *db, Table *pTab, const char *zName){ 24803d863b5eSdrh int nName; /* Length of zName */ 24813d863b5eSdrh Module *pMod; /* Module for the virtual table */ 24823d863b5eSdrh 24833d863b5eSdrh if( !IsVirtual(pTab) ) return 0; 24843d863b5eSdrh nName = sqlite3Strlen30(pTab->zName); 24853d863b5eSdrh if( sqlite3_strnicmp(zName, pTab->zName, nName)!=0 ) return 0; 24863d863b5eSdrh if( zName[nName]!='_' ) return 0; 2487f38524d2Sdrh pMod = (Module*)sqlite3HashFind(&db->aModule, pTab->u.vtab.azArg[0]); 24883d863b5eSdrh if( pMod==0 ) return 0; 24893d863b5eSdrh if( pMod->pModule->iVersion<3 ) return 0; 24903d863b5eSdrh if( pMod->pModule->xShadowName==0 ) return 0; 24913d863b5eSdrh return pMod->pModule->xShadowName(zName+nName+1); 24923d863b5eSdrh } 24933d863b5eSdrh #endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */ 24943d863b5eSdrh 2495f6e015faSdan #ifndef SQLITE_OMIT_VIRTUALTABLE 2496fdaac671Sdrh /* 2497*ddfec00dSdrh ** Table pTab is a virtual table. If it the virtual table implementation 2498*ddfec00dSdrh ** exists and has an xShadowName method, then loop over all other ordinary 2499*ddfec00dSdrh ** tables within the same schema looking for shadow tables of pTab, and mark 2500*ddfec00dSdrh ** any shadow tables seen using the TF_Shadow flag. 2501*ddfec00dSdrh */ 2502*ddfec00dSdrh void sqlite3MarkAllShadowTablesOf(sqlite3 *db, Table *pTab){ 2503*ddfec00dSdrh int nName; /* Length of pTab->zName */ 2504*ddfec00dSdrh Module *pMod; /* Module for the virtual table */ 2505*ddfec00dSdrh HashElem *k; /* For looping through the symbol table */ 2506*ddfec00dSdrh 2507*ddfec00dSdrh assert( IsVirtual(pTab) ); 2508*ddfec00dSdrh pMod = (Module*)sqlite3HashFind(&db->aModule, pTab->u.vtab.azArg[0]); 2509*ddfec00dSdrh if( pMod==0 ) return; 2510*ddfec00dSdrh if( NEVER(pMod->pModule==0) ) return; 2511*ddfec00dSdrh if( pMod->pModule->xShadowName==0 ) return; 2512*ddfec00dSdrh assert( pTab->zName!=0 ); 2513*ddfec00dSdrh nName = sqlite3Strlen30(pTab->zName); 2514*ddfec00dSdrh for(k=sqliteHashFirst(&pTab->pSchema->tblHash); k; k=sqliteHashNext(k)){ 2515*ddfec00dSdrh Table *pOther = sqliteHashData(k); 2516*ddfec00dSdrh assert( pOther->zName!=0 ); 2517*ddfec00dSdrh if( !IsOrdinaryTable(pOther) ) continue; 2518*ddfec00dSdrh if( pOther->tabFlags & TF_Shadow ) continue; 2519*ddfec00dSdrh if( sqlite3StrNICmp(pOther->zName, pTab->zName, nName)==0 2520*ddfec00dSdrh && pOther->zName[nName]=='_' 2521*ddfec00dSdrh && pMod->pModule->xShadowName(pOther->zName+nName+1) 2522*ddfec00dSdrh ){ 2523*ddfec00dSdrh pOther->tabFlags |= TF_Shadow; 2524*ddfec00dSdrh } 2525*ddfec00dSdrh } 2526*ddfec00dSdrh } 2527*ddfec00dSdrh #endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */ 2528*ddfec00dSdrh 2529*ddfec00dSdrh #ifndef SQLITE_OMIT_VIRTUALTABLE 2530*ddfec00dSdrh /* 253184c501baSdrh ** Return true if zName is a shadow table name in the current database 253284c501baSdrh ** connection. 253384c501baSdrh ** 253484c501baSdrh ** zName is temporarily modified while this routine is running, but is 253584c501baSdrh ** restored to its original value prior to this routine returning. 253684c501baSdrh */ 2537527cbd4aSdrh int sqlite3ShadowTableName(sqlite3 *db, const char *zName){ 253884c501baSdrh char *zTail; /* Pointer to the last "_" in zName */ 253984c501baSdrh Table *pTab; /* Table that zName is a shadow of */ 254084c501baSdrh zTail = strrchr(zName, '_'); 254184c501baSdrh if( zTail==0 ) return 0; 254284c501baSdrh *zTail = 0; 254384c501baSdrh pTab = sqlite3FindTable(db, zName, 0); 254484c501baSdrh *zTail = '_'; 254584c501baSdrh if( pTab==0 ) return 0; 254684c501baSdrh if( !IsVirtual(pTab) ) return 0; 25473d863b5eSdrh return sqlite3IsShadowTableOf(db, pTab, zName); 254884c501baSdrh } 2549f6e015faSdan #endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */ 255084c501baSdrh 25513d863b5eSdrh 2552e7375bfaSdrh #ifdef SQLITE_DEBUG 2553e7375bfaSdrh /* 2554e7375bfaSdrh ** Mark all nodes of an expression as EP_Immutable, indicating that 2555e7375bfaSdrh ** they should not be changed. Expressions attached to a table or 2556e7375bfaSdrh ** index definition are tagged this way to help ensure that we do 2557e7375bfaSdrh ** not pass them into code generator routines by mistake. 2558e7375bfaSdrh */ 2559e7375bfaSdrh static int markImmutableExprStep(Walker *pWalker, Expr *pExpr){ 2560e7375bfaSdrh ExprSetVVAProperty(pExpr, EP_Immutable); 2561e7375bfaSdrh return WRC_Continue; 2562e7375bfaSdrh } 2563e7375bfaSdrh static void markExprListImmutable(ExprList *pList){ 2564e7375bfaSdrh if( pList ){ 2565e7375bfaSdrh Walker w; 2566e7375bfaSdrh memset(&w, 0, sizeof(w)); 2567e7375bfaSdrh w.xExprCallback = markImmutableExprStep; 2568e7375bfaSdrh w.xSelectCallback = sqlite3SelectWalkNoop; 2569e7375bfaSdrh w.xSelectCallback2 = 0; 2570e7375bfaSdrh sqlite3WalkExprList(&w, pList); 2571e7375bfaSdrh } 2572e7375bfaSdrh } 2573e7375bfaSdrh #else 2574e7375bfaSdrh #define markExprListImmutable(X) /* no-op */ 2575e7375bfaSdrh #endif /* SQLITE_DEBUG */ 2576e7375bfaSdrh 2577e7375bfaSdrh 257884c501baSdrh /* 257975897234Sdrh ** This routine is called to report the final ")" that terminates 258075897234Sdrh ** a CREATE TABLE statement. 258175897234Sdrh ** 2582f57b3399Sdrh ** The table structure that other action routines have been building 2583f57b3399Sdrh ** is added to the internal hash tables, assuming no errors have 2584f57b3399Sdrh ** occurred. 258575897234Sdrh ** 2586067b92baSdrh ** An entry for the table is made in the schema table on disk, unless 25871d85d931Sdrh ** this is a temporary table or db->init.busy==1. When db->init.busy==1 25881e32bed3Sdrh ** it means we are reading the sqlite_schema table because we just 25891e32bed3Sdrh ** connected to the database or because the sqlite_schema table has 2590ddba9e54Sdrh ** recently changed, so the entry for this table already exists in 25911e32bed3Sdrh ** the sqlite_schema table. We do not want to create it again. 2592969fa7c1Sdrh ** 2593969fa7c1Sdrh ** If the pSelect argument is not NULL, it means that this routine 2594969fa7c1Sdrh ** was called to create a table generated from a 2595969fa7c1Sdrh ** "CREATE TABLE ... AS SELECT ..." statement. The column names of 2596969fa7c1Sdrh ** the new table will match the result set of the SELECT. 259775897234Sdrh */ 259819a8e7e8Sdanielk1977 void sqlite3EndTable( 259919a8e7e8Sdanielk1977 Parse *pParse, /* Parse context */ 260019a8e7e8Sdanielk1977 Token *pCons, /* The ',' token after the last column defn. */ 26015969da4aSdrh Token *pEnd, /* The ')' before options in the CREATE TABLE */ 260244183f83Sdrh u32 tabOpts, /* Extra table options. Usually 0. */ 260319a8e7e8Sdanielk1977 Select *pSelect /* Select from a "CREATE ... AS SELECT" */ 260419a8e7e8Sdanielk1977 ){ 2605fdaac671Sdrh Table *p; /* The new table */ 2606fdaac671Sdrh sqlite3 *db = pParse->db; /* The database connection */ 2607fdaac671Sdrh int iDb; /* Database in which the table lives */ 2608fdaac671Sdrh Index *pIdx; /* An implied index of the table */ 260975897234Sdrh 2610027616d4Sdrh if( pEnd==0 && pSelect==0 ){ 26115969da4aSdrh return; 2612261919ccSdanielk1977 } 26132803757aSdrh p = pParse->pNewTable; 26145969da4aSdrh if( p==0 ) return; 261575897234Sdrh 2616527cbd4aSdrh if( pSelect==0 && sqlite3ShadowTableName(db, p->zName) ){ 261784c501baSdrh p->tabFlags |= TF_Shadow; 261884c501baSdrh } 261984c501baSdrh 2620c6bd4e4aSdrh /* If the db->init.busy is 1 it means we are reading the SQL off the 26211e32bed3Sdrh ** "sqlite_schema" or "sqlite_temp_schema" table on the disk. 2622c6bd4e4aSdrh ** So do not write to the disk again. Extract the root page number 2623c6bd4e4aSdrh ** for the table from the db->init.newTnum field. (The page number 2624c6bd4e4aSdrh ** should have been put there by the sqliteOpenCb routine.) 2625055f298aSdrh ** 26261e32bed3Sdrh ** If the root page number is 1, that means this is the sqlite_schema 2627055f298aSdrh ** table itself. So mark it read-only. 2628c6bd4e4aSdrh */ 2629c6bd4e4aSdrh if( db->init.busy ){ 263054e3f94eSdrh if( pSelect || (!IsOrdinaryTable(p) && db->init.newTnum) ){ 26311e9c47beSdrh sqlite3ErrorMsg(pParse, ""); 26321e9c47beSdrh return; 26331e9c47beSdrh } 2634c6bd4e4aSdrh p->tnum = db->init.newTnum; 2635055f298aSdrh if( p->tnum==1 ) p->tabFlags |= TF_Readonly; 2636c6bd4e4aSdrh } 2637c6bd4e4aSdrh 263871c770fbSdrh /* Special processing for tables that include the STRICT keyword: 263971c770fbSdrh ** 264071c770fbSdrh ** * Do not allow custom column datatypes. Every column must have 264171c770fbSdrh ** a datatype that is one of INT, INTEGER, REAL, TEXT, or BLOB. 264271c770fbSdrh ** 264371c770fbSdrh ** * If a PRIMARY KEY is defined, other than the INTEGER PRIMARY KEY, 264471c770fbSdrh ** then all columns of the PRIMARY KEY must have a NOT NULL 264571c770fbSdrh ** constraint. 264671c770fbSdrh */ 264744183f83Sdrh if( tabOpts & TF_Strict ){ 264844183f83Sdrh int ii; 264944183f83Sdrh p->tabFlags |= TF_Strict; 265044183f83Sdrh for(ii=0; ii<p->nCol; ii++){ 2651ab16578bSdrh Column *pCol = &p->aCol[ii]; 2652b9fd0101Sdrh if( pCol->eCType==COLTYPE_CUSTOM ){ 2653b9fd0101Sdrh if( pCol->colFlags & COLFLAG_HASTYPE ){ 265444183f83Sdrh sqlite3ErrorMsg(pParse, 265544183f83Sdrh "unknown datatype for %s.%s: \"%s\"", 2656ab16578bSdrh p->zName, pCol->zCnName, sqlite3ColumnType(pCol, "") 265744183f83Sdrh ); 2658b9fd0101Sdrh }else{ 2659b9fd0101Sdrh sqlite3ErrorMsg(pParse, "missing datatype for %s.%s", 2660b9fd0101Sdrh p->zName, pCol->zCnName); 2661b9fd0101Sdrh } 266244183f83Sdrh return; 2663b9fd0101Sdrh }else if( pCol->eCType==COLTYPE_ANY ){ 2664b9fd0101Sdrh pCol->affinity = SQLITE_AFF_BLOB; 266544183f83Sdrh } 2666ab16578bSdrh if( (pCol->colFlags & COLFLAG_PRIMKEY)!=0 2667ab16578bSdrh && p->iPKey!=ii 2668ab16578bSdrh && pCol->notNull == OE_None 2669ab16578bSdrh ){ 2670ab16578bSdrh pCol->notNull = OE_Abort; 2671ab16578bSdrh p->tabFlags |= TF_HasNotNull; 2672ab16578bSdrh } 267344183f83Sdrh } 267444183f83Sdrh } 267544183f83Sdrh 26763cbd2b72Sdrh assert( (p->tabFlags & TF_HasPrimaryKey)==0 26773cbd2b72Sdrh || p->iPKey>=0 || sqlite3PrimaryKeyIndex(p)!=0 ); 26783cbd2b72Sdrh assert( (p->tabFlags & TF_HasPrimaryKey)!=0 26793cbd2b72Sdrh || (p->iPKey<0 && sqlite3PrimaryKeyIndex(p)==0) ); 26803cbd2b72Sdrh 2681c6bd4e4aSdrh /* Special processing for WITHOUT ROWID Tables */ 26825969da4aSdrh if( tabOpts & TF_WithoutRowid ){ 2683d2fe3358Sdrh if( (p->tabFlags & TF_Autoincrement) ){ 2684d2fe3358Sdrh sqlite3ErrorMsg(pParse, 2685d2fe3358Sdrh "AUTOINCREMENT not allowed on WITHOUT ROWID tables"); 2686d2fe3358Sdrh return; 2687d2fe3358Sdrh } 268881eba73eSdrh if( (p->tabFlags & TF_HasPrimaryKey)==0 ){ 2689d2fe3358Sdrh sqlite3ErrorMsg(pParse, "PRIMARY KEY missing on table %s", p->zName); 26908e10d74bSdrh return; 26918e10d74bSdrh } 2692fccda8a1Sdrh p->tabFlags |= TF_WithoutRowid | TF_NoVisibleRowid; 26937f9c5dbfSdrh convertToWithoutRowidTable(pParse, p); 26947f9c5dbfSdrh } 2695b9bb7c18Sdrh iDb = sqlite3SchemaToIndex(db, p->pSchema); 2696da184236Sdanielk1977 2697ffe07b2dSdrh #ifndef SQLITE_OMIT_CHECK 2698ffe07b2dSdrh /* Resolve names in all CHECK constraint expressions. 2699ffe07b2dSdrh */ 2700ffe07b2dSdrh if( p->pCheck ){ 27013780be11Sdrh sqlite3ResolveSelfReference(pParse, p, NC_IsCheck, 0, p->pCheck); 27029524a7eaSdrh if( pParse->nErr ){ 27039524a7eaSdrh /* If errors are seen, delete the CHECK constraints now, else they might 27049524a7eaSdrh ** actually be used if PRAGMA writable_schema=ON is set. */ 27059524a7eaSdrh sqlite3ExprListDelete(db, p->pCheck); 27069524a7eaSdrh p->pCheck = 0; 2707e7375bfaSdrh }else{ 2708e7375bfaSdrh markExprListImmutable(p->pCheck); 27099524a7eaSdrh } 27102938f924Sdrh } 2711ffe07b2dSdrh #endif /* !defined(SQLITE_OMIT_CHECK) */ 271281f7b372Sdrh #ifndef SQLITE_OMIT_GENERATED_COLUMNS 2713427b96aeSdrh if( p->tabFlags & TF_HasGenerated ){ 2714f4658b68Sdrh int ii, nNG = 0; 2715427b96aeSdrh testcase( p->tabFlags & TF_HasVirtual ); 2716427b96aeSdrh testcase( p->tabFlags & TF_HasStored ); 271781f7b372Sdrh for(ii=0; ii<p->nCol; ii++){ 27180b0b3a95Sdrh u32 colFlags = p->aCol[ii].colFlags; 2719427b96aeSdrh if( (colFlags & COLFLAG_GENERATED)!=0 ){ 272079cf2b71Sdrh Expr *pX = sqlite3ColumnExpr(p, &p->aCol[ii]); 2721427b96aeSdrh testcase( colFlags & COLFLAG_VIRTUAL ); 2722427b96aeSdrh testcase( colFlags & COLFLAG_STORED ); 27237e3f135cSdrh if( sqlite3ResolveSelfReference(pParse, p, NC_GenCol, pX, 0) ){ 27247e3f135cSdrh /* If there are errors in resolving the expression, change the 27257e3f135cSdrh ** expression to a NULL. This prevents code generators that operate 27267e3f135cSdrh ** on the expression from inserting extra parts into the expression 27277e3f135cSdrh ** tree that have been allocated from lookaside memory, which is 27282d58b7f4Sdrh ** illegal in a schema and will lead to errors or heap corruption 27292d58b7f4Sdrh ** when the database connection closes. */ 273079cf2b71Sdrh sqlite3ColumnSetExpr(pParse, p, &p->aCol[ii], 273179cf2b71Sdrh sqlite3ExprAlloc(db, TK_NULL, 0, 0)); 27327e3f135cSdrh } 2733f4658b68Sdrh }else{ 2734f4658b68Sdrh nNG++; 273581f7b372Sdrh } 27362c40a3ebSdrh } 2737f4658b68Sdrh if( nNG==0 ){ 2738f4658b68Sdrh sqlite3ErrorMsg(pParse, "must have at least one non-generated column"); 27392c40a3ebSdrh return; 274081f7b372Sdrh } 274181f7b372Sdrh } 274281f7b372Sdrh #endif 2743ffe07b2dSdrh 2744e13e9f54Sdrh /* Estimate the average row size for the table and for all implied indices */ 2745e13e9f54Sdrh estimateTableWidth(p); 2746fdaac671Sdrh for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){ 2747e13e9f54Sdrh estimateIndexWidth(pIdx); 2748fdaac671Sdrh } 2749fdaac671Sdrh 2750e3c41372Sdrh /* If not initializing, then create a record for the new table 2751346a70caSdrh ** in the schema table of the database. 2752f57b3399Sdrh ** 2753e0bc4048Sdrh ** If this is a TEMPORARY table, write the entry into the auxiliary 2754e0bc4048Sdrh ** file instead of into the main database file. 275575897234Sdrh */ 27561d85d931Sdrh if( !db->init.busy ){ 27574ff6dfa7Sdrh int n; 2758d8bc7086Sdrh Vdbe *v; 27594794f735Sdrh char *zType; /* "view" or "table" */ 27604794f735Sdrh char *zType2; /* "VIEW" or "TABLE" */ 27614794f735Sdrh char *zStmt; /* Text of the CREATE TABLE or CREATE VIEW statement */ 276275897234Sdrh 27634adee20fSdanielk1977 v = sqlite3GetVdbe(pParse); 27645969da4aSdrh if( NEVER(v==0) ) return; 2765517eb646Sdanielk1977 276666a5167bSdrh sqlite3VdbeAddOp1(v, OP_Close, 0); 2767e6efa74bSdanielk1977 27680fa991b9Sdrh /* 27690fa991b9Sdrh ** Initialize zType for the new view or table. 27704794f735Sdrh */ 2771f38524d2Sdrh if( IsOrdinaryTable(p) ){ 27724ff6dfa7Sdrh /* A regular table */ 27734794f735Sdrh zType = "table"; 27744794f735Sdrh zType2 = "TABLE"; 2775576ec6b3Sdanielk1977 #ifndef SQLITE_OMIT_VIEW 27764ff6dfa7Sdrh }else{ 27774ff6dfa7Sdrh /* A view */ 27784794f735Sdrh zType = "view"; 27794794f735Sdrh zType2 = "VIEW"; 2780576ec6b3Sdanielk1977 #endif 27814ff6dfa7Sdrh } 2782517eb646Sdanielk1977 2783517eb646Sdanielk1977 /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT 2784517eb646Sdanielk1977 ** statement to populate the new table. The root-page number for the 27850fa991b9Sdrh ** new table is in register pParse->regRoot. 2786517eb646Sdanielk1977 ** 2787517eb646Sdanielk1977 ** Once the SELECT has been coded by sqlite3Select(), it is in a 2788517eb646Sdanielk1977 ** suitable state to query for the column names and types to be used 2789517eb646Sdanielk1977 ** by the new table. 2790c00da105Sdanielk1977 ** 2791c00da105Sdanielk1977 ** A shared-cache write-lock is not required to write to the new table, 2792c00da105Sdanielk1977 ** as a schema-lock must have already been obtained to create it. Since 2793c00da105Sdanielk1977 ** a schema-lock excludes all other database users, the write-lock would 2794c00da105Sdanielk1977 ** be redundant. 2795517eb646Sdanielk1977 */ 2796517eb646Sdanielk1977 if( pSelect ){ 279792632204Sdrh SelectDest dest; /* Where the SELECT should store results */ 27989df25c47Sdrh int regYield; /* Register holding co-routine entry-point */ 27999df25c47Sdrh int addrTop; /* Top of the co-routine */ 280092632204Sdrh int regRec; /* A record to be insert into the new table */ 280192632204Sdrh int regRowid; /* Rowid of the next row to insert */ 280292632204Sdrh int addrInsLoop; /* Top of the loop for inserting rows */ 280392632204Sdrh Table *pSelTab; /* A table that describes the SELECT results */ 28041013c932Sdrh 28059df25c47Sdrh regYield = ++pParse->nMem; 280692632204Sdrh regRec = ++pParse->nMem; 280792632204Sdrh regRowid = ++pParse->nMem; 28086ab3a2ecSdanielk1977 assert(pParse->nTab==1); 28090dd5cdaeSdrh sqlite3MayAbort(pParse); 2810b7654111Sdrh sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb); 2811428c218cSdan sqlite3VdbeChangeP5(v, OPFLAG_P2ISREG); 2812517eb646Sdanielk1977 pParse->nTab = 2; 28139df25c47Sdrh addrTop = sqlite3VdbeCurrentAddr(v) + 1; 28149df25c47Sdrh sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, addrTop); 2815512795dfSdrh if( pParse->nErr ) return; 281681506b88Sdrh pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect, SQLITE_AFF_BLOB); 28175969da4aSdrh if( pSelTab==0 ) return; 2818517eb646Sdanielk1977 assert( p->aCol==0 ); 2819f5f1915dSdrh p->nCol = p->nNVCol = pSelTab->nCol; 2820517eb646Sdanielk1977 p->aCol = pSelTab->aCol; 2821517eb646Sdanielk1977 pSelTab->nCol = 0; 2822517eb646Sdanielk1977 pSelTab->aCol = 0; 28231feeaed2Sdan sqlite3DeleteTable(db, pSelTab); 2824755b0fd3Sdrh sqlite3SelectDestInit(&dest, SRT_Coroutine, regYield); 2825755b0fd3Sdrh sqlite3Select(pParse, pSelect, &dest); 28265060a67cSdrh if( pParse->nErr ) return; 2827755b0fd3Sdrh sqlite3VdbeEndCoroutine(v, regYield); 2828755b0fd3Sdrh sqlite3VdbeJumpHere(v, addrTop - 1); 28299df25c47Sdrh addrInsLoop = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm); 28309df25c47Sdrh VdbeCoverage(v); 28319df25c47Sdrh sqlite3VdbeAddOp3(v, OP_MakeRecord, dest.iSdst, dest.nSdst, regRec); 28329df25c47Sdrh sqlite3TableAffinity(v, p, 0); 28339df25c47Sdrh sqlite3VdbeAddOp2(v, OP_NewRowid, 1, regRowid); 28349df25c47Sdrh sqlite3VdbeAddOp3(v, OP_Insert, 1, regRec, regRowid); 2835076e85f5Sdrh sqlite3VdbeGoto(v, addrInsLoop); 28369df25c47Sdrh sqlite3VdbeJumpHere(v, addrInsLoop); 28379df25c47Sdrh sqlite3VdbeAddOp1(v, OP_Close, 1); 2838517eb646Sdanielk1977 } 2839517eb646Sdanielk1977 28404794f735Sdrh /* Compute the complete text of the CREATE statement */ 28414794f735Sdrh if( pSelect ){ 28421d34fdecSdrh zStmt = createTableStmt(db, p); 28434794f735Sdrh }else{ 28448ea30bfcSdrh Token *pEnd2 = tabOpts ? &pParse->sLastToken : pEnd; 28458ea30bfcSdrh n = (int)(pEnd2->z - pParse->sNameToken.z); 28468ea30bfcSdrh if( pEnd2->z[0]!=';' ) n += pEnd2->n; 28471e536953Sdanielk1977 zStmt = sqlite3MPrintf(db, 28481e536953Sdanielk1977 "CREATE %s %.*s", zType2, n, pParse->sNameToken.z 28491e536953Sdanielk1977 ); 28504794f735Sdrh } 28514794f735Sdrh 28524794f735Sdrh /* A slot for the record has already been allocated in the 2853346a70caSdrh ** schema table. We just need to update that slot with all 28540fa991b9Sdrh ** the information we've collected. 28554794f735Sdrh */ 28564794f735Sdrh sqlite3NestedParse(pParse, 2857346a70caSdrh "UPDATE %Q." DFLT_SCHEMA_TABLE 2858b7654111Sdrh " SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q" 2859b7654111Sdrh " WHERE rowid=#%d", 2860346a70caSdrh db->aDb[iDb].zDbSName, 28614794f735Sdrh zType, 28624794f735Sdrh p->zName, 28634794f735Sdrh p->zName, 2864b7654111Sdrh pParse->regRoot, 2865b7654111Sdrh zStmt, 2866b7654111Sdrh pParse->regRowid 28674794f735Sdrh ); 2868633e6d57Sdrh sqlite3DbFree(db, zStmt); 28699cbf3425Sdrh sqlite3ChangeCookie(pParse, iDb); 28702958a4e6Sdrh 28712958a4e6Sdrh #ifndef SQLITE_OMIT_AUTOINCREMENT 28722958a4e6Sdrh /* Check to see if we need to create an sqlite_sequence table for 28732958a4e6Sdrh ** keeping track of autoincrement keys. 28742958a4e6Sdrh */ 2875755ed41fSdan if( (p->tabFlags & TF_Autoincrement)!=0 && !IN_SPECIAL_PARSE ){ 2876da184236Sdanielk1977 Db *pDb = &db->aDb[iDb]; 28772120608eSdrh assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); 2878da184236Sdanielk1977 if( pDb->pSchema->pSeqTab==0 ){ 28792958a4e6Sdrh sqlite3NestedParse(pParse, 2880f3388144Sdrh "CREATE TABLE %Q.sqlite_sequence(name,seq)", 288169c33826Sdrh pDb->zDbSName 28822958a4e6Sdrh ); 28832958a4e6Sdrh } 28842958a4e6Sdrh } 28852958a4e6Sdrh #endif 28864794f735Sdrh 28874794f735Sdrh /* Reparse everything to update our internal data structures */ 28885d9c9da6Sdrh sqlite3VdbeAddParseSchemaOp(v, iDb, 28896a5a13dfSdan sqlite3MPrintf(db, "tbl_name='%q' AND type!='trigger'", p->zName),0); 289075897234Sdrh } 289117e9e29dSdrh 289217e9e29dSdrh /* Add the table to the in-memory representation of the database. 289317e9e29dSdrh */ 28948af73d41Sdrh if( db->init.busy ){ 289517e9e29dSdrh Table *pOld; 2896e501b89aSdanielk1977 Schema *pSchema = p->pSchema; 28972120608eSdrh assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); 28981bb89e9cSdrh assert( HasRowid(p) || p->iPKey<0 ); 2899acbcb7e0Sdrh pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName, p); 290017e9e29dSdrh if( pOld ){ 290117e9e29dSdrh assert( p==pOld ); /* Malloc must have failed inside HashInsert() */ 29024a642b60Sdrh sqlite3OomFault(db); 29035969da4aSdrh return; 290417e9e29dSdrh } 290517e9e29dSdrh pParse->pNewTable = 0; 29068257aa8dSdrh db->mDbFlags |= DBFLAG_SchemaChange; 2907d4b64699Sdan 2908d4b64699Sdan /* If this is the magic sqlite_sequence table used by autoincrement, 2909d4b64699Sdan ** then record a pointer to this table in the main database structure 2910d4b64699Sdan ** so that INSERT can find the table easily. */ 2911d4b64699Sdan assert( !pParse->nested ); 2912d4b64699Sdan #ifndef SQLITE_OMIT_AUTOINCREMENT 2913d4b64699Sdan if( strcmp(p->zName, "sqlite_sequence")==0 ){ 2914d4b64699Sdan assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); 2915d4b64699Sdan p->pSchema->pSeqTab = p; 2916d4b64699Sdan } 2917d4b64699Sdan #endif 2918578277c2Sdan } 291919a8e7e8Sdanielk1977 292019a8e7e8Sdanielk1977 #ifndef SQLITE_OMIT_ALTERTABLE 2921f38524d2Sdrh if( !pSelect && IsOrdinaryTable(p) ){ 2922578277c2Sdan assert( pCons && pEnd ); 2923bab45c64Sdanielk1977 if( pCons->z==0 ){ 29245969da4aSdrh pCons = pEnd; 2925bab45c64Sdanielk1977 } 2926f38524d2Sdrh p->u.tab.addColOffset = 13 + (int)(pCons->z - pParse->sNameToken.z); 292719a8e7e8Sdanielk1977 } 292819a8e7e8Sdanielk1977 #endif 292917e9e29dSdrh } 293075897234Sdrh 2931b7f9164eSdrh #ifndef SQLITE_OMIT_VIEW 293275897234Sdrh /* 2933a76b5dfcSdrh ** The parser calls this routine in order to create a new VIEW 2934a76b5dfcSdrh */ 29354adee20fSdanielk1977 void sqlite3CreateView( 2936a76b5dfcSdrh Parse *pParse, /* The parsing context */ 2937a76b5dfcSdrh Token *pBegin, /* The CREATE token that begins the statement */ 293848dec7e2Sdanielk1977 Token *pName1, /* The token that holds the name of the view */ 293948dec7e2Sdanielk1977 Token *pName2, /* The token that holds the name of the view */ 29408981b904Sdrh ExprList *pCNames, /* Optional list of view column names */ 29416276c1cbSdrh Select *pSelect, /* A SELECT statement that will become the new view */ 2942fdd48a76Sdrh int isTemp, /* TRUE for a TEMPORARY view */ 2943fdd48a76Sdrh int noErr /* Suppress error messages if VIEW already exists */ 2944a76b5dfcSdrh ){ 2945a76b5dfcSdrh Table *p; 29464b59ab5eSdrh int n; 2947b7916a78Sdrh const char *z; 29484b59ab5eSdrh Token sEnd; 2949f26e09c8Sdrh DbFixer sFix; 295088caeac7Sdrh Token *pName = 0; 2951da184236Sdanielk1977 int iDb; 295217435752Sdrh sqlite3 *db = pParse->db; 2953a76b5dfcSdrh 29547c3d64f1Sdrh if( pParse->nVar>0 ){ 29557c3d64f1Sdrh sqlite3ErrorMsg(pParse, "parameters are not allowed in views"); 295632498f13Sdrh goto create_view_fail; 29577c3d64f1Sdrh } 2958fdd48a76Sdrh sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr); 2959a76b5dfcSdrh p = pParse->pNewTable; 29608981b904Sdrh if( p==0 || pParse->nErr ) goto create_view_fail; 29616e5020e8Sdrh 29626e5020e8Sdrh /* Legacy versions of SQLite allowed the use of the magic "rowid" column 29636e5020e8Sdrh ** on a view, even though views do not have rowids. The following flag 29646e5020e8Sdrh ** setting fixes this problem. But the fix can be disabled by compiling 29656e5020e8Sdrh ** with -DSQLITE_ALLOW_ROWID_IN_VIEW in case there are legacy apps that 29666e5020e8Sdrh ** depend upon the old buggy behavior. */ 29676e5020e8Sdrh #ifndef SQLITE_ALLOW_ROWID_IN_VIEW 2968a6c54defSdrh p->tabFlags |= TF_NoVisibleRowid; 29696e5020e8Sdrh #endif 29706e5020e8Sdrh 2971ef2cb63eSdanielk1977 sqlite3TwoPartName(pParse, pName1, pName2, &pName); 297217435752Sdrh iDb = sqlite3SchemaToIndex(db, p->pSchema); 2973d100f691Sdrh sqlite3FixInit(&sFix, pParse, iDb, "view", pName); 29748981b904Sdrh if( sqlite3FixSelect(&sFix, pSelect) ) goto create_view_fail; 2975174b6195Sdrh 29764b59ab5eSdrh /* Make a copy of the entire SELECT statement that defines the view. 29774b59ab5eSdrh ** This will force all the Expr.token.z values to be dynamically 29784b59ab5eSdrh ** allocated rather than point to the input string - which means that 297924b03fd0Sdanielk1977 ** they will persist after the current sqlite3_exec() call returns. 29804b59ab5eSdrh */ 298138096961Sdan pSelect->selFlags |= SF_View; 2982c9461eccSdan if( IN_RENAME_OBJECT ){ 2983f38524d2Sdrh p->u.view.pSelect = pSelect; 2984987db767Sdan pSelect = 0; 2985987db767Sdan }else{ 2986f38524d2Sdrh p->u.view.pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE); 2987987db767Sdan } 29888981b904Sdrh p->pCheck = sqlite3ExprListDup(db, pCNames, EXPRDUP_REDUCE); 2989f38524d2Sdrh p->eTabType = TABTYP_VIEW; 29908981b904Sdrh if( db->mallocFailed ) goto create_view_fail; 29914b59ab5eSdrh 29924b59ab5eSdrh /* Locate the end of the CREATE VIEW statement. Make sEnd point to 29934b59ab5eSdrh ** the end. 29944b59ab5eSdrh */ 2995a76b5dfcSdrh sEnd = pParse->sLastToken; 29966116ee4eSdrh assert( sEnd.z[0]!=0 || sEnd.n==0 ); 29978981b904Sdrh if( sEnd.z[0]!=';' ){ 2998a76b5dfcSdrh sEnd.z += sEnd.n; 2999a76b5dfcSdrh } 3000a76b5dfcSdrh sEnd.n = 0; 30011bd10f8aSdrh n = (int)(sEnd.z - pBegin->z); 30028981b904Sdrh assert( n>0 ); 3003b7916a78Sdrh z = pBegin->z; 30048981b904Sdrh while( sqlite3Isspace(z[n-1]) ){ n--; } 30054ff6dfa7Sdrh sEnd.z = &z[n-1]; 30064ff6dfa7Sdrh sEnd.n = 1; 30074b59ab5eSdrh 3008346a70caSdrh /* Use sqlite3EndTable() to add the view to the schema table */ 30095969da4aSdrh sqlite3EndTable(pParse, 0, &sEnd, 0, 0); 30108981b904Sdrh 30118981b904Sdrh create_view_fail: 30128981b904Sdrh sqlite3SelectDelete(db, pSelect); 3013e8ab40d2Sdan if( IN_RENAME_OBJECT ){ 3014e8ab40d2Sdan sqlite3RenameExprlistUnmap(pParse, pCNames); 3015e8ab40d2Sdan } 30168981b904Sdrh sqlite3ExprListDelete(db, pCNames); 3017a76b5dfcSdrh return; 3018417be79cSdrh } 3019b7f9164eSdrh #endif /* SQLITE_OMIT_VIEW */ 3020a76b5dfcSdrh 3021fe3fcbe2Sdanielk1977 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) 3022417be79cSdrh /* 3023417be79cSdrh ** The Table structure pTable is really a VIEW. Fill in the names of 3024417be79cSdrh ** the columns of the view in the pTable structure. Return the number 3025cfa5684dSjplyon ** of errors. If an error is seen leave an error message in pParse->zErrMsg. 3026417be79cSdrh */ 30274adee20fSdanielk1977 int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){ 30289b3187e1Sdrh Table *pSelTab; /* A fake table from which we get the result set */ 30299b3187e1Sdrh Select *pSel; /* Copy of the SELECT that implements the view */ 30309b3187e1Sdrh int nErr = 0; /* Number of errors encountered */ 30319b3187e1Sdrh int n; /* Temporarily holds the number of cursors assigned */ 303217435752Sdrh sqlite3 *db = pParse->db; /* Database connection for malloc errors */ 3033dc6b41edSdrh #ifndef SQLITE_OMIT_VIRTUALTABLE 3034dc6b41edSdrh int rc; 3035dc6b41edSdrh #endif 3036a0daa751Sdrh #ifndef SQLITE_OMIT_AUTHORIZATION 303732c6a48bSdrh sqlite3_xauth xAuth; /* Saved xAuth pointer */ 3038a0daa751Sdrh #endif 3039417be79cSdrh 3040417be79cSdrh assert( pTable ); 3041417be79cSdrh 3042fe3fcbe2Sdanielk1977 #ifndef SQLITE_OMIT_VIRTUALTABLE 3043*ddfec00dSdrh if( IsVirtual(pTable) ){ 3044dc6b41edSdrh db->nSchemaLock++; 3045dc6b41edSdrh rc = sqlite3VtabCallConnect(pParse, pTable); 3046dc6b41edSdrh db->nSchemaLock--; 3047*ddfec00dSdrh return rc; 3048fe3fcbe2Sdanielk1977 } 3049fe3fcbe2Sdanielk1977 #endif 3050fe3fcbe2Sdanielk1977 3051fe3fcbe2Sdanielk1977 #ifndef SQLITE_OMIT_VIEW 3052417be79cSdrh /* A positive nCol means the columns names for this view are 3053417be79cSdrh ** already known. 3054417be79cSdrh */ 3055417be79cSdrh if( pTable->nCol>0 ) return 0; 3056417be79cSdrh 3057417be79cSdrh /* A negative nCol is a special marker meaning that we are currently 3058417be79cSdrh ** trying to compute the column names. If we enter this routine with 3059417be79cSdrh ** a negative nCol, it means two or more views form a loop, like this: 3060417be79cSdrh ** 3061417be79cSdrh ** CREATE VIEW one AS SELECT * FROM two; 3062417be79cSdrh ** CREATE VIEW two AS SELECT * FROM one; 30633b167c75Sdrh ** 3064768578eeSdrh ** Actually, the error above is now caught prior to reaching this point. 3065768578eeSdrh ** But the following test is still important as it does come up 3066768578eeSdrh ** in the following: 3067768578eeSdrh ** 3068768578eeSdrh ** CREATE TABLE main.ex1(a); 3069768578eeSdrh ** CREATE TEMP VIEW ex1 AS SELECT a FROM ex1; 3070768578eeSdrh ** SELECT * FROM temp.ex1; 3071417be79cSdrh */ 3072417be79cSdrh if( pTable->nCol<0 ){ 30734adee20fSdanielk1977 sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName); 3074417be79cSdrh return 1; 3075417be79cSdrh } 307685c23c61Sdrh assert( pTable->nCol>=0 ); 3077417be79cSdrh 3078417be79cSdrh /* If we get this far, it means we need to compute the table names. 30799b3187e1Sdrh ** Note that the call to sqlite3ResultSetOfSelect() will expand any 30809b3187e1Sdrh ** "*" elements in the results set of the view and will assign cursors 30819b3187e1Sdrh ** to the elements of the FROM clause. But we do not want these changes 30829b3187e1Sdrh ** to be permanent. So the computation is done on a copy of the SELECT 30839b3187e1Sdrh ** statement that defines the view. 3084417be79cSdrh */ 3085f38524d2Sdrh assert( IsView(pTable) ); 3086f38524d2Sdrh pSel = sqlite3SelectDup(db, pTable->u.view.pSelect, 0); 3087261919ccSdanielk1977 if( pSel ){ 30880208337cSdan u8 eParseMode = pParse->eParseMode; 30890208337cSdan pParse->eParseMode = PARSE_MODE_NORMAL; 30909b3187e1Sdrh n = pParse->nTab; 30919b3187e1Sdrh sqlite3SrcListAssignCursors(pParse, pSel->pSrc); 3092417be79cSdrh pTable->nCol = -1; 309331f69626Sdrh DisableLookaside; 3094db2d286bSdanielk1977 #ifndef SQLITE_OMIT_AUTHORIZATION 3095a6d0ffc3Sdrh xAuth = db->xAuth; 3096a6d0ffc3Sdrh db->xAuth = 0; 309796fb16eeSdrh pSelTab = sqlite3ResultSetOfSelect(pParse, pSel, SQLITE_AFF_NONE); 3098a6d0ffc3Sdrh db->xAuth = xAuth; 3099db2d286bSdanielk1977 #else 310096fb16eeSdrh pSelTab = sqlite3ResultSetOfSelect(pParse, pSel, SQLITE_AFF_NONE); 3101db2d286bSdanielk1977 #endif 31029b3187e1Sdrh pParse->nTab = n; 31035d59102aSdan if( pSelTab==0 ){ 31045d59102aSdan pTable->nCol = 0; 31055d59102aSdan nErr++; 31065d59102aSdan }else if( pTable->pCheck ){ 3107ed06a131Sdrh /* CREATE VIEW name(arglist) AS ... 3108ed06a131Sdrh ** The names of the columns in the table are taken from 3109ed06a131Sdrh ** arglist which is stored in pTable->pCheck. The pCheck field 3110ed06a131Sdrh ** normally holds CHECK constraints on an ordinary table, but for 3111ed06a131Sdrh ** a VIEW it holds the list of column names. 3112ed06a131Sdrh */ 3113ed06a131Sdrh sqlite3ColumnsFromExprList(pParse, pTable->pCheck, 3114ed06a131Sdrh &pTable->nCol, &pTable->aCol); 3115ed06a131Sdrh if( db->mallocFailed==0 31164c983b2fSdrh && pParse->nErr==0 3117ed06a131Sdrh && pTable->nCol==pSel->pEList->nExpr 3118ed06a131Sdrh ){ 311996fb16eeSdrh sqlite3SelectAddColumnTypeAndCollation(pParse, pTable, pSel, 312096fb16eeSdrh SQLITE_AFF_NONE); 3121ed06a131Sdrh } 31225d59102aSdan }else{ 3123ed06a131Sdrh /* CREATE VIEW name AS... without an argument list. Construct 3124ed06a131Sdrh ** the column names from the SELECT statement that defines the view. 3125ed06a131Sdrh */ 3126417be79cSdrh assert( pTable->aCol==0 ); 312703836614Sdrh pTable->nCol = pSelTab->nCol; 3128417be79cSdrh pTable->aCol = pSelTab->aCol; 31293dc864b5Sdan pTable->tabFlags |= (pSelTab->tabFlags & COLFLAG_NOINSERT); 3130417be79cSdrh pSelTab->nCol = 0; 3131417be79cSdrh pSelTab->aCol = 0; 31322120608eSdrh assert( sqlite3SchemaMutexHeld(db, 0, pTable->pSchema) ); 3133417be79cSdrh } 313403836614Sdrh pTable->nNVCol = pTable->nCol; 3135e8da01c1Sdrh sqlite3DeleteTable(db, pSelTab); 3136633e6d57Sdrh sqlite3SelectDelete(db, pSel); 313731f69626Sdrh EnableLookaside; 31380208337cSdan pParse->eParseMode = eParseMode; 3139261919ccSdanielk1977 } else { 3140261919ccSdanielk1977 nErr++; 3141261919ccSdanielk1977 } 31428981b904Sdrh pTable->pSchema->schemaFlags |= DB_UnresetViews; 314377f3f402Sdan if( db->mallocFailed ){ 314477f3f402Sdan sqlite3DeleteColumnNames(db, pTable); 314577f3f402Sdan } 3146b7f9164eSdrh #endif /* SQLITE_OMIT_VIEW */ 31474b2688abSdanielk1977 return nErr; 3148fe3fcbe2Sdanielk1977 } 3149fe3fcbe2Sdanielk1977 #endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */ 3150417be79cSdrh 3151b7f9164eSdrh #ifndef SQLITE_OMIT_VIEW 3152417be79cSdrh /* 31538bf8dc92Sdrh ** Clear the column names from every VIEW in database idx. 3154417be79cSdrh */ 31559bb575fdSdrh static void sqliteViewResetAll(sqlite3 *db, int idx){ 3156417be79cSdrh HashElem *i; 31572120608eSdrh assert( sqlite3SchemaMutexHeld(db, idx, 0) ); 31588bf8dc92Sdrh if( !DbHasProperty(db, idx, DB_UnresetViews) ) return; 3159da184236Sdanielk1977 for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){ 3160417be79cSdrh Table *pTab = sqliteHashData(i); 3161f38524d2Sdrh if( IsView(pTab) ){ 316251be3873Sdrh sqlite3DeleteColumnNames(db, pTab); 3163417be79cSdrh } 3164417be79cSdrh } 31658bf8dc92Sdrh DbClearProperty(db, idx, DB_UnresetViews); 3166a76b5dfcSdrh } 3167b7f9164eSdrh #else 3168b7f9164eSdrh # define sqliteViewResetAll(A,B) 3169b7f9164eSdrh #endif /* SQLITE_OMIT_VIEW */ 3170a76b5dfcSdrh 317175897234Sdrh /* 3172a0bf2652Sdanielk1977 ** This function is called by the VDBE to adjust the internal schema 3173a0bf2652Sdanielk1977 ** used by SQLite when the btree layer moves a table root page. The 3174a0bf2652Sdanielk1977 ** root-page of a table or index in database iDb has changed from iFrom 3175a0bf2652Sdanielk1977 ** to iTo. 31766205d4a4Sdrh ** 31776205d4a4Sdrh ** Ticket #1728: The symbol table might still contain information 31786205d4a4Sdrh ** on tables and/or indices that are the process of being deleted. 31796205d4a4Sdrh ** If you are unlucky, one of those deleted indices or tables might 31806205d4a4Sdrh ** have the same rootpage number as the real table or index that is 31816205d4a4Sdrh ** being moved. So we cannot stop searching after the first match 31826205d4a4Sdrh ** because the first match might be for one of the deleted indices 31836205d4a4Sdrh ** or tables and not the table/index that is actually being moved. 31846205d4a4Sdrh ** We must continue looping until all tables and indices with 31856205d4a4Sdrh ** rootpage==iFrom have been converted to have a rootpage of iTo 31866205d4a4Sdrh ** in order to be certain that we got the right one. 3187a0bf2652Sdanielk1977 */ 3188a0bf2652Sdanielk1977 #ifndef SQLITE_OMIT_AUTOVACUUM 3189abc38158Sdrh void sqlite3RootPageMoved(sqlite3 *db, int iDb, Pgno iFrom, Pgno iTo){ 3190a0bf2652Sdanielk1977 HashElem *pElem; 3191da184236Sdanielk1977 Hash *pHash; 3192cdf011dcSdrh Db *pDb; 3193a0bf2652Sdanielk1977 3194cdf011dcSdrh assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); 3195cdf011dcSdrh pDb = &db->aDb[iDb]; 3196da184236Sdanielk1977 pHash = &pDb->pSchema->tblHash; 3197da184236Sdanielk1977 for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){ 3198a0bf2652Sdanielk1977 Table *pTab = sqliteHashData(pElem); 3199a0bf2652Sdanielk1977 if( pTab->tnum==iFrom ){ 3200a0bf2652Sdanielk1977 pTab->tnum = iTo; 3201a0bf2652Sdanielk1977 } 3202a0bf2652Sdanielk1977 } 3203da184236Sdanielk1977 pHash = &pDb->pSchema->idxHash; 3204da184236Sdanielk1977 for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){ 3205a0bf2652Sdanielk1977 Index *pIdx = sqliteHashData(pElem); 3206a0bf2652Sdanielk1977 if( pIdx->tnum==iFrom ){ 3207a0bf2652Sdanielk1977 pIdx->tnum = iTo; 3208a0bf2652Sdanielk1977 } 3209a0bf2652Sdanielk1977 } 3210a0bf2652Sdanielk1977 } 3211a0bf2652Sdanielk1977 #endif 3212a0bf2652Sdanielk1977 3213a0bf2652Sdanielk1977 /* 3214a0bf2652Sdanielk1977 ** Write code to erase the table with root-page iTable from database iDb. 32151e32bed3Sdrh ** Also write code to modify the sqlite_schema table and internal schema 3216a0bf2652Sdanielk1977 ** if a root-page of another table is moved by the btree-layer whilst 3217a0bf2652Sdanielk1977 ** erasing iTable (this can happen with an auto-vacuum database). 3218a0bf2652Sdanielk1977 */ 32194e0cff60Sdrh static void destroyRootPage(Parse *pParse, int iTable, int iDb){ 32204e0cff60Sdrh Vdbe *v = sqlite3GetVdbe(pParse); 3221b7654111Sdrh int r1 = sqlite3GetTempReg(pParse); 322219918882Sdrh if( iTable<2 ) sqlite3ErrorMsg(pParse, "corrupt schema"); 3223b7654111Sdrh sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb); 3224e0af83acSdan sqlite3MayAbort(pParse); 322540e016e4Sdrh #ifndef SQLITE_OMIT_AUTOVACUUM 3226b7654111Sdrh /* OP_Destroy stores an in integer r1. If this integer 32274e0cff60Sdrh ** is non-zero, then it is the root page number of a table moved to 32281e32bed3Sdrh ** location iTable. The following code modifies the sqlite_schema table to 32294e0cff60Sdrh ** reflect this. 32304e0cff60Sdrh ** 32310fa991b9Sdrh ** The "#NNN" in the SQL is a special constant that means whatever value 3232b74b1017Sdrh ** is in register NNN. See grammar rules associated with the TK_REGISTER 3233b74b1017Sdrh ** token for additional information. 32344e0cff60Sdrh */ 323563e3e9f8Sdanielk1977 sqlite3NestedParse(pParse, 3236346a70caSdrh "UPDATE %Q." DFLT_SCHEMA_TABLE 3237346a70caSdrh " SET rootpage=%d WHERE #%d AND rootpage=#%d", 3238346a70caSdrh pParse->db->aDb[iDb].zDbSName, iTable, r1, r1); 3239a0bf2652Sdanielk1977 #endif 3240b7654111Sdrh sqlite3ReleaseTempReg(pParse, r1); 3241a0bf2652Sdanielk1977 } 3242a0bf2652Sdanielk1977 3243a0bf2652Sdanielk1977 /* 3244a0bf2652Sdanielk1977 ** Write VDBE code to erase table pTab and all associated indices on disk. 32451e32bed3Sdrh ** Code to update the sqlite_schema tables and internal schema definitions 3246a0bf2652Sdanielk1977 ** in case a root-page belonging to another table is moved by the btree layer 3247a0bf2652Sdanielk1977 ** is also added (this can happen with an auto-vacuum database). 3248a0bf2652Sdanielk1977 */ 32494e0cff60Sdrh static void destroyTable(Parse *pParse, Table *pTab){ 3250a0bf2652Sdanielk1977 /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM 3251a0bf2652Sdanielk1977 ** is not defined), then it is important to call OP_Destroy on the 3252a0bf2652Sdanielk1977 ** table and index root-pages in order, starting with the numerically 3253a0bf2652Sdanielk1977 ** largest root-page number. This guarantees that none of the root-pages 3254a0bf2652Sdanielk1977 ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the 3255a0bf2652Sdanielk1977 ** following were coded: 3256a0bf2652Sdanielk1977 ** 3257a0bf2652Sdanielk1977 ** OP_Destroy 4 0 3258a0bf2652Sdanielk1977 ** ... 3259a0bf2652Sdanielk1977 ** OP_Destroy 5 0 3260a0bf2652Sdanielk1977 ** 3261a0bf2652Sdanielk1977 ** and root page 5 happened to be the largest root-page number in the 3262a0bf2652Sdanielk1977 ** database, then root page 5 would be moved to page 4 by the 3263a0bf2652Sdanielk1977 ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit 3264a0bf2652Sdanielk1977 ** a free-list page. 3265a0bf2652Sdanielk1977 */ 3266abc38158Sdrh Pgno iTab = pTab->tnum; 32678deae5adSdrh Pgno iDestroyed = 0; 3268a0bf2652Sdanielk1977 3269a0bf2652Sdanielk1977 while( 1 ){ 3270a0bf2652Sdanielk1977 Index *pIdx; 32718deae5adSdrh Pgno iLargest = 0; 3272a0bf2652Sdanielk1977 3273a0bf2652Sdanielk1977 if( iDestroyed==0 || iTab<iDestroyed ){ 3274a0bf2652Sdanielk1977 iLargest = iTab; 3275a0bf2652Sdanielk1977 } 3276a0bf2652Sdanielk1977 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ 3277abc38158Sdrh Pgno iIdx = pIdx->tnum; 3278da184236Sdanielk1977 assert( pIdx->pSchema==pTab->pSchema ); 3279a0bf2652Sdanielk1977 if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){ 3280a0bf2652Sdanielk1977 iLargest = iIdx; 3281a0bf2652Sdanielk1977 } 3282a0bf2652Sdanielk1977 } 3283da184236Sdanielk1977 if( iLargest==0 ){ 3284da184236Sdanielk1977 return; 3285da184236Sdanielk1977 }else{ 3286da184236Sdanielk1977 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema); 32875a05be1bSdrh assert( iDb>=0 && iDb<pParse->db->nDb ); 3288da184236Sdanielk1977 destroyRootPage(pParse, iLargest, iDb); 3289a0bf2652Sdanielk1977 iDestroyed = iLargest; 3290a0bf2652Sdanielk1977 } 3291da184236Sdanielk1977 } 3292a0bf2652Sdanielk1977 } 3293a0bf2652Sdanielk1977 3294a0bf2652Sdanielk1977 /* 329574e7c8f5Sdrh ** Remove entries from the sqlite_statN tables (for N in (1,2,3)) 3296a5ae4c33Sdrh ** after a DROP INDEX or DROP TABLE command. 3297a5ae4c33Sdrh */ 3298a5ae4c33Sdrh static void sqlite3ClearStatTables( 3299a5ae4c33Sdrh Parse *pParse, /* The parsing context */ 3300a5ae4c33Sdrh int iDb, /* The database number */ 3301a5ae4c33Sdrh const char *zType, /* "idx" or "tbl" */ 3302a5ae4c33Sdrh const char *zName /* Name of index or table */ 3303a5ae4c33Sdrh ){ 3304a5ae4c33Sdrh int i; 330569c33826Sdrh const char *zDbName = pParse->db->aDb[iDb].zDbSName; 3306f52bb8d3Sdan for(i=1; i<=4; i++){ 330774e7c8f5Sdrh char zTab[24]; 330874e7c8f5Sdrh sqlite3_snprintf(sizeof(zTab),zTab,"sqlite_stat%d",i); 330974e7c8f5Sdrh if( sqlite3FindTable(pParse->db, zTab, zDbName) ){ 3310a5ae4c33Sdrh sqlite3NestedParse(pParse, 3311a5ae4c33Sdrh "DELETE FROM %Q.%s WHERE %s=%Q", 331274e7c8f5Sdrh zDbName, zTab, zType, zName 3313a5ae4c33Sdrh ); 3314a5ae4c33Sdrh } 3315a5ae4c33Sdrh } 3316a5ae4c33Sdrh } 3317a5ae4c33Sdrh 3318a5ae4c33Sdrh /* 3319faacf17cSdrh ** Generate code to drop a table. 3320faacf17cSdrh */ 3321faacf17cSdrh void sqlite3CodeDropTable(Parse *pParse, Table *pTab, int iDb, int isView){ 3322faacf17cSdrh Vdbe *v; 3323faacf17cSdrh sqlite3 *db = pParse->db; 3324faacf17cSdrh Trigger *pTrigger; 3325faacf17cSdrh Db *pDb = &db->aDb[iDb]; 3326faacf17cSdrh 3327faacf17cSdrh v = sqlite3GetVdbe(pParse); 3328faacf17cSdrh assert( v!=0 ); 3329faacf17cSdrh sqlite3BeginWriteOperation(pParse, 1, iDb); 3330faacf17cSdrh 3331faacf17cSdrh #ifndef SQLITE_OMIT_VIRTUALTABLE 3332faacf17cSdrh if( IsVirtual(pTab) ){ 3333faacf17cSdrh sqlite3VdbeAddOp0(v, OP_VBegin); 3334faacf17cSdrh } 3335faacf17cSdrh #endif 3336faacf17cSdrh 3337faacf17cSdrh /* Drop all triggers associated with the table being dropped. Code 33381e32bed3Sdrh ** is generated to remove entries from sqlite_schema and/or 33391e32bed3Sdrh ** sqlite_temp_schema if required. 3340faacf17cSdrh */ 3341faacf17cSdrh pTrigger = sqlite3TriggerList(pParse, pTab); 3342faacf17cSdrh while( pTrigger ){ 3343faacf17cSdrh assert( pTrigger->pSchema==pTab->pSchema || 3344faacf17cSdrh pTrigger->pSchema==db->aDb[1].pSchema ); 3345faacf17cSdrh sqlite3DropTriggerPtr(pParse, pTrigger); 3346faacf17cSdrh pTrigger = pTrigger->pNext; 3347faacf17cSdrh } 3348faacf17cSdrh 3349faacf17cSdrh #ifndef SQLITE_OMIT_AUTOINCREMENT 3350faacf17cSdrh /* Remove any entries of the sqlite_sequence table associated with 3351faacf17cSdrh ** the table being dropped. This is done before the table is dropped 3352faacf17cSdrh ** at the btree level, in case the sqlite_sequence table needs to 3353faacf17cSdrh ** move as a result of the drop (can happen in auto-vacuum mode). 3354faacf17cSdrh */ 3355faacf17cSdrh if( pTab->tabFlags & TF_Autoincrement ){ 3356faacf17cSdrh sqlite3NestedParse(pParse, 3357faacf17cSdrh "DELETE FROM %Q.sqlite_sequence WHERE name=%Q", 335869c33826Sdrh pDb->zDbSName, pTab->zName 3359faacf17cSdrh ); 3360faacf17cSdrh } 3361faacf17cSdrh #endif 3362faacf17cSdrh 3363346a70caSdrh /* Drop all entries in the schema table that refer to the 3364067b92baSdrh ** table. The program name loops through the schema table and deletes 3365faacf17cSdrh ** every row that refers to a table of the same name as the one being 336648864df9Smistachkin ** dropped. Triggers are handled separately because a trigger can be 3367faacf17cSdrh ** created in the temp database that refers to a table in another 3368faacf17cSdrh ** database. 3369faacf17cSdrh */ 3370faacf17cSdrh sqlite3NestedParse(pParse, 3371346a70caSdrh "DELETE FROM %Q." DFLT_SCHEMA_TABLE 3372346a70caSdrh " WHERE tbl_name=%Q and type!='trigger'", 3373346a70caSdrh pDb->zDbSName, pTab->zName); 3374faacf17cSdrh if( !isView && !IsVirtual(pTab) ){ 3375faacf17cSdrh destroyTable(pParse, pTab); 3376faacf17cSdrh } 3377faacf17cSdrh 3378faacf17cSdrh /* Remove the table entry from SQLite's internal schema and modify 3379faacf17cSdrh ** the schema cookie. 3380faacf17cSdrh */ 3381faacf17cSdrh if( IsVirtual(pTab) ){ 3382faacf17cSdrh sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0); 33831d4b1640Sdan sqlite3MayAbort(pParse); 3384faacf17cSdrh } 3385faacf17cSdrh sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0); 3386faacf17cSdrh sqlite3ChangeCookie(pParse, iDb); 3387faacf17cSdrh sqliteViewResetAll(db, iDb); 3388faacf17cSdrh } 3389faacf17cSdrh 3390faacf17cSdrh /* 3391070ae3beSdrh ** Return TRUE if shadow tables should be read-only in the current 3392070ae3beSdrh ** context. 3393070ae3beSdrh */ 3394070ae3beSdrh int sqlite3ReadOnlyShadowTables(sqlite3 *db){ 3395070ae3beSdrh #ifndef SQLITE_OMIT_VIRTUALTABLE 3396070ae3beSdrh if( (db->flags & SQLITE_Defensive)!=0 3397070ae3beSdrh && db->pVtabCtx==0 3398070ae3beSdrh && db->nVdbeExec==0 339973983658Sdan && !sqlite3VtabInSync(db) 3400070ae3beSdrh ){ 3401070ae3beSdrh return 1; 3402070ae3beSdrh } 3403070ae3beSdrh #endif 3404070ae3beSdrh return 0; 3405070ae3beSdrh } 3406070ae3beSdrh 3407070ae3beSdrh /* 3408d0c51d1aSdrh ** Return true if it is not allowed to drop the given table 3409d0c51d1aSdrh */ 3410070ae3beSdrh static int tableMayNotBeDropped(sqlite3 *db, Table *pTab){ 3411d0c51d1aSdrh if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){ 3412d0c51d1aSdrh if( sqlite3StrNICmp(pTab->zName+7, "stat", 4)==0 ) return 0; 3413d0c51d1aSdrh if( sqlite3StrNICmp(pTab->zName+7, "parameters", 10)==0 ) return 0; 3414d0c51d1aSdrh return 1; 3415d0c51d1aSdrh } 3416070ae3beSdrh if( (pTab->tabFlags & TF_Shadow)!=0 && sqlite3ReadOnlyShadowTables(db) ){ 3417070ae3beSdrh return 1; 3418d0c51d1aSdrh } 3419d0c51d1aSdrh return 0; 3420d0c51d1aSdrh } 3421d0c51d1aSdrh 3422d0c51d1aSdrh /* 342375897234Sdrh ** This routine is called to do the work of a DROP TABLE statement. 3424d9b0257aSdrh ** pName is the name of the table to be dropped. 342575897234Sdrh */ 3426a073384fSdrh void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){ 3427a8858103Sdanielk1977 Table *pTab; 342875897234Sdrh Vdbe *v; 34299bb575fdSdrh sqlite3 *db = pParse->db; 3430d24cc427Sdrh int iDb; 343175897234Sdrh 34328af73d41Sdrh if( db->mallocFailed ){ 34336f7adc8aSdrh goto exit_drop_table; 34346f7adc8aSdrh } 34358af73d41Sdrh assert( pParse->nErr==0 ); 3436a8858103Sdanielk1977 assert( pName->nSrc==1 ); 343775209969Sdrh if( sqlite3ReadSchema(pParse) ) goto exit_drop_table; 3438a7564663Sdrh if( noErr ) db->suppressErr++; 34394d249e61Sdrh assert( isView==0 || isView==LOCATE_VIEW ); 344041fb5cd1Sdan pTab = sqlite3LocateTableItem(pParse, isView, &pName->a[0]); 3441a7564663Sdrh if( noErr ) db->suppressErr--; 3442a8858103Sdanielk1977 3443a073384fSdrh if( pTab==0 ){ 344431da7be9Sdrh if( noErr ){ 344531da7be9Sdrh sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase); 344631da7be9Sdrh sqlite3ForceNotReadOnly(pParse); 344731da7be9Sdrh } 3448a073384fSdrh goto exit_drop_table; 3449a073384fSdrh } 3450da184236Sdanielk1977 iDb = sqlite3SchemaToIndex(db, pTab->pSchema); 3451e22a334bSdrh assert( iDb>=0 && iDb<db->nDb ); 3452b5258c3dSdanielk1977 3453b5258c3dSdanielk1977 /* If pTab is a virtual table, call ViewGetColumnNames() to ensure 3454b5258c3dSdanielk1977 ** it is initialized. 3455b5258c3dSdanielk1977 */ 3456b5258c3dSdanielk1977 if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){ 3457b5258c3dSdanielk1977 goto exit_drop_table; 3458b5258c3dSdanielk1977 } 3459e5f9c644Sdrh #ifndef SQLITE_OMIT_AUTHORIZATION 3460e5f9c644Sdrh { 3461e5f9c644Sdrh int code; 3462da184236Sdanielk1977 const char *zTab = SCHEMA_TABLE(iDb); 346369c33826Sdrh const char *zDb = db->aDb[iDb].zDbSName; 3464f1a381e7Sdanielk1977 const char *zArg2 = 0; 34654adee20fSdanielk1977 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){ 3466a8858103Sdanielk1977 goto exit_drop_table; 3467e22a334bSdrh } 3468e5f9c644Sdrh if( isView ){ 346953c0f748Sdanielk1977 if( !OMIT_TEMPDB && iDb==1 ){ 3470e5f9c644Sdrh code = SQLITE_DROP_TEMP_VIEW; 3471e5f9c644Sdrh }else{ 3472e5f9c644Sdrh code = SQLITE_DROP_VIEW; 3473e5f9c644Sdrh } 34744b2688abSdanielk1977 #ifndef SQLITE_OMIT_VIRTUALTABLE 3475f1a381e7Sdanielk1977 }else if( IsVirtual(pTab) ){ 3476f1a381e7Sdanielk1977 code = SQLITE_DROP_VTABLE; 3477595a523aSdanielk1977 zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName; 34784b2688abSdanielk1977 #endif 3479e5f9c644Sdrh }else{ 348053c0f748Sdanielk1977 if( !OMIT_TEMPDB && iDb==1 ){ 3481e5f9c644Sdrh code = SQLITE_DROP_TEMP_TABLE; 3482e5f9c644Sdrh }else{ 3483e5f9c644Sdrh code = SQLITE_DROP_TABLE; 3484e5f9c644Sdrh } 3485e5f9c644Sdrh } 3486f1a381e7Sdanielk1977 if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){ 3487a8858103Sdanielk1977 goto exit_drop_table; 3488e5f9c644Sdrh } 3489a8858103Sdanielk1977 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){ 3490a8858103Sdanielk1977 goto exit_drop_table; 349177ad4e41Sdrh } 3492e5f9c644Sdrh } 3493e5f9c644Sdrh #endif 3494070ae3beSdrh if( tableMayNotBeDropped(db, pTab) ){ 3495a8858103Sdanielk1977 sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName); 3496a8858103Sdanielk1977 goto exit_drop_table; 349775897234Sdrh } 3498576ec6b3Sdanielk1977 3499576ec6b3Sdanielk1977 #ifndef SQLITE_OMIT_VIEW 3500576ec6b3Sdanielk1977 /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used 3501576ec6b3Sdanielk1977 ** on a table. 3502576ec6b3Sdanielk1977 */ 3503f38524d2Sdrh if( isView && !IsView(pTab) ){ 3504a8858103Sdanielk1977 sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName); 3505a8858103Sdanielk1977 goto exit_drop_table; 35064ff6dfa7Sdrh } 3507f38524d2Sdrh if( !isView && IsView(pTab) ){ 3508a8858103Sdanielk1977 sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName); 3509a8858103Sdanielk1977 goto exit_drop_table; 35104ff6dfa7Sdrh } 3511576ec6b3Sdanielk1977 #endif 351275897234Sdrh 3513067b92baSdrh /* Generate code to remove the table from the schema table 35141ccde15dSdrh ** on disk. 35151ccde15dSdrh */ 35164adee20fSdanielk1977 v = sqlite3GetVdbe(pParse); 351775897234Sdrh if( v ){ 351877658e2fSdrh sqlite3BeginWriteOperation(pParse, 1, iDb); 35190fc2da3fSmistachkin if( !isView ){ 3520a5ae4c33Sdrh sqlite3ClearStatTables(pParse, iDb, "tbl", pTab->zName); 3521e0bc4048Sdrh sqlite3FkDropTable(pParse, pName, pTab); 35220fc2da3fSmistachkin } 3523faacf17cSdrh sqlite3CodeDropTable(pParse, pTab, iDb, isView); 35244ff6dfa7Sdrh } 35252958a4e6Sdrh 3526a8858103Sdanielk1977 exit_drop_table: 3527633e6d57Sdrh sqlite3SrcListDelete(db, pName); 352875897234Sdrh } 352975897234Sdrh 353075897234Sdrh /* 3531c2eef3b3Sdrh ** This routine is called to create a new foreign key on the table 3532c2eef3b3Sdrh ** currently under construction. pFromCol determines which columns 3533c2eef3b3Sdrh ** in the current table point to the foreign key. If pFromCol==0 then 3534c2eef3b3Sdrh ** connect the key to the last column inserted. pTo is the name of 3535bd50a926Sdrh ** the table referred to (a.k.a the "parent" table). pToCol is a list 3536bd50a926Sdrh ** of tables in the parent pTo table. flags contains all 3537c2eef3b3Sdrh ** information about the conflict resolution algorithms specified 3538c2eef3b3Sdrh ** in the ON DELETE, ON UPDATE and ON INSERT clauses. 3539c2eef3b3Sdrh ** 3540c2eef3b3Sdrh ** An FKey structure is created and added to the table currently 3541e61922a6Sdrh ** under construction in the pParse->pNewTable field. 3542c2eef3b3Sdrh ** 3543c2eef3b3Sdrh ** The foreign key is set for IMMEDIATE processing. A subsequent call 35444adee20fSdanielk1977 ** to sqlite3DeferForeignKey() might change this to DEFERRED. 3545c2eef3b3Sdrh */ 35464adee20fSdanielk1977 void sqlite3CreateForeignKey( 3547c2eef3b3Sdrh Parse *pParse, /* Parsing context */ 35480202b29eSdanielk1977 ExprList *pFromCol, /* Columns in this table that point to other table */ 3549c2eef3b3Sdrh Token *pTo, /* Name of the other table */ 35500202b29eSdanielk1977 ExprList *pToCol, /* Columns in the other table */ 3551c2eef3b3Sdrh int flags /* Conflict resolution algorithms. */ 3552c2eef3b3Sdrh ){ 35531857693dSdanielk1977 sqlite3 *db = pParse->db; 3554b7f9164eSdrh #ifndef SQLITE_OMIT_FOREIGN_KEY 355540e016e4Sdrh FKey *pFKey = 0; 35561da40a38Sdan FKey *pNextTo; 3557c2eef3b3Sdrh Table *p = pParse->pNewTable; 3558c2eef3b3Sdrh int nByte; 3559c2eef3b3Sdrh int i; 3560c2eef3b3Sdrh int nCol; 3561c2eef3b3Sdrh char *z; 3562c2eef3b3Sdrh 3563c2eef3b3Sdrh assert( pTo!=0 ); 35648af73d41Sdrh if( p==0 || IN_DECLARE_VTAB ) goto fk_end; 3565c2eef3b3Sdrh if( pFromCol==0 ){ 3566c2eef3b3Sdrh int iCol = p->nCol-1; 3567d3001711Sdrh if( NEVER(iCol<0) ) goto fk_end; 35680202b29eSdanielk1977 if( pToCol && pToCol->nExpr!=1 ){ 35694adee20fSdanielk1977 sqlite3ErrorMsg(pParse, "foreign key on %s" 3570f7a9e1acSdrh " should reference only one column of table %T", 3571cf9d36d1Sdrh p->aCol[iCol].zCnName, pTo); 3572c2eef3b3Sdrh goto fk_end; 3573c2eef3b3Sdrh } 3574c2eef3b3Sdrh nCol = 1; 35750202b29eSdanielk1977 }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){ 35764adee20fSdanielk1977 sqlite3ErrorMsg(pParse, 3577c2eef3b3Sdrh "number of columns in foreign key does not match the number of " 3578f7a9e1acSdrh "columns in the referenced table"); 3579c2eef3b3Sdrh goto fk_end; 3580c2eef3b3Sdrh }else{ 35810202b29eSdanielk1977 nCol = pFromCol->nExpr; 3582c2eef3b3Sdrh } 3583e61922a6Sdrh nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1; 3584c2eef3b3Sdrh if( pToCol ){ 35850202b29eSdanielk1977 for(i=0; i<pToCol->nExpr; i++){ 358641cee668Sdrh nByte += sqlite3Strlen30(pToCol->a[i].zEName) + 1; 3587c2eef3b3Sdrh } 3588c2eef3b3Sdrh } 3589633e6d57Sdrh pFKey = sqlite3DbMallocZero(db, nByte ); 359017435752Sdrh if( pFKey==0 ){ 359117435752Sdrh goto fk_end; 359217435752Sdrh } 3593c2eef3b3Sdrh pFKey->pFrom = p; 359478b2fa86Sdrh assert( IsOrdinaryTable(p) ); 3595f38524d2Sdrh pFKey->pNextFrom = p->u.tab.pFKey; 3596e61922a6Sdrh z = (char*)&pFKey->aCol[nCol]; 3597df68f6b7Sdrh pFKey->zTo = z; 3598c9461eccSdan if( IN_RENAME_OBJECT ){ 3599c9461eccSdan sqlite3RenameTokenMap(pParse, (void*)z, pTo); 3600c9461eccSdan } 3601c2eef3b3Sdrh memcpy(z, pTo->z, pTo->n); 3602c2eef3b3Sdrh z[pTo->n] = 0; 360370d9e9ccSdanielk1977 sqlite3Dequote(z); 3604c2eef3b3Sdrh z += pTo->n+1; 3605c2eef3b3Sdrh pFKey->nCol = nCol; 3606c2eef3b3Sdrh if( pFromCol==0 ){ 3607c2eef3b3Sdrh pFKey->aCol[0].iFrom = p->nCol-1; 3608c2eef3b3Sdrh }else{ 3609c2eef3b3Sdrh for(i=0; i<nCol; i++){ 3610c2eef3b3Sdrh int j; 3611c2eef3b3Sdrh for(j=0; j<p->nCol; j++){ 3612cf9d36d1Sdrh if( sqlite3StrICmp(p->aCol[j].zCnName, pFromCol->a[i].zEName)==0 ){ 3613c2eef3b3Sdrh pFKey->aCol[i].iFrom = j; 3614c2eef3b3Sdrh break; 3615c2eef3b3Sdrh } 3616c2eef3b3Sdrh } 3617c2eef3b3Sdrh if( j>=p->nCol ){ 36184adee20fSdanielk1977 sqlite3ErrorMsg(pParse, 3619f7a9e1acSdrh "unknown column \"%s\" in foreign key definition", 362041cee668Sdrh pFromCol->a[i].zEName); 3621c2eef3b3Sdrh goto fk_end; 3622c2eef3b3Sdrh } 3623c9461eccSdan if( IN_RENAME_OBJECT ){ 362441cee668Sdrh sqlite3RenameTokenRemap(pParse, &pFKey->aCol[i], pFromCol->a[i].zEName); 3625cf8f2895Sdan } 3626c2eef3b3Sdrh } 3627c2eef3b3Sdrh } 3628c2eef3b3Sdrh if( pToCol ){ 3629c2eef3b3Sdrh for(i=0; i<nCol; i++){ 363041cee668Sdrh int n = sqlite3Strlen30(pToCol->a[i].zEName); 3631c2eef3b3Sdrh pFKey->aCol[i].zCol = z; 3632c9461eccSdan if( IN_RENAME_OBJECT ){ 363341cee668Sdrh sqlite3RenameTokenRemap(pParse, z, pToCol->a[i].zEName); 36346fe7f23fSdan } 363541cee668Sdrh memcpy(z, pToCol->a[i].zEName, n); 3636c2eef3b3Sdrh z[n] = 0; 3637c2eef3b3Sdrh z += n+1; 3638c2eef3b3Sdrh } 3639c2eef3b3Sdrh } 3640c2eef3b3Sdrh pFKey->isDeferred = 0; 36418099ce6fSdan pFKey->aAction[0] = (u8)(flags & 0xff); /* ON DELETE action */ 36428099ce6fSdan pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff); /* ON UPDATE action */ 3643c2eef3b3Sdrh 36442120608eSdrh assert( sqlite3SchemaMutexHeld(db, 0, p->pSchema) ); 36451da40a38Sdan pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash, 3646acbcb7e0Sdrh pFKey->zTo, (void *)pFKey 36471da40a38Sdan ); 3648f59c5cacSdan if( pNextTo==pFKey ){ 36494a642b60Sdrh sqlite3OomFault(db); 3650f59c5cacSdan goto fk_end; 3651f59c5cacSdan } 36521da40a38Sdan if( pNextTo ){ 36531da40a38Sdan assert( pNextTo->pPrevTo==0 ); 36541da40a38Sdan pFKey->pNextTo = pNextTo; 36551da40a38Sdan pNextTo->pPrevTo = pFKey; 36561da40a38Sdan } 36571da40a38Sdan 3658c2eef3b3Sdrh /* Link the foreign key to the table as the last step. 3659c2eef3b3Sdrh */ 366078b2fa86Sdrh assert( IsOrdinaryTable(p) ); 3661f38524d2Sdrh p->u.tab.pFKey = pFKey; 3662c2eef3b3Sdrh pFKey = 0; 3663c2eef3b3Sdrh 3664c2eef3b3Sdrh fk_end: 3665633e6d57Sdrh sqlite3DbFree(db, pFKey); 3666b7f9164eSdrh #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */ 3667633e6d57Sdrh sqlite3ExprListDelete(db, pFromCol); 3668633e6d57Sdrh sqlite3ExprListDelete(db, pToCol); 3669c2eef3b3Sdrh } 3670c2eef3b3Sdrh 3671c2eef3b3Sdrh /* 3672c2eef3b3Sdrh ** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED 3673c2eef3b3Sdrh ** clause is seen as part of a foreign key definition. The isDeferred 3674c2eef3b3Sdrh ** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE. 3675c2eef3b3Sdrh ** The behavior of the most recently created foreign key is adjusted 3676c2eef3b3Sdrh ** accordingly. 3677c2eef3b3Sdrh */ 36784adee20fSdanielk1977 void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){ 3679b7f9164eSdrh #ifndef SQLITE_OMIT_FOREIGN_KEY 3680c2eef3b3Sdrh Table *pTab; 3681c2eef3b3Sdrh FKey *pFKey; 3682f38524d2Sdrh if( (pTab = pParse->pNewTable)==0 ) return; 368378b2fa86Sdrh if( NEVER(!IsOrdinaryTable(pTab)) ) return; 3684f38524d2Sdrh if( (pFKey = pTab->u.tab.pFKey)==0 ) return; 36854c429839Sdrh assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */ 36861bd10f8aSdrh pFKey->isDeferred = (u8)isDeferred; 3687b7f9164eSdrh #endif 3688c2eef3b3Sdrh } 3689c2eef3b3Sdrh 3690c2eef3b3Sdrh /* 3691063336a5Sdrh ** Generate code that will erase and refill index *pIdx. This is 3692063336a5Sdrh ** used to initialize a newly created index or to recompute the 3693063336a5Sdrh ** content of an index in response to a REINDEX command. 3694063336a5Sdrh ** 3695063336a5Sdrh ** if memRootPage is not negative, it means that the index is newly 36961db639ceSdrh ** created. The register specified by memRootPage contains the 3697063336a5Sdrh ** root page number of the index. If memRootPage is negative, then 3698063336a5Sdrh ** the index already exists and must be cleared before being refilled and 3699063336a5Sdrh ** the root page number of the index is taken from pIndex->tnum. 3700063336a5Sdrh */ 3701063336a5Sdrh static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){ 3702063336a5Sdrh Table *pTab = pIndex->pTable; /* The table that is indexed */ 37036ab3a2ecSdanielk1977 int iTab = pParse->nTab++; /* Btree cursor used for pTab */ 37046ab3a2ecSdanielk1977 int iIdx = pParse->nTab++; /* Btree cursor used for pIndex */ 3705b07028f7Sdrh int iSorter; /* Cursor opened by OpenSorter (if in use) */ 3706063336a5Sdrh int addr1; /* Address of top of loop */ 37075134d135Sdan int addr2; /* Address to jump to for next iteration */ 3708abc38158Sdrh Pgno tnum; /* Root page of index */ 3709b2b9d3d7Sdrh int iPartIdxLabel; /* Jump to this label to skip a row */ 3710063336a5Sdrh Vdbe *v; /* Generate code into this virtual machine */ 3711b3bf556eSdanielk1977 KeyInfo *pKey; /* KeyInfo for index */ 371260ec914cSpeter.d.reid int regRecord; /* Register holding assembled index record */ 371317435752Sdrh sqlite3 *db = pParse->db; /* The database connection */ 371417435752Sdrh int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema); 3715063336a5Sdrh 37161d54df88Sdanielk1977 #ifndef SQLITE_OMIT_AUTHORIZATION 37171d54df88Sdanielk1977 if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0, 371869c33826Sdrh db->aDb[iDb].zDbSName ) ){ 37191d54df88Sdanielk1977 return; 37201d54df88Sdanielk1977 } 37211d54df88Sdanielk1977 #endif 37221d54df88Sdanielk1977 3723c00da105Sdanielk1977 /* Require a write-lock on the table to perform this operation */ 3724c00da105Sdanielk1977 sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName); 3725c00da105Sdanielk1977 3726063336a5Sdrh v = sqlite3GetVdbe(pParse); 3727063336a5Sdrh if( v==0 ) return; 3728063336a5Sdrh if( memRootPage>=0 ){ 3729abc38158Sdrh tnum = (Pgno)memRootPage; 3730063336a5Sdrh }else{ 3731063336a5Sdrh tnum = pIndex->tnum; 3732063336a5Sdrh } 37332ec2fb22Sdrh pKey = sqlite3KeyInfoOfIndex(pParse, pIndex); 373460de73e8Sdrh assert( pKey!=0 || db->mallocFailed || pParse->nErr ); 3735a20fde64Sdan 3736689ab897Sdan /* Open the sorter cursor if we are to use one. */ 3737689ab897Sdan iSorter = pParse->nTab++; 3738fad9f9a8Sdan sqlite3VdbeAddOp4(v, OP_SorterOpen, iSorter, 0, pIndex->nKeyCol, (char*) 37392ec2fb22Sdrh sqlite3KeyInfoRef(pKey), P4_KEYINFO); 3740a20fde64Sdan 3741a20fde64Sdan /* Open the table. Loop through all rows of the table, inserting index 3742a20fde64Sdan ** records into the sorter. */ 3743c00da105Sdanielk1977 sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead); 3744688852abSdrh addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0); VdbeCoverage(v); 37452d401ab8Sdrh regRecord = sqlite3GetTempReg(pParse); 37464031bafaSdrh sqlite3MultiWrite(pParse); 3747689ab897Sdan 37481c2c0b77Sdrh sqlite3GenerateIndexKey(pParse,pIndex,iTab,regRecord,0,&iPartIdxLabel,0,0); 37495134d135Sdan sqlite3VdbeAddOp2(v, OP_SorterInsert, iSorter, regRecord); 375087744513Sdrh sqlite3ResolvePartIdxLabel(pParse, iPartIdxLabel); 3751688852abSdrh sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1); VdbeCoverage(v); 3752a20fde64Sdan sqlite3VdbeJumpHere(v, addr1); 37534415628aSdrh if( memRootPage<0 ) sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb); 3754abc38158Sdrh sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, (int)tnum, iDb, 37552ec2fb22Sdrh (char *)pKey, P4_KEYINFO); 37564415628aSdrh sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR|((memRootPage>=0)?OPFLAG_P2ISREG:0)); 37574415628aSdrh 3758688852abSdrh addr1 = sqlite3VdbeAddOp2(v, OP_SorterSort, iSorter, 0); VdbeCoverage(v); 375960de73e8Sdrh if( IsUniqueIndex(pIndex) ){ 37604031bafaSdrh int j2 = sqlite3VdbeGoto(v, 1); 37615134d135Sdan addr2 = sqlite3VdbeCurrentAddr(v); 37624031bafaSdrh sqlite3VdbeVerifyAbortable(v, OE_Abort); 37631153c7b2Sdrh sqlite3VdbeAddOp4Int(v, OP_SorterCompare, iSorter, j2, regRecord, 3764ac50232dSdrh pIndex->nKeyCol); VdbeCoverage(v); 3765f9c8ce3cSdrh sqlite3UniqueConstraint(pParse, OE_Abort, pIndex); 37664031bafaSdrh sqlite3VdbeJumpHere(v, j2); 37675134d135Sdan }else{ 37687ed6c068Sdan /* Most CREATE INDEX and REINDEX statements that are not UNIQUE can not 37697ed6c068Sdan ** abort. The exception is if one of the indexed expressions contains a 37707ed6c068Sdan ** user function that throws an exception when it is evaluated. But the 37717ed6c068Sdan ** overhead of adding a statement journal to a CREATE INDEX statement is 37727ed6c068Sdan ** very small (since most of the pages written do not contain content that 37737ed6c068Sdan ** needs to be restored if the statement aborts), so we call 37747ed6c068Sdan ** sqlite3MayAbort() for all CREATE INDEX statements. */ 3775ef14abbfSdan sqlite3MayAbort(pParse); 37765134d135Sdan addr2 = sqlite3VdbeCurrentAddr(v); 3777689ab897Sdan } 37786cf4a7dfSdrh sqlite3VdbeAddOp3(v, OP_SorterData, iSorter, regRecord, iIdx); 3779bf9ff256Sdrh if( !pIndex->bAscKeyBug ){ 3780bf9ff256Sdrh /* This OP_SeekEnd opcode makes index insert for a REINDEX go much 3781bf9ff256Sdrh ** faster by avoiding unnecessary seeks. But the optimization does 3782bf9ff256Sdrh ** not work for UNIQUE constraint indexes on WITHOUT ROWID tables 3783bf9ff256Sdrh ** with DESC primary keys, since those indexes have there keys in 3784bf9ff256Sdrh ** a different order from the main table. 3785bf9ff256Sdrh ** See ticket: https://www.sqlite.org/src/info/bba7b69f9849b5bf 3786bf9ff256Sdrh */ 378786b40dfdSdrh sqlite3VdbeAddOp1(v, OP_SeekEnd, iIdx); 3788bf9ff256Sdrh } 37899b4eaebcSdrh sqlite3VdbeAddOp2(v, OP_IdxInsert, iIdx, regRecord); 3790ca892a72Sdrh sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT); 37912d401ab8Sdrh sqlite3ReleaseTempReg(pParse, regRecord); 3792688852abSdrh sqlite3VdbeAddOp2(v, OP_SorterNext, iSorter, addr2); VdbeCoverage(v); 3793d654be80Sdrh sqlite3VdbeJumpHere(v, addr1); 3794a20fde64Sdan 379566a5167bSdrh sqlite3VdbeAddOp1(v, OP_Close, iTab); 379666a5167bSdrh sqlite3VdbeAddOp1(v, OP_Close, iIdx); 3797689ab897Sdan sqlite3VdbeAddOp1(v, OP_Close, iSorter); 3798063336a5Sdrh } 3799063336a5Sdrh 3800063336a5Sdrh /* 380177e57dfbSdrh ** Allocate heap space to hold an Index object with nCol columns. 380277e57dfbSdrh ** 380377e57dfbSdrh ** Increase the allocation size to provide an extra nExtra bytes 380477e57dfbSdrh ** of 8-byte aligned space after the Index object and return a 380577e57dfbSdrh ** pointer to this extra space in *ppExtra. 380677e57dfbSdrh */ 380777e57dfbSdrh Index *sqlite3AllocateIndexObject( 380877e57dfbSdrh sqlite3 *db, /* Database connection */ 3809bbbdc83bSdrh i16 nCol, /* Total number of columns in the index */ 381077e57dfbSdrh int nExtra, /* Number of bytes of extra space to alloc */ 381177e57dfbSdrh char **ppExtra /* Pointer to the "extra" space */ 381277e57dfbSdrh ){ 381377e57dfbSdrh Index *p; /* Allocated index object */ 381477e57dfbSdrh int nByte; /* Bytes of space for Index object + arrays */ 381577e57dfbSdrh 381677e57dfbSdrh nByte = ROUND8(sizeof(Index)) + /* Index structure */ 381777e57dfbSdrh ROUND8(sizeof(char*)*nCol) + /* Index.azColl */ 3818cfc9df76Sdan ROUND8(sizeof(LogEst)*(nCol+1) + /* Index.aiRowLogEst */ 3819bbbdc83bSdrh sizeof(i16)*nCol + /* Index.aiColumn */ 382077e57dfbSdrh sizeof(u8)*nCol); /* Index.aSortOrder */ 382177e57dfbSdrh p = sqlite3DbMallocZero(db, nByte + nExtra); 382277e57dfbSdrh if( p ){ 382377e57dfbSdrh char *pExtra = ((char*)p)+ROUND8(sizeof(Index)); 3824f19aa5faSdrh p->azColl = (const char**)pExtra; pExtra += ROUND8(sizeof(char*)*nCol); 3825cfc9df76Sdan p->aiRowLogEst = (LogEst*)pExtra; pExtra += sizeof(LogEst)*(nCol+1); 3826bbbdc83bSdrh p->aiColumn = (i16*)pExtra; pExtra += sizeof(i16)*nCol; 382777e57dfbSdrh p->aSortOrder = (u8*)pExtra; 382877e57dfbSdrh p->nColumn = nCol; 3829bbbdc83bSdrh p->nKeyCol = nCol - 1; 383077e57dfbSdrh *ppExtra = ((char*)p) + nByte; 383177e57dfbSdrh } 383277e57dfbSdrh return p; 383377e57dfbSdrh } 383477e57dfbSdrh 383577e57dfbSdrh /* 38369105fd51Sdan ** If expression list pList contains an expression that was parsed with 38379105fd51Sdan ** an explicit "NULLS FIRST" or "NULLS LAST" clause, leave an error in 38389105fd51Sdan ** pParse and return non-zero. Otherwise, return zero. 38399105fd51Sdan */ 38409105fd51Sdan int sqlite3HasExplicitNulls(Parse *pParse, ExprList *pList){ 38419105fd51Sdan if( pList ){ 38429105fd51Sdan int i; 38439105fd51Sdan for(i=0; i<pList->nExpr; i++){ 38449105fd51Sdan if( pList->a[i].bNulls ){ 38459105fd51Sdan u8 sf = pList->a[i].sortFlags; 38469105fd51Sdan sqlite3ErrorMsg(pParse, "unsupported use of NULLS %s", 38479105fd51Sdan (sf==0 || sf==3) ? "FIRST" : "LAST" 38489105fd51Sdan ); 38499105fd51Sdan return 1; 38509105fd51Sdan } 38519105fd51Sdan } 38529105fd51Sdan } 38539105fd51Sdan return 0; 38549105fd51Sdan } 38559105fd51Sdan 38569105fd51Sdan /* 385723bf66d6Sdrh ** Create a new index for an SQL table. pName1.pName2 is the name of the index 385823bf66d6Sdrh ** and pTblList is the name of the table that is to be indexed. Both will 3859adbca9cfSdrh ** be NULL for a primary key or an index that is created to satisfy a 3860adbca9cfSdrh ** UNIQUE constraint. If pTable and pIndex are NULL, use pParse->pNewTable 3861382c0247Sdrh ** as the table to be indexed. pParse->pNewTable is a table that is 3862382c0247Sdrh ** currently being constructed by a CREATE TABLE statement. 386375897234Sdrh ** 3864382c0247Sdrh ** pList is a list of columns to be indexed. pList will be NULL if this 3865382c0247Sdrh ** is a primary key or unique-constraint on the most recent column added 3866382c0247Sdrh ** to the table currently under construction. 386775897234Sdrh */ 386862340f84Sdrh void sqlite3CreateIndex( 386975897234Sdrh Parse *pParse, /* All information about this parse */ 3870cbb18d22Sdanielk1977 Token *pName1, /* First part of index name. May be NULL */ 3871cbb18d22Sdanielk1977 Token *pName2, /* Second part of index name. May be NULL */ 38720202b29eSdanielk1977 SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */ 38730202b29eSdanielk1977 ExprList *pList, /* A list of columns to be indexed */ 38749cfcf5d4Sdrh int onError, /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */ 38751c55ba09Sdrh Token *pStart, /* The CREATE token that begins this statement */ 38761fe0537eSdrh Expr *pPIWhere, /* WHERE clause for partial indices */ 38774d91a701Sdrh int sortOrder, /* Sort order of primary key when pList==NULL */ 387862340f84Sdrh int ifNotExist, /* Omit error if index already exists */ 387962340f84Sdrh u8 idxType /* The index type */ 388075897234Sdrh ){ 3881cbb18d22Sdanielk1977 Table *pTab = 0; /* Table to be indexed */ 3882d8123366Sdanielk1977 Index *pIndex = 0; /* The index to be created */ 3883fdd6e85aSdrh char *zName = 0; /* Name of the index */ 3884fdd6e85aSdrh int nName; /* Number of characters in zName */ 3885beae3194Sdrh int i, j; 3886f26e09c8Sdrh DbFixer sFix; /* For assigning database names to pTable */ 3887fdd6e85aSdrh int sortOrderMask; /* 1 to honor DESC in index. 0 to ignore. */ 38889bb575fdSdrh sqlite3 *db = pParse->db; 3889fdd6e85aSdrh Db *pDb; /* The specific table containing the indexed database */ 3890cbb18d22Sdanielk1977 int iDb; /* Index of the database that is being written */ 3891cbb18d22Sdanielk1977 Token *pName = 0; /* Unqualified name of the index to create */ 3892fdd6e85aSdrh struct ExprList_item *pListItem; /* For looping over pList */ 3893c28c4e50Sdrh int nExtra = 0; /* Space allocated for zExtra[] */ 38944415628aSdrh int nExtraCol; /* Number of extra columns needed */ 389547b927d2Sdrh char *zExtra = 0; /* Extra space after the Index object */ 38964415628aSdrh Index *pPk = 0; /* PRIMARY KEY index for WITHOUT ROWID tables */ 3897cbb18d22Sdanielk1977 389862340f84Sdrh if( db->mallocFailed || pParse->nErr>0 ){ 389962340f84Sdrh goto exit_create_index; 390062340f84Sdrh } 390162340f84Sdrh if( IN_DECLARE_VTAB && idxType!=SQLITE_IDXTYPE_PRIMARYKEY ){ 3902d3001711Sdrh goto exit_create_index; 3903d3001711Sdrh } 3904d3001711Sdrh if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){ 3905e501b89aSdanielk1977 goto exit_create_index; 3906e501b89aSdanielk1977 } 39079105fd51Sdan if( sqlite3HasExplicitNulls(pParse, pList) ){ 39089105fd51Sdan goto exit_create_index; 39099105fd51Sdan } 3910daffd0e5Sdrh 391175897234Sdrh /* 391275897234Sdrh ** Find the table that is to be indexed. Return early if not found. 391375897234Sdrh */ 3914cbb18d22Sdanielk1977 if( pTblName!=0 ){ 3915cbb18d22Sdanielk1977 3916cbb18d22Sdanielk1977 /* Use the two-part index name to determine the database 3917ef2cb63eSdanielk1977 ** to search for the table. 'Fix' the table name to this db 3918ef2cb63eSdanielk1977 ** before looking up the table. 3919cbb18d22Sdanielk1977 */ 3920cbb18d22Sdanielk1977 assert( pName1 && pName2 ); 3921ef2cb63eSdanielk1977 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName); 3922cbb18d22Sdanielk1977 if( iDb<0 ) goto exit_create_index; 3923b07028f7Sdrh assert( pName && pName->z ); 3924cbb18d22Sdanielk1977 392553c0f748Sdanielk1977 #ifndef SQLITE_OMIT_TEMPDB 3926d5578433Smistachkin /* If the index name was unqualified, check if the table 3927fe910339Sdanielk1977 ** is a temp table. If so, set the database to 1. Do not do this 3928fe910339Sdanielk1977 ** if initialising a database schema. 3929cbb18d22Sdanielk1977 */ 3930fe910339Sdanielk1977 if( !db->init.busy ){ 3931ef2cb63eSdanielk1977 pTab = sqlite3SrcListLookup(pParse, pTblName); 3932d3001711Sdrh if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){ 3933ef2cb63eSdanielk1977 iDb = 1; 3934ef2cb63eSdanielk1977 } 3935fe910339Sdanielk1977 } 393653c0f748Sdanielk1977 #endif 3937ef2cb63eSdanielk1977 3938d100f691Sdrh sqlite3FixInit(&sFix, pParse, iDb, "index", pName); 3939d100f691Sdrh if( sqlite3FixSrcList(&sFix, pTblName) ){ 394085c23c61Sdrh /* Because the parser constructs pTblName from a single identifier, 394185c23c61Sdrh ** sqlite3FixSrcList can never fail. */ 394285c23c61Sdrh assert(0); 3943cbb18d22Sdanielk1977 } 394441fb5cd1Sdan pTab = sqlite3LocateTableItem(pParse, 0, &pTblName->a[0]); 3945c31c7c1cSdrh assert( db->mallocFailed==0 || pTab==0 ); 3946c31c7c1cSdrh if( pTab==0 ) goto exit_create_index; 3947989b116aSdrh if( iDb==1 && db->aDb[iDb].pSchema!=pTab->pSchema ){ 3948989b116aSdrh sqlite3ErrorMsg(pParse, 3949989b116aSdrh "cannot create a TEMP index on non-TEMP table \"%s\"", 3950989b116aSdrh pTab->zName); 3951989b116aSdrh goto exit_create_index; 3952989b116aSdrh } 39534415628aSdrh if( !HasRowid(pTab) ) pPk = sqlite3PrimaryKeyIndex(pTab); 395475897234Sdrh }else{ 3955e3c41372Sdrh assert( pName==0 ); 3956b07028f7Sdrh assert( pStart==0 ); 395775897234Sdrh pTab = pParse->pNewTable; 3958a6370df1Sdrh if( !pTab ) goto exit_create_index; 3959da184236Sdanielk1977 iDb = sqlite3SchemaToIndex(db, pTab->pSchema); 396075897234Sdrh } 3961fdd6e85aSdrh pDb = &db->aDb[iDb]; 3962cbb18d22Sdanielk1977 3963d3001711Sdrh assert( pTab!=0 ); 3964d3001711Sdrh assert( pParse->nErr==0 ); 39650388123fSdrh if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 39663a3a03f2Sdrh && db->init.busy==0 3967346f4e26Sdrh && pTblName!=0 3968d4530979Sdrh #if SQLITE_USER_AUTHENTICATION 3969d4530979Sdrh && sqlite3UserAuthTable(pTab->zName)==0 3970d4530979Sdrh #endif 39718c2e6c5fSdrh ){ 39724adee20fSdanielk1977 sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName); 39730be9df07Sdrh goto exit_create_index; 39740be9df07Sdrh } 3975576ec6b3Sdanielk1977 #ifndef SQLITE_OMIT_VIEW 3976f38524d2Sdrh if( IsView(pTab) ){ 39774adee20fSdanielk1977 sqlite3ErrorMsg(pParse, "views may not be indexed"); 3978a76b5dfcSdrh goto exit_create_index; 3979a76b5dfcSdrh } 3980576ec6b3Sdanielk1977 #endif 39815ee9d697Sdanielk1977 #ifndef SQLITE_OMIT_VIRTUALTABLE 39825ee9d697Sdanielk1977 if( IsVirtual(pTab) ){ 39835ee9d697Sdanielk1977 sqlite3ErrorMsg(pParse, "virtual tables may not be indexed"); 39845ee9d697Sdanielk1977 goto exit_create_index; 39855ee9d697Sdanielk1977 } 39865ee9d697Sdanielk1977 #endif 398775897234Sdrh 398875897234Sdrh /* 398975897234Sdrh ** Find the name of the index. Make sure there is not already another 3990f57b3399Sdrh ** index or table with the same name. 3991f57b3399Sdrh ** 3992f57b3399Sdrh ** Exception: If we are reading the names of permanent indices from the 39931e32bed3Sdrh ** sqlite_schema table (because some other process changed the schema) and 3994f57b3399Sdrh ** one of the index names collides with the name of a temporary table or 3995d24cc427Sdrh ** index, then we will continue to process this index. 3996f57b3399Sdrh ** 3997f57b3399Sdrh ** If pName==0 it means that we are 3998adbca9cfSdrh ** dealing with a primary key or UNIQUE constraint. We have to invent our 3999adbca9cfSdrh ** own name. 400075897234Sdrh */ 4001d8123366Sdanielk1977 if( pName ){ 400217435752Sdrh zName = sqlite3NameFromToken(db, pName); 4003d8123366Sdanielk1977 if( zName==0 ) goto exit_create_index; 4004b07028f7Sdrh assert( pName->z!=0 ); 4005c5a93d4cSdrh if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName,"index",pTab->zName) ){ 4006d8123366Sdanielk1977 goto exit_create_index; 4007d8123366Sdanielk1977 } 4008c9461eccSdan if( !IN_RENAME_OBJECT ){ 4009d8123366Sdanielk1977 if( !db->init.busy ){ 4010d45a0315Sdanielk1977 if( sqlite3FindTable(db, zName, 0)!=0 ){ 4011d45a0315Sdanielk1977 sqlite3ErrorMsg(pParse, "there is already a table named %s", zName); 4012d45a0315Sdanielk1977 goto exit_create_index; 4013d45a0315Sdanielk1977 } 4014d45a0315Sdanielk1977 } 401569c33826Sdrh if( sqlite3FindIndex(db, zName, pDb->zDbSName)!=0 ){ 40164d91a701Sdrh if( !ifNotExist ){ 40174adee20fSdanielk1977 sqlite3ErrorMsg(pParse, "index %s already exists", zName); 40187687c83dSdan }else{ 40197687c83dSdan assert( !db->init.busy ); 40207687c83dSdan sqlite3CodeVerifySchema(pParse, iDb); 402131da7be9Sdrh sqlite3ForceNotReadOnly(pParse); 40224d91a701Sdrh } 402375897234Sdrh goto exit_create_index; 402475897234Sdrh } 4025cf8f2895Sdan } 4026a21c6b6fSdanielk1977 }else{ 4027adbca9cfSdrh int n; 4028adbca9cfSdrh Index *pLoop; 4029adbca9cfSdrh for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){} 4030f089aa45Sdrh zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n); 4031a1644fd8Sdanielk1977 if( zName==0 ){ 4032a1644fd8Sdanielk1977 goto exit_create_index; 4033a1644fd8Sdanielk1977 } 40340aafa9c8Sdrh 40350aafa9c8Sdrh /* Automatic index names generated from within sqlite3_declare_vtab() 40360aafa9c8Sdrh ** must have names that are distinct from normal automatic index names. 40370aafa9c8Sdrh ** The following statement converts "sqlite3_autoindex..." into 40380aafa9c8Sdrh ** "sqlite3_butoindex..." in order to make the names distinct. 40390aafa9c8Sdrh ** The "vtab_err.test" test demonstrates the need of this statement. */ 4040cf8f2895Sdan if( IN_SPECIAL_PARSE ) zName[7]++; 4041e3c41372Sdrh } 404275897234Sdrh 4043e5f9c644Sdrh /* Check for authorization to create an index. 4044e5f9c644Sdrh */ 4045e5f9c644Sdrh #ifndef SQLITE_OMIT_AUTHORIZATION 4046c9461eccSdan if( !IN_RENAME_OBJECT ){ 404769c33826Sdrh const char *zDb = pDb->zDbSName; 404853c0f748Sdanielk1977 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){ 4049e5f9c644Sdrh goto exit_create_index; 4050e5f9c644Sdrh } 4051e5f9c644Sdrh i = SQLITE_CREATE_INDEX; 405253c0f748Sdanielk1977 if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX; 40534adee20fSdanielk1977 if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){ 4054e5f9c644Sdrh goto exit_create_index; 4055e5f9c644Sdrh } 4056e22a334bSdrh } 4057e5f9c644Sdrh #endif 4058e5f9c644Sdrh 405975897234Sdrh /* If pList==0, it means this routine was called to make a primary 40601ccde15dSdrh ** key out of the last column added to the table under construction. 406175897234Sdrh ** So create a fake list to simulate this. 406275897234Sdrh */ 406375897234Sdrh if( pList==0 ){ 4064108aa00aSdrh Token prevCol; 406526e731ccSdan Column *pCol = &pTab->aCol[pTab->nCol-1]; 406626e731ccSdan pCol->colFlags |= COLFLAG_UNIQUE; 4067cf9d36d1Sdrh sqlite3TokenInit(&prevCol, pCol->zCnName); 4068108aa00aSdrh pList = sqlite3ExprListAppend(pParse, 0, 4069108aa00aSdrh sqlite3ExprAlloc(db, TK_ID, &prevCol, 0)); 407075897234Sdrh if( pList==0 ) goto exit_create_index; 4071bc622bc0Sdrh assert( pList->nExpr==1 ); 40725b32bdffSdan sqlite3ExprListSetSortOrder(pList, sortOrder, SQLITE_SO_UNDEFINED); 4073108aa00aSdrh }else{ 4074108aa00aSdrh sqlite3ExprListCheckLength(pParse, pList, "index"); 40758fe25c64Sdrh if( pParse->nErr ) goto exit_create_index; 407675897234Sdrh } 407775897234Sdrh 4078b3bf556eSdanielk1977 /* Figure out how many bytes of space are required to store explicitly 4079b3bf556eSdanielk1977 ** specified collation sequence names. 4080b3bf556eSdanielk1977 */ 4081b3bf556eSdanielk1977 for(i=0; i<pList->nExpr; i++){ 4082d3001711Sdrh Expr *pExpr = pList->a[i].pExpr; 40837d3d9daeSdrh assert( pExpr!=0 ); 40847d3d9daeSdrh if( pExpr->op==TK_COLLATE ){ 4085f9751074Sdrh assert( !ExprHasProperty(pExpr, EP_IntValue) ); 4086911ce418Sdan nExtra += (1 + sqlite3Strlen30(pExpr->u.zToken)); 4087b3bf556eSdanielk1977 } 4088d3001711Sdrh } 4089b3bf556eSdanielk1977 409075897234Sdrh /* 409175897234Sdrh ** Allocate the index structure. 409275897234Sdrh */ 4093ea678832Sdrh nName = sqlite3Strlen30(zName); 40944415628aSdrh nExtraCol = pPk ? pPk->nKeyCol : 1; 40958fe25c64Sdrh assert( pList->nExpr + nExtraCol <= 32767 /* Fits in i16 */ ); 40964415628aSdrh pIndex = sqlite3AllocateIndexObject(db, pList->nExpr + nExtraCol, 409777e57dfbSdrh nName + nExtra + 1, &zExtra); 409817435752Sdrh if( db->mallocFailed ){ 409917435752Sdrh goto exit_create_index; 410017435752Sdrh } 4101cfc9df76Sdan assert( EIGHT_BYTE_ALIGNMENT(pIndex->aiRowLogEst) ); 4102e09b84c5Sdrh assert( EIGHT_BYTE_ALIGNMENT(pIndex->azColl) ); 410377e57dfbSdrh pIndex->zName = zExtra; 410477e57dfbSdrh zExtra += nName + 1; 41055bb3eb9bSdrh memcpy(pIndex->zName, zName, nName+1); 410675897234Sdrh pIndex->pTable = pTab; 41071bd10f8aSdrh pIndex->onError = (u8)onError; 41089eade087Sdrh pIndex->uniqNotNull = onError!=OE_None; 410962340f84Sdrh pIndex->idxType = idxType; 4110da184236Sdanielk1977 pIndex->pSchema = db->aDb[iDb].pSchema; 411172ffd091Sdrh pIndex->nKeyCol = pList->nExpr; 41123780be11Sdrh if( pPIWhere ){ 41133780be11Sdrh sqlite3ResolveSelfReference(pParse, pTab, NC_PartIdx, pPIWhere, 0); 41141fe0537eSdrh pIndex->pPartIdxWhere = pPIWhere; 41151fe0537eSdrh pPIWhere = 0; 41163780be11Sdrh } 41172120608eSdrh assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); 411875897234Sdrh 4119fdd6e85aSdrh /* Check to see if we should honor DESC requests on index columns 4120fdd6e85aSdrh */ 4121da184236Sdanielk1977 if( pDb->pSchema->file_format>=4 ){ 4122fdd6e85aSdrh sortOrderMask = -1; /* Honor DESC */ 4123fdd6e85aSdrh }else{ 4124fdd6e85aSdrh sortOrderMask = 0; /* Ignore DESC */ 4125fdd6e85aSdrh } 4126fdd6e85aSdrh 41271f9ca2c8Sdrh /* Analyze the list of expressions that form the terms of the index and 41281f9ca2c8Sdrh ** report any errors. In the common case where the expression is exactly 41291f9ca2c8Sdrh ** a table column, store that column in aiColumn[]. For general expressions, 41304b92f98cSdrh ** populate pIndex->aColExpr and store XN_EXPR (-2) in aiColumn[]. 4131d3001711Sdrh ** 41321f9ca2c8Sdrh ** TODO: Issue a warning if two or more columns of the index are identical. 41331f9ca2c8Sdrh ** TODO: Issue a warning if the table primary key is used as part of the 41341f9ca2c8Sdrh ** index key. 413575897234Sdrh */ 4136cf8f2895Sdan pListItem = pList->a; 4137c9461eccSdan if( IN_RENAME_OBJECT ){ 4138cf8f2895Sdan pIndex->aColExpr = pList; 4139cf8f2895Sdan pList = 0; 4140cf8f2895Sdan } 4141cf8f2895Sdan for(i=0; i<pIndex->nKeyCol; i++, pListItem++){ 41421f9ca2c8Sdrh Expr *pCExpr; /* The i-th index expression */ 41431f9ca2c8Sdrh int requestedSortOrder; /* ASC or DESC on the i-th expression */ 4144f19aa5faSdrh const char *zColl; /* Collation sequence name */ 4145b3bf556eSdanielk1977 4146edb04ed9Sdrh sqlite3StringToId(pListItem->pExpr); 4147a514b8ebSdrh sqlite3ResolveSelfReference(pParse, pTab, NC_IdxExpr, pListItem->pExpr, 0); 4148a514b8ebSdrh if( pParse->nErr ) goto exit_create_index; 4149108aa00aSdrh pCExpr = sqlite3ExprSkipCollate(pListItem->pExpr); 4150a514b8ebSdrh if( pCExpr->op!=TK_COLUMN ){ 41511f9ca2c8Sdrh if( pTab==pParse->pNewTable ){ 41521f9ca2c8Sdrh sqlite3ErrorMsg(pParse, "expressions prohibited in PRIMARY KEY and " 41531f9ca2c8Sdrh "UNIQUE constraints"); 41541f9ca2c8Sdrh goto exit_create_index; 4155108aa00aSdrh } 41561f9ca2c8Sdrh if( pIndex->aColExpr==0 ){ 4157cf8f2895Sdan pIndex->aColExpr = pList; 4158cf8f2895Sdan pList = 0; 41591f9ca2c8Sdrh } 41604b92f98cSdrh j = XN_EXPR; 41614b92f98cSdrh pIndex->aiColumn[i] = XN_EXPR; 41628492653cSdrh pIndex->uniqNotNull = 0; 41631f9ca2c8Sdrh }else{ 4164a514b8ebSdrh j = pCExpr->iColumn; 4165bf20a35dSdrh assert( j<=0x7fff ); 41661f9ca2c8Sdrh if( j<0 ){ 41671f9ca2c8Sdrh j = pTab->iPKey; 4168c7476735Sdrh }else{ 4169c7476735Sdrh if( pTab->aCol[j].notNull==0 ){ 41701f9ca2c8Sdrh pIndex->uniqNotNull = 0; 41711f9ca2c8Sdrh } 4172c7476735Sdrh if( pTab->aCol[j].colFlags & COLFLAG_VIRTUAL ){ 4173c7476735Sdrh pIndex->bHasVCol = 1; 4174c7476735Sdrh } 4175c7476735Sdrh } 4176bbbdc83bSdrh pIndex->aiColumn[i] = (i16)j; 41771f9ca2c8Sdrh } 4178a514b8ebSdrh zColl = 0; 4179108aa00aSdrh if( pListItem->pExpr->op==TK_COLLATE ){ 4180d3001711Sdrh int nColl; 4181f9751074Sdrh assert( !ExprHasProperty(pListItem->pExpr, EP_IntValue) ); 4182911ce418Sdan zColl = pListItem->pExpr->u.zToken; 4183d3001711Sdrh nColl = sqlite3Strlen30(zColl) + 1; 4184d3001711Sdrh assert( nExtra>=nColl ); 4185d3001711Sdrh memcpy(zExtra, zColl, nColl); 4186b3bf556eSdanielk1977 zColl = zExtra; 4187d3001711Sdrh zExtra += nColl; 4188d3001711Sdrh nExtra -= nColl; 4189a514b8ebSdrh }else if( j>=0 ){ 419065b40093Sdrh zColl = sqlite3ColumnColl(&pTab->aCol[j]); 4191b3bf556eSdanielk1977 } 4192f19aa5faSdrh if( !zColl ) zColl = sqlite3StrBINARY; 4193b7f24de2Sdrh if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){ 41947cedc8d4Sdanielk1977 goto exit_create_index; 41957cedc8d4Sdanielk1977 } 4196b3bf556eSdanielk1977 pIndex->azColl[i] = zColl; 41976e11892dSdan requestedSortOrder = pListItem->sortFlags & sortOrderMask; 41981bd10f8aSdrh pIndex->aSortOrder[i] = (u8)requestedSortOrder; 41990202b29eSdanielk1977 } 42001f9ca2c8Sdrh 42011f9ca2c8Sdrh /* Append the table key to the end of the index. For WITHOUT ROWID 42021f9ca2c8Sdrh ** tables (when pPk!=0) this will be the declared PRIMARY KEY. For 42031f9ca2c8Sdrh ** normal tables (when pPk==0) this will be the rowid. 42041f9ca2c8Sdrh */ 42054415628aSdrh if( pPk ){ 42067913e41fSdrh for(j=0; j<pPk->nKeyCol; j++){ 42077913e41fSdrh int x = pPk->aiColumn[j]; 42081f9ca2c8Sdrh assert( x>=0 ); 4209f78d0f42Sdrh if( isDupColumn(pIndex, pIndex->nKeyCol, pPk, j) ){ 42107913e41fSdrh pIndex->nColumn--; 42117913e41fSdrh }else{ 4212f78d0f42Sdrh testcase( hasColumn(pIndex->aiColumn,pIndex->nKeyCol,x) ); 42137913e41fSdrh pIndex->aiColumn[i] = x; 42144415628aSdrh pIndex->azColl[i] = pPk->azColl[j]; 42154415628aSdrh pIndex->aSortOrder[i] = pPk->aSortOrder[j]; 42167913e41fSdrh i++; 42174415628aSdrh } 42187913e41fSdrh } 42197913e41fSdrh assert( i==pIndex->nColumn ); 42204415628aSdrh }else{ 42214b92f98cSdrh pIndex->aiColumn[i] = XN_ROWID; 4222f19aa5faSdrh pIndex->azColl[i] = sqlite3StrBINARY; 4223f769cd61Sdan } 4224f769cd61Sdan sqlite3DefaultRowEst(pIndex); 4225f769cd61Sdan if( pParse->pNewTable==0 ) estimateIndexWidth(pIndex); 4226f769cd61Sdan 4227e1dd0608Sdrh /* If this index contains every column of its table, then mark 4228e1dd0608Sdrh ** it as a covering index */ 4229f769cd61Sdan assert( HasRowid(pTab) 4230b9bcf7caSdrh || pTab->iPKey<0 || sqlite3TableColumnToIndex(pIndex, pTab->iPKey)>=0 ); 42311fe3ac73Sdrh recomputeColumnsNotIndexed(pIndex); 4232e1dd0608Sdrh if( pTblName!=0 && pIndex->nColumn>=pTab->nCol ){ 4233e1dd0608Sdrh pIndex->isCovering = 1; 4234e1dd0608Sdrh for(j=0; j<pTab->nCol; j++){ 4235e1dd0608Sdrh if( j==pTab->iPKey ) continue; 4236b9bcf7caSdrh if( sqlite3TableColumnToIndex(pIndex,j)>=0 ) continue; 4237e1dd0608Sdrh pIndex->isCovering = 0; 4238e1dd0608Sdrh break; 4239e1dd0608Sdrh } 4240e1dd0608Sdrh } 424175897234Sdrh 4242d8123366Sdanielk1977 if( pTab==pParse->pNewTable ){ 4243d8123366Sdanielk1977 /* This routine has been called to create an automatic index as a 4244d8123366Sdanielk1977 ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or 4245d8123366Sdanielk1977 ** a PRIMARY KEY or UNIQUE clause following the column definitions. 4246d8123366Sdanielk1977 ** i.e. one of: 4247d8123366Sdanielk1977 ** 4248d8123366Sdanielk1977 ** CREATE TABLE t(x PRIMARY KEY, y); 4249d8123366Sdanielk1977 ** CREATE TABLE t(x, y, UNIQUE(x, y)); 4250d8123366Sdanielk1977 ** 4251d8123366Sdanielk1977 ** Either way, check to see if the table already has such an index. If 4252d8123366Sdanielk1977 ** so, don't bother creating this one. This only applies to 4253d8123366Sdanielk1977 ** automatically created indices. Users can do as they wish with 4254d8123366Sdanielk1977 ** explicit indices. 4255d3001711Sdrh ** 4256d3001711Sdrh ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent 4257d3001711Sdrh ** (and thus suppressing the second one) even if they have different 4258d3001711Sdrh ** sort orders. 4259d3001711Sdrh ** 4260d3001711Sdrh ** If there are different collating sequences or if the columns of 4261d3001711Sdrh ** the constraint occur in different orders, then the constraints are 4262d3001711Sdrh ** considered distinct and both result in separate indices. 4263d8123366Sdanielk1977 */ 4264d8123366Sdanielk1977 Index *pIdx; 4265d8123366Sdanielk1977 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ 4266d8123366Sdanielk1977 int k; 42675f1d1d9cSdrh assert( IsUniqueIndex(pIdx) ); 426848dd1d8eSdrh assert( pIdx->idxType!=SQLITE_IDXTYPE_APPDEF ); 42695f1d1d9cSdrh assert( IsUniqueIndex(pIndex) ); 4270d8123366Sdanielk1977 4271bbbdc83bSdrh if( pIdx->nKeyCol!=pIndex->nKeyCol ) continue; 4272bbbdc83bSdrh for(k=0; k<pIdx->nKeyCol; k++){ 4273d3001711Sdrh const char *z1; 4274d3001711Sdrh const char *z2; 42751f9ca2c8Sdrh assert( pIdx->aiColumn[k]>=0 ); 4276d8123366Sdanielk1977 if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break; 4277d3001711Sdrh z1 = pIdx->azColl[k]; 4278d3001711Sdrh z2 = pIndex->azColl[k]; 4279c41c132cSdrh if( sqlite3StrICmp(z1, z2) ) break; 4280d8123366Sdanielk1977 } 4281bbbdc83bSdrh if( k==pIdx->nKeyCol ){ 4282f736b771Sdanielk1977 if( pIdx->onError!=pIndex->onError ){ 4283f736b771Sdanielk1977 /* This constraint creates the same index as a previous 4284f736b771Sdanielk1977 ** constraint specified somewhere in the CREATE TABLE statement. 4285f736b771Sdanielk1977 ** However the ON CONFLICT clauses are different. If both this 4286f736b771Sdanielk1977 ** constraint and the previous equivalent constraint have explicit 4287f736b771Sdanielk1977 ** ON CONFLICT clauses this is an error. Otherwise, use the 428848864df9Smistachkin ** explicitly specified behavior for the index. 4289d8123366Sdanielk1977 */ 4290f736b771Sdanielk1977 if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){ 4291f736b771Sdanielk1977 sqlite3ErrorMsg(pParse, 4292f736b771Sdanielk1977 "conflicting ON CONFLICT clauses specified", 0); 4293f736b771Sdanielk1977 } 4294f736b771Sdanielk1977 if( pIdx->onError==OE_Default ){ 4295f736b771Sdanielk1977 pIdx->onError = pIndex->onError; 4296f736b771Sdanielk1977 } 4297f736b771Sdanielk1977 } 4298273bfe9fSdrh if( idxType==SQLITE_IDXTYPE_PRIMARYKEY ) pIdx->idxType = idxType; 4299885eeb67Sdrh if( IN_RENAME_OBJECT ){ 4300885eeb67Sdrh pIndex->pNext = pParse->pNewIndex; 4301885eeb67Sdrh pParse->pNewIndex = pIndex; 4302885eeb67Sdrh pIndex = 0; 4303885eeb67Sdrh } 4304d8123366Sdanielk1977 goto exit_create_index; 4305d8123366Sdanielk1977 } 4306d8123366Sdanielk1977 } 4307d8123366Sdanielk1977 } 4308d8123366Sdanielk1977 4309c9461eccSdan if( !IN_RENAME_OBJECT ){ 4310cf8f2895Sdan 431175897234Sdrh /* Link the new Index structure to its table and to the other 4312adbca9cfSdrh ** in-memory database structures. 431375897234Sdrh */ 43147d3d9daeSdrh assert( pParse->nErr==0 ); 4315cc971738Sdrh if( db->init.busy ){ 43166d4abfbeSdrh Index *p; 4317cf8f2895Sdan assert( !IN_SPECIAL_PARSE ); 43182120608eSdrh assert( sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) ); 4319234c39dfSdrh if( pTblName!=0 ){ 43201d85d931Sdrh pIndex->tnum = db->init.newTnum; 43218d40673cSdrh if( sqlite3IndexHasDuplicateRootPage(pIndex) ){ 43228d40673cSdrh sqlite3ErrorMsg(pParse, "invalid rootpage"); 43238d40673cSdrh pParse->rc = SQLITE_CORRUPT_BKPT; 43248d40673cSdrh goto exit_create_index; 43258d40673cSdrh } 4326d78eeee1Sdrh } 4327da7a4c0fSdan p = sqlite3HashInsert(&pIndex->pSchema->idxHash, 4328da7a4c0fSdan pIndex->zName, pIndex); 4329da7a4c0fSdan if( p ){ 4330da7a4c0fSdan assert( p==pIndex ); /* Malloc must have failed */ 4331da7a4c0fSdan sqlite3OomFault(db); 4332da7a4c0fSdan goto exit_create_index; 4333da7a4c0fSdan } 4334da7a4c0fSdan db->mDbFlags |= DBFLAG_SchemaChange; 4335234c39dfSdrh } 4336d78eeee1Sdrh 43375838340bSdrh /* If this is the initial CREATE INDEX statement (or CREATE TABLE if the 43385838340bSdrh ** index is an implied index for a UNIQUE or PRIMARY KEY constraint) then 43395838340bSdrh ** emit code to allocate the index rootpage on disk and make an entry for 43401e32bed3Sdrh ** the index in the sqlite_schema table and populate the index with 43411e32bed3Sdrh ** content. But, do not do this if we are simply reading the sqlite_schema 43425838340bSdrh ** table to parse the schema, or if this index is the PRIMARY KEY index 43435838340bSdrh ** of a WITHOUT ROWID table. 434475897234Sdrh ** 43455838340bSdrh ** If pTblName==0 it means this index is generated as an implied PRIMARY KEY 43465838340bSdrh ** or UNIQUE index in a CREATE TABLE statement. Since the table 4347382c0247Sdrh ** has just been created, it contains no data and the index initialization 4348382c0247Sdrh ** step can be skipped. 434975897234Sdrh */ 43507d3d9daeSdrh else if( HasRowid(pTab) || pTblName!=0 ){ 4351adbca9cfSdrh Vdbe *v; 4352063336a5Sdrh char *zStmt; 43530a07c107Sdrh int iMem = ++pParse->nMem; 435475897234Sdrh 43554adee20fSdanielk1977 v = sqlite3GetVdbe(pParse); 435675897234Sdrh if( v==0 ) goto exit_create_index; 4357063336a5Sdrh 4358aee128dcSdrh sqlite3BeginWriteOperation(pParse, 1, iDb); 4359c5b73585Sdan 4360c5b73585Sdan /* Create the rootpage for the index using CreateIndex. But before 4361c5b73585Sdan ** doing so, code a Noop instruction and store its address in 4362c5b73585Sdan ** Index.tnum. This is required in case this index is actually a 4363c5b73585Sdan ** PRIMARY KEY and the table is actually a WITHOUT ROWID table. In 4364c5b73585Sdan ** that case the convertToWithoutRowidTable() routine will replace 4365c5b73585Sdan ** the Noop with a Goto to jump over the VDBE code generated below. */ 4366abc38158Sdrh pIndex->tnum = (Pgno)sqlite3VdbeAddOp0(v, OP_Noop); 43670f3f7664Sdrh sqlite3VdbeAddOp3(v, OP_CreateBtree, iDb, iMem, BTREE_BLOBKEY); 4368063336a5Sdrh 4369063336a5Sdrh /* Gather the complete text of the CREATE INDEX statement into 4370063336a5Sdrh ** the zStmt variable 4371063336a5Sdrh */ 437255f66b34Sdrh assert( pName!=0 || pStart==0 ); 4373d3001711Sdrh if( pStart ){ 437477dfd5bbSdrh int n = (int)(pParse->sLastToken.z - pName->z) + pParse->sLastToken.n; 43758a9789b6Sdrh if( pName->z[n-1]==';' ) n--; 4376063336a5Sdrh /* A named index with an explicit CREATE INDEX statement */ 43771e536953Sdanielk1977 zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s", 43788a9789b6Sdrh onError==OE_None ? "" : " UNIQUE", n, pName->z); 43790202b29eSdanielk1977 }else{ 4380063336a5Sdrh /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */ 4381e497f005Sdrh /* zStmt = sqlite3MPrintf(""); */ 4382e497f005Sdrh zStmt = 0; 43830202b29eSdanielk1977 } 4384063336a5Sdrh 43851e32bed3Sdrh /* Add an entry in sqlite_schema for this index 4386063336a5Sdrh */ 4387063336a5Sdrh sqlite3NestedParse(pParse, 4388346a70caSdrh "INSERT INTO %Q." DFLT_SCHEMA_TABLE " VALUES('index',%Q,%Q,#%d,%Q);", 4389346a70caSdrh db->aDb[iDb].zDbSName, 4390063336a5Sdrh pIndex->zName, 4391063336a5Sdrh pTab->zName, 4392b7654111Sdrh iMem, 4393063336a5Sdrh zStmt 4394063336a5Sdrh ); 4395633e6d57Sdrh sqlite3DbFree(db, zStmt); 4396063336a5Sdrh 4397a21c6b6fSdanielk1977 /* Fill the index with data and reparse the schema. Code an OP_Expire 4398a21c6b6fSdanielk1977 ** to invalidate all pre-compiled statements. 4399063336a5Sdrh */ 4400cbb18d22Sdanielk1977 if( pTblName ){ 4401063336a5Sdrh sqlite3RefillIndex(pParse, pIndex, iMem); 44029cbf3425Sdrh sqlite3ChangeCookie(pParse, iDb); 44035d9c9da6Sdrh sqlite3VdbeAddParseSchemaOp(v, iDb, 44046a5a13dfSdan sqlite3MPrintf(db, "name='%q' AND type='index'", pIndex->zName), 0); 4405ba968dbfSdrh sqlite3VdbeAddOp2(v, OP_Expire, 0, 1); 440675897234Sdrh } 4407c5b73585Sdan 4408abc38158Sdrh sqlite3VdbeJumpHere(v, (int)pIndex->tnum); 440975897234Sdrh } 4410cf8f2895Sdan } 4411234c39dfSdrh if( db->init.busy || pTblName==0 ){ 4412d8123366Sdanielk1977 pIndex->pNext = pTab->pIndex; 4413d8123366Sdanielk1977 pTab->pIndex = pIndex; 4414d8123366Sdanielk1977 pIndex = 0; 4415234c39dfSdrh } 4416c9461eccSdan else if( IN_RENAME_OBJECT ){ 4417cf8f2895Sdan assert( pParse->pNewIndex==0 ); 4418cf8f2895Sdan pParse->pNewIndex = pIndex; 4419cf8f2895Sdan pIndex = 0; 4420cf8f2895Sdan } 4421d8123366Sdanielk1977 442275897234Sdrh /* Clean up before exiting */ 442375897234Sdrh exit_create_index: 4424cf8f2895Sdan if( pIndex ) sqlite3FreeIndex(db, pIndex); 442597060e5aSdrh if( pTab ){ 442697060e5aSdrh /* Ensure all REPLACE indexes on pTab are at the end of the pIndex list. 442797060e5aSdrh ** The list was already ordered when this routine was entered, so at this 442897060e5aSdrh ** point at most a single index (the newly added index) will be out of 442997060e5aSdrh ** order. So we have to reorder at most one index. */ 4430e85e1da0Sdrh Index **ppFrom; 4431d35bdd6cSdrh Index *pThis; 4432d35bdd6cSdrh for(ppFrom=&pTab->pIndex; (pThis = *ppFrom)!=0; ppFrom=&pThis->pNext){ 4433d35bdd6cSdrh Index *pNext; 4434d35bdd6cSdrh if( pThis->onError!=OE_Replace ) continue; 4435d35bdd6cSdrh while( (pNext = pThis->pNext)!=0 && pNext->onError!=OE_Replace ){ 4436d35bdd6cSdrh *ppFrom = pNext; 4437d35bdd6cSdrh pThis->pNext = pNext->pNext; 4438d35bdd6cSdrh pNext->pNext = pThis; 4439d35bdd6cSdrh ppFrom = &pNext->pNext; 4440d35bdd6cSdrh } 4441d35bdd6cSdrh break; 4442d35bdd6cSdrh } 444397060e5aSdrh #ifdef SQLITE_DEBUG 444497060e5aSdrh /* Verify that all REPLACE indexes really are now at the end 444597060e5aSdrh ** of the index list. In other words, no other index type ever 444697060e5aSdrh ** comes after a REPLACE index on the list. */ 444797060e5aSdrh for(pThis = pTab->pIndex; pThis; pThis=pThis->pNext){ 444897060e5aSdrh assert( pThis->onError!=OE_Replace 444997060e5aSdrh || pThis->pNext==0 445097060e5aSdrh || pThis->pNext->onError==OE_Replace ); 445197060e5aSdrh } 445297060e5aSdrh #endif 4453d35bdd6cSdrh } 44541fe0537eSdrh sqlite3ExprDelete(db, pPIWhere); 4455633e6d57Sdrh sqlite3ExprListDelete(db, pList); 4456633e6d57Sdrh sqlite3SrcListDelete(db, pTblName); 4457633e6d57Sdrh sqlite3DbFree(db, zName); 445875897234Sdrh } 445975897234Sdrh 446075897234Sdrh /* 446151147baaSdrh ** Fill the Index.aiRowEst[] array with default information - information 446291124b35Sdrh ** to be used when we have not run the ANALYZE command. 446328c4cf42Sdrh ** 446460ec914cSpeter.d.reid ** aiRowEst[0] is supposed to contain the number of elements in the index. 446528c4cf42Sdrh ** Since we do not know, guess 1 million. aiRowEst[1] is an estimate of the 446628c4cf42Sdrh ** number of rows in the table that match any particular value of the 446728c4cf42Sdrh ** first column of the index. aiRowEst[2] is an estimate of the number 4468cfc9df76Sdan ** of rows that match any particular combination of the first 2 columns 446928c4cf42Sdrh ** of the index. And so forth. It must always be the case that 447028c4cf42Sdrh * 447128c4cf42Sdrh ** aiRowEst[N]<=aiRowEst[N-1] 447228c4cf42Sdrh ** aiRowEst[N]>=1 447328c4cf42Sdrh ** 447428c4cf42Sdrh ** Apart from that, we have little to go on besides intuition as to 447528c4cf42Sdrh ** how aiRowEst[] should be initialized. The numbers generated here 447628c4cf42Sdrh ** are based on typical values found in actual indices. 447751147baaSdrh */ 447851147baaSdrh void sqlite3DefaultRowEst(Index *pIdx){ 4479264d2b97Sdan /* 10, 9, 8, 7, 6 */ 448056c65c92Sdrh static const LogEst aVal[] = { 33, 32, 30, 28, 26 }; 4481cfc9df76Sdan LogEst *a = pIdx->aiRowLogEst; 448256c65c92Sdrh LogEst x; 4483cfc9df76Sdan int nCopy = MIN(ArraySize(aVal), pIdx->nKeyCol); 448451147baaSdrh int i; 4485cfc9df76Sdan 448633bec3f5Sdrh /* Indexes with default row estimates should not have stat1 data */ 448733bec3f5Sdrh assert( !pIdx->hasStat1 ); 448833bec3f5Sdrh 4489264d2b97Sdan /* Set the first entry (number of rows in the index) to the estimated 44908dc570b6Sdrh ** number of rows in the table, or half the number of rows in the table 449156c65c92Sdrh ** for a partial index. 449256c65c92Sdrh ** 449356c65c92Sdrh ** 2020-05-27: If some of the stat data is coming from the sqlite_stat1 449456c65c92Sdrh ** table but other parts we are having to guess at, then do not let the 449556c65c92Sdrh ** estimated number of rows in the table be less than 1000 (LogEst 99). 449656c65c92Sdrh ** Failure to do this can cause the indexes for which we do not have 44978c1fbe81Sdrh ** stat1 data to be ignored by the query planner. 449856c65c92Sdrh */ 449956c65c92Sdrh x = pIdx->pTable->nRowLogEst; 450056c65c92Sdrh assert( 99==sqlite3LogEst(1000) ); 450156c65c92Sdrh if( x<99 ){ 450256c65c92Sdrh pIdx->pTable->nRowLogEst = x = 99; 450356c65c92Sdrh } 45045f086ddeSdrh if( pIdx->pPartIdxWhere!=0 ){ x -= 10; assert( 10==sqlite3LogEst(2) ); } 450556c65c92Sdrh a[0] = x; 4506264d2b97Sdan 4507264d2b97Sdan /* Estimate that a[1] is 10, a[2] is 9, a[3] is 8, a[4] is 7, a[5] is 4508264d2b97Sdan ** 6 and each subsequent value (if any) is 5. */ 4509cfc9df76Sdan memcpy(&a[1], aVal, nCopy*sizeof(LogEst)); 4510264d2b97Sdan for(i=nCopy+1; i<=pIdx->nKeyCol; i++){ 4511264d2b97Sdan a[i] = 23; assert( 23==sqlite3LogEst(5) ); 451228c4cf42Sdrh } 4513264d2b97Sdan 4514264d2b97Sdan assert( 0==sqlite3LogEst(1) ); 45155f1d1d9cSdrh if( IsUniqueIndex(pIdx) ) a[pIdx->nKeyCol] = 0; 451651147baaSdrh } 451751147baaSdrh 451851147baaSdrh /* 451974e24cd0Sdrh ** This routine will drop an existing named index. This routine 452074e24cd0Sdrh ** implements the DROP INDEX statement. 452175897234Sdrh */ 45224d91a701Sdrh void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){ 452375897234Sdrh Index *pIndex; 452475897234Sdrh Vdbe *v; 45259bb575fdSdrh sqlite3 *db = pParse->db; 4526da184236Sdanielk1977 int iDb; 452775897234Sdrh 45288af73d41Sdrh assert( pParse->nErr==0 ); /* Never called with prior errors */ 45298af73d41Sdrh if( db->mallocFailed ){ 4530d5d56523Sdanielk1977 goto exit_drop_index; 4531d5d56523Sdanielk1977 } 4532d24cc427Sdrh assert( pName->nSrc==1 ); 4533d5d56523Sdanielk1977 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){ 4534d5d56523Sdanielk1977 goto exit_drop_index; 4535d5d56523Sdanielk1977 } 45364adee20fSdanielk1977 pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase); 453775897234Sdrh if( pIndex==0 ){ 45384d91a701Sdrh if( !ifExists ){ 4539a979993bSdrh sqlite3ErrorMsg(pParse, "no such index: %S", pName->a); 454057966753Sdan }else{ 454157966753Sdan sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase); 454231da7be9Sdrh sqlite3ForceNotReadOnly(pParse); 45434d91a701Sdrh } 4544a6ecd338Sdrh pParse->checkSchema = 1; 4545d24cc427Sdrh goto exit_drop_index; 454675897234Sdrh } 454748dd1d8eSdrh if( pIndex->idxType!=SQLITE_IDXTYPE_APPDEF ){ 45484adee20fSdanielk1977 sqlite3ErrorMsg(pParse, "index associated with UNIQUE " 4549485b39b4Sdrh "or PRIMARY KEY constraint cannot be dropped", 0); 4550d24cc427Sdrh goto exit_drop_index; 4551d24cc427Sdrh } 4552da184236Sdanielk1977 iDb = sqlite3SchemaToIndex(db, pIndex->pSchema); 4553e5f9c644Sdrh #ifndef SQLITE_OMIT_AUTHORIZATION 4554e5f9c644Sdrh { 4555e5f9c644Sdrh int code = SQLITE_DROP_INDEX; 4556e5f9c644Sdrh Table *pTab = pIndex->pTable; 455769c33826Sdrh const char *zDb = db->aDb[iDb].zDbSName; 4558da184236Sdanielk1977 const char *zTab = SCHEMA_TABLE(iDb); 45594adee20fSdanielk1977 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){ 4560d24cc427Sdrh goto exit_drop_index; 4561ed6c8671Sdrh } 456293fd5420Sdrh if( !OMIT_TEMPDB && iDb==1 ) code = SQLITE_DROP_TEMP_INDEX; 45634adee20fSdanielk1977 if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){ 4564d24cc427Sdrh goto exit_drop_index; 4565e5f9c644Sdrh } 4566e5f9c644Sdrh } 4567e5f9c644Sdrh #endif 456875897234Sdrh 4569067b92baSdrh /* Generate code to remove the index and from the schema table */ 45704adee20fSdanielk1977 v = sqlite3GetVdbe(pParse); 457175897234Sdrh if( v ){ 457277658e2fSdrh sqlite3BeginWriteOperation(pParse, 1, iDb); 4573b17131a0Sdrh sqlite3NestedParse(pParse, 4574346a70caSdrh "DELETE FROM %Q." DFLT_SCHEMA_TABLE " WHERE name=%Q AND type='index'", 4575346a70caSdrh db->aDb[iDb].zDbSName, pIndex->zName 4576b17131a0Sdrh ); 4577a5ae4c33Sdrh sqlite3ClearStatTables(pParse, iDb, "idx", pIndex->zName); 45789cbf3425Sdrh sqlite3ChangeCookie(pParse, iDb); 4579b17131a0Sdrh destroyRootPage(pParse, pIndex->tnum, iDb); 458066a5167bSdrh sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0); 458175897234Sdrh } 458275897234Sdrh 4583d24cc427Sdrh exit_drop_index: 4584633e6d57Sdrh sqlite3SrcListDelete(db, pName); 458575897234Sdrh } 458675897234Sdrh 458775897234Sdrh /* 4588cf643729Sdrh ** pArray is a pointer to an array of objects. Each object in the 45899ace112cSdan ** array is szEntry bytes in size. This routine uses sqlite3DbRealloc() 45909ace112cSdan ** to extend the array so that there is space for a new object at the end. 459113449892Sdrh ** 45929ace112cSdan ** When this function is called, *pnEntry contains the current size of 45939ace112cSdan ** the array (in entries - so the allocation is ((*pnEntry) * szEntry) bytes 45949ace112cSdan ** in total). 459513449892Sdrh ** 45969ace112cSdan ** If the realloc() is successful (i.e. if no OOM condition occurs), the 45979ace112cSdan ** space allocated for the new object is zeroed, *pnEntry updated to 45989ace112cSdan ** reflect the new size of the array and a pointer to the new allocation 45999ace112cSdan ** returned. *pIdx is set to the index of the new array entry in this case. 460013449892Sdrh ** 46019ace112cSdan ** Otherwise, if the realloc() fails, *pIdx is set to -1, *pnEntry remains 46029ace112cSdan ** unchanged and a copy of pArray returned. 460313449892Sdrh */ 4604cf643729Sdrh void *sqlite3ArrayAllocate( 460517435752Sdrh sqlite3 *db, /* Connection to notify of malloc failures */ 4606cf643729Sdrh void *pArray, /* Array of objects. Might be reallocated */ 4607cf643729Sdrh int szEntry, /* Size of each object in the array */ 4608cf643729Sdrh int *pnEntry, /* Number of objects currently in use */ 4609cf643729Sdrh int *pIdx /* Write the index of a new slot here */ 4610cf643729Sdrh ){ 4611cf643729Sdrh char *z; 4612f6ad201aSdrh sqlite3_int64 n = *pIdx = *pnEntry; 46136c535158Sdrh if( (n & (n-1))==0 ){ 46140aa3231fSdrh sqlite3_int64 sz = (n==0) ? 1 : 2*n; 46156c535158Sdrh void *pNew = sqlite3DbRealloc(db, pArray, sz*szEntry); 461613449892Sdrh if( pNew==0 ){ 4617cf643729Sdrh *pIdx = -1; 4618cf643729Sdrh return pArray; 461913449892Sdrh } 4620cf643729Sdrh pArray = pNew; 462113449892Sdrh } 4622cf643729Sdrh z = (char*)pArray; 46236c535158Sdrh memset(&z[n * szEntry], 0, szEntry); 4624cf643729Sdrh ++*pnEntry; 4625cf643729Sdrh return pArray; 462613449892Sdrh } 462713449892Sdrh 462813449892Sdrh /* 462975897234Sdrh ** Append a new element to the given IdList. Create a new IdList if 463075897234Sdrh ** need be. 4631daffd0e5Sdrh ** 4632daffd0e5Sdrh ** A new IdList is returned, or NULL if malloc() fails. 463375897234Sdrh */ 46345496d6a2Sdan IdList *sqlite3IdListAppend(Parse *pParse, IdList *pList, Token *pToken){ 46355496d6a2Sdan sqlite3 *db = pParse->db; 463613449892Sdrh int i; 463775897234Sdrh if( pList==0 ){ 463817435752Sdrh pList = sqlite3DbMallocZero(db, sizeof(IdList) ); 463975897234Sdrh if( pList==0 ) return 0; 464075897234Sdrh } 4641cf643729Sdrh pList->a = sqlite3ArrayAllocate( 464217435752Sdrh db, 4643cf643729Sdrh pList->a, 4644cf643729Sdrh sizeof(pList->a[0]), 4645cf643729Sdrh &pList->nId, 4646cf643729Sdrh &i 4647cf643729Sdrh ); 464813449892Sdrh if( i<0 ){ 4649633e6d57Sdrh sqlite3IdListDelete(db, pList); 4650daffd0e5Sdrh return 0; 465175897234Sdrh } 465217435752Sdrh pList->a[i].zName = sqlite3NameFromToken(db, pToken); 4653c9461eccSdan if( IN_RENAME_OBJECT && pList->a[i].zName ){ 465407e95233Sdan sqlite3RenameTokenMap(pParse, (void*)pList->a[i].zName, pToken); 46555496d6a2Sdan } 465675897234Sdrh return pList; 465775897234Sdrh } 465875897234Sdrh 465975897234Sdrh /* 4660fe05af87Sdrh ** Delete an IdList. 4661fe05af87Sdrh */ 4662633e6d57Sdrh void sqlite3IdListDelete(sqlite3 *db, IdList *pList){ 4663fe05af87Sdrh int i; 4664fe05af87Sdrh if( pList==0 ) return; 4665fe05af87Sdrh for(i=0; i<pList->nId; i++){ 4666633e6d57Sdrh sqlite3DbFree(db, pList->a[i].zName); 4667fe05af87Sdrh } 4668633e6d57Sdrh sqlite3DbFree(db, pList->a); 4669dbd6a7dcSdrh sqlite3DbFreeNN(db, pList); 4670fe05af87Sdrh } 4671fe05af87Sdrh 4672fe05af87Sdrh /* 4673fe05af87Sdrh ** Return the index in pList of the identifier named zId. Return -1 4674fe05af87Sdrh ** if not found. 4675fe05af87Sdrh */ 4676fe05af87Sdrh int sqlite3IdListIndex(IdList *pList, const char *zName){ 4677fe05af87Sdrh int i; 4678fe05af87Sdrh if( pList==0 ) return -1; 4679fe05af87Sdrh for(i=0; i<pList->nId; i++){ 4680fe05af87Sdrh if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i; 4681fe05af87Sdrh } 4682fe05af87Sdrh return -1; 4683fe05af87Sdrh } 4684fe05af87Sdrh 4685fe05af87Sdrh /* 46860ad7aa81Sdrh ** Maximum size of a SrcList object. 46870ad7aa81Sdrh ** The SrcList object is used to represent the FROM clause of a 46880ad7aa81Sdrh ** SELECT statement, and the query planner cannot deal with more 46890ad7aa81Sdrh ** than 64 tables in a join. So any value larger than 64 here 46900ad7aa81Sdrh ** is sufficient for most uses. Smaller values, like say 10, are 46910ad7aa81Sdrh ** appropriate for small and memory-limited applications. 46920ad7aa81Sdrh */ 46930ad7aa81Sdrh #ifndef SQLITE_MAX_SRCLIST 46940ad7aa81Sdrh # define SQLITE_MAX_SRCLIST 200 46950ad7aa81Sdrh #endif 46960ad7aa81Sdrh 46970ad7aa81Sdrh /* 4698a78c22c4Sdrh ** Expand the space allocated for the given SrcList object by 4699a78c22c4Sdrh ** creating nExtra new slots beginning at iStart. iStart is zero based. 4700a78c22c4Sdrh ** New slots are zeroed. 4701a78c22c4Sdrh ** 4702a78c22c4Sdrh ** For example, suppose a SrcList initially contains two entries: A,B. 4703a78c22c4Sdrh ** To append 3 new entries onto the end, do this: 4704a78c22c4Sdrh ** 4705a78c22c4Sdrh ** sqlite3SrcListEnlarge(db, pSrclist, 3, 2); 4706a78c22c4Sdrh ** 4707a78c22c4Sdrh ** After the call above it would contain: A, B, nil, nil, nil. 4708a78c22c4Sdrh ** If the iStart argument had been 1 instead of 2, then the result 4709a78c22c4Sdrh ** would have been: A, nil, nil, nil, B. To prepend the new slots, 4710a78c22c4Sdrh ** the iStart value would be 0. The result then would 4711a78c22c4Sdrh ** be: nil, nil, nil, A, B. 4712a78c22c4Sdrh ** 471329c992cbSdrh ** If a memory allocation fails or the SrcList becomes too large, leave 471429c992cbSdrh ** the original SrcList unchanged, return NULL, and leave an error message 471529c992cbSdrh ** in pParse. 4716a78c22c4Sdrh */ 4717a78c22c4Sdrh SrcList *sqlite3SrcListEnlarge( 471829c992cbSdrh Parse *pParse, /* Parsing context into which errors are reported */ 4719a78c22c4Sdrh SrcList *pSrc, /* The SrcList to be enlarged */ 4720a78c22c4Sdrh int nExtra, /* Number of new slots to add to pSrc->a[] */ 4721a78c22c4Sdrh int iStart /* Index in pSrc->a[] of first new slot */ 4722a78c22c4Sdrh ){ 4723a78c22c4Sdrh int i; 4724a78c22c4Sdrh 4725a78c22c4Sdrh /* Sanity checking on calling parameters */ 4726a78c22c4Sdrh assert( iStart>=0 ); 4727a78c22c4Sdrh assert( nExtra>=1 ); 47288af73d41Sdrh assert( pSrc!=0 ); 47298af73d41Sdrh assert( iStart<=pSrc->nSrc ); 4730a78c22c4Sdrh 4731a78c22c4Sdrh /* Allocate additional space if needed */ 4732fc5717ccSdrh if( (u32)pSrc->nSrc+nExtra>pSrc->nAlloc ){ 4733a78c22c4Sdrh SrcList *pNew; 47340aa3231fSdrh sqlite3_int64 nAlloc = 2*(sqlite3_int64)pSrc->nSrc+nExtra; 473529c992cbSdrh sqlite3 *db = pParse->db; 47360ad7aa81Sdrh 47370ad7aa81Sdrh if( pSrc->nSrc+nExtra>=SQLITE_MAX_SRCLIST ){ 473829c992cbSdrh sqlite3ErrorMsg(pParse, "too many FROM clause terms, max: %d", 473929c992cbSdrh SQLITE_MAX_SRCLIST); 474029c992cbSdrh return 0; 47410ad7aa81Sdrh } 47420ad7aa81Sdrh if( nAlloc>SQLITE_MAX_SRCLIST ) nAlloc = SQLITE_MAX_SRCLIST; 4743a78c22c4Sdrh pNew = sqlite3DbRealloc(db, pSrc, 4744a78c22c4Sdrh sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) ); 4745a78c22c4Sdrh if( pNew==0 ){ 4746a78c22c4Sdrh assert( db->mallocFailed ); 474729c992cbSdrh return 0; 4748a78c22c4Sdrh } 4749a78c22c4Sdrh pSrc = pNew; 4750d0ee3a1eSdrh pSrc->nAlloc = nAlloc; 4751a78c22c4Sdrh } 4752a78c22c4Sdrh 4753a78c22c4Sdrh /* Move existing slots that come after the newly inserted slots 4754a78c22c4Sdrh ** out of the way */ 4755a78c22c4Sdrh for(i=pSrc->nSrc-1; i>=iStart; i--){ 4756a78c22c4Sdrh pSrc->a[i+nExtra] = pSrc->a[i]; 4757a78c22c4Sdrh } 47586d1626ebSdrh pSrc->nSrc += nExtra; 4759a78c22c4Sdrh 4760a78c22c4Sdrh /* Zero the newly allocated slots */ 4761a78c22c4Sdrh memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra); 4762a78c22c4Sdrh for(i=iStart; i<iStart+nExtra; i++){ 4763a78c22c4Sdrh pSrc->a[i].iCursor = -1; 4764a78c22c4Sdrh } 4765a78c22c4Sdrh 4766a78c22c4Sdrh /* Return a pointer to the enlarged SrcList */ 4767a78c22c4Sdrh return pSrc; 4768a78c22c4Sdrh } 4769a78c22c4Sdrh 4770a78c22c4Sdrh 4771a78c22c4Sdrh /* 4772ad3cab52Sdrh ** Append a new table name to the given SrcList. Create a new SrcList if 4773b7916a78Sdrh ** need be. A new entry is created in the SrcList even if pTable is NULL. 4774ad3cab52Sdrh ** 477529c992cbSdrh ** A SrcList is returned, or NULL if there is an OOM error or if the 477629c992cbSdrh ** SrcList grows to large. The returned 4777a78c22c4Sdrh ** SrcList might be the same as the SrcList that was input or it might be 4778a78c22c4Sdrh ** a new one. If an OOM error does occurs, then the prior value of pList 4779a78c22c4Sdrh ** that is input to this routine is automatically freed. 4780113088ecSdrh ** 4781113088ecSdrh ** If pDatabase is not null, it means that the table has an optional 4782113088ecSdrh ** database name prefix. Like this: "database.table". The pDatabase 4783113088ecSdrh ** points to the table name and the pTable points to the database name. 4784113088ecSdrh ** The SrcList.a[].zName field is filled with the table name which might 4785113088ecSdrh ** come from pTable (if pDatabase is NULL) or from pDatabase. 4786113088ecSdrh ** SrcList.a[].zDatabase is filled with the database name from pTable, 4787113088ecSdrh ** or with NULL if no database is specified. 4788113088ecSdrh ** 4789113088ecSdrh ** In other words, if call like this: 4790113088ecSdrh ** 479117435752Sdrh ** sqlite3SrcListAppend(D,A,B,0); 4792113088ecSdrh ** 4793113088ecSdrh ** Then B is a table name and the database name is unspecified. If called 4794113088ecSdrh ** like this: 4795113088ecSdrh ** 479617435752Sdrh ** sqlite3SrcListAppend(D,A,B,C); 4797113088ecSdrh ** 4798d3001711Sdrh ** Then C is the table name and B is the database name. If C is defined 4799d3001711Sdrh ** then so is B. In other words, we never have a case where: 4800d3001711Sdrh ** 4801d3001711Sdrh ** sqlite3SrcListAppend(D,A,0,C); 4802b7916a78Sdrh ** 4803b7916a78Sdrh ** Both pTable and pDatabase are assumed to be quoted. They are dequoted 4804b7916a78Sdrh ** before being added to the SrcList. 4805ad3cab52Sdrh */ 480617435752Sdrh SrcList *sqlite3SrcListAppend( 480729c992cbSdrh Parse *pParse, /* Parsing context, in which errors are reported */ 480817435752Sdrh SrcList *pList, /* Append to this SrcList. NULL creates a new SrcList */ 480917435752Sdrh Token *pTable, /* Table to append */ 481017435752Sdrh Token *pDatabase /* Database of the table */ 481117435752Sdrh ){ 48127601294aSdrh SrcItem *pItem; 481329c992cbSdrh sqlite3 *db; 4814d3001711Sdrh assert( pDatabase==0 || pTable!=0 ); /* Cannot have C without B */ 481529c992cbSdrh assert( pParse!=0 ); 481629c992cbSdrh assert( pParse->db!=0 ); 481729c992cbSdrh db = pParse->db; 4818ad3cab52Sdrh if( pList==0 ){ 481929c992cbSdrh pList = sqlite3DbMallocRawNN(pParse->db, sizeof(SrcList) ); 4820ad3cab52Sdrh if( pList==0 ) return 0; 48214305d103Sdrh pList->nAlloc = 1; 4822ac178b3dSdrh pList->nSrc = 1; 4823ac178b3dSdrh memset(&pList->a[0], 0, sizeof(pList->a[0])); 4824ac178b3dSdrh pList->a[0].iCursor = -1; 4825ac178b3dSdrh }else{ 482629c992cbSdrh SrcList *pNew = sqlite3SrcListEnlarge(pParse, pList, 1, pList->nSrc); 482729c992cbSdrh if( pNew==0 ){ 4828633e6d57Sdrh sqlite3SrcListDelete(db, pList); 4829ad3cab52Sdrh return 0; 483029c992cbSdrh }else{ 483129c992cbSdrh pList = pNew; 483229c992cbSdrh } 4833ad3cab52Sdrh } 4834a78c22c4Sdrh pItem = &pList->a[pList->nSrc-1]; 4835113088ecSdrh if( pDatabase && pDatabase->z==0 ){ 4836113088ecSdrh pDatabase = 0; 4837113088ecSdrh } 4838d3001711Sdrh if( pDatabase ){ 4839169a689fSdrh pItem->zName = sqlite3NameFromToken(db, pDatabase); 4840169a689fSdrh pItem->zDatabase = sqlite3NameFromToken(db, pTable); 4841169a689fSdrh }else{ 484217435752Sdrh pItem->zName = sqlite3NameFromToken(db, pTable); 4843169a689fSdrh pItem->zDatabase = 0; 4844169a689fSdrh } 4845ad3cab52Sdrh return pList; 4846ad3cab52Sdrh } 4847ad3cab52Sdrh 4848ad3cab52Sdrh /* 4849dfe88eceSdrh ** Assign VdbeCursor index numbers to all tables in a SrcList 485063eb5f29Sdrh */ 48514adee20fSdanielk1977 void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){ 485263eb5f29Sdrh int i; 48537601294aSdrh SrcItem *pItem; 485492a2824cSdrh assert( pList || pParse->db->mallocFailed ); 48559da977f1Sdrh if( ALWAYS(pList) ){ 48569b3187e1Sdrh for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){ 485734055854Sdrh if( pItem->iCursor>=0 ) continue; 48589b3187e1Sdrh pItem->iCursor = pParse->nTab++; 48599b3187e1Sdrh if( pItem->pSelect ){ 48609b3187e1Sdrh sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc); 486163eb5f29Sdrh } 486263eb5f29Sdrh } 486363eb5f29Sdrh } 4864261919ccSdanielk1977 } 486563eb5f29Sdrh 486663eb5f29Sdrh /* 4867ad3cab52Sdrh ** Delete an entire SrcList including all its substructure. 4868ad3cab52Sdrh */ 4869633e6d57Sdrh void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){ 4870ad3cab52Sdrh int i; 48717601294aSdrh SrcItem *pItem; 4872ad3cab52Sdrh if( pList==0 ) return; 4873be5c89acSdrh for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){ 487445d827cbSdrh if( pItem->zDatabase ) sqlite3DbFreeNN(db, pItem->zDatabase); 4875633e6d57Sdrh sqlite3DbFree(db, pItem->zName); 487645d827cbSdrh if( pItem->zAlias ) sqlite3DbFreeNN(db, pItem->zAlias); 48778a48b9c0Sdrh if( pItem->fg.isIndexedBy ) sqlite3DbFree(db, pItem->u1.zIndexedBy); 48788a48b9c0Sdrh if( pItem->fg.isTabFunc ) sqlite3ExprListDelete(db, pItem->u1.pFuncArg); 48791feeaed2Sdan sqlite3DeleteTable(db, pItem->pTab); 488045d827cbSdrh if( pItem->pSelect ) sqlite3SelectDelete(db, pItem->pSelect); 488145d827cbSdrh if( pItem->pOn ) sqlite3ExprDelete(db, pItem->pOn); 488245d827cbSdrh if( pItem->pUsing ) sqlite3IdListDelete(db, pItem->pUsing); 488375897234Sdrh } 4884dbd6a7dcSdrh sqlite3DbFreeNN(db, pList); 488575897234Sdrh } 488675897234Sdrh 4887982cef7eSdrh /* 488861dfc31dSdrh ** This routine is called by the parser to add a new term to the 488961dfc31dSdrh ** end of a growing FROM clause. The "p" parameter is the part of 489061dfc31dSdrh ** the FROM clause that has already been constructed. "p" is NULL 489161dfc31dSdrh ** if this is the first term of the FROM clause. pTable and pDatabase 489261dfc31dSdrh ** are the name of the table and database named in the FROM clause term. 489361dfc31dSdrh ** pDatabase is NULL if the database name qualifier is missing - the 489460ec914cSpeter.d.reid ** usual case. If the term has an alias, then pAlias points to the 489561dfc31dSdrh ** alias token. If the term is a subquery, then pSubquery is the 489661dfc31dSdrh ** SELECT statement that the subquery encodes. The pTable and 489761dfc31dSdrh ** pDatabase parameters are NULL for subqueries. The pOn and pUsing 489861dfc31dSdrh ** parameters are the content of the ON and USING clauses. 489961dfc31dSdrh ** 490061dfc31dSdrh ** Return a new SrcList which encodes is the FROM with the new 490161dfc31dSdrh ** term added. 490261dfc31dSdrh */ 490361dfc31dSdrh SrcList *sqlite3SrcListAppendFromTerm( 490417435752Sdrh Parse *pParse, /* Parsing context */ 490561dfc31dSdrh SrcList *p, /* The left part of the FROM clause already seen */ 490661dfc31dSdrh Token *pTable, /* Name of the table to add to the FROM clause */ 490761dfc31dSdrh Token *pDatabase, /* Name of the database containing pTable */ 490861dfc31dSdrh Token *pAlias, /* The right-hand side of the AS subexpression */ 490961dfc31dSdrh Select *pSubquery, /* A subquery used in place of a table name */ 491061dfc31dSdrh Expr *pOn, /* The ON clause of a join */ 491161dfc31dSdrh IdList *pUsing /* The USING clause of a join */ 491261dfc31dSdrh ){ 49137601294aSdrh SrcItem *pItem; 491417435752Sdrh sqlite3 *db = pParse->db; 4915bd1a0a4fSdanielk1977 if( !p && (pOn || pUsing) ){ 4916bd1a0a4fSdanielk1977 sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s", 4917bd1a0a4fSdanielk1977 (pOn ? "ON" : "USING") 4918bd1a0a4fSdanielk1977 ); 4919bd1a0a4fSdanielk1977 goto append_from_error; 4920bd1a0a4fSdanielk1977 } 492129c992cbSdrh p = sqlite3SrcListAppend(pParse, p, pTable, pDatabase); 49229d9c41e2Sdrh if( p==0 ){ 4923bd1a0a4fSdanielk1977 goto append_from_error; 492461dfc31dSdrh } 49259d9c41e2Sdrh assert( p->nSrc>0 ); 492661dfc31dSdrh pItem = &p->a[p->nSrc-1]; 4927a488ec9fSdrh assert( (pTable==0)==(pDatabase==0) ); 4928a488ec9fSdrh assert( pItem->zName==0 || pDatabase!=0 ); 4929c9461eccSdan if( IN_RENAME_OBJECT && pItem->zName ){ 4930a488ec9fSdrh Token *pToken = (ALWAYS(pDatabase) && pDatabase->z) ? pDatabase : pTable; 4931c9461eccSdan sqlite3RenameTokenMap(pParse, pItem->zName, pToken); 4932c9461eccSdan } 49338af73d41Sdrh assert( pAlias!=0 ); 49348af73d41Sdrh if( pAlias->n ){ 493517435752Sdrh pItem->zAlias = sqlite3NameFromToken(db, pAlias); 493661dfc31dSdrh } 493761dfc31dSdrh pItem->pSelect = pSubquery; 493861dfc31dSdrh pItem->pOn = pOn; 493961dfc31dSdrh pItem->pUsing = pUsing; 4940bd1a0a4fSdanielk1977 return p; 4941bd1a0a4fSdanielk1977 4942bd1a0a4fSdanielk1977 append_from_error: 4943bd1a0a4fSdanielk1977 assert( p==0 ); 49449b87d7b9Sdanielk1977 sqlite3ExprDelete(db, pOn); 49459b87d7b9Sdanielk1977 sqlite3IdListDelete(db, pUsing); 4946bd1a0a4fSdanielk1977 sqlite3SelectDelete(db, pSubquery); 4947bd1a0a4fSdanielk1977 return 0; 494861dfc31dSdrh } 494961dfc31dSdrh 495061dfc31dSdrh /* 4951b1c685b0Sdanielk1977 ** Add an INDEXED BY or NOT INDEXED clause to the most recently added 4952b1c685b0Sdanielk1977 ** element of the source-list passed as the second argument. 4953b1c685b0Sdanielk1977 */ 4954b1c685b0Sdanielk1977 void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){ 49558af73d41Sdrh assert( pIndexedBy!=0 ); 49568abc80b2Sdrh if( p && pIndexedBy->n>0 ){ 49577601294aSdrh SrcItem *pItem; 49588abc80b2Sdrh assert( p->nSrc>0 ); 49598abc80b2Sdrh pItem = &p->a[p->nSrc-1]; 49608a48b9c0Sdrh assert( pItem->fg.notIndexed==0 ); 49618a48b9c0Sdrh assert( pItem->fg.isIndexedBy==0 ); 49628a48b9c0Sdrh assert( pItem->fg.isTabFunc==0 ); 4963b1c685b0Sdanielk1977 if( pIndexedBy->n==1 && !pIndexedBy->z ){ 4964b1c685b0Sdanielk1977 /* A "NOT INDEXED" clause was supplied. See parse.y 4965b1c685b0Sdanielk1977 ** construct "indexed_opt" for details. */ 49668a48b9c0Sdrh pItem->fg.notIndexed = 1; 4967b1c685b0Sdanielk1977 }else{ 49688a48b9c0Sdrh pItem->u1.zIndexedBy = sqlite3NameFromToken(pParse->db, pIndexedBy); 49698abc80b2Sdrh pItem->fg.isIndexedBy = 1; 4970dbfbb5a0Sdrh assert( pItem->fg.isCte==0 ); /* No collision on union u2 */ 4971b1c685b0Sdanielk1977 } 4972b1c685b0Sdanielk1977 } 4973b1c685b0Sdanielk1977 } 4974b1c685b0Sdanielk1977 4975b1c685b0Sdanielk1977 /* 497669887c99Sdan ** Append the contents of SrcList p2 to SrcList p1 and return the resulting 497769887c99Sdan ** SrcList. Or, if an error occurs, return NULL. In all cases, p1 and p2 497869887c99Sdan ** are deleted by this function. 497969887c99Sdan */ 498069887c99Sdan SrcList *sqlite3SrcListAppendList(Parse *pParse, SrcList *p1, SrcList *p2){ 49818b023cf5Sdan assert( p1 && p1->nSrc==1 ); 49828b023cf5Sdan if( p2 ){ 49838b023cf5Sdan SrcList *pNew = sqlite3SrcListEnlarge(pParse, p1, p2->nSrc, 1); 49848b023cf5Sdan if( pNew==0 ){ 49858b023cf5Sdan sqlite3SrcListDelete(pParse->db, p2); 49868b023cf5Sdan }else{ 49878b023cf5Sdan p1 = pNew; 49887601294aSdrh memcpy(&p1->a[1], p2->a, p2->nSrc*sizeof(SrcItem)); 4989525326efSdrh sqlite3DbFree(pParse->db, p2); 499069887c99Sdan } 499169887c99Sdan } 499269887c99Sdan return p1; 499369887c99Sdan } 499469887c99Sdan 499569887c99Sdan /* 499601d230ceSdrh ** Add the list of function arguments to the SrcList entry for a 499701d230ceSdrh ** table-valued-function. 499801d230ceSdrh */ 499901d230ceSdrh void sqlite3SrcListFuncArgs(Parse *pParse, SrcList *p, ExprList *pList){ 500020292310Sdrh if( p ){ 50017601294aSdrh SrcItem *pItem = &p->a[p->nSrc-1]; 500201d230ceSdrh assert( pItem->fg.notIndexed==0 ); 500301d230ceSdrh assert( pItem->fg.isIndexedBy==0 ); 500401d230ceSdrh assert( pItem->fg.isTabFunc==0 ); 500501d230ceSdrh pItem->u1.pFuncArg = pList; 500601d230ceSdrh pItem->fg.isTabFunc = 1; 5007d8b1bfc6Sdrh }else{ 5008d8b1bfc6Sdrh sqlite3ExprListDelete(pParse->db, pList); 500901d230ceSdrh } 501001d230ceSdrh } 501101d230ceSdrh 501201d230ceSdrh /* 501361dfc31dSdrh ** When building up a FROM clause in the parser, the join operator 501461dfc31dSdrh ** is initially attached to the left operand. But the code generator 501561dfc31dSdrh ** expects the join operator to be on the right operand. This routine 501661dfc31dSdrh ** Shifts all join operators from left to right for an entire FROM 501761dfc31dSdrh ** clause. 501861dfc31dSdrh ** 501961dfc31dSdrh ** Example: Suppose the join is like this: 502061dfc31dSdrh ** 502161dfc31dSdrh ** A natural cross join B 502261dfc31dSdrh ** 502361dfc31dSdrh ** The operator is "natural cross join". The A and B operands are stored 502461dfc31dSdrh ** in p->a[0] and p->a[1], respectively. The parser initially stores the 502561dfc31dSdrh ** operator with A. This routine shifts that operator over to B. 502661dfc31dSdrh */ 502761dfc31dSdrh void sqlite3SrcListShiftJoinType(SrcList *p){ 5028d017ab99Sdrh if( p ){ 502961dfc31dSdrh int i; 503061dfc31dSdrh for(i=p->nSrc-1; i>0; i--){ 50318a48b9c0Sdrh p->a[i].fg.jointype = p->a[i-1].fg.jointype; 503261dfc31dSdrh } 50338a48b9c0Sdrh p->a[0].fg.jointype = 0; 503461dfc31dSdrh } 503561dfc31dSdrh } 503661dfc31dSdrh 503761dfc31dSdrh /* 5038b0c88651Sdrh ** Generate VDBE code for a BEGIN statement. 5039c4a3c779Sdrh */ 5040684917c2Sdrh void sqlite3BeginTransaction(Parse *pParse, int type){ 50419bb575fdSdrh sqlite3 *db; 50421d850a72Sdanielk1977 Vdbe *v; 5043684917c2Sdrh int i; 50445e00f6c7Sdrh 5045d3001711Sdrh assert( pParse!=0 ); 5046d3001711Sdrh db = pParse->db; 5047d3001711Sdrh assert( db!=0 ); 5048d3001711Sdrh if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){ 5049d3001711Sdrh return; 5050d3001711Sdrh } 50511d850a72Sdanielk1977 v = sqlite3GetVdbe(pParse); 50521d850a72Sdanielk1977 if( !v ) return; 5053684917c2Sdrh if( type!=TK_DEFERRED ){ 5054684917c2Sdrh for(i=0; i<db->nDb; i++){ 50551ca037f4Sdrh int eTxnType; 50561ca037f4Sdrh Btree *pBt = db->aDb[i].pBt; 50571ca037f4Sdrh if( pBt && sqlite3BtreeIsReadonly(pBt) ){ 50581ca037f4Sdrh eTxnType = 0; /* Read txn */ 50591ca037f4Sdrh }else if( type==TK_EXCLUSIVE ){ 50601ca037f4Sdrh eTxnType = 2; /* Exclusive txn */ 50611ca037f4Sdrh }else{ 50621ca037f4Sdrh eTxnType = 1; /* Write txn */ 50631ca037f4Sdrh } 50641ca037f4Sdrh sqlite3VdbeAddOp2(v, OP_Transaction, i, eTxnType); 5065fb98264aSdrh sqlite3VdbeUsesBtree(v, i); 5066684917c2Sdrh } 5067684917c2Sdrh } 5068b0c88651Sdrh sqlite3VdbeAddOp0(v, OP_AutoCommit); 506902f75f19Sdrh } 5070c4a3c779Sdrh 5071c4a3c779Sdrh /* 507207a3b11aSdrh ** Generate VDBE code for a COMMIT or ROLLBACK statement. 507307a3b11aSdrh ** Code for ROLLBACK is generated if eType==TK_ROLLBACK. Otherwise 507407a3b11aSdrh ** code is generated for a COMMIT. 5075c4a3c779Sdrh */ 507607a3b11aSdrh void sqlite3EndTransaction(Parse *pParse, int eType){ 50771d850a72Sdanielk1977 Vdbe *v; 507807a3b11aSdrh int isRollback; 50795e00f6c7Sdrh 5080d3001711Sdrh assert( pParse!=0 ); 5081b07028f7Sdrh assert( pParse->db!=0 ); 508207a3b11aSdrh assert( eType==TK_COMMIT || eType==TK_END || eType==TK_ROLLBACK ); 508307a3b11aSdrh isRollback = eType==TK_ROLLBACK; 508407a3b11aSdrh if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, 508507a3b11aSdrh isRollback ? "ROLLBACK" : "COMMIT", 0, 0) ){ 5086d3001711Sdrh return; 5087d3001711Sdrh } 50881d850a72Sdanielk1977 v = sqlite3GetVdbe(pParse); 50891d850a72Sdanielk1977 if( v ){ 509007a3b11aSdrh sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, isRollback); 5091c4a3c779Sdrh } 509202f75f19Sdrh } 5093f57b14a6Sdrh 5094f57b14a6Sdrh /* 5095fd7f0452Sdanielk1977 ** This function is called by the parser when it parses a command to create, 5096fd7f0452Sdanielk1977 ** release or rollback an SQL savepoint. 5097fd7f0452Sdanielk1977 */ 5098fd7f0452Sdanielk1977 void sqlite3Savepoint(Parse *pParse, int op, Token *pName){ 5099ab9b703fSdanielk1977 char *zName = sqlite3NameFromToken(pParse->db, pName); 5100ab9b703fSdanielk1977 if( zName ){ 5101ab9b703fSdanielk1977 Vdbe *v = sqlite3GetVdbe(pParse); 5102ab9b703fSdanielk1977 #ifndef SQLITE_OMIT_AUTHORIZATION 5103558814f8Sdan static const char * const az[] = { "BEGIN", "RELEASE", "ROLLBACK" }; 5104ab9b703fSdanielk1977 assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 ); 5105ab9b703fSdanielk1977 #endif 5106ab9b703fSdanielk1977 if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){ 5107ab9b703fSdanielk1977 sqlite3DbFree(pParse->db, zName); 5108ab9b703fSdanielk1977 return; 5109ab9b703fSdanielk1977 } 5110ab9b703fSdanielk1977 sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC); 5111fd7f0452Sdanielk1977 } 5112fd7f0452Sdanielk1977 } 5113fd7f0452Sdanielk1977 5114fd7f0452Sdanielk1977 /* 5115dc3ff9c3Sdrh ** Make sure the TEMP database is open and available for use. Return 5116dc3ff9c3Sdrh ** the number of errors. Leave any error messages in the pParse structure. 5117dc3ff9c3Sdrh */ 5118ddfb2f03Sdanielk1977 int sqlite3OpenTempDatabase(Parse *pParse){ 5119dc3ff9c3Sdrh sqlite3 *db = pParse->db; 5120dc3ff9c3Sdrh if( db->aDb[1].pBt==0 && !pParse->explain ){ 512133f4e02aSdrh int rc; 512210a76c90Sdrh Btree *pBt; 512333f4e02aSdrh static const int flags = 512433f4e02aSdrh SQLITE_OPEN_READWRITE | 512533f4e02aSdrh SQLITE_OPEN_CREATE | 512633f4e02aSdrh SQLITE_OPEN_EXCLUSIVE | 512733f4e02aSdrh SQLITE_OPEN_DELETEONCLOSE | 512833f4e02aSdrh SQLITE_OPEN_TEMP_DB; 512933f4e02aSdrh 51303a6d8aecSdan rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pBt, 0, flags); 5131dc3ff9c3Sdrh if( rc!=SQLITE_OK ){ 5132dc3ff9c3Sdrh sqlite3ErrorMsg(pParse, "unable to open a temporary database " 5133dc3ff9c3Sdrh "file for storing temporary tables"); 5134dc3ff9c3Sdrh pParse->rc = rc; 5135dc3ff9c3Sdrh return 1; 5136dc3ff9c3Sdrh } 513710a76c90Sdrh db->aDb[1].pBt = pBt; 513814db2665Sdanielk1977 assert( db->aDb[1].pSchema ); 5139e937df81Sdrh if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, 0, 0) ){ 51404a642b60Sdrh sqlite3OomFault(db); 51417c9c9868Sdrh return 1; 514210a76c90Sdrh } 5143dc3ff9c3Sdrh } 5144dc3ff9c3Sdrh return 0; 5145dc3ff9c3Sdrh } 5146dc3ff9c3Sdrh 5147dc3ff9c3Sdrh /* 5148aceb31b1Sdrh ** Record the fact that the schema cookie will need to be verified 5149aceb31b1Sdrh ** for database iDb. The code to actually verify the schema cookie 5150aceb31b1Sdrh ** will occur at the end of the top-level VDBE and will be generated 5151aceb31b1Sdrh ** later, by sqlite3FinishCoding(). 5152001bbcbbSdrh */ 51531d8f892aSdrh static void sqlite3CodeVerifySchemaAtToplevel(Parse *pToplevel, int iDb){ 51541d8f892aSdrh assert( iDb>=0 && iDb<pToplevel->db->nDb ); 51551d8f892aSdrh assert( pToplevel->db->aDb[iDb].pBt!=0 || iDb==1 ); 5156099b385dSdrh assert( iDb<SQLITE_MAX_DB ); 51571d8f892aSdrh assert( sqlite3SchemaMutexHeld(pToplevel->db, iDb, 0) ); 5158a7ab6d81Sdrh if( DbMaskTest(pToplevel->cookieMask, iDb)==0 ){ 5159a7ab6d81Sdrh DbMaskSet(pToplevel->cookieMask, iDb); 516053c0f748Sdanielk1977 if( !OMIT_TEMPDB && iDb==1 ){ 516165a7cd16Sdan sqlite3OpenTempDatabase(pToplevel); 5162dc3ff9c3Sdrh } 5163001bbcbbSdrh } 5164c275b4eaSdrh } 51651d8f892aSdrh void sqlite3CodeVerifySchema(Parse *pParse, int iDb){ 51661d8f892aSdrh sqlite3CodeVerifySchemaAtToplevel(sqlite3ParseToplevel(pParse), iDb); 51671d8f892aSdrh } 51681d8f892aSdrh 5169001bbcbbSdrh 5170001bbcbbSdrh /* 517157966753Sdan ** If argument zDb is NULL, then call sqlite3CodeVerifySchema() for each 517257966753Sdan ** attached database. Otherwise, invoke it for the database named zDb only. 517357966753Sdan */ 517457966753Sdan void sqlite3CodeVerifyNamedSchema(Parse *pParse, const char *zDb){ 517557966753Sdan sqlite3 *db = pParse->db; 517657966753Sdan int i; 517757966753Sdan for(i=0; i<db->nDb; i++){ 517857966753Sdan Db *pDb = &db->aDb[i]; 517969c33826Sdrh if( pDb->pBt && (!zDb || 0==sqlite3StrICmp(zDb, pDb->zDbSName)) ){ 518057966753Sdan sqlite3CodeVerifySchema(pParse, i); 518157966753Sdan } 518257966753Sdan } 518357966753Sdan } 518457966753Sdan 518557966753Sdan /* 51861c92853dSdrh ** Generate VDBE code that prepares for doing an operation that 5187c977f7f5Sdrh ** might change the database. 5188c977f7f5Sdrh ** 5189c977f7f5Sdrh ** This routine starts a new transaction if we are not already within 5190c977f7f5Sdrh ** a transaction. If we are already within a transaction, then a checkpoint 51917f0f12e3Sdrh ** is set if the setStatement parameter is true. A checkpoint should 5192c977f7f5Sdrh ** be set for operations that might fail (due to a constraint) part of 5193c977f7f5Sdrh ** the way through and which will need to undo some writes without having to 5194c977f7f5Sdrh ** rollback the whole transaction. For operations where all constraints 5195c977f7f5Sdrh ** can be checked before any changes are made to the database, it is never 5196c977f7f5Sdrh ** necessary to undo a write and the checkpoint should not be set. 51971c92853dSdrh */ 51987f0f12e3Sdrh void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){ 519965a7cd16Sdan Parse *pToplevel = sqlite3ParseToplevel(pParse); 52001d8f892aSdrh sqlite3CodeVerifySchemaAtToplevel(pToplevel, iDb); 5201a7ab6d81Sdrh DbMaskSet(pToplevel->writeMask, iDb); 5202e0af83acSdan pToplevel->isMultiWrite |= setStatement; 52031d850a72Sdanielk1977 } 5204e0af83acSdan 5205e0af83acSdan /* 5206ff738bceSdrh ** Indicate that the statement currently under construction might write 5207ff738bceSdrh ** more than one entry (example: deleting one row then inserting another, 5208ff738bceSdrh ** inserting multiple rows in a table, or inserting a row and index entries.) 5209ff738bceSdrh ** If an abort occurs after some of these writes have completed, then it will 5210ff738bceSdrh ** be necessary to undo the completed writes. 5211ff738bceSdrh */ 5212ff738bceSdrh void sqlite3MultiWrite(Parse *pParse){ 5213ff738bceSdrh Parse *pToplevel = sqlite3ParseToplevel(pParse); 5214ff738bceSdrh pToplevel->isMultiWrite = 1; 5215ff738bceSdrh } 5216ff738bceSdrh 5217ff738bceSdrh /* 5218ff738bceSdrh ** The code generator calls this routine if is discovers that it is 5219ff738bceSdrh ** possible to abort a statement prior to completion. In order to 5220ff738bceSdrh ** perform this abort without corrupting the database, we need to make 5221ff738bceSdrh ** sure that the statement is protected by a statement transaction. 5222ff738bceSdrh ** 5223ff738bceSdrh ** Technically, we only need to set the mayAbort flag if the 5224ff738bceSdrh ** isMultiWrite flag was previously set. There is a time dependency 5225ff738bceSdrh ** such that the abort must occur after the multiwrite. This makes 5226ff738bceSdrh ** some statements involving the REPLACE conflict resolution algorithm 5227ff738bceSdrh ** go a little faster. But taking advantage of this time dependency 5228ff738bceSdrh ** makes it more difficult to prove that the code is correct (in 5229ff738bceSdrh ** particular, it prevents us from writing an effective 5230ff738bceSdrh ** implementation of sqlite3AssertMayAbort()) and so we have chosen 5231ff738bceSdrh ** to take the safe route and skip the optimization. 5232e0af83acSdan */ 5233e0af83acSdan void sqlite3MayAbort(Parse *pParse){ 5234e0af83acSdan Parse *pToplevel = sqlite3ParseToplevel(pParse); 5235e0af83acSdan pToplevel->mayAbort = 1; 5236e0af83acSdan } 5237e0af83acSdan 5238e0af83acSdan /* 5239e0af83acSdan ** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT 5240e0af83acSdan ** error. The onError parameter determines which (if any) of the statement 5241e0af83acSdan ** and/or current transaction is rolled back. 5242e0af83acSdan */ 5243d91c1a17Sdrh void sqlite3HaltConstraint( 5244d91c1a17Sdrh Parse *pParse, /* Parsing context */ 5245d91c1a17Sdrh int errCode, /* extended error code */ 5246d91c1a17Sdrh int onError, /* Constraint type */ 5247d91c1a17Sdrh char *p4, /* Error message */ 5248f9c8ce3cSdrh i8 p4type, /* P4_STATIC or P4_TRANSIENT */ 5249f9c8ce3cSdrh u8 p5Errmsg /* P5_ErrMsg type */ 5250d91c1a17Sdrh ){ 5251289a0c84Sdrh Vdbe *v; 5252289a0c84Sdrh assert( pParse->pVdbe!=0 ); 5253289a0c84Sdrh v = sqlite3GetVdbe(pParse); 52549e5fdc41Sdrh assert( (errCode&0xff)==SQLITE_CONSTRAINT || pParse->nested ); 5255e0af83acSdan if( onError==OE_Abort ){ 5256e0af83acSdan sqlite3MayAbort(pParse); 5257e0af83acSdan } 5258d91c1a17Sdrh sqlite3VdbeAddOp4(v, OP_Halt, errCode, onError, 0, p4, p4type); 52599b34abeeSdrh sqlite3VdbeChangeP5(v, p5Errmsg); 5260f9c8ce3cSdrh } 5261f9c8ce3cSdrh 5262f9c8ce3cSdrh /* 5263f9c8ce3cSdrh ** Code an OP_Halt due to UNIQUE or PRIMARY KEY constraint violation. 5264f9c8ce3cSdrh */ 5265f9c8ce3cSdrh void sqlite3UniqueConstraint( 5266f9c8ce3cSdrh Parse *pParse, /* Parsing context */ 5267f9c8ce3cSdrh int onError, /* Constraint type */ 5268f9c8ce3cSdrh Index *pIdx /* The index that triggers the constraint */ 5269f9c8ce3cSdrh ){ 5270f9c8ce3cSdrh char *zErr; 5271f9c8ce3cSdrh int j; 5272f9c8ce3cSdrh StrAccum errMsg; 5273f9c8ce3cSdrh Table *pTab = pIdx->pTable; 5274f9c8ce3cSdrh 527586ec1eddSdrh sqlite3StrAccumInit(&errMsg, pParse->db, 0, 0, 527686ec1eddSdrh pParse->db->aLimit[SQLITE_LIMIT_LENGTH]); 52778b576422Sdrh if( pIdx->aColExpr ){ 52780cdbe1aeSdrh sqlite3_str_appendf(&errMsg, "index '%q'", pIdx->zName); 52798b576422Sdrh }else{ 5280f9c8ce3cSdrh for(j=0; j<pIdx->nKeyCol; j++){ 52811f9ca2c8Sdrh char *zCol; 52821f9ca2c8Sdrh assert( pIdx->aiColumn[j]>=0 ); 5283cf9d36d1Sdrh zCol = pTab->aCol[pIdx->aiColumn[j]].zCnName; 52840cdbe1aeSdrh if( j ) sqlite3_str_append(&errMsg, ", ", 2); 52850cdbe1aeSdrh sqlite3_str_appendall(&errMsg, pTab->zName); 52860cdbe1aeSdrh sqlite3_str_append(&errMsg, ".", 1); 52870cdbe1aeSdrh sqlite3_str_appendall(&errMsg, zCol); 52888b576422Sdrh } 5289f9c8ce3cSdrh } 5290f9c8ce3cSdrh zErr = sqlite3StrAccumFinish(&errMsg); 5291f9c8ce3cSdrh sqlite3HaltConstraint(pParse, 529248dd1d8eSdrh IsPrimaryKeyIndex(pIdx) ? SQLITE_CONSTRAINT_PRIMARYKEY 529348dd1d8eSdrh : SQLITE_CONSTRAINT_UNIQUE, 529493889d93Sdan onError, zErr, P4_DYNAMIC, P5_ConstraintUnique); 5295f9c8ce3cSdrh } 5296f9c8ce3cSdrh 5297f9c8ce3cSdrh 5298f9c8ce3cSdrh /* 5299f9c8ce3cSdrh ** Code an OP_Halt due to non-unique rowid. 5300f9c8ce3cSdrh */ 5301f9c8ce3cSdrh void sqlite3RowidConstraint( 5302f9c8ce3cSdrh Parse *pParse, /* Parsing context */ 5303f9c8ce3cSdrh int onError, /* Conflict resolution algorithm */ 5304f9c8ce3cSdrh Table *pTab /* The table with the non-unique rowid */ 5305f9c8ce3cSdrh ){ 5306f9c8ce3cSdrh char *zMsg; 5307f9c8ce3cSdrh int rc; 5308f9c8ce3cSdrh if( pTab->iPKey>=0 ){ 5309f9c8ce3cSdrh zMsg = sqlite3MPrintf(pParse->db, "%s.%s", pTab->zName, 5310cf9d36d1Sdrh pTab->aCol[pTab->iPKey].zCnName); 5311f9c8ce3cSdrh rc = SQLITE_CONSTRAINT_PRIMARYKEY; 5312f9c8ce3cSdrh }else{ 5313f9c8ce3cSdrh zMsg = sqlite3MPrintf(pParse->db, "%s.rowid", pTab->zName); 5314f9c8ce3cSdrh rc = SQLITE_CONSTRAINT_ROWID; 5315f9c8ce3cSdrh } 5316f9c8ce3cSdrh sqlite3HaltConstraint(pParse, rc, onError, zMsg, P4_DYNAMIC, 5317f9c8ce3cSdrh P5_ConstraintUnique); 5318663fc63aSdrh } 5319663fc63aSdrh 53204343fea2Sdrh /* 53214343fea2Sdrh ** Check to see if pIndex uses the collating sequence pColl. Return 53224343fea2Sdrh ** true if it does and false if it does not. 53234343fea2Sdrh */ 53244343fea2Sdrh #ifndef SQLITE_OMIT_REINDEX 5325b3bf556eSdanielk1977 static int collationMatch(const char *zColl, Index *pIndex){ 5326b3bf556eSdanielk1977 int i; 53270449171eSdrh assert( zColl!=0 ); 5328b3bf556eSdanielk1977 for(i=0; i<pIndex->nColumn; i++){ 5329b3bf556eSdanielk1977 const char *z = pIndex->azColl[i]; 5330bbbdc83bSdrh assert( z!=0 || pIndex->aiColumn[i]<0 ); 5331bbbdc83bSdrh if( pIndex->aiColumn[i]>=0 && 0==sqlite3StrICmp(z, zColl) ){ 5332b3bf556eSdanielk1977 return 1; 5333b3bf556eSdanielk1977 } 53344343fea2Sdrh } 53354343fea2Sdrh return 0; 53364343fea2Sdrh } 53374343fea2Sdrh #endif 53384343fea2Sdrh 53394343fea2Sdrh /* 53404343fea2Sdrh ** Recompute all indices of pTab that use the collating sequence pColl. 53414343fea2Sdrh ** If pColl==0 then recompute all indices of pTab. 53424343fea2Sdrh */ 53434343fea2Sdrh #ifndef SQLITE_OMIT_REINDEX 5344b3bf556eSdanielk1977 static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){ 5345e6370e9cSdan if( !IsVirtual(pTab) ){ 53464343fea2Sdrh Index *pIndex; /* An index associated with pTab */ 53474343fea2Sdrh 53484343fea2Sdrh for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){ 5349b3bf556eSdanielk1977 if( zColl==0 || collationMatch(zColl, pIndex) ){ 5350da184236Sdanielk1977 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema); 5351da184236Sdanielk1977 sqlite3BeginWriteOperation(pParse, 0, iDb); 53524343fea2Sdrh sqlite3RefillIndex(pParse, pIndex, -1); 53534343fea2Sdrh } 53544343fea2Sdrh } 53554343fea2Sdrh } 5356e6370e9cSdan } 53574343fea2Sdrh #endif 53584343fea2Sdrh 53594343fea2Sdrh /* 53604343fea2Sdrh ** Recompute all indices of all tables in all databases where the 53614343fea2Sdrh ** indices use the collating sequence pColl. If pColl==0 then recompute 53624343fea2Sdrh ** all indices everywhere. 53634343fea2Sdrh */ 53644343fea2Sdrh #ifndef SQLITE_OMIT_REINDEX 5365b3bf556eSdanielk1977 static void reindexDatabases(Parse *pParse, char const *zColl){ 53664343fea2Sdrh Db *pDb; /* A single database */ 53674343fea2Sdrh int iDb; /* The database index number */ 53684343fea2Sdrh sqlite3 *db = pParse->db; /* The database connection */ 53694343fea2Sdrh HashElem *k; /* For looping over tables in pDb */ 53704343fea2Sdrh Table *pTab; /* A table in the database */ 53714343fea2Sdrh 53722120608eSdrh assert( sqlite3BtreeHoldsAllMutexes(db) ); /* Needed for schema access */ 53734343fea2Sdrh for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){ 537443617e9aSdrh assert( pDb!=0 ); 5375da184236Sdanielk1977 for(k=sqliteHashFirst(&pDb->pSchema->tblHash); k; k=sqliteHashNext(k)){ 53764343fea2Sdrh pTab = (Table*)sqliteHashData(k); 5377b3bf556eSdanielk1977 reindexTable(pParse, pTab, zColl); 53784343fea2Sdrh } 53794343fea2Sdrh } 53804343fea2Sdrh } 53814343fea2Sdrh #endif 53824343fea2Sdrh 53834343fea2Sdrh /* 5384eee46cf3Sdrh ** Generate code for the REINDEX command. 5385eee46cf3Sdrh ** 5386eee46cf3Sdrh ** REINDEX -- 1 5387eee46cf3Sdrh ** REINDEX <collation> -- 2 5388eee46cf3Sdrh ** REINDEX ?<database>.?<tablename> -- 3 5389eee46cf3Sdrh ** REINDEX ?<database>.?<indexname> -- 4 5390eee46cf3Sdrh ** 5391eee46cf3Sdrh ** Form 1 causes all indices in all attached databases to be rebuilt. 5392eee46cf3Sdrh ** Form 2 rebuilds all indices in all databases that use the named 5393eee46cf3Sdrh ** collating function. Forms 3 and 4 rebuild the named index or all 5394eee46cf3Sdrh ** indices associated with the named table. 53954343fea2Sdrh */ 53964343fea2Sdrh #ifndef SQLITE_OMIT_REINDEX 53974343fea2Sdrh void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){ 53984343fea2Sdrh CollSeq *pColl; /* Collating sequence to be reindexed, or NULL */ 53994343fea2Sdrh char *z; /* Name of a table or index */ 54004343fea2Sdrh const char *zDb; /* Name of the database */ 54014343fea2Sdrh Table *pTab; /* A table in the database */ 54024343fea2Sdrh Index *pIndex; /* An index associated with pTab */ 54034343fea2Sdrh int iDb; /* The database index number */ 54044343fea2Sdrh sqlite3 *db = pParse->db; /* The database connection */ 54054343fea2Sdrh Token *pObjName; /* Name of the table or index to be reindexed */ 54064343fea2Sdrh 540733a5edc3Sdanielk1977 /* Read the database schema. If an error occurs, leave an error message 540833a5edc3Sdanielk1977 ** and code in pParse and return NULL. */ 540933a5edc3Sdanielk1977 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){ 5410e63739a8Sdanielk1977 return; 541133a5edc3Sdanielk1977 } 541233a5edc3Sdanielk1977 54138af73d41Sdrh if( pName1==0 ){ 54144343fea2Sdrh reindexDatabases(pParse, 0); 54154343fea2Sdrh return; 5416d3001711Sdrh }else if( NEVER(pName2==0) || pName2->z==0 ){ 541739002505Sdanielk1977 char *zColl; 5418b3bf556eSdanielk1977 assert( pName1->z ); 541939002505Sdanielk1977 zColl = sqlite3NameFromToken(pParse->db, pName1); 542039002505Sdanielk1977 if( !zColl ) return; 5421c4a64facSdrh pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0); 54224343fea2Sdrh if( pColl ){ 5423f0113000Sdanielk1977 reindexDatabases(pParse, zColl); 5424633e6d57Sdrh sqlite3DbFree(db, zColl); 54254343fea2Sdrh return; 54264343fea2Sdrh } 5427633e6d57Sdrh sqlite3DbFree(db, zColl); 54284343fea2Sdrh } 54294343fea2Sdrh iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName); 54304343fea2Sdrh if( iDb<0 ) return; 543117435752Sdrh z = sqlite3NameFromToken(db, pObjName); 543284f31128Sdrh if( z==0 ) return; 543369c33826Sdrh zDb = db->aDb[iDb].zDbSName; 54344343fea2Sdrh pTab = sqlite3FindTable(db, z, zDb); 54354343fea2Sdrh if( pTab ){ 54364343fea2Sdrh reindexTable(pParse, pTab, 0); 5437633e6d57Sdrh sqlite3DbFree(db, z); 54384343fea2Sdrh return; 54394343fea2Sdrh } 54404343fea2Sdrh pIndex = sqlite3FindIndex(db, z, zDb); 5441633e6d57Sdrh sqlite3DbFree(db, z); 54424343fea2Sdrh if( pIndex ){ 54434343fea2Sdrh sqlite3BeginWriteOperation(pParse, 0, iDb); 54444343fea2Sdrh sqlite3RefillIndex(pParse, pIndex, -1); 54454343fea2Sdrh return; 54464343fea2Sdrh } 54474343fea2Sdrh sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed"); 54484343fea2Sdrh } 54494343fea2Sdrh #endif 5450b3bf556eSdanielk1977 5451b3bf556eSdanielk1977 /* 54522ec2fb22Sdrh ** Return a KeyInfo structure that is appropriate for the given Index. 5453b3bf556eSdanielk1977 ** 54542ec2fb22Sdrh ** The caller should invoke sqlite3KeyInfoUnref() on the returned object 54552ec2fb22Sdrh ** when it has finished using it. 5456b3bf556eSdanielk1977 */ 54572ec2fb22Sdrh KeyInfo *sqlite3KeyInfoOfIndex(Parse *pParse, Index *pIdx){ 5458b3bf556eSdanielk1977 int i; 5459ad124329Sdrh int nCol = pIdx->nColumn; 5460ad124329Sdrh int nKey = pIdx->nKeyCol; 5461323df790Sdrh KeyInfo *pKey; 546218b67f3fSdrh if( pParse->nErr ) return 0; 54631153c7b2Sdrh if( pIdx->uniqNotNull ){ 5464ad124329Sdrh pKey = sqlite3KeyInfoAlloc(pParse->db, nKey, nCol-nKey); 54651153c7b2Sdrh }else{ 54661153c7b2Sdrh pKey = sqlite3KeyInfoAlloc(pParse->db, nCol, 0); 54671153c7b2Sdrh } 5468b3bf556eSdanielk1977 if( pKey ){ 54692ec2fb22Sdrh assert( sqlite3KeyInfoIsWriteable(pKey) ); 5470b3bf556eSdanielk1977 for(i=0; i<nCol; i++){ 5471f19aa5faSdrh const char *zColl = pIdx->azColl[i]; 5472f19aa5faSdrh pKey->aColl[i] = zColl==sqlite3StrBINARY ? 0 : 5473b8a9bb4fSdrh sqlite3LocateCollSeq(pParse, zColl); 54746e11892dSdan pKey->aSortFlags[i] = pIdx->aSortOrder[i]; 54756e11892dSdan assert( 0==(pKey->aSortFlags[i] & KEYINFO_ORDER_BIGNULL) ); 5476b3bf556eSdanielk1977 } 5477b3bf556eSdanielk1977 if( pParse->nErr ){ 54787e8515d8Sdrh assert( pParse->rc==SQLITE_ERROR_MISSING_COLLSEQ ); 54797e8515d8Sdrh if( pIdx->bNoQuery==0 ){ 54807e8515d8Sdrh /* Deactivate the index because it contains an unknown collating 54817e8515d8Sdrh ** sequence. The only way to reactive the index is to reload the 54827e8515d8Sdrh ** schema. Adding the missing collating sequence later does not 54837e8515d8Sdrh ** reactive the index. The application had the chance to register 54847e8515d8Sdrh ** the missing index using the collation-needed callback. For 54857e8515d8Sdrh ** simplicity, SQLite will not give the application a second chance. 54867e8515d8Sdrh */ 54877e8515d8Sdrh pIdx->bNoQuery = 1; 54887e8515d8Sdrh pParse->rc = SQLITE_ERROR_RETRY; 54897e8515d8Sdrh } 54902ec2fb22Sdrh sqlite3KeyInfoUnref(pKey); 549118b67f3fSdrh pKey = 0; 5492b3bf556eSdanielk1977 } 54932ec2fb22Sdrh } 549418b67f3fSdrh return pKey; 5495b3bf556eSdanielk1977 } 54968b471863Sdrh 54978b471863Sdrh #ifndef SQLITE_OMIT_CTE 54987d562dbeSdan /* 5499f824b41eSdrh ** Create a new CTE object 5500f824b41eSdrh */ 5501f824b41eSdrh Cte *sqlite3CteNew( 5502f824b41eSdrh Parse *pParse, /* Parsing context */ 5503f824b41eSdrh Token *pName, /* Name of the common-table */ 5504f824b41eSdrh ExprList *pArglist, /* Optional column name list for the table */ 5505745912efSdrh Select *pQuery, /* Query used to initialize the table */ 5506745912efSdrh u8 eM10d /* The MATERIALIZED flag */ 5507f824b41eSdrh ){ 5508f824b41eSdrh Cte *pNew; 5509f824b41eSdrh sqlite3 *db = pParse->db; 5510f824b41eSdrh 5511f824b41eSdrh pNew = sqlite3DbMallocZero(db, sizeof(*pNew)); 5512f824b41eSdrh assert( pNew!=0 || db->mallocFailed ); 5513f824b41eSdrh 5514f824b41eSdrh if( db->mallocFailed ){ 5515f824b41eSdrh sqlite3ExprListDelete(db, pArglist); 5516f824b41eSdrh sqlite3SelectDelete(db, pQuery); 5517f824b41eSdrh }else{ 5518f824b41eSdrh pNew->pSelect = pQuery; 5519f824b41eSdrh pNew->pCols = pArglist; 5520f824b41eSdrh pNew->zName = sqlite3NameFromToken(pParse->db, pName); 5521745912efSdrh pNew->eM10d = eM10d; 5522f824b41eSdrh } 5523f824b41eSdrh return pNew; 5524f824b41eSdrh } 5525f824b41eSdrh 5526f824b41eSdrh /* 5527f824b41eSdrh ** Clear information from a Cte object, but do not deallocate storage 5528f824b41eSdrh ** for the object itself. 5529f824b41eSdrh */ 5530f824b41eSdrh static void cteClear(sqlite3 *db, Cte *pCte){ 5531f824b41eSdrh assert( pCte!=0 ); 5532f824b41eSdrh sqlite3ExprListDelete(db, pCte->pCols); 5533f824b41eSdrh sqlite3SelectDelete(db, pCte->pSelect); 5534f824b41eSdrh sqlite3DbFree(db, pCte->zName); 5535f824b41eSdrh } 5536f824b41eSdrh 5537f824b41eSdrh /* 5538f824b41eSdrh ** Free the contents of the CTE object passed as the second argument. 5539f824b41eSdrh */ 5540f824b41eSdrh void sqlite3CteDelete(sqlite3 *db, Cte *pCte){ 5541f824b41eSdrh assert( pCte!=0 ); 5542f824b41eSdrh cteClear(db, pCte); 5543f824b41eSdrh sqlite3DbFree(db, pCte); 5544f824b41eSdrh } 5545f824b41eSdrh 5546f824b41eSdrh /* 55477d562dbeSdan ** This routine is invoked once per CTE by the parser while parsing a 5548f824b41eSdrh ** WITH clause. The CTE described by teh third argument is added to 5549f824b41eSdrh ** the WITH clause of the second argument. If the second argument is 5550f824b41eSdrh ** NULL, then a new WITH argument is created. 55518b471863Sdrh */ 55527d562dbeSdan With *sqlite3WithAdd( 55538b471863Sdrh Parse *pParse, /* Parsing context */ 55547d562dbeSdan With *pWith, /* Existing WITH clause, or NULL */ 5555f824b41eSdrh Cte *pCte /* CTE to add to the WITH clause */ 55568b471863Sdrh ){ 55574e9119d9Sdan sqlite3 *db = pParse->db; 55584e9119d9Sdan With *pNew; 55594e9119d9Sdan char *zName; 55604e9119d9Sdan 5561f824b41eSdrh if( pCte==0 ){ 5562f824b41eSdrh return pWith; 5563f824b41eSdrh } 5564f824b41eSdrh 55654e9119d9Sdan /* Check that the CTE name is unique within this WITH clause. If 55664e9119d9Sdan ** not, store an error in the Parse structure. */ 5567f824b41eSdrh zName = pCte->zName; 55684e9119d9Sdan if( zName && pWith ){ 55694e9119d9Sdan int i; 55704e9119d9Sdan for(i=0; i<pWith->nCte; i++){ 55714e9119d9Sdan if( sqlite3StrICmp(zName, pWith->a[i].zName)==0 ){ 5572727a99f1Sdrh sqlite3ErrorMsg(pParse, "duplicate WITH table name: %s", zName); 55734e9119d9Sdan } 55744e9119d9Sdan } 55754e9119d9Sdan } 55764e9119d9Sdan 55774e9119d9Sdan if( pWith ){ 55780aa3231fSdrh sqlite3_int64 nByte = sizeof(*pWith) + (sizeof(pWith->a[1]) * pWith->nCte); 55794e9119d9Sdan pNew = sqlite3DbRealloc(db, pWith, nByte); 55804e9119d9Sdan }else{ 55814e9119d9Sdan pNew = sqlite3DbMallocZero(db, sizeof(*pWith)); 55824e9119d9Sdan } 5583b84e574cSdrh assert( (pNew!=0 && zName!=0) || db->mallocFailed ); 55844e9119d9Sdan 5585b84e574cSdrh if( db->mallocFailed ){ 5586f824b41eSdrh sqlite3CteDelete(db, pCte); 5587a9f5c13dSdan pNew = pWith; 55884e9119d9Sdan }else{ 5589f824b41eSdrh pNew->a[pNew->nCte++] = *pCte; 5590f824b41eSdrh sqlite3DbFree(db, pCte); 55914e9119d9Sdan } 55924e9119d9Sdan 55934e9119d9Sdan return pNew; 55948b471863Sdrh } 55958b471863Sdrh 55967d562dbeSdan /* 55977d562dbeSdan ** Free the contents of the With object passed as the second argument. 55988b471863Sdrh */ 55997d562dbeSdan void sqlite3WithDelete(sqlite3 *db, With *pWith){ 56004e9119d9Sdan if( pWith ){ 56014e9119d9Sdan int i; 56024e9119d9Sdan for(i=0; i<pWith->nCte; i++){ 5603f824b41eSdrh cteClear(db, &pWith->a[i]); 56044e9119d9Sdan } 56054e9119d9Sdan sqlite3DbFree(db, pWith); 56064e9119d9Sdan } 56078b471863Sdrh } 56088b471863Sdrh #endif /* !defined(SQLITE_OMIT_CTE) */ 5609