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 2775897234Sdrh /* 28e0bc4048Sdrh ** This routine is called when a new SQL statement is beginning to 2923bf66d6Sdrh ** be parsed. Initialize the pParse structure as needed. 30e0bc4048Sdrh */ 314adee20fSdanielk1977 void sqlite3BeginParse(Parse *pParse, int explainFlag){ 321bd10f8aSdrh pParse->explain = (u8)explainFlag; 337c972decSdrh pParse->nVar = 0; 34e0bc4048Sdrh } 35e0bc4048Sdrh 36c00da105Sdanielk1977 #ifndef SQLITE_OMIT_SHARED_CACHE 37c00da105Sdanielk1977 /* 38c00da105Sdanielk1977 ** The TableLock structure is only used by the sqlite3TableLock() and 39c00da105Sdanielk1977 ** codeTableLocks() functions. 40c00da105Sdanielk1977 */ 41c00da105Sdanielk1977 struct TableLock { 42d698bc15Sdrh int iDb; /* The database containing the table to be locked */ 43d698bc15Sdrh int iTab; /* The root page of the table to be locked */ 44d698bc15Sdrh u8 isWriteLock; /* True for write lock. False for a read lock */ 45d698bc15Sdrh const char *zName; /* Name of the table */ 46c00da105Sdanielk1977 }; 47c00da105Sdanielk1977 48c00da105Sdanielk1977 /* 49d698bc15Sdrh ** Record the fact that we want to lock a table at run-time. 50c00da105Sdanielk1977 ** 51d698bc15Sdrh ** The table to be locked has root page iTab and is found in database iDb. 52d698bc15Sdrh ** A read or a write lock can be taken depending on isWritelock. 53d698bc15Sdrh ** 54d698bc15Sdrh ** This routine just records the fact that the lock is desired. The 55d698bc15Sdrh ** code to make the lock occur is generated by a later call to 56d698bc15Sdrh ** codeTableLocks() which occurs during sqlite3FinishCoding(). 57c00da105Sdanielk1977 */ 58c00da105Sdanielk1977 void sqlite3TableLock( 59d698bc15Sdrh Parse *pParse, /* Parsing context */ 60d698bc15Sdrh int iDb, /* Index of the database containing the table to lock */ 61d698bc15Sdrh int iTab, /* Root page number of the table to be locked */ 62d698bc15Sdrh u8 isWriteLock, /* True for a write lock */ 63d698bc15Sdrh const char *zName /* Name of the table to be locked */ 64c00da105Sdanielk1977 ){ 6565a7cd16Sdan Parse *pToplevel = sqlite3ParseToplevel(pParse); 66c00da105Sdanielk1977 int i; 67c00da105Sdanielk1977 int nBytes; 68c00da105Sdanielk1977 TableLock *p; 698af73d41Sdrh assert( iDb>=0 ); 70165921a7Sdan 7165a7cd16Sdan for(i=0; i<pToplevel->nTableLock; i++){ 7265a7cd16Sdan p = &pToplevel->aTableLock[i]; 73c00da105Sdanielk1977 if( p->iDb==iDb && p->iTab==iTab ){ 74c00da105Sdanielk1977 p->isWriteLock = (p->isWriteLock || isWriteLock); 75c00da105Sdanielk1977 return; 76c00da105Sdanielk1977 } 77c00da105Sdanielk1977 } 78c00da105Sdanielk1977 7965a7cd16Sdan nBytes = sizeof(TableLock) * (pToplevel->nTableLock+1); 8065a7cd16Sdan pToplevel->aTableLock = 8165a7cd16Sdan sqlite3DbReallocOrFree(pToplevel->db, pToplevel->aTableLock, nBytes); 8265a7cd16Sdan if( pToplevel->aTableLock ){ 8365a7cd16Sdan p = &pToplevel->aTableLock[pToplevel->nTableLock++]; 84c00da105Sdanielk1977 p->iDb = iDb; 85c00da105Sdanielk1977 p->iTab = iTab; 86c00da105Sdanielk1977 p->isWriteLock = isWriteLock; 87c00da105Sdanielk1977 p->zName = zName; 88f3a65f7eSdrh }else{ 8965a7cd16Sdan pToplevel->nTableLock = 0; 9065a7cd16Sdan pToplevel->db->mallocFailed = 1; 91c00da105Sdanielk1977 } 92c00da105Sdanielk1977 } 93c00da105Sdanielk1977 94c00da105Sdanielk1977 /* 95c00da105Sdanielk1977 ** Code an OP_TableLock instruction for each table locked by the 96c00da105Sdanielk1977 ** statement (configured by calls to sqlite3TableLock()). 97c00da105Sdanielk1977 */ 98c00da105Sdanielk1977 static void codeTableLocks(Parse *pParse){ 99c00da105Sdanielk1977 int i; 100c00da105Sdanielk1977 Vdbe *pVdbe; 101c00da105Sdanielk1977 1020449171eSdrh pVdbe = sqlite3GetVdbe(pParse); 1030449171eSdrh assert( pVdbe!=0 ); /* sqlite3GetVdbe cannot fail: VDBE already allocated */ 104c00da105Sdanielk1977 105c00da105Sdanielk1977 for(i=0; i<pParse->nTableLock; i++){ 106c00da105Sdanielk1977 TableLock *p = &pParse->aTableLock[i]; 107c00da105Sdanielk1977 int p1 = p->iDb; 1086a9ad3daSdrh sqlite3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, p->isWriteLock, 1096a9ad3daSdrh p->zName, P4_STATIC); 110c00da105Sdanielk1977 } 111c00da105Sdanielk1977 } 112c00da105Sdanielk1977 #else 113c00da105Sdanielk1977 #define codeTableLocks(x) 114c00da105Sdanielk1977 #endif 115c00da105Sdanielk1977 116e0bc4048Sdrh /* 117a7ab6d81Sdrh ** Return TRUE if the given yDbMask object is empty - if it contains no 118a7ab6d81Sdrh ** 1 bits. This routine is used by the DbMaskAllZero() and DbMaskNotZero() 119a7ab6d81Sdrh ** macros when SQLITE_MAX_ATTACHED is greater than 30. 120a7ab6d81Sdrh */ 121a7ab6d81Sdrh #if SQLITE_MAX_ATTACHED>30 122a7ab6d81Sdrh int sqlite3DbMaskAllZero(yDbMask m){ 123a7ab6d81Sdrh int i; 124a7ab6d81Sdrh for(i=0; i<sizeof(yDbMask); i++) if( m[i] ) return 0; 125a7ab6d81Sdrh return 1; 126a7ab6d81Sdrh } 127a7ab6d81Sdrh #endif 128a7ab6d81Sdrh 129a7ab6d81Sdrh /* 13075897234Sdrh ** This routine is called after a single SQL statement has been 13180242055Sdrh ** parsed and a VDBE program to execute that statement has been 13280242055Sdrh ** prepared. This routine puts the finishing touches on the 13380242055Sdrh ** VDBE program and resets the pParse structure for the next 13480242055Sdrh ** parse. 13575897234Sdrh ** 13675897234Sdrh ** Note that if an error occurred, it might be the case that 13775897234Sdrh ** no VDBE code was generated. 13875897234Sdrh */ 13980242055Sdrh void sqlite3FinishCoding(Parse *pParse){ 1409bb575fdSdrh sqlite3 *db; 14180242055Sdrh Vdbe *v; 142b86ccfb2Sdrh 143f78baafeSdan assert( pParse->pToplevel==0 ); 14417435752Sdrh db = pParse->db; 145205f48e6Sdrh if( pParse->nested ) return; 146d99d2836Sdrh if( db->mallocFailed || pParse->nErr ){ 147d99d2836Sdrh if( pParse->rc==SQLITE_OK ) pParse->rc = SQLITE_ERROR; 148d99d2836Sdrh return; 149d99d2836Sdrh } 15048d0d866Sdanielk1977 15180242055Sdrh /* Begin by generating some termination code at the end of the 15280242055Sdrh ** vdbe program 15380242055Sdrh */ 15480242055Sdrh v = sqlite3GetVdbe(pParse); 155f3677212Sdan assert( !pParse->isMultiWrite 156f3677212Sdan || sqlite3VdbeAssertMayAbort(v, pParse->mayAbort)); 15780242055Sdrh if( v ){ 15861019c78Sdrh while( sqlite3VdbeDeletePriorOpcode(v, OP_Close) ){} 15966a5167bSdrh sqlite3VdbeAddOp0(v, OP_Halt); 1600e3d7476Sdrh 161b2445d5eSdrh #if SQLITE_USER_AUTHENTICATION 162b2445d5eSdrh if( pParse->nTableLock>0 && db->init.busy==0 ){ 1637883ecfcSdrh sqlite3UserAuthInit(db); 164b2445d5eSdrh if( db->auth.authLevel<UAUTH_User ){ 165b2445d5eSdrh pParse->rc = SQLITE_AUTH_USER; 166b2445d5eSdrh sqlite3ErrorMsg(pParse, "user not authenticated"); 167b2445d5eSdrh return; 168b2445d5eSdrh } 169b2445d5eSdrh } 170b2445d5eSdrh #endif 171b2445d5eSdrh 1720e3d7476Sdrh /* The cookie mask contains one bit for each database file open. 1730e3d7476Sdrh ** (Bit 0 is for main, bit 1 is for temp, and so forth.) Bits are 1740e3d7476Sdrh ** set for each database that is used. Generate code to start a 1750e3d7476Sdrh ** transaction on each used database and to verify the schema cookie 1760e3d7476Sdrh ** on each used database. 1770e3d7476Sdrh */ 178a7ab6d81Sdrh if( db->mallocFailed==0 179a7ab6d81Sdrh && (DbMaskNonZero(pParse->cookieMask) || pParse->pConstExpr) 180a7ab6d81Sdrh ){ 181aceb31b1Sdrh int iDb, i; 182aceb31b1Sdrh assert( sqlite3VdbeGetOp(v, 0)->opcode==OP_Init ); 183aceb31b1Sdrh sqlite3VdbeJumpHere(v, 0); 184a7ab6d81Sdrh for(iDb=0; iDb<db->nDb; iDb++){ 185a7ab6d81Sdrh if( DbMaskTest(pParse->cookieMask, iDb)==0 ) continue; 186fb98264aSdrh sqlite3VdbeUsesBtree(v, iDb); 187b22f7c83Sdrh sqlite3VdbeAddOp4Int(v, 188b22f7c83Sdrh OP_Transaction, /* Opcode */ 189b22f7c83Sdrh iDb, /* P1 */ 190a7ab6d81Sdrh DbMaskTest(pParse->writeMask,iDb), /* P2 */ 191b22f7c83Sdrh pParse->cookieValue[iDb], /* P3 */ 192b22f7c83Sdrh db->aDb[iDb].pSchema->iGeneration /* P4 */ 193b22f7c83Sdrh ); 194b22f7c83Sdrh if( db->init.busy==0 ) sqlite3VdbeChangeP5(v, 1); 1958a939190Sdrh } 196f9e7dda7Sdanielk1977 #ifndef SQLITE_OMIT_VIRTUALTABLE 1974f3dd150Sdrh for(i=0; i<pParse->nVtabLock; i++){ 198595a523aSdanielk1977 char *vtab = (char *)sqlite3GetVTable(db, pParse->apVtabLock[i]); 19966a5167bSdrh sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB); 200f9e7dda7Sdanielk1977 } 2014f3dd150Sdrh pParse->nVtabLock = 0; 202f9e7dda7Sdanielk1977 #endif 203c00da105Sdanielk1977 204c00da105Sdanielk1977 /* Once all the cookies have been verified and transactions opened, 205c00da105Sdanielk1977 ** obtain the required table-locks. This is a no-op unless the 206c00da105Sdanielk1977 ** shared-cache feature is enabled. 207c00da105Sdanielk1977 */ 208c00da105Sdanielk1977 codeTableLocks(pParse); 2090b9f50d8Sdrh 2100b9f50d8Sdrh /* Initialize any AUTOINCREMENT data structures required. 2110b9f50d8Sdrh */ 2120b9f50d8Sdrh sqlite3AutoincrementBegin(pParse); 2130b9f50d8Sdrh 214f30a969bSdrh /* Code constant expressions that where factored out of inner loops */ 215f30a969bSdrh if( pParse->pConstExpr ){ 216f30a969bSdrh ExprList *pEL = pParse->pConstExpr; 217aceb31b1Sdrh pParse->okConstFactor = 0; 218f30a969bSdrh for(i=0; i<pEL->nExpr; i++){ 219c2acc4e4Sdrh sqlite3ExprCode(pParse, pEL->a[i].pExpr, pEL->a[i].u.iConstExprReg); 220f30a969bSdrh } 221f30a969bSdrh } 222f30a969bSdrh 2230b9f50d8Sdrh /* Finally, jump back to the beginning of the executable code. */ 224aceb31b1Sdrh sqlite3VdbeAddOp2(v, OP_Goto, 0, 1); 22580242055Sdrh } 22671c697efSdrh } 22771c697efSdrh 2283f7d4e49Sdrh 22980242055Sdrh /* Get the VDBE program ready for execution 23080242055Sdrh */ 231126a6e26Sdrh if( v && pParse->nErr==0 && !db->mallocFailed ){ 232ceea3321Sdrh assert( pParse->iCacheLevel==0 ); /* Disables and re-enables match */ 2333492dd71Sdrh /* A minimum of one cursor is required if autoincrement is used 2343492dd71Sdrh * See ticket [a696379c1f08866] */ 2353492dd71Sdrh if( pParse->pAinc!=0 && pParse->nTab==0 ) pParse->nTab = 1; 236124c0b49Sdrh sqlite3VdbeMakeReady(v, pParse); 237441daf68Sdanielk1977 pParse->rc = SQLITE_DONE; 238b86ccfb2Sdrh pParse->colNamesSet = 0; 239e294da02Sdrh }else{ 240483750baSdrh pParse->rc = SQLITE_ERROR; 24175897234Sdrh } 242a226d054Sdrh pParse->nTab = 0; 243a226d054Sdrh pParse->nMem = 0; 244a226d054Sdrh pParse->nSet = 0; 2457c972decSdrh pParse->nVar = 0; 246a7ab6d81Sdrh DbMaskZero(pParse->cookieMask); 24775897234Sdrh } 24875897234Sdrh 24975897234Sdrh /* 250205f48e6Sdrh ** Run the parser and code generator recursively in order to generate 251205f48e6Sdrh ** code for the SQL statement given onto the end of the pParse context 252205f48e6Sdrh ** currently under construction. When the parser is run recursively 253205f48e6Sdrh ** this way, the final OP_Halt is not appended and other initialization 254205f48e6Sdrh ** and finalization steps are omitted because those are handling by the 255205f48e6Sdrh ** outermost parser. 256205f48e6Sdrh ** 257205f48e6Sdrh ** Not everything is nestable. This facility is designed to permit 258205f48e6Sdrh ** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER. Use 259f1974846Sdrh ** care if you decide to try to use this routine for some other purposes. 260205f48e6Sdrh */ 261205f48e6Sdrh void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){ 262205f48e6Sdrh va_list ap; 263205f48e6Sdrh char *zSql; 264fb45d8c5Sdrh char *zErrMsg = 0; 265633e6d57Sdrh sqlite3 *db = pParse->db; 266f1974846Sdrh # define SAVE_SZ (sizeof(Parse) - offsetof(Parse,nVar)) 267f1974846Sdrh char saveBuf[SAVE_SZ]; 268f1974846Sdrh 269205f48e6Sdrh if( pParse->nErr ) return; 270205f48e6Sdrh assert( pParse->nested<10 ); /* Nesting should only be of limited depth */ 271205f48e6Sdrh va_start(ap, zFormat); 272633e6d57Sdrh zSql = sqlite3VMPrintf(db, zFormat, ap); 273205f48e6Sdrh va_end(ap); 27473c42a13Sdrh if( zSql==0 ){ 27573c42a13Sdrh return; /* A malloc must have failed */ 27673c42a13Sdrh } 277205f48e6Sdrh pParse->nested++; 278f1974846Sdrh memcpy(saveBuf, &pParse->nVar, SAVE_SZ); 279f1974846Sdrh memset(&pParse->nVar, 0, SAVE_SZ); 280fb45d8c5Sdrh sqlite3RunParser(pParse, zSql, &zErrMsg); 281633e6d57Sdrh sqlite3DbFree(db, zErrMsg); 282633e6d57Sdrh sqlite3DbFree(db, zSql); 283f1974846Sdrh memcpy(&pParse->nVar, saveBuf, SAVE_SZ); 284205f48e6Sdrh pParse->nested--; 285205f48e6Sdrh } 286205f48e6Sdrh 287d4530979Sdrh #if SQLITE_USER_AUTHENTICATION 288d4530979Sdrh /* 289d4530979Sdrh ** Return TRUE if zTable is the name of the system table that stores the 290d4530979Sdrh ** list of users and their access credentials. 291d4530979Sdrh */ 292d4530979Sdrh int sqlite3UserAuthTable(const char *zTable){ 293d4530979Sdrh return sqlite3_stricmp(zTable, "sqlite_user")==0; 294d4530979Sdrh } 295d4530979Sdrh #endif 296d4530979Sdrh 297205f48e6Sdrh /* 2988a41449eSdanielk1977 ** Locate the in-memory structure that describes a particular database 2998a41449eSdanielk1977 ** table given the name of that table and (optionally) the name of the 3008a41449eSdanielk1977 ** database containing the table. Return NULL if not found. 301a69d9168Sdrh ** 3028a41449eSdanielk1977 ** If zDatabase is 0, all databases are searched for the table and the 3038a41449eSdanielk1977 ** first matching table is returned. (No checking for duplicate table 3048a41449eSdanielk1977 ** names is done.) The search order is TEMP first, then MAIN, then any 3058a41449eSdanielk1977 ** auxiliary databases added using the ATTACH command. 306f26e09c8Sdrh ** 3074adee20fSdanielk1977 ** See also sqlite3LocateTable(). 30875897234Sdrh */ 3099bb575fdSdrh Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){ 310d24cc427Sdrh Table *p = 0; 311d24cc427Sdrh int i; 3129ca95730Sdrh 3132120608eSdrh /* All mutexes are required for schema access. Make sure we hold them. */ 3142120608eSdrh assert( zDatabase!=0 || sqlite3BtreeHoldsAllMutexes(db) ); 315d4530979Sdrh #if SQLITE_USER_AUTHENTICATION 316d4530979Sdrh /* Only the admin user is allowed to know that the sqlite_user table 317d4530979Sdrh ** exists */ 318e933b83fSdrh if( db->auth.authLevel<UAUTH_Admin && sqlite3UserAuthTable(zName)!=0 ){ 319e933b83fSdrh return 0; 320e933b83fSdrh } 321d4530979Sdrh #endif 32253c0f748Sdanielk1977 for(i=OMIT_TEMPDB; i<db->nDb; i++){ 323812d7a21Sdrh int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */ 3244adee20fSdanielk1977 if( zDatabase!=0 && sqlite3StrICmp(zDatabase, db->aDb[j].zName) ) continue; 3252120608eSdrh assert( sqlite3SchemaMutexHeld(db, j, 0) ); 326acbcb7e0Sdrh p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName); 327d24cc427Sdrh if( p ) break; 328d24cc427Sdrh } 32974e24cd0Sdrh return p; 33075897234Sdrh } 33175897234Sdrh 33275897234Sdrh /* 3338a41449eSdanielk1977 ** Locate the in-memory structure that describes a particular database 3348a41449eSdanielk1977 ** table given the name of that table and (optionally) the name of the 3358a41449eSdanielk1977 ** database containing the table. Return NULL if not found. Also leave an 3368a41449eSdanielk1977 ** error message in pParse->zErrMsg. 337a69d9168Sdrh ** 3388a41449eSdanielk1977 ** The difference between this routine and sqlite3FindTable() is that this 3398a41449eSdanielk1977 ** routine leaves an error message in pParse->zErrMsg where 3408a41449eSdanielk1977 ** sqlite3FindTable() does not. 341a69d9168Sdrh */ 342ca424114Sdrh Table *sqlite3LocateTable( 343ca424114Sdrh Parse *pParse, /* context in which to report errors */ 344ca424114Sdrh int isView, /* True if looking for a VIEW rather than a TABLE */ 345ca424114Sdrh const char *zName, /* Name of the table we are looking for */ 346ca424114Sdrh const char *zDbase /* Name of the database. Might be NULL */ 347ca424114Sdrh ){ 348a69d9168Sdrh Table *p; 349f26e09c8Sdrh 3508a41449eSdanielk1977 /* Read the database schema. If an error occurs, leave an error message 3518a41449eSdanielk1977 ** and code in pParse and return NULL. */ 3528a41449eSdanielk1977 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){ 3538a41449eSdanielk1977 return 0; 3548a41449eSdanielk1977 } 3558a41449eSdanielk1977 3564adee20fSdanielk1977 p = sqlite3FindTable(pParse->db, zName, zDbase); 357a69d9168Sdrh if( p==0 ){ 358c743579eSdrh const char *zMsg = isView ? "no such view" : "no such table"; 35951be3873Sdrh #ifndef SQLITE_OMIT_VIRTUAL_TABLE 36051be3873Sdrh /* If zName is the not the name of a table in the schema created using 36151be3873Sdrh ** CREATE, then check to see if it is the name of an virtual table that 36251be3873Sdrh ** can be an eponymous virtual table. */ 36351be3873Sdrh Module *pMod = (Module*)sqlite3HashFind(&pParse->db->aModule, zName); 36451be3873Sdrh if( pMod && sqlite3VtabEponymousTableInit(pParse, pMod) ){ 36551be3873Sdrh return pMod->pEpoTab; 36651be3873Sdrh } 36751be3873Sdrh #endif 3688a41449eSdanielk1977 if( zDbase ){ 369ca424114Sdrh sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName); 370a69d9168Sdrh }else{ 371ca424114Sdrh sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName); 372a69d9168Sdrh } 373a6ecd338Sdrh pParse->checkSchema = 1; 374a69d9168Sdrh } 375e933b83fSdrh #if SQLITE_USER_AUTHENICATION 376e933b83fSdrh else if( pParse->db->auth.authLevel<UAUTH_User ){ 377e933b83fSdrh sqlite3ErrorMsg(pParse, "user not authenticated"); 378e933b83fSdrh p = 0; 379e933b83fSdrh } 380e933b83fSdrh #endif 381a69d9168Sdrh return p; 382a69d9168Sdrh } 383a69d9168Sdrh 384a69d9168Sdrh /* 38541fb5cd1Sdan ** Locate the table identified by *p. 38641fb5cd1Sdan ** 38741fb5cd1Sdan ** This is a wrapper around sqlite3LocateTable(). The difference between 38841fb5cd1Sdan ** sqlite3LocateTable() and this function is that this function restricts 38941fb5cd1Sdan ** the search to schema (p->pSchema) if it is not NULL. p->pSchema may be 39041fb5cd1Sdan ** non-NULL if it is part of a view or trigger program definition. See 39141fb5cd1Sdan ** sqlite3FixSrcList() for details. 39241fb5cd1Sdan */ 39341fb5cd1Sdan Table *sqlite3LocateTableItem( 39441fb5cd1Sdan Parse *pParse, 39541fb5cd1Sdan int isView, 39641fb5cd1Sdan struct SrcList_item *p 39741fb5cd1Sdan ){ 39841fb5cd1Sdan const char *zDb; 39941fb5cd1Sdan assert( p->pSchema==0 || p->zDatabase==0 ); 40041fb5cd1Sdan if( p->pSchema ){ 40141fb5cd1Sdan int iDb = sqlite3SchemaToIndex(pParse->db, p->pSchema); 40241fb5cd1Sdan zDb = pParse->db->aDb[iDb].zName; 40341fb5cd1Sdan }else{ 40441fb5cd1Sdan zDb = p->zDatabase; 40541fb5cd1Sdan } 40641fb5cd1Sdan return sqlite3LocateTable(pParse, isView, p->zName, zDb); 40741fb5cd1Sdan } 40841fb5cd1Sdan 40941fb5cd1Sdan /* 410a69d9168Sdrh ** Locate the in-memory structure that describes 411a69d9168Sdrh ** a particular index given the name of that index 412a69d9168Sdrh ** and the name of the database that contains the index. 413f57b3399Sdrh ** Return NULL if not found. 414f26e09c8Sdrh ** 415f26e09c8Sdrh ** If zDatabase is 0, all databases are searched for the 416f26e09c8Sdrh ** table and the first matching index is returned. (No checking 417f26e09c8Sdrh ** for duplicate index names is done.) The search order is 418f26e09c8Sdrh ** TEMP first, then MAIN, then any auxiliary databases added 419f26e09c8Sdrh ** using the ATTACH command. 42075897234Sdrh */ 4219bb575fdSdrh Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){ 422d24cc427Sdrh Index *p = 0; 423d24cc427Sdrh int i; 4242120608eSdrh /* All mutexes are required for schema access. Make sure we hold them. */ 4252120608eSdrh assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) ); 42653c0f748Sdanielk1977 for(i=OMIT_TEMPDB; i<db->nDb; i++){ 427812d7a21Sdrh int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */ 428e501b89aSdanielk1977 Schema *pSchema = db->aDb[j].pSchema; 4290449171eSdrh assert( pSchema ); 4304adee20fSdanielk1977 if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zName) ) continue; 4312120608eSdrh assert( sqlite3SchemaMutexHeld(db, j, 0) ); 432acbcb7e0Sdrh p = sqlite3HashFind(&pSchema->idxHash, zName); 433d24cc427Sdrh if( p ) break; 434d24cc427Sdrh } 43574e24cd0Sdrh return p; 43675897234Sdrh } 43775897234Sdrh 43875897234Sdrh /* 439956bc92cSdrh ** Reclaim the memory used by an index 440956bc92cSdrh */ 4411feeaed2Sdan static void freeIndex(sqlite3 *db, Index *p){ 44292aa5eacSdrh #ifndef SQLITE_OMIT_ANALYZE 443d46def77Sdan sqlite3DeleteIndexSamples(db, p); 44492aa5eacSdrh #endif 4451fe0537eSdrh sqlite3ExprDelete(db, p->pPartIdxWhere); 446633e6d57Sdrh sqlite3DbFree(db, p->zColAff); 4477f9c5dbfSdrh if( p->isResized ) sqlite3DbFree(db, p->azColl); 44875b170b1Sdrh #ifdef SQLITE_ENABLE_STAT3_OR_STAT4 44975b170b1Sdrh sqlite3_free(p->aiRowEst); 45075b170b1Sdrh #endif 451633e6d57Sdrh sqlite3DbFree(db, p); 452956bc92cSdrh } 453956bc92cSdrh 454956bc92cSdrh /* 455c96d8530Sdrh ** For the index called zIdxName which is found in the database iDb, 456c96d8530Sdrh ** unlike that index from its Table then remove the index from 457c96d8530Sdrh ** the index hash table and free all memory structures associated 458c96d8530Sdrh ** with the index. 4595e00f6c7Sdrh */ 4609bb575fdSdrh void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){ 461956bc92cSdrh Index *pIndex; 4622120608eSdrh Hash *pHash; 463956bc92cSdrh 4642120608eSdrh assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); 4652120608eSdrh pHash = &db->aDb[iDb].pSchema->idxHash; 466acbcb7e0Sdrh pIndex = sqlite3HashInsert(pHash, zIdxName, 0); 46722645842Sdrh if( ALWAYS(pIndex) ){ 4685e00f6c7Sdrh if( pIndex->pTable->pIndex==pIndex ){ 4695e00f6c7Sdrh pIndex->pTable->pIndex = pIndex->pNext; 4705e00f6c7Sdrh }else{ 4715e00f6c7Sdrh Index *p; 4720449171eSdrh /* Justification of ALWAYS(); The index must be on the list of 4730449171eSdrh ** indices. */ 4740449171eSdrh p = pIndex->pTable->pIndex; 4750449171eSdrh while( ALWAYS(p) && p->pNext!=pIndex ){ p = p->pNext; } 4760449171eSdrh if( ALWAYS(p && p->pNext==pIndex) ){ 4775e00f6c7Sdrh p->pNext = pIndex->pNext; 4785e00f6c7Sdrh } 4795e00f6c7Sdrh } 4801feeaed2Sdan freeIndex(db, pIndex); 481956bc92cSdrh } 482956bc92cSdrh db->flags |= SQLITE_InternChanges; 4835e00f6c7Sdrh } 4845e00f6c7Sdrh 4855e00f6c7Sdrh /* 48681028a45Sdrh ** Look through the list of open database files in db->aDb[] and if 48781028a45Sdrh ** any have been closed, remove them from the list. Reallocate the 48881028a45Sdrh ** db->aDb[] structure to a smaller size, if possible. 4891c2d8414Sdrh ** 49081028a45Sdrh ** Entry 0 (the "main" database) and entry 1 (the "temp" database) 49181028a45Sdrh ** are never candidates for being collapsed. 49274e24cd0Sdrh */ 49381028a45Sdrh void sqlite3CollapseDatabaseArray(sqlite3 *db){ 4941c2d8414Sdrh int i, j; 4951c2d8414Sdrh for(i=j=2; i<db->nDb; i++){ 4964d189ca4Sdrh struct Db *pDb = &db->aDb[i]; 4974d189ca4Sdrh if( pDb->pBt==0 ){ 498633e6d57Sdrh sqlite3DbFree(db, pDb->zName); 4994d189ca4Sdrh pDb->zName = 0; 5001c2d8414Sdrh continue; 5011c2d8414Sdrh } 5021c2d8414Sdrh if( j<i ){ 5038bf8dc92Sdrh db->aDb[j] = db->aDb[i]; 5041c2d8414Sdrh } 5058bf8dc92Sdrh j++; 5061c2d8414Sdrh } 5071c2d8414Sdrh memset(&db->aDb[j], 0, (db->nDb-j)*sizeof(db->aDb[j])); 5081c2d8414Sdrh db->nDb = j; 5091c2d8414Sdrh if( db->nDb<=2 && db->aDb!=db->aDbStatic ){ 5101c2d8414Sdrh memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0])); 511633e6d57Sdrh sqlite3DbFree(db, db->aDb); 5121c2d8414Sdrh db->aDb = db->aDbStatic; 5131c2d8414Sdrh } 514e0bc4048Sdrh } 515e0bc4048Sdrh 516e0bc4048Sdrh /* 51781028a45Sdrh ** Reset the schema for the database at index iDb. Also reset the 51881028a45Sdrh ** TEMP schema. 51981028a45Sdrh */ 52081028a45Sdrh void sqlite3ResetOneSchema(sqlite3 *db, int iDb){ 521bae591a9Sdrh Db *pDb; 52281028a45Sdrh assert( iDb<db->nDb ); 52381028a45Sdrh 52481028a45Sdrh /* Case 1: Reset the single schema identified by iDb */ 525bae591a9Sdrh pDb = &db->aDb[iDb]; 52681028a45Sdrh assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); 52781028a45Sdrh assert( pDb->pSchema!=0 ); 52881028a45Sdrh sqlite3SchemaClear(pDb->pSchema); 52981028a45Sdrh 53081028a45Sdrh /* If any database other than TEMP is reset, then also reset TEMP 53181028a45Sdrh ** since TEMP might be holding triggers that reference tables in the 53281028a45Sdrh ** other database. 53381028a45Sdrh */ 53481028a45Sdrh if( iDb!=1 ){ 53581028a45Sdrh pDb = &db->aDb[1]; 53681028a45Sdrh assert( pDb->pSchema!=0 ); 53781028a45Sdrh sqlite3SchemaClear(pDb->pSchema); 53881028a45Sdrh } 53981028a45Sdrh return; 54081028a45Sdrh } 54181028a45Sdrh 54281028a45Sdrh /* 54381028a45Sdrh ** Erase all schema information from all attached databases (including 54481028a45Sdrh ** "main" and "temp") for a single database connection. 54581028a45Sdrh */ 54681028a45Sdrh void sqlite3ResetAllSchemasOfConnection(sqlite3 *db){ 54781028a45Sdrh int i; 54881028a45Sdrh sqlite3BtreeEnterAll(db); 54981028a45Sdrh for(i=0; i<db->nDb; i++){ 55081028a45Sdrh Db *pDb = &db->aDb[i]; 55181028a45Sdrh if( pDb->pSchema ){ 55281028a45Sdrh sqlite3SchemaClear(pDb->pSchema); 55381028a45Sdrh } 55481028a45Sdrh } 55581028a45Sdrh db->flags &= ~SQLITE_InternChanges; 55681028a45Sdrh sqlite3VtabUnlockList(db); 55781028a45Sdrh sqlite3BtreeLeaveAll(db); 55881028a45Sdrh sqlite3CollapseDatabaseArray(db); 55981028a45Sdrh } 56081028a45Sdrh 56181028a45Sdrh /* 562e0bc4048Sdrh ** This routine is called when a commit occurs. 563e0bc4048Sdrh */ 5649bb575fdSdrh void sqlite3CommitInternalChanges(sqlite3 *db){ 565e0bc4048Sdrh db->flags &= ~SQLITE_InternChanges; 56674e24cd0Sdrh } 56774e24cd0Sdrh 56874e24cd0Sdrh /* 569d46def77Sdan ** Delete memory allocated for the column names of a table or view (the 570d46def77Sdan ** Table.aCol[] array). 571956bc92cSdrh */ 57251be3873Sdrh void sqlite3DeleteColumnNames(sqlite3 *db, Table *pTable){ 573956bc92cSdrh int i; 574956bc92cSdrh Column *pCol; 575956bc92cSdrh assert( pTable!=0 ); 576dd5b2fa5Sdrh if( (pCol = pTable->aCol)!=0 ){ 577dd5b2fa5Sdrh for(i=0; i<pTable->nCol; i++, pCol++){ 578633e6d57Sdrh sqlite3DbFree(db, pCol->zName); 579633e6d57Sdrh sqlite3ExprDelete(db, pCol->pDflt); 580b7916a78Sdrh sqlite3DbFree(db, pCol->zDflt); 581633e6d57Sdrh sqlite3DbFree(db, pCol->zType); 582633e6d57Sdrh sqlite3DbFree(db, pCol->zColl); 583956bc92cSdrh } 584633e6d57Sdrh sqlite3DbFree(db, pTable->aCol); 585dd5b2fa5Sdrh } 586956bc92cSdrh } 587956bc92cSdrh 588956bc92cSdrh /* 58975897234Sdrh ** Remove the memory data structures associated with the given 590967e8b73Sdrh ** Table. No changes are made to disk by this routine. 59175897234Sdrh ** 59275897234Sdrh ** This routine just deletes the data structure. It does not unlink 593e61922a6Sdrh ** the table data structure from the hash table. But it does destroy 594c2eef3b3Sdrh ** memory structures of the indices and foreign keys associated with 595c2eef3b3Sdrh ** the table. 59629ddd3acSdrh ** 59729ddd3acSdrh ** The db parameter is optional. It is needed if the Table object 59829ddd3acSdrh ** contains lookaside memory. (Table objects in the schema do not use 59929ddd3acSdrh ** lookaside memory, but some ephemeral Table objects do.) Or the 60029ddd3acSdrh ** db parameter can be used with db->pnBytesFreed to measure the memory 60129ddd3acSdrh ** used by the Table object. 60275897234Sdrh */ 6031feeaed2Sdan void sqlite3DeleteTable(sqlite3 *db, Table *pTable){ 60475897234Sdrh Index *pIndex, *pNext; 60529ddd3acSdrh TESTONLY( int nLookaside; ) /* Used to verify lookaside not used for schema */ 606c2eef3b3Sdrh 607d46def77Sdan assert( !pTable || pTable->nRef>0 ); 608c2eef3b3Sdrh 609ed8a3bb1Sdrh /* Do not delete the table until the reference count reaches zero. */ 610d46def77Sdan if( !pTable ) return; 611d46def77Sdan if( ((!db || db->pnBytesFreed==0) && (--pTable->nRef)>0) ) return; 612ed8a3bb1Sdrh 61329ddd3acSdrh /* Record the number of outstanding lookaside allocations in schema Tables 61429ddd3acSdrh ** prior to doing any free() operations. Since schema Tables do not use 61529ddd3acSdrh ** lookaside, this number should not change. */ 61629ddd3acSdrh TESTONLY( nLookaside = (db && (pTable->tabFlags & TF_Ephemeral)==0) ? 61729ddd3acSdrh db->lookaside.nOut : 0 ); 61829ddd3acSdrh 619d46def77Sdan /* Delete all indices associated with this table. */ 620c2eef3b3Sdrh for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){ 621c2eef3b3Sdrh pNext = pIndex->pNext; 622da184236Sdanielk1977 assert( pIndex->pSchema==pTable->pSchema ); 623d46def77Sdan if( !db || db->pnBytesFreed==0 ){ 624d46def77Sdan char *zName = pIndex->zName; 625d46def77Sdan TESTONLY ( Index *pOld = ) sqlite3HashInsert( 626acbcb7e0Sdrh &pIndex->pSchema->idxHash, zName, 0 627d46def77Sdan ); 6282120608eSdrh assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) ); 629d46def77Sdan assert( pOld==pIndex || pOld==0 ); 630d46def77Sdan } 631d46def77Sdan freeIndex(db, pIndex); 632c2eef3b3Sdrh } 633c2eef3b3Sdrh 6341da40a38Sdan /* Delete any foreign keys attached to this table. */ 6351feeaed2Sdan sqlite3FkDelete(db, pTable); 636c2eef3b3Sdrh 637c2eef3b3Sdrh /* Delete the Table structure itself. 638c2eef3b3Sdrh */ 63951be3873Sdrh sqlite3DeleteColumnNames(db, pTable); 640633e6d57Sdrh sqlite3DbFree(db, pTable->zName); 641633e6d57Sdrh sqlite3DbFree(db, pTable->zColAff); 642633e6d57Sdrh sqlite3SelectDelete(db, pTable->pSelect); 6432938f924Sdrh sqlite3ExprListDelete(db, pTable->pCheck); 644078e4084Sdrh #ifndef SQLITE_OMIT_VIRTUALTABLE 6451feeaed2Sdan sqlite3VtabClear(db, pTable); 646078e4084Sdrh #endif 647633e6d57Sdrh sqlite3DbFree(db, pTable); 64829ddd3acSdrh 64929ddd3acSdrh /* Verify that no lookaside memory was used by schema tables */ 65029ddd3acSdrh assert( nLookaside==0 || nLookaside==db->lookaside.nOut ); 65175897234Sdrh } 65275897234Sdrh 65375897234Sdrh /* 6545edc3124Sdrh ** Unlink the given table from the hash tables and the delete the 655c2eef3b3Sdrh ** table structure with all its indices and foreign keys. 6565edc3124Sdrh */ 6579bb575fdSdrh void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){ 658956bc92cSdrh Table *p; 659956bc92cSdrh Db *pDb; 660956bc92cSdrh 661d229ca94Sdrh assert( db!=0 ); 662956bc92cSdrh assert( iDb>=0 && iDb<db->nDb ); 663972a2311Sdrh assert( zTabName ); 6642120608eSdrh assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); 665972a2311Sdrh testcase( zTabName[0]==0 ); /* Zero-length table names are allowed */ 666956bc92cSdrh pDb = &db->aDb[iDb]; 667acbcb7e0Sdrh p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName, 0); 6681feeaed2Sdan sqlite3DeleteTable(db, p); 669956bc92cSdrh db->flags |= SQLITE_InternChanges; 670956bc92cSdrh } 67174e24cd0Sdrh 67274e24cd0Sdrh /* 673a99db3b6Sdrh ** Given a token, return a string that consists of the text of that 67424fb627aSdrh ** token. Space to hold the returned string 675a99db3b6Sdrh ** is obtained from sqliteMalloc() and must be freed by the calling 676a99db3b6Sdrh ** function. 67775897234Sdrh ** 67824fb627aSdrh ** Any quotation marks (ex: "name", 'name', [name], or `name`) that 67924fb627aSdrh ** surround the body of the token are removed. 68024fb627aSdrh ** 681c96d8530Sdrh ** Tokens are often just pointers into the original SQL text and so 682a99db3b6Sdrh ** are not \000 terminated and are not persistent. The returned string 683a99db3b6Sdrh ** is \000 terminated and is persistent. 68475897234Sdrh */ 68517435752Sdrh char *sqlite3NameFromToken(sqlite3 *db, Token *pName){ 686a99db3b6Sdrh char *zName; 687a99db3b6Sdrh if( pName ){ 68817435752Sdrh zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n); 689b7916a78Sdrh sqlite3Dequote(zName); 690a99db3b6Sdrh }else{ 691a99db3b6Sdrh zName = 0; 692a99db3b6Sdrh } 69375897234Sdrh return zName; 69475897234Sdrh } 69575897234Sdrh 69675897234Sdrh /* 697cbb18d22Sdanielk1977 ** Open the sqlite_master table stored in database number iDb for 698cbb18d22Sdanielk1977 ** writing. The table is opened using cursor 0. 699e0bc4048Sdrh */ 700c00da105Sdanielk1977 void sqlite3OpenMasterTable(Parse *p, int iDb){ 701c00da105Sdanielk1977 Vdbe *v = sqlite3GetVdbe(p); 702c00da105Sdanielk1977 sqlite3TableLock(p, iDb, MASTER_ROOT, 1, SCHEMA_TABLE(iDb)); 703261c02d9Sdrh sqlite3VdbeAddOp4Int(v, OP_OpenWrite, 0, MASTER_ROOT, iDb, 5); 7046ab3a2ecSdanielk1977 if( p->nTab==0 ){ 7056ab3a2ecSdanielk1977 p->nTab = 1; 7066ab3a2ecSdanielk1977 } 707e0bc4048Sdrh } 708e0bc4048Sdrh 709e0bc4048Sdrh /* 7100410302eSdanielk1977 ** Parameter zName points to a nul-terminated buffer containing the name 7110410302eSdanielk1977 ** of a database ("main", "temp" or the name of an attached db). This 7120410302eSdanielk1977 ** function returns the index of the named database in db->aDb[], or 7130410302eSdanielk1977 ** -1 if the named db cannot be found. 714cbb18d22Sdanielk1977 */ 7150410302eSdanielk1977 int sqlite3FindDbName(sqlite3 *db, const char *zName){ 716576ec6b3Sdanielk1977 int i = -1; /* Database number */ 71773c42a13Sdrh if( zName ){ 7180410302eSdanielk1977 Db *pDb; 7190410302eSdanielk1977 int n = sqlite3Strlen30(zName); 720576ec6b3Sdanielk1977 for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){ 721ea678832Sdrh if( (!OMIT_TEMPDB || i!=1 ) && n==sqlite3Strlen30(pDb->zName) && 72253c0f748Sdanielk1977 0==sqlite3StrICmp(pDb->zName, zName) ){ 723576ec6b3Sdanielk1977 break; 724576ec6b3Sdanielk1977 } 725576ec6b3Sdanielk1977 } 726576ec6b3Sdanielk1977 } 727cbb18d22Sdanielk1977 return i; 728cbb18d22Sdanielk1977 } 729cbb18d22Sdanielk1977 7300410302eSdanielk1977 /* 7310410302eSdanielk1977 ** The token *pName contains the name of a database (either "main" or 7320410302eSdanielk1977 ** "temp" or the name of an attached db). This routine returns the 7330410302eSdanielk1977 ** index of the named database in db->aDb[], or -1 if the named db 7340410302eSdanielk1977 ** does not exist. 7350410302eSdanielk1977 */ 7360410302eSdanielk1977 int sqlite3FindDb(sqlite3 *db, Token *pName){ 7370410302eSdanielk1977 int i; /* Database number */ 7380410302eSdanielk1977 char *zName; /* Name we are searching for */ 7390410302eSdanielk1977 zName = sqlite3NameFromToken(db, pName); 7400410302eSdanielk1977 i = sqlite3FindDbName(db, zName); 7410410302eSdanielk1977 sqlite3DbFree(db, zName); 7420410302eSdanielk1977 return i; 7430410302eSdanielk1977 } 7440410302eSdanielk1977 7450e3d7476Sdrh /* The table or view or trigger name is passed to this routine via tokens 7460e3d7476Sdrh ** pName1 and pName2. If the table name was fully qualified, for example: 7470e3d7476Sdrh ** 7480e3d7476Sdrh ** CREATE TABLE xxx.yyy (...); 7490e3d7476Sdrh ** 7500e3d7476Sdrh ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if 7510e3d7476Sdrh ** the table name is not fully qualified, i.e.: 7520e3d7476Sdrh ** 7530e3d7476Sdrh ** CREATE TABLE yyy(...); 7540e3d7476Sdrh ** 7550e3d7476Sdrh ** Then pName1 is set to "yyy" and pName2 is "". 7560e3d7476Sdrh ** 7570e3d7476Sdrh ** This routine sets the *ppUnqual pointer to point at the token (pName1 or 7580e3d7476Sdrh ** pName2) that stores the unqualified table name. The index of the 7590e3d7476Sdrh ** database "xxx" is returned. 7600e3d7476Sdrh */ 761ef2cb63eSdanielk1977 int sqlite3TwoPartName( 7620e3d7476Sdrh Parse *pParse, /* Parsing and code generating context */ 76390f5ecb3Sdrh Token *pName1, /* The "xxx" in the name "xxx.yyy" or "xxx" */ 7640e3d7476Sdrh Token *pName2, /* The "yyy" in the name "xxx.yyy" */ 7650e3d7476Sdrh Token **pUnqual /* Write the unqualified object name here */ 766cbb18d22Sdanielk1977 ){ 7670e3d7476Sdrh int iDb; /* Database holding the object */ 768cbb18d22Sdanielk1977 sqlite3 *db = pParse->db; 769cbb18d22Sdanielk1977 770c4a64facSdrh if( ALWAYS(pName2!=0) && pName2->n>0 ){ 771dcc50b74Sshane if( db->init.busy ) { 772dcc50b74Sshane sqlite3ErrorMsg(pParse, "corrupt database"); 773dcc50b74Sshane return -1; 774dcc50b74Sshane } 775cbb18d22Sdanielk1977 *pUnqual = pName2; 776ff2d5ea4Sdrh iDb = sqlite3FindDb(db, pName1); 777cbb18d22Sdanielk1977 if( iDb<0 ){ 778cbb18d22Sdanielk1977 sqlite3ErrorMsg(pParse, "unknown database %T", pName1); 779cbb18d22Sdanielk1977 return -1; 780cbb18d22Sdanielk1977 } 781cbb18d22Sdanielk1977 }else{ 782cbb18d22Sdanielk1977 assert( db->init.iDb==0 || db->init.busy ); 783cbb18d22Sdanielk1977 iDb = db->init.iDb; 784cbb18d22Sdanielk1977 *pUnqual = pName1; 785cbb18d22Sdanielk1977 } 786cbb18d22Sdanielk1977 return iDb; 787cbb18d22Sdanielk1977 } 788cbb18d22Sdanielk1977 789cbb18d22Sdanielk1977 /* 790d8123366Sdanielk1977 ** This routine is used to check if the UTF-8 string zName is a legal 791d8123366Sdanielk1977 ** unqualified name for a new schema object (table, index, view or 792d8123366Sdanielk1977 ** trigger). All names are legal except those that begin with the string 793d8123366Sdanielk1977 ** "sqlite_" (in upper, lower or mixed case). This portion of the namespace 794d8123366Sdanielk1977 ** is reserved for internal use. 795d8123366Sdanielk1977 */ 796d8123366Sdanielk1977 int sqlite3CheckObjectName(Parse *pParse, const char *zName){ 797f1974846Sdrh if( !pParse->db->init.busy && pParse->nested==0 7983a3f38e0Sdanielk1977 && (pParse->db->flags & SQLITE_WriteSchema)==0 799f1974846Sdrh && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){ 800d8123366Sdanielk1977 sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName); 801d8123366Sdanielk1977 return SQLITE_ERROR; 802d8123366Sdanielk1977 } 803d8123366Sdanielk1977 return SQLITE_OK; 804d8123366Sdanielk1977 } 805d8123366Sdanielk1977 806d8123366Sdanielk1977 /* 8074415628aSdrh ** Return the PRIMARY KEY index of a table 8084415628aSdrh */ 8094415628aSdrh Index *sqlite3PrimaryKeyIndex(Table *pTab){ 8104415628aSdrh Index *p; 81148dd1d8eSdrh for(p=pTab->pIndex; p && !IsPrimaryKeyIndex(p); p=p->pNext){} 8124415628aSdrh return p; 8134415628aSdrh } 8144415628aSdrh 8154415628aSdrh /* 8164415628aSdrh ** Return the column of index pIdx that corresponds to table 8174415628aSdrh ** column iCol. Return -1 if not found. 8184415628aSdrh */ 8194415628aSdrh i16 sqlite3ColumnOfIndex(Index *pIdx, i16 iCol){ 8204415628aSdrh int i; 8214415628aSdrh for(i=0; i<pIdx->nColumn; i++){ 8224415628aSdrh if( iCol==pIdx->aiColumn[i] ) return i; 8234415628aSdrh } 8244415628aSdrh return -1; 8254415628aSdrh } 8264415628aSdrh 8274415628aSdrh /* 82875897234Sdrh ** Begin constructing a new table representation in memory. This is 82975897234Sdrh ** the first of several action routines that get called in response 830d9b0257aSdrh ** to a CREATE TABLE statement. In particular, this routine is called 83174161705Sdrh ** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp 832e0bc4048Sdrh ** flag is true if the table should be stored in the auxiliary database 833e0bc4048Sdrh ** file instead of in the main database file. This is normally the case 834e0bc4048Sdrh ** when the "TEMP" or "TEMPORARY" keyword occurs in between 835f57b3399Sdrh ** CREATE and TABLE. 836d9b0257aSdrh ** 837f57b3399Sdrh ** The new table record is initialized and put in pParse->pNewTable. 838f57b3399Sdrh ** As more of the CREATE TABLE statement is parsed, additional action 839f57b3399Sdrh ** routines will be called to add more information to this record. 8404adee20fSdanielk1977 ** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine 841f57b3399Sdrh ** is called to complete the construction of the new table record. 84275897234Sdrh */ 8434adee20fSdanielk1977 void sqlite3StartTable( 844e5f9c644Sdrh Parse *pParse, /* Parser context */ 845cbb18d22Sdanielk1977 Token *pName1, /* First part of the name of the table or view */ 846cbb18d22Sdanielk1977 Token *pName2, /* Second part of the name of the table or view */ 847e5f9c644Sdrh int isTemp, /* True if this is a TEMP table */ 848faa59554Sdrh int isView, /* True if this is a VIEW */ 849f1a381e7Sdanielk1977 int isVirtual, /* True if this is a VIRTUAL table */ 850faa59554Sdrh int noErr /* Do nothing if table already exists */ 851e5f9c644Sdrh ){ 85275897234Sdrh Table *pTable; 85323bf66d6Sdrh char *zName = 0; /* The name of the new table */ 8549bb575fdSdrh sqlite3 *db = pParse->db; 855adbca9cfSdrh Vdbe *v; 856cbb18d22Sdanielk1977 int iDb; /* Database number to create the table in */ 857cbb18d22Sdanielk1977 Token *pName; /* Unqualified name of the table to create */ 85875897234Sdrh 859cbb18d22Sdanielk1977 /* The table or view name to create is passed to this routine via tokens 860cbb18d22Sdanielk1977 ** pName1 and pName2. If the table name was fully qualified, for example: 861cbb18d22Sdanielk1977 ** 862cbb18d22Sdanielk1977 ** CREATE TABLE xxx.yyy (...); 863cbb18d22Sdanielk1977 ** 864cbb18d22Sdanielk1977 ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if 865cbb18d22Sdanielk1977 ** the table name is not fully qualified, i.e.: 866cbb18d22Sdanielk1977 ** 867cbb18d22Sdanielk1977 ** CREATE TABLE yyy(...); 868cbb18d22Sdanielk1977 ** 869cbb18d22Sdanielk1977 ** Then pName1 is set to "yyy" and pName2 is "". 870cbb18d22Sdanielk1977 ** 871cbb18d22Sdanielk1977 ** The call below sets the pName pointer to point at the token (pName1 or 872cbb18d22Sdanielk1977 ** pName2) that stores the unqualified table name. The variable iDb is 873cbb18d22Sdanielk1977 ** set to the index of the database that the table or view is to be 874cbb18d22Sdanielk1977 ** created in. 875cbb18d22Sdanielk1977 */ 876ef2cb63eSdanielk1977 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName); 877cbb18d22Sdanielk1977 if( iDb<0 ) return; 87872c5ea32Sdan if( !OMIT_TEMPDB && isTemp && pName2->n>0 && iDb!=1 ){ 87972c5ea32Sdan /* If creating a temp table, the name may not be qualified. Unless 88072c5ea32Sdan ** the database name is "temp" anyway. */ 881cbb18d22Sdanielk1977 sqlite3ErrorMsg(pParse, "temporary table name must be unqualified"); 882cbb18d22Sdanielk1977 return; 883cbb18d22Sdanielk1977 } 88453c0f748Sdanielk1977 if( !OMIT_TEMPDB && isTemp ) iDb = 1; 885cbb18d22Sdanielk1977 886cbb18d22Sdanielk1977 pParse->sNameToken = *pName; 88717435752Sdrh zName = sqlite3NameFromToken(db, pName); 888e0048400Sdanielk1977 if( zName==0 ) return; 889d8123366Sdanielk1977 if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){ 89023bf66d6Sdrh goto begin_table_error; 891d8123366Sdanielk1977 } 8921d85d931Sdrh if( db->init.iDb==1 ) isTemp = 1; 893e5f9c644Sdrh #ifndef SQLITE_OMIT_AUTHORIZATION 894d24cc427Sdrh assert( (isTemp & 1)==isTemp ); 895e22a334bSdrh { 896e22a334bSdrh int code; 897cbb18d22Sdanielk1977 char *zDb = db->aDb[iDb].zName; 8984adee20fSdanielk1977 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){ 89923bf66d6Sdrh goto begin_table_error; 900ed6c8671Sdrh } 901e5f9c644Sdrh if( isView ){ 90253c0f748Sdanielk1977 if( !OMIT_TEMPDB && isTemp ){ 903e5f9c644Sdrh code = SQLITE_CREATE_TEMP_VIEW; 904e5f9c644Sdrh }else{ 905e5f9c644Sdrh code = SQLITE_CREATE_VIEW; 906e5f9c644Sdrh } 907e5f9c644Sdrh }else{ 90853c0f748Sdanielk1977 if( !OMIT_TEMPDB && isTemp ){ 909e5f9c644Sdrh code = SQLITE_CREATE_TEMP_TABLE; 910e5f9c644Sdrh }else{ 911e5f9c644Sdrh code = SQLITE_CREATE_TABLE; 912e5f9c644Sdrh } 913e5f9c644Sdrh } 914f1a381e7Sdanielk1977 if( !isVirtual && sqlite3AuthCheck(pParse, code, zName, 0, zDb) ){ 91523bf66d6Sdrh goto begin_table_error; 916e5f9c644Sdrh } 917e5f9c644Sdrh } 918e5f9c644Sdrh #endif 919e5f9c644Sdrh 920f57b3399Sdrh /* Make sure the new table name does not collide with an existing 9213df6b257Sdanielk1977 ** index or table name in the same database. Issue an error message if 9227e6ebfb2Sdanielk1977 ** it does. The exception is if the statement being parsed was passed 9237e6ebfb2Sdanielk1977 ** to an sqlite3_declare_vtab() call. In that case only the column names 9247e6ebfb2Sdanielk1977 ** and types will be used, so there is no need to test for namespace 9257e6ebfb2Sdanielk1977 ** collisions. 926f57b3399Sdrh */ 9277e6ebfb2Sdanielk1977 if( !IN_DECLARE_VTAB ){ 928a16d1060Sdan char *zDb = db->aDb[iDb].zName; 9295558a8a6Sdanielk1977 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){ 9305558a8a6Sdanielk1977 goto begin_table_error; 9315558a8a6Sdanielk1977 } 932a16d1060Sdan pTable = sqlite3FindTable(db, zName, zDb); 9333df6b257Sdanielk1977 if( pTable ){ 934faa59554Sdrh if( !noErr ){ 9354adee20fSdanielk1977 sqlite3ErrorMsg(pParse, "table %T already exists", pName); 9367687c83dSdan }else{ 93733c59ecaSdrh assert( !db->init.busy || CORRUPT_DB ); 9387687c83dSdan sqlite3CodeVerifySchema(pParse, iDb); 939faa59554Sdrh } 94023bf66d6Sdrh goto begin_table_error; 94175897234Sdrh } 9428a8a0d1dSdrh if( sqlite3FindIndex(db, zName, zDb)!=0 ){ 9434adee20fSdanielk1977 sqlite3ErrorMsg(pParse, "there is already an index named %s", zName); 94423bf66d6Sdrh goto begin_table_error; 94575897234Sdrh } 9467e6ebfb2Sdanielk1977 } 9477e6ebfb2Sdanielk1977 94826783a58Sdanielk1977 pTable = sqlite3DbMallocZero(db, sizeof(Table)); 9496d4abfbeSdrh if( pTable==0 ){ 95017435752Sdrh db->mallocFailed = 1; 951e0048400Sdanielk1977 pParse->rc = SQLITE_NOMEM; 952e0048400Sdanielk1977 pParse->nErr++; 95323bf66d6Sdrh goto begin_table_error; 9546d4abfbeSdrh } 95575897234Sdrh pTable->zName = zName; 9564a32431cSdrh pTable->iPKey = -1; 957da184236Sdanielk1977 pTable->pSchema = db->aDb[iDb].pSchema; 958ed8a3bb1Sdrh pTable->nRef = 1; 959cfc9df76Sdan pTable->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) ); 960c4a64facSdrh assert( pParse->pNewTable==0 ); 96175897234Sdrh pParse->pNewTable = pTable; 96217f71934Sdrh 9634794f735Sdrh /* If this is the magic sqlite_sequence table used by autoincrement, 9644794f735Sdrh ** then record a pointer to this table in the main database structure 9654794f735Sdrh ** so that INSERT can find the table easily. 9664794f735Sdrh */ 9674794f735Sdrh #ifndef SQLITE_OMIT_AUTOINCREMENT 96878776ecdSdrh if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){ 9692120608eSdrh assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); 970da184236Sdanielk1977 pTable->pSchema->pSeqTab = pTable; 9714794f735Sdrh } 9724794f735Sdrh #endif 9734794f735Sdrh 97417f71934Sdrh /* Begin generating the code that will insert the table record into 97517f71934Sdrh ** the SQLITE_MASTER table. Note in particular that we must go ahead 97617f71934Sdrh ** and allocate the record number for the table entry now. Before any 97717f71934Sdrh ** PRIMARY KEY or UNIQUE keywords are parsed. Those keywords will cause 97817f71934Sdrh ** indices to be created and the table record must come before the 97917f71934Sdrh ** indices. Hence, the record number for the table must be allocated 98017f71934Sdrh ** now. 98117f71934Sdrh */ 9824adee20fSdanielk1977 if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){ 983b7654111Sdrh int j1; 984e321c29aSdrh int fileFormat; 985b7654111Sdrh int reg1, reg2, reg3; 9860dd5cdaeSdrh sqlite3BeginWriteOperation(pParse, 1, iDb); 987b17131a0Sdrh 98820b1eaffSdanielk1977 #ifndef SQLITE_OMIT_VIRTUALTABLE 98920b1eaffSdanielk1977 if( isVirtual ){ 99066a5167bSdrh sqlite3VdbeAddOp0(v, OP_VBegin); 99120b1eaffSdanielk1977 } 99220b1eaffSdanielk1977 #endif 99320b1eaffSdanielk1977 99436963fdcSdanielk1977 /* If the file format and encoding in the database have not been set, 99536963fdcSdanielk1977 ** set them now. 996cbb18d22Sdanielk1977 */ 997b7654111Sdrh reg1 = pParse->regRowid = ++pParse->nMem; 998b7654111Sdrh reg2 = pParse->regRoot = ++pParse->nMem; 999b7654111Sdrh reg3 = ++pParse->nMem; 10000d19f7acSdanielk1977 sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT); 1001fb98264aSdrh sqlite3VdbeUsesBtree(v, iDb); 1002688852abSdrh j1 = sqlite3VdbeAddOp1(v, OP_If, reg3); VdbeCoverage(v); 1003e321c29aSdrh fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ? 100476fe8032Sdrh 1 : SQLITE_MAX_FILE_FORMAT; 1005b7654111Sdrh sqlite3VdbeAddOp2(v, OP_Integer, fileFormat, reg3); 10060d19f7acSdanielk1977 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, reg3); 1007b7654111Sdrh sqlite3VdbeAddOp2(v, OP_Integer, ENC(db), reg3); 10080d19f7acSdanielk1977 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, reg3); 1009b7654111Sdrh sqlite3VdbeJumpHere(v, j1); 1010d008cfe3Sdanielk1977 10114794f735Sdrh /* This just creates a place-holder record in the sqlite_master table. 10124794f735Sdrh ** The record created does not contain anything yet. It will be replaced 10134794f735Sdrh ** by the real entry in code generated at sqlite3EndTable(). 1014b17131a0Sdrh ** 10150fa991b9Sdrh ** The rowid for the new entry is left in register pParse->regRowid. 10160fa991b9Sdrh ** The root page number of the new table is left in reg pParse->regRoot. 10170fa991b9Sdrh ** The rowid and root page number values are needed by the code that 10180fa991b9Sdrh ** sqlite3EndTable will generate. 10194794f735Sdrh */ 1020f1a381e7Sdanielk1977 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) 1021f1a381e7Sdanielk1977 if( isView || isVirtual ){ 1022b7654111Sdrh sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2); 1023a21c6b6fSdanielk1977 }else 1024a21c6b6fSdanielk1977 #endif 1025a21c6b6fSdanielk1977 { 10268a120f8bSdrh pParse->addrCrTab = sqlite3VdbeAddOp2(v, OP_CreateTable, iDb, reg2); 1027a21c6b6fSdanielk1977 } 1028c00da105Sdanielk1977 sqlite3OpenMasterTable(pParse, iDb); 1029b7654111Sdrh sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1); 1030b7654111Sdrh sqlite3VdbeAddOp2(v, OP_Null, 0, reg3); 1031b7654111Sdrh sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1); 1032b7654111Sdrh sqlite3VdbeChangeP5(v, OPFLAG_APPEND); 103366a5167bSdrh sqlite3VdbeAddOp0(v, OP_Close); 10345e00f6c7Sdrh } 103523bf66d6Sdrh 103623bf66d6Sdrh /* Normal (non-error) return. */ 103723bf66d6Sdrh return; 103823bf66d6Sdrh 103923bf66d6Sdrh /* If an error occurs, we jump here */ 104023bf66d6Sdrh begin_table_error: 1041633e6d57Sdrh sqlite3DbFree(db, zName); 104223bf66d6Sdrh return; 104375897234Sdrh } 104475897234Sdrh 104575897234Sdrh /* 1046c60e9b82Sdanielk1977 ** This macro is used to compare two strings in a case-insensitive manner. 1047c60e9b82Sdanielk1977 ** It is slightly faster than calling sqlite3StrICmp() directly, but 1048c60e9b82Sdanielk1977 ** produces larger code. 1049c60e9b82Sdanielk1977 ** 1050c60e9b82Sdanielk1977 ** WARNING: This macro is not compatible with the strcmp() family. It 1051c60e9b82Sdanielk1977 ** returns true if the two strings are equal, otherwise false. 1052c60e9b82Sdanielk1977 */ 1053c60e9b82Sdanielk1977 #define STRICMP(x, y) (\ 1054c60e9b82Sdanielk1977 sqlite3UpperToLower[*(unsigned char *)(x)]== \ 1055c60e9b82Sdanielk1977 sqlite3UpperToLower[*(unsigned char *)(y)] \ 1056c60e9b82Sdanielk1977 && sqlite3StrICmp((x)+1,(y)+1)==0 ) 1057c60e9b82Sdanielk1977 1058c60e9b82Sdanielk1977 /* 105975897234Sdrh ** Add a new column to the table currently being constructed. 1060d9b0257aSdrh ** 1061d9b0257aSdrh ** The parser calls this routine once for each column declaration 10624adee20fSdanielk1977 ** in a CREATE TABLE statement. sqlite3StartTable() gets called 1063d9b0257aSdrh ** first to get things going. Then this routine is called for each 1064d9b0257aSdrh ** column. 106575897234Sdrh */ 10664adee20fSdanielk1977 void sqlite3AddColumn(Parse *pParse, Token *pName){ 106775897234Sdrh Table *p; 106897fc3d06Sdrh int i; 1069a99db3b6Sdrh char *z; 1070c9b84a1fSdrh Column *pCol; 1071bb4957f8Sdrh sqlite3 *db = pParse->db; 107275897234Sdrh if( (p = pParse->pNewTable)==0 ) return; 1073bb4957f8Sdrh #if SQLITE_MAX_COLUMN 1074bb4957f8Sdrh if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){ 1075e5c941b8Sdrh sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName); 1076e5c941b8Sdrh return; 1077e5c941b8Sdrh } 1078bb4957f8Sdrh #endif 1079ae74e03eSdanielk1977 z = sqlite3NameFromToken(db, pName); 108097fc3d06Sdrh if( z==0 ) return; 108197fc3d06Sdrh for(i=0; i<p->nCol; i++){ 1082c60e9b82Sdanielk1977 if( STRICMP(z, p->aCol[i].zName) ){ 10834adee20fSdanielk1977 sqlite3ErrorMsg(pParse, "duplicate column name: %s", z); 1084633e6d57Sdrh sqlite3DbFree(db, z); 108597fc3d06Sdrh return; 108697fc3d06Sdrh } 108797fc3d06Sdrh } 108875897234Sdrh if( (p->nCol & 0x7)==0 ){ 10896d4abfbeSdrh Column *aNew; 1090ae74e03eSdanielk1977 aNew = sqlite3DbRealloc(db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0])); 1091d5d56523Sdanielk1977 if( aNew==0 ){ 1092633e6d57Sdrh sqlite3DbFree(db, z); 1093d5d56523Sdanielk1977 return; 1094d5d56523Sdanielk1977 } 10956d4abfbeSdrh p->aCol = aNew; 1096daffd0e5Sdrh } 1097c9b84a1fSdrh pCol = &p->aCol[p->nCol]; 1098c9b84a1fSdrh memset(pCol, 0, sizeof(p->aCol[0])); 1099c9b84a1fSdrh pCol->zName = z; 1100a37cdde0Sdanielk1977 1101a37cdde0Sdanielk1977 /* If there is no type specified, columns have the default affinity 110205883a34Sdrh ** 'BLOB'. If there is a type specified, then sqlite3AddColumnType() will 11034f057f90Sdanielk1977 ** be called next to set pCol->affinity correctly. 1104a37cdde0Sdanielk1977 */ 110505883a34Sdrh pCol->affinity = SQLITE_AFF_BLOB; 1106fdaac671Sdrh pCol->szEst = 1; 1107c9b84a1fSdrh p->nCol++; 110875897234Sdrh } 110975897234Sdrh 111075897234Sdrh /* 1111382c0247Sdrh ** This routine is called by the parser while in the middle of 1112382c0247Sdrh ** parsing a CREATE TABLE statement. A "NOT NULL" constraint has 1113382c0247Sdrh ** been seen on a column. This routine sets the notNull flag on 1114382c0247Sdrh ** the column currently under construction. 1115382c0247Sdrh */ 11164adee20fSdanielk1977 void sqlite3AddNotNull(Parse *pParse, int onError){ 1117382c0247Sdrh Table *p; 1118c4a64facSdrh p = pParse->pNewTable; 1119c4a64facSdrh if( p==0 || NEVER(p->nCol<1) ) return; 1120c4a64facSdrh p->aCol[p->nCol-1].notNull = (u8)onError; 1121382c0247Sdrh } 1122382c0247Sdrh 1123382c0247Sdrh /* 112452a83fbbSdanielk1977 ** Scan the column type name zType (length nType) and return the 112552a83fbbSdanielk1977 ** associated affinity type. 1126b3dff964Sdanielk1977 ** 1127b3dff964Sdanielk1977 ** This routine does a case-independent search of zType for the 1128b3dff964Sdanielk1977 ** substrings in the following table. If one of the substrings is 1129b3dff964Sdanielk1977 ** found, the corresponding affinity is returned. If zType contains 1130b3dff964Sdanielk1977 ** more than one of the substrings, entries toward the top of 1131b3dff964Sdanielk1977 ** the table take priority. For example, if zType is 'BLOBINT', 11328a51256cSdrh ** SQLITE_AFF_INTEGER is returned. 1133b3dff964Sdanielk1977 ** 1134b3dff964Sdanielk1977 ** Substring | Affinity 1135b3dff964Sdanielk1977 ** -------------------------------- 1136b3dff964Sdanielk1977 ** 'INT' | SQLITE_AFF_INTEGER 1137b3dff964Sdanielk1977 ** 'CHAR' | SQLITE_AFF_TEXT 1138b3dff964Sdanielk1977 ** 'CLOB' | SQLITE_AFF_TEXT 1139b3dff964Sdanielk1977 ** 'TEXT' | SQLITE_AFF_TEXT 114005883a34Sdrh ** 'BLOB' | SQLITE_AFF_BLOB 11418a51256cSdrh ** 'REAL' | SQLITE_AFF_REAL 11428a51256cSdrh ** 'FLOA' | SQLITE_AFF_REAL 11438a51256cSdrh ** 'DOUB' | SQLITE_AFF_REAL 1144b3dff964Sdanielk1977 ** 1145b3dff964Sdanielk1977 ** If none of the substrings in the above table are found, 1146b3dff964Sdanielk1977 ** SQLITE_AFF_NUMERIC is returned. 114752a83fbbSdanielk1977 */ 1148fdaac671Sdrh char sqlite3AffinityType(const char *zIn, u8 *pszEst){ 1149b3dff964Sdanielk1977 u32 h = 0; 1150b3dff964Sdanielk1977 char aff = SQLITE_AFF_NUMERIC; 1151d3037a41Sdrh const char *zChar = 0; 115252a83fbbSdanielk1977 1153fdaac671Sdrh if( zIn==0 ) return aff; 1154fdaac671Sdrh while( zIn[0] ){ 1155b7916a78Sdrh h = (h<<8) + sqlite3UpperToLower[(*zIn)&0xff]; 1156b3dff964Sdanielk1977 zIn++; 1157201f7168Sdanielk1977 if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){ /* CHAR */ 1158201f7168Sdanielk1977 aff = SQLITE_AFF_TEXT; 1159fdaac671Sdrh zChar = zIn; 1160201f7168Sdanielk1977 }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){ /* CLOB */ 1161201f7168Sdanielk1977 aff = SQLITE_AFF_TEXT; 1162201f7168Sdanielk1977 }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){ /* TEXT */ 1163201f7168Sdanielk1977 aff = SQLITE_AFF_TEXT; 1164201f7168Sdanielk1977 }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b') /* BLOB */ 11658a51256cSdrh && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){ 116605883a34Sdrh aff = SQLITE_AFF_BLOB; 1167d3037a41Sdrh if( zIn[0]=='(' ) zChar = zIn; 11688a51256cSdrh #ifndef SQLITE_OMIT_FLOATING_POINT 11698a51256cSdrh }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l') /* REAL */ 11708a51256cSdrh && aff==SQLITE_AFF_NUMERIC ){ 11718a51256cSdrh aff = SQLITE_AFF_REAL; 11728a51256cSdrh }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a') /* FLOA */ 11738a51256cSdrh && aff==SQLITE_AFF_NUMERIC ){ 11748a51256cSdrh aff = SQLITE_AFF_REAL; 11758a51256cSdrh }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b') /* DOUB */ 11768a51256cSdrh && aff==SQLITE_AFF_NUMERIC ){ 11778a51256cSdrh aff = SQLITE_AFF_REAL; 11788a51256cSdrh #endif 1179201f7168Sdanielk1977 }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){ /* INT */ 11808a51256cSdrh aff = SQLITE_AFF_INTEGER; 1181b3dff964Sdanielk1977 break; 118252a83fbbSdanielk1977 } 118352a83fbbSdanielk1977 } 1184d3037a41Sdrh 1185d3037a41Sdrh /* If pszEst is not NULL, store an estimate of the field size. The 1186d3037a41Sdrh ** estimate is scaled so that the size of an integer is 1. */ 1187fdaac671Sdrh if( pszEst ){ 1188d3037a41Sdrh *pszEst = 1; /* default size is approx 4 bytes */ 11897ea31ccbSdrh if( aff<SQLITE_AFF_NUMERIC ){ 1190d3037a41Sdrh if( zChar ){ 1191fdaac671Sdrh while( zChar[0] ){ 1192d3037a41Sdrh if( sqlite3Isdigit(zChar[0]) ){ 11934f991890Sdrh int v = 0; 1194d3037a41Sdrh sqlite3GetInt32(zChar, &v); 1195fdaac671Sdrh v = v/4 + 1; 1196fdaac671Sdrh if( v>255 ) v = 255; 1197d3037a41Sdrh *pszEst = v; /* BLOB(k), VARCHAR(k), CHAR(k) -> r=(k/4+1) */ 1198fdaac671Sdrh break; 1199fdaac671Sdrh } 1200fdaac671Sdrh zChar++; 1201fdaac671Sdrh } 1202fdaac671Sdrh }else{ 1203d3037a41Sdrh *pszEst = 5; /* BLOB, TEXT, CLOB -> r=5 (approx 20 bytes)*/ 1204d3037a41Sdrh } 1205fdaac671Sdrh } 1206fdaac671Sdrh } 1207b3dff964Sdanielk1977 return aff; 120852a83fbbSdanielk1977 } 120952a83fbbSdanielk1977 121052a83fbbSdanielk1977 /* 1211382c0247Sdrh ** This routine is called by the parser while in the middle of 1212382c0247Sdrh ** parsing a CREATE TABLE statement. The pFirst token is the first 1213382c0247Sdrh ** token in the sequence of tokens that describe the type of the 1214382c0247Sdrh ** column currently under construction. pLast is the last token 1215382c0247Sdrh ** in the sequence. Use this information to construct a string 1216382c0247Sdrh ** that contains the typename of the column and store that string 1217382c0247Sdrh ** in zType. 1218382c0247Sdrh */ 1219487e262fSdrh void sqlite3AddColumnType(Parse *pParse, Token *pType){ 1220382c0247Sdrh Table *p; 1221c9b84a1fSdrh Column *pCol; 1222487e262fSdrh 1223c4a64facSdrh p = pParse->pNewTable; 1224c4a64facSdrh if( p==0 || NEVER(p->nCol<1) ) return; 1225c4a64facSdrh pCol = &p->aCol[p->nCol-1]; 12265f1d2fa4Sdrh assert( pCol->zType==0 || CORRUPT_DB ); 12275f1d2fa4Sdrh sqlite3DbFree(pParse->db, pCol->zType); 1228c4a64facSdrh pCol->zType = sqlite3NameFromToken(pParse->db, pType); 1229fdaac671Sdrh pCol->affinity = sqlite3AffinityType(pCol->zType, &pCol->szEst); 12303d037a91Sdrh } 1231382c0247Sdrh 1232382c0247Sdrh /* 12337977a17fSdanielk1977 ** The expression is the default value for the most recently added column 12347977a17fSdanielk1977 ** of the table currently under construction. 12357977a17fSdanielk1977 ** 12367977a17fSdanielk1977 ** Default value expressions must be constant. Raise an exception if this 12377977a17fSdanielk1977 ** is not the case. 1238d9b0257aSdrh ** 1239d9b0257aSdrh ** This routine is called by the parser while in the middle of 1240d9b0257aSdrh ** parsing a CREATE TABLE statement. 12417020f651Sdrh */ 1242b7916a78Sdrh void sqlite3AddDefaultValue(Parse *pParse, ExprSpan *pSpan){ 12437020f651Sdrh Table *p; 12447977a17fSdanielk1977 Column *pCol; 1245633e6d57Sdrh sqlite3 *db = pParse->db; 1246c4a64facSdrh p = pParse->pNewTable; 1247c4a64facSdrh if( p!=0 ){ 12487977a17fSdanielk1977 pCol = &(p->aCol[p->nCol-1]); 1249feada2dfSdrh if( !sqlite3ExprIsConstantOrFunction(pSpan->pExpr, db->init.busy) ){ 12507977a17fSdanielk1977 sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant", 12517977a17fSdanielk1977 pCol->zName); 12527977a17fSdanielk1977 }else{ 12536ab3a2ecSdanielk1977 /* A copy of pExpr is used instead of the original, as pExpr contains 12546ab3a2ecSdanielk1977 ** tokens that point to volatile memory. The 'span' of the expression 12556ab3a2ecSdanielk1977 ** is required by pragma table_info. 12566ab3a2ecSdanielk1977 */ 1257633e6d57Sdrh sqlite3ExprDelete(db, pCol->pDflt); 1258b7916a78Sdrh pCol->pDflt = sqlite3ExprDup(db, pSpan->pExpr, EXPRDUP_REDUCE); 1259b7916a78Sdrh sqlite3DbFree(db, pCol->zDflt); 1260b7916a78Sdrh pCol->zDflt = sqlite3DbStrNDup(db, (char*)pSpan->zStart, 1261cf697396Sshane (int)(pSpan->zEnd - pSpan->zStart)); 12627977a17fSdanielk1977 } 126342b9d7c5Sdrh } 1264b7916a78Sdrh sqlite3ExprDelete(db, pSpan->pExpr); 12657020f651Sdrh } 12667020f651Sdrh 12677020f651Sdrh /* 12684a32431cSdrh ** Designate the PRIMARY KEY for the table. pList is a list of names 12694a32431cSdrh ** of columns that form the primary key. If pList is NULL, then the 12704a32431cSdrh ** most recently added column of the table is the primary key. 12714a32431cSdrh ** 12724a32431cSdrh ** A table can have at most one primary key. If the table already has 12734a32431cSdrh ** a primary key (and this is the second primary key) then create an 12744a32431cSdrh ** error. 12754a32431cSdrh ** 12764a32431cSdrh ** If the PRIMARY KEY is on a single column whose datatype is INTEGER, 127723bf66d6Sdrh ** then we will try to use that column as the rowid. Set the Table.iPKey 12784a32431cSdrh ** field of the table under construction to be the index of the 12794a32431cSdrh ** INTEGER PRIMARY KEY column. Table.iPKey is set to -1 if there is 12804a32431cSdrh ** no INTEGER PRIMARY KEY. 12814a32431cSdrh ** 12824a32431cSdrh ** If the key is not an INTEGER PRIMARY KEY, then create a unique 12834a32431cSdrh ** index for the key. No index is created for INTEGER PRIMARY KEYs. 12844a32431cSdrh */ 1285205f48e6Sdrh void sqlite3AddPrimaryKey( 1286205f48e6Sdrh Parse *pParse, /* Parsing context */ 1287205f48e6Sdrh ExprList *pList, /* List of field names to be indexed */ 1288205f48e6Sdrh int onError, /* What to do with a uniqueness conflict */ 1289fdd6e85aSdrh int autoInc, /* True if the AUTOINCREMENT keyword is present */ 1290fdd6e85aSdrh int sortOrder /* SQLITE_SO_ASC or SQLITE_SO_DESC */ 1291205f48e6Sdrh ){ 12924a32431cSdrh Table *pTab = pParse->pNewTable; 12934a32431cSdrh char *zType = 0; 129478100cc9Sdrh int iCol = -1, i; 12958ea30bfcSdrh int nTerm; 1296c7d54101Sdanielk1977 if( pTab==0 || IN_DECLARE_VTAB ) goto primary_key_exit; 12977d10d5a6Sdrh if( pTab->tabFlags & TF_HasPrimaryKey ){ 12984adee20fSdanielk1977 sqlite3ErrorMsg(pParse, 1299f7a9e1acSdrh "table \"%s\" has more than one primary key", pTab->zName); 1300e0194f2bSdrh goto primary_key_exit; 13014a32431cSdrh } 13027d10d5a6Sdrh pTab->tabFlags |= TF_HasPrimaryKey; 13034a32431cSdrh if( pList==0 ){ 13044a32431cSdrh iCol = pTab->nCol - 1; 1305a371ace4Sdrh pTab->aCol[iCol].colFlags |= COLFLAG_PRIMKEY; 13068ea30bfcSdrh zType = pTab->aCol[iCol].zType; 13078ea30bfcSdrh nTerm = 1; 130878100cc9Sdrh }else{ 13098ea30bfcSdrh nTerm = pList->nExpr; 13108ea30bfcSdrh for(i=0; i<nTerm; i++){ 1311108aa00aSdrh Expr *pCExpr = sqlite3ExprSkipCollate(pList->a[i].pExpr); 1312108aa00aSdrh if( pCExpr && pCExpr->op==TK_ID ){ 1313108aa00aSdrh const char *zCName = pCExpr->u.zToken; 13144a32431cSdrh for(iCol=0; iCol<pTab->nCol; iCol++){ 1315108aa00aSdrh if( sqlite3StrICmp(zCName, pTab->aCol[iCol].zName)==0 ){ 13168ea30bfcSdrh pTab->aCol[iCol].colFlags |= COLFLAG_PRIMKEY; 13178ea30bfcSdrh zType = pTab->aCol[iCol].zType; 1318d3d39e93Sdrh break; 1319d3d39e93Sdrh } 13204a32431cSdrh } 13216e4fc2caSdrh } 132278100cc9Sdrh } 1323108aa00aSdrh } 13248ea30bfcSdrh if( nTerm==1 13258ea30bfcSdrh && zType && sqlite3StrICmp(zType, "INTEGER")==0 1326bc622bc0Sdrh && sortOrder!=SQLITE_SO_DESC 13278ea30bfcSdrh ){ 13284a32431cSdrh pTab->iPKey = iCol; 13291bd10f8aSdrh pTab->keyConf = (u8)onError; 13307d10d5a6Sdrh assert( autoInc==0 || autoInc==1 ); 13317d10d5a6Sdrh pTab->tabFlags |= autoInc*TF_Autoincrement; 13327f9c5dbfSdrh if( pList ) pParse->iPkSortOrder = pList->a[0].sortOrder; 1333205f48e6Sdrh }else if( autoInc ){ 13344794f735Sdrh #ifndef SQLITE_OMIT_AUTOINCREMENT 1335205f48e6Sdrh sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an " 1336205f48e6Sdrh "INTEGER PRIMARY KEY"); 13374794f735Sdrh #endif 13384a32431cSdrh }else{ 13391da40a38Sdan Index *p; 13408a9789b6Sdrh p = sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0, 13411fe0537eSdrh 0, sortOrder, 0); 13421da40a38Sdan if( p ){ 134348dd1d8eSdrh p->idxType = SQLITE_IDXTYPE_PRIMARYKEY; 13441da40a38Sdan } 1345e0194f2bSdrh pList = 0; 13464a32431cSdrh } 1347e0194f2bSdrh 1348e0194f2bSdrh primary_key_exit: 1349633e6d57Sdrh sqlite3ExprListDelete(pParse->db, pList); 1350e0194f2bSdrh return; 13514a32431cSdrh } 13524a32431cSdrh 13534a32431cSdrh /* 1354ffe07b2dSdrh ** Add a new CHECK constraint to the table currently under construction. 1355ffe07b2dSdrh */ 1356ffe07b2dSdrh void sqlite3AddCheckConstraint( 1357ffe07b2dSdrh Parse *pParse, /* Parsing context */ 1358ffe07b2dSdrh Expr *pCheckExpr /* The check expression */ 1359ffe07b2dSdrh ){ 1360ffe07b2dSdrh #ifndef SQLITE_OMIT_CHECK 1361ffe07b2dSdrh Table *pTab = pParse->pNewTable; 1362c9bbb011Sdrh sqlite3 *db = pParse->db; 1363c9bbb011Sdrh if( pTab && !IN_DECLARE_VTAB 1364c9bbb011Sdrh && !sqlite3BtreeIsReadonly(db->aDb[db->init.iDb].pBt) 1365c9bbb011Sdrh ){ 13662938f924Sdrh pTab->pCheck = sqlite3ExprListAppend(pParse, pTab->pCheck, pCheckExpr); 13672938f924Sdrh if( pParse->constraintName.n ){ 13682938f924Sdrh sqlite3ExprListSetName(pParse, pTab->pCheck, &pParse->constraintName, 1); 13692938f924Sdrh } 137033e619fcSdrh }else 1371ffe07b2dSdrh #endif 137233e619fcSdrh { 13732938f924Sdrh sqlite3ExprDelete(pParse->db, pCheckExpr); 1374ffe07b2dSdrh } 137533e619fcSdrh } 1376ffe07b2dSdrh 1377ffe07b2dSdrh /* 1378d3d39e93Sdrh ** Set the collation function of the most recently parsed table column 1379d3d39e93Sdrh ** to the CollSeq given. 13808e2ca029Sdrh */ 138139002505Sdanielk1977 void sqlite3AddCollateType(Parse *pParse, Token *pToken){ 13828e2ca029Sdrh Table *p; 13830202b29eSdanielk1977 int i; 138439002505Sdanielk1977 char *zColl; /* Dequoted name of collation sequence */ 1385633e6d57Sdrh sqlite3 *db; 1386a37cdde0Sdanielk1977 1387b8cbb872Sdanielk1977 if( (p = pParse->pNewTable)==0 ) return; 13880202b29eSdanielk1977 i = p->nCol-1; 1389633e6d57Sdrh db = pParse->db; 1390633e6d57Sdrh zColl = sqlite3NameFromToken(db, pToken); 139139002505Sdanielk1977 if( !zColl ) return; 139239002505Sdanielk1977 1393c4a64facSdrh if( sqlite3LocateCollSeq(pParse, zColl) ){ 1394b3bf556eSdanielk1977 Index *pIdx; 1395fe685c83Sdrh sqlite3DbFree(db, p->aCol[i].zColl); 139639002505Sdanielk1977 p->aCol[i].zColl = zColl; 13970202b29eSdanielk1977 13980202b29eSdanielk1977 /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>", 13990202b29eSdanielk1977 ** then an index may have been created on this column before the 14000202b29eSdanielk1977 ** collation type was added. Correct this if it is the case. 14010202b29eSdanielk1977 */ 14020202b29eSdanielk1977 for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){ 1403bbbdc83bSdrh assert( pIdx->nKeyCol==1 ); 1404b3bf556eSdanielk1977 if( pIdx->aiColumn[0]==i ){ 1405b3bf556eSdanielk1977 pIdx->azColl[0] = p->aCol[i].zColl; 14067cedc8d4Sdanielk1977 } 14077cedc8d4Sdanielk1977 } 140839002505Sdanielk1977 }else{ 1409633e6d57Sdrh sqlite3DbFree(db, zColl); 14107cedc8d4Sdanielk1977 } 14117cedc8d4Sdanielk1977 } 14127cedc8d4Sdanielk1977 1413466be56bSdanielk1977 /* 1414466be56bSdanielk1977 ** This function returns the collation sequence for database native text 1415466be56bSdanielk1977 ** encoding identified by the string zName, length nName. 1416466be56bSdanielk1977 ** 1417466be56bSdanielk1977 ** If the requested collation sequence is not available, or not available 1418466be56bSdanielk1977 ** in the database native encoding, the collation factory is invoked to 1419466be56bSdanielk1977 ** request it. If the collation factory does not supply such a sequence, 1420466be56bSdanielk1977 ** and the sequence is available in another text encoding, then that is 1421466be56bSdanielk1977 ** returned instead. 1422466be56bSdanielk1977 ** 1423466be56bSdanielk1977 ** If no versions of the requested collations sequence are available, or 1424466be56bSdanielk1977 ** another error occurs, NULL is returned and an error message written into 1425466be56bSdanielk1977 ** pParse. 1426a34001c9Sdrh ** 1427a34001c9Sdrh ** This routine is a wrapper around sqlite3FindCollSeq(). This routine 1428a34001c9Sdrh ** invokes the collation factory if the named collation cannot be found 1429a34001c9Sdrh ** and generates an error message. 1430c4a64facSdrh ** 1431c4a64facSdrh ** See also: sqlite3FindCollSeq(), sqlite3GetCollSeq() 1432466be56bSdanielk1977 */ 1433c4a64facSdrh CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName){ 14344dade037Sdanielk1977 sqlite3 *db = pParse->db; 143514db2665Sdanielk1977 u8 enc = ENC(db); 14364dade037Sdanielk1977 u8 initbusy = db->init.busy; 1437b3bf556eSdanielk1977 CollSeq *pColl; 14384dade037Sdanielk1977 1439c4a64facSdrh pColl = sqlite3FindCollSeq(db, enc, zName, initbusy); 14407cedc8d4Sdanielk1977 if( !initbusy && (!pColl || !pColl->xCmp) ){ 144179e72a50Sdrh pColl = sqlite3GetCollSeq(pParse, enc, pColl, zName); 1442466be56bSdanielk1977 } 1443466be56bSdanielk1977 14440202b29eSdanielk1977 return pColl; 14450202b29eSdanielk1977 } 14460202b29eSdanielk1977 14470202b29eSdanielk1977 14488e2ca029Sdrh /* 14493f7d4e49Sdrh ** Generate code that will increment the schema cookie. 145050e5dadfSdrh ** 145150e5dadfSdrh ** The schema cookie is used to determine when the schema for the 145250e5dadfSdrh ** database changes. After each schema change, the cookie value 145350e5dadfSdrh ** changes. When a process first reads the schema it records the 145450e5dadfSdrh ** cookie. Thereafter, whenever it goes to access the database, 145550e5dadfSdrh ** it checks the cookie to make sure the schema has not changed 145650e5dadfSdrh ** since it was last read. 145750e5dadfSdrh ** 145850e5dadfSdrh ** This plan is not completely bullet-proof. It is possible for 145950e5dadfSdrh ** the schema to change multiple times and for the cookie to be 146050e5dadfSdrh ** set back to prior value. But schema changes are infrequent 146150e5dadfSdrh ** and the probability of hitting the same cookie value is only 146250e5dadfSdrh ** 1 chance in 2^32. So we're safe enough. 146350e5dadfSdrh */ 14649cbf3425Sdrh void sqlite3ChangeCookie(Parse *pParse, int iDb){ 14659cbf3425Sdrh int r1 = sqlite3GetTempReg(pParse); 14669cbf3425Sdrh sqlite3 *db = pParse->db; 14679cbf3425Sdrh Vdbe *v = pParse->pVdbe; 14682120608eSdrh assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); 14699cbf3425Sdrh sqlite3VdbeAddOp2(v, OP_Integer, db->aDb[iDb].pSchema->schema_cookie+1, r1); 14700d19f7acSdanielk1977 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION, r1); 14719cbf3425Sdrh sqlite3ReleaseTempReg(pParse, r1); 147250e5dadfSdrh } 147350e5dadfSdrh 147450e5dadfSdrh /* 1475969fa7c1Sdrh ** Measure the number of characters needed to output the given 1476969fa7c1Sdrh ** identifier. The number returned includes any quotes used 1477969fa7c1Sdrh ** but does not include the null terminator. 1478234c39dfSdrh ** 1479234c39dfSdrh ** The estimate is conservative. It might be larger that what is 1480234c39dfSdrh ** really needed. 1481969fa7c1Sdrh */ 1482969fa7c1Sdrh static int identLength(const char *z){ 1483969fa7c1Sdrh int n; 148417f71934Sdrh for(n=0; *z; n++, z++){ 1485234c39dfSdrh if( *z=='"' ){ n++; } 1486969fa7c1Sdrh } 1487234c39dfSdrh return n + 2; 1488969fa7c1Sdrh } 1489969fa7c1Sdrh 1490969fa7c1Sdrh /* 14911b870de6Sdanielk1977 ** The first parameter is a pointer to an output buffer. The second 14921b870de6Sdanielk1977 ** parameter is a pointer to an integer that contains the offset at 14931b870de6Sdanielk1977 ** which to write into the output buffer. This function copies the 14941b870de6Sdanielk1977 ** nul-terminated string pointed to by the third parameter, zSignedIdent, 14951b870de6Sdanielk1977 ** to the specified offset in the buffer and updates *pIdx to refer 14961b870de6Sdanielk1977 ** to the first byte after the last byte written before returning. 14971b870de6Sdanielk1977 ** 14981b870de6Sdanielk1977 ** If the string zSignedIdent consists entirely of alpha-numeric 14991b870de6Sdanielk1977 ** characters, does not begin with a digit and is not an SQL keyword, 15001b870de6Sdanielk1977 ** then it is copied to the output buffer exactly as it is. Otherwise, 15011b870de6Sdanielk1977 ** it is quoted using double-quotes. 15021b870de6Sdanielk1977 */ 1503c4a64facSdrh static void identPut(char *z, int *pIdx, char *zSignedIdent){ 15044c755c0fSdrh unsigned char *zIdent = (unsigned char*)zSignedIdent; 150517f71934Sdrh int i, j, needQuote; 1506969fa7c1Sdrh i = *pIdx; 15071b870de6Sdanielk1977 150817f71934Sdrh for(j=0; zIdent[j]; j++){ 150978ca0e7eSdanielk1977 if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break; 151017f71934Sdrh } 1511c7407524Sdrh needQuote = sqlite3Isdigit(zIdent[0]) 1512c7407524Sdrh || sqlite3KeywordCode(zIdent, j)!=TK_ID 1513c7407524Sdrh || zIdent[j]!=0 1514c7407524Sdrh || j==0; 15151b870de6Sdanielk1977 1516234c39dfSdrh if( needQuote ) z[i++] = '"'; 1517969fa7c1Sdrh for(j=0; zIdent[j]; j++){ 1518969fa7c1Sdrh z[i++] = zIdent[j]; 1519234c39dfSdrh if( zIdent[j]=='"' ) z[i++] = '"'; 1520969fa7c1Sdrh } 1521234c39dfSdrh if( needQuote ) z[i++] = '"'; 1522969fa7c1Sdrh z[i] = 0; 1523969fa7c1Sdrh *pIdx = i; 1524969fa7c1Sdrh } 1525969fa7c1Sdrh 1526969fa7c1Sdrh /* 1527969fa7c1Sdrh ** Generate a CREATE TABLE statement appropriate for the given 1528969fa7c1Sdrh ** table. Memory to hold the text of the statement is obtained 1529969fa7c1Sdrh ** from sqliteMalloc() and must be freed by the calling function. 1530969fa7c1Sdrh */ 15311d34fdecSdrh static char *createTableStmt(sqlite3 *db, Table *p){ 1532969fa7c1Sdrh int i, k, n; 1533969fa7c1Sdrh char *zStmt; 1534c4a64facSdrh char *zSep, *zSep2, *zEnd; 1535234c39dfSdrh Column *pCol; 1536969fa7c1Sdrh n = 0; 1537234c39dfSdrh for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){ 1538c4a64facSdrh n += identLength(pCol->zName) + 5; 1539969fa7c1Sdrh } 1540969fa7c1Sdrh n += identLength(p->zName); 1541234c39dfSdrh if( n<50 ){ 1542969fa7c1Sdrh zSep = ""; 1543969fa7c1Sdrh zSep2 = ","; 1544969fa7c1Sdrh zEnd = ")"; 1545969fa7c1Sdrh }else{ 1546969fa7c1Sdrh zSep = "\n "; 1547969fa7c1Sdrh zSep2 = ",\n "; 1548969fa7c1Sdrh zEnd = "\n)"; 1549969fa7c1Sdrh } 1550e0bc4048Sdrh n += 35 + 6*p->nCol; 1551b975598eSdrh zStmt = sqlite3DbMallocRaw(0, n); 1552820a9069Sdrh if( zStmt==0 ){ 1553820a9069Sdrh db->mallocFailed = 1; 1554820a9069Sdrh return 0; 1555820a9069Sdrh } 1556bdb339ffSdrh sqlite3_snprintf(n, zStmt, "CREATE TABLE "); 1557ea678832Sdrh k = sqlite3Strlen30(zStmt); 1558c4a64facSdrh identPut(zStmt, &k, p->zName); 1559969fa7c1Sdrh zStmt[k++] = '('; 1560234c39dfSdrh for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){ 1561c4a64facSdrh static const char * const azType[] = { 156205883a34Sdrh /* SQLITE_AFF_BLOB */ "", 15637ea31ccbSdrh /* SQLITE_AFF_TEXT */ " TEXT", 1564c4a64facSdrh /* SQLITE_AFF_NUMERIC */ " NUM", 1565c4a64facSdrh /* SQLITE_AFF_INTEGER */ " INT", 1566c4a64facSdrh /* SQLITE_AFF_REAL */ " REAL" 1567c4a64facSdrh }; 1568c4a64facSdrh int len; 1569c4a64facSdrh const char *zType; 1570c4a64facSdrh 15715bb3eb9bSdrh sqlite3_snprintf(n-k, &zStmt[k], zSep); 1572ea678832Sdrh k += sqlite3Strlen30(&zStmt[k]); 1573969fa7c1Sdrh zSep = zSep2; 1574c4a64facSdrh identPut(zStmt, &k, pCol->zName); 157505883a34Sdrh assert( pCol->affinity-SQLITE_AFF_BLOB >= 0 ); 157605883a34Sdrh assert( pCol->affinity-SQLITE_AFF_BLOB < ArraySize(azType) ); 157705883a34Sdrh testcase( pCol->affinity==SQLITE_AFF_BLOB ); 15787ea31ccbSdrh testcase( pCol->affinity==SQLITE_AFF_TEXT ); 1579c4a64facSdrh testcase( pCol->affinity==SQLITE_AFF_NUMERIC ); 1580c4a64facSdrh testcase( pCol->affinity==SQLITE_AFF_INTEGER ); 1581c4a64facSdrh testcase( pCol->affinity==SQLITE_AFF_REAL ); 1582c4a64facSdrh 158305883a34Sdrh zType = azType[pCol->affinity - SQLITE_AFF_BLOB]; 1584c4a64facSdrh len = sqlite3Strlen30(zType); 158505883a34Sdrh assert( pCol->affinity==SQLITE_AFF_BLOB 1586fdaac671Sdrh || pCol->affinity==sqlite3AffinityType(zType, 0) ); 1587c4a64facSdrh memcpy(&zStmt[k], zType, len); 1588c4a64facSdrh k += len; 1589c4a64facSdrh assert( k<=n ); 1590969fa7c1Sdrh } 15915bb3eb9bSdrh sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd); 1592969fa7c1Sdrh return zStmt; 1593969fa7c1Sdrh } 1594969fa7c1Sdrh 1595969fa7c1Sdrh /* 15967f9c5dbfSdrh ** Resize an Index object to hold N columns total. Return SQLITE_OK 15977f9c5dbfSdrh ** on success and SQLITE_NOMEM on an OOM error. 15987f9c5dbfSdrh */ 15997f9c5dbfSdrh static int resizeIndexObject(sqlite3 *db, Index *pIdx, int N){ 16007f9c5dbfSdrh char *zExtra; 16017f9c5dbfSdrh int nByte; 16027f9c5dbfSdrh if( pIdx->nColumn>=N ) return SQLITE_OK; 16037f9c5dbfSdrh assert( pIdx->isResized==0 ); 16047f9c5dbfSdrh nByte = (sizeof(char*) + sizeof(i16) + 1)*N; 16057f9c5dbfSdrh zExtra = sqlite3DbMallocZero(db, nByte); 16067f9c5dbfSdrh if( zExtra==0 ) return SQLITE_NOMEM; 16077f9c5dbfSdrh memcpy(zExtra, pIdx->azColl, sizeof(char*)*pIdx->nColumn); 16087f9c5dbfSdrh pIdx->azColl = (char**)zExtra; 16097f9c5dbfSdrh zExtra += sizeof(char*)*N; 16107f9c5dbfSdrh memcpy(zExtra, pIdx->aiColumn, sizeof(i16)*pIdx->nColumn); 16117f9c5dbfSdrh pIdx->aiColumn = (i16*)zExtra; 16127f9c5dbfSdrh zExtra += sizeof(i16)*N; 16137f9c5dbfSdrh memcpy(zExtra, pIdx->aSortOrder, pIdx->nColumn); 16147f9c5dbfSdrh pIdx->aSortOrder = (u8*)zExtra; 16157f9c5dbfSdrh pIdx->nColumn = N; 16167f9c5dbfSdrh pIdx->isResized = 1; 16177f9c5dbfSdrh return SQLITE_OK; 16187f9c5dbfSdrh } 16197f9c5dbfSdrh 16207f9c5dbfSdrh /* 1621fdaac671Sdrh ** Estimate the total row width for a table. 1622fdaac671Sdrh */ 1623e13e9f54Sdrh static void estimateTableWidth(Table *pTab){ 1624fdaac671Sdrh unsigned wTable = 0; 1625fdaac671Sdrh const Column *pTabCol; 1626fdaac671Sdrh int i; 1627fdaac671Sdrh for(i=pTab->nCol, pTabCol=pTab->aCol; i>0; i--, pTabCol++){ 1628fdaac671Sdrh wTable += pTabCol->szEst; 1629fdaac671Sdrh } 1630fdaac671Sdrh if( pTab->iPKey<0 ) wTable++; 1631e13e9f54Sdrh pTab->szTabRow = sqlite3LogEst(wTable*4); 1632fdaac671Sdrh } 1633fdaac671Sdrh 1634fdaac671Sdrh /* 1635e13e9f54Sdrh ** Estimate the average size of a row for an index. 1636fdaac671Sdrh */ 1637e13e9f54Sdrh static void estimateIndexWidth(Index *pIdx){ 1638bbbdc83bSdrh unsigned wIndex = 0; 1639fdaac671Sdrh int i; 1640fdaac671Sdrh const Column *aCol = pIdx->pTable->aCol; 1641fdaac671Sdrh for(i=0; i<pIdx->nColumn; i++){ 1642bbbdc83bSdrh i16 x = pIdx->aiColumn[i]; 1643bbbdc83bSdrh assert( x<pIdx->pTable->nCol ); 1644bbbdc83bSdrh wIndex += x<0 ? 1 : aCol[pIdx->aiColumn[i]].szEst; 1645fdaac671Sdrh } 1646e13e9f54Sdrh pIdx->szIdxRow = sqlite3LogEst(wIndex*4); 1647fdaac671Sdrh } 1648fdaac671Sdrh 16497f9c5dbfSdrh /* Return true if value x is found any of the first nCol entries of aiCol[] 16507f9c5dbfSdrh */ 16517f9c5dbfSdrh static int hasColumn(const i16 *aiCol, int nCol, int x){ 16527f9c5dbfSdrh while( nCol-- > 0 ) if( x==*(aiCol++) ) return 1; 16537f9c5dbfSdrh return 0; 16547f9c5dbfSdrh } 16557f9c5dbfSdrh 16567f9c5dbfSdrh /* 1657c6bd4e4aSdrh ** This routine runs at the end of parsing a CREATE TABLE statement that 1658c6bd4e4aSdrh ** has a WITHOUT ROWID clause. The job of this routine is to convert both 1659c6bd4e4aSdrh ** internal schema data structures and the generated VDBE code so that they 1660c6bd4e4aSdrh ** are appropriate for a WITHOUT ROWID table instead of a rowid table. 1661c6bd4e4aSdrh ** Changes include: 16627f9c5dbfSdrh ** 1663c6bd4e4aSdrh ** (1) Convert the OP_CreateTable into an OP_CreateIndex. There is 1664c6bd4e4aSdrh ** no rowid btree for a WITHOUT ROWID. Instead, the canonical 1665c6bd4e4aSdrh ** data storage is a covering index btree. 1666c6bd4e4aSdrh ** (2) Bypass the creation of the sqlite_master table entry 166760ec914cSpeter.d.reid ** for the PRIMARY KEY as the primary key index is now 1668c6bd4e4aSdrh ** identified by the sqlite_master table entry of the table itself. 1669c6bd4e4aSdrh ** (3) Set the Index.tnum of the PRIMARY KEY Index object in the 1670c6bd4e4aSdrh ** schema to the rootpage from the main table. 1671c6bd4e4aSdrh ** (4) Set all columns of the PRIMARY KEY schema object to be NOT NULL. 1672c6bd4e4aSdrh ** (5) Add all table columns to the PRIMARY KEY Index object 1673c6bd4e4aSdrh ** so that the PRIMARY KEY is a covering index. The surplus 1674c6bd4e4aSdrh ** columns are part of KeyInfo.nXField and are not used for 1675c6bd4e4aSdrh ** sorting or lookup or uniqueness checks. 1676c6bd4e4aSdrh ** (6) Replace the rowid tail on all automatically generated UNIQUE 1677c6bd4e4aSdrh ** indices with the PRIMARY KEY columns. 16787f9c5dbfSdrh */ 16797f9c5dbfSdrh static void convertToWithoutRowidTable(Parse *pParse, Table *pTab){ 16807f9c5dbfSdrh Index *pIdx; 16817f9c5dbfSdrh Index *pPk; 16827f9c5dbfSdrh int nPk; 16837f9c5dbfSdrh int i, j; 16847f9c5dbfSdrh sqlite3 *db = pParse->db; 1685c6bd4e4aSdrh Vdbe *v = pParse->pVdbe; 16867f9c5dbfSdrh 16877f9c5dbfSdrh /* Convert the OP_CreateTable opcode that would normally create the 168860ec914cSpeter.d.reid ** root-page for the table into an OP_CreateIndex opcode. The index 1689c6bd4e4aSdrh ** created will become the PRIMARY KEY index. 16907f9c5dbfSdrh */ 16917f9c5dbfSdrh if( pParse->addrCrTab ){ 1692c6bd4e4aSdrh assert( v ); 1693c6bd4e4aSdrh sqlite3VdbeGetOp(v, pParse->addrCrTab)->opcode = OP_CreateIndex; 1694c6bd4e4aSdrh } 1695c6bd4e4aSdrh 16967f9c5dbfSdrh /* Locate the PRIMARY KEY index. Or, if this table was originally 16977f9c5dbfSdrh ** an INTEGER PRIMARY KEY table, create a new PRIMARY KEY index. 16987f9c5dbfSdrh */ 16997f9c5dbfSdrh if( pTab->iPKey>=0 ){ 17007f9c5dbfSdrh ExprList *pList; 1701108aa00aSdrh Token ipkToken; 1702108aa00aSdrh ipkToken.z = pTab->aCol[pTab->iPKey].zName; 1703108aa00aSdrh ipkToken.n = sqlite3Strlen30(ipkToken.z); 1704108aa00aSdrh pList = sqlite3ExprListAppend(pParse, 0, 1705108aa00aSdrh sqlite3ExprAlloc(db, TK_ID, &ipkToken, 0)); 17067f9c5dbfSdrh if( pList==0 ) return; 17077f9c5dbfSdrh pList->a[0].sortOrder = pParse->iPkSortOrder; 17087f9c5dbfSdrh assert( pParse->pNewTable==pTab ); 17097f9c5dbfSdrh pPk = sqlite3CreateIndex(pParse, 0, 0, 0, pList, pTab->keyConf, 0, 0, 0, 0); 17107f9c5dbfSdrh if( pPk==0 ) return; 171148dd1d8eSdrh pPk->idxType = SQLITE_IDXTYPE_PRIMARYKEY; 17127f9c5dbfSdrh pTab->iPKey = -1; 17134415628aSdrh }else{ 17144415628aSdrh pPk = sqlite3PrimaryKeyIndex(pTab); 1715c5b73585Sdan 1716c5b73585Sdan /* Bypass the creation of the PRIMARY KEY btree and the sqlite_master 1717c5b73585Sdan ** table entry. This is only required if currently generating VDBE 1718c5b73585Sdan ** code for a CREATE TABLE (not when parsing one as part of reading 1719c5b73585Sdan ** a database schema). */ 1720c5b73585Sdan if( v ){ 1721c5b73585Sdan assert( db->init.busy==0 ); 1722c5b73585Sdan sqlite3VdbeGetOp(v, pPk->tnum)->opcode = OP_Goto; 1723c5b73585Sdan } 1724c5b73585Sdan 1725e385d887Sdrh /* 1726e385d887Sdrh ** Remove all redundant columns from the PRIMARY KEY. For example, change 1727e385d887Sdrh ** "PRIMARY KEY(a,b,a,b,c,b,c,d)" into just "PRIMARY KEY(a,b,c,d)". Later 1728e385d887Sdrh ** code assumes the PRIMARY KEY contains no repeated columns. 1729e385d887Sdrh */ 1730e385d887Sdrh for(i=j=1; i<pPk->nKeyCol; i++){ 1731e385d887Sdrh if( hasColumn(pPk->aiColumn, j, pPk->aiColumn[i]) ){ 1732e385d887Sdrh pPk->nColumn--; 1733e385d887Sdrh }else{ 1734e385d887Sdrh pPk->aiColumn[j++] = pPk->aiColumn[i]; 1735e385d887Sdrh } 1736e385d887Sdrh } 1737e385d887Sdrh pPk->nKeyCol = j; 17387f9c5dbfSdrh } 17391282609bSdrh pPk->isCovering = 1; 17407f9c5dbfSdrh assert( pPk!=0 ); 17417f9c5dbfSdrh nPk = pPk->nKeyCol; 17427f9c5dbfSdrh 17431ffede8cSdrh /* Make sure every column of the PRIMARY KEY is NOT NULL. (Except, 17441ffede8cSdrh ** do not enforce this for imposter tables.) */ 17451ffede8cSdrh if( !db->init.imposterTable ){ 1746ec95c441Sdrh for(i=0; i<nPk; i++){ 1747ec95c441Sdrh pTab->aCol[pPk->aiColumn[i]].notNull = 1; 1748ec95c441Sdrh } 17499eade087Sdrh pPk->uniqNotNull = 1; 17501ffede8cSdrh } 1751ec95c441Sdrh 1752c6bd4e4aSdrh /* The root page of the PRIMARY KEY is the table root page */ 1753c6bd4e4aSdrh pPk->tnum = pTab->tnum; 1754c6bd4e4aSdrh 17557f9c5dbfSdrh /* Update the in-memory representation of all UNIQUE indices by converting 17567f9c5dbfSdrh ** the final rowid column into one or more columns of the PRIMARY KEY. 17577f9c5dbfSdrh */ 17587f9c5dbfSdrh for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ 17597f9c5dbfSdrh int n; 176048dd1d8eSdrh if( IsPrimaryKeyIndex(pIdx) ) continue; 17617f9c5dbfSdrh for(i=n=0; i<nPk; i++){ 17627f9c5dbfSdrh if( !hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) ) n++; 17637f9c5dbfSdrh } 17645a9a37b7Sdrh if( n==0 ){ 17655a9a37b7Sdrh /* This index is a superset of the primary key */ 17665a9a37b7Sdrh pIdx->nColumn = pIdx->nKeyCol; 17675a9a37b7Sdrh continue; 17685a9a37b7Sdrh } 17697f9c5dbfSdrh if( resizeIndexObject(db, pIdx, pIdx->nKeyCol+n) ) return; 17707f9c5dbfSdrh for(i=0, j=pIdx->nKeyCol; i<nPk; i++){ 17717913e41fSdrh if( !hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) ){ 17727f9c5dbfSdrh pIdx->aiColumn[j] = pPk->aiColumn[i]; 17737f9c5dbfSdrh pIdx->azColl[j] = pPk->azColl[i]; 17747f9c5dbfSdrh j++; 17757f9c5dbfSdrh } 17767f9c5dbfSdrh } 177700012df4Sdrh assert( pIdx->nColumn>=pIdx->nKeyCol+n ); 177800012df4Sdrh assert( pIdx->nColumn>=j ); 17797f9c5dbfSdrh } 17807f9c5dbfSdrh 17817f9c5dbfSdrh /* Add all table columns to the PRIMARY KEY index 17827f9c5dbfSdrh */ 17837f9c5dbfSdrh if( nPk<pTab->nCol ){ 17847f9c5dbfSdrh if( resizeIndexObject(db, pPk, pTab->nCol) ) return; 17857f9c5dbfSdrh for(i=0, j=nPk; i<pTab->nCol; i++){ 17867f9c5dbfSdrh if( !hasColumn(pPk->aiColumn, j, i) ){ 17877f9c5dbfSdrh assert( j<pPk->nColumn ); 17887f9c5dbfSdrh pPk->aiColumn[j] = i; 17897f9c5dbfSdrh pPk->azColl[j] = "BINARY"; 17907f9c5dbfSdrh j++; 17917f9c5dbfSdrh } 17927f9c5dbfSdrh } 17937f9c5dbfSdrh assert( pPk->nColumn==j ); 17947f9c5dbfSdrh assert( pTab->nCol==j ); 1795c3e356feSdrh }else{ 1796c3e356feSdrh pPk->nColumn = pTab->nCol; 17977f9c5dbfSdrh } 17987f9c5dbfSdrh } 17997f9c5dbfSdrh 1800fdaac671Sdrh /* 180175897234Sdrh ** This routine is called to report the final ")" that terminates 180275897234Sdrh ** a CREATE TABLE statement. 180375897234Sdrh ** 1804f57b3399Sdrh ** The table structure that other action routines have been building 1805f57b3399Sdrh ** is added to the internal hash tables, assuming no errors have 1806f57b3399Sdrh ** occurred. 180775897234Sdrh ** 18081d85d931Sdrh ** An entry for the table is made in the master table on disk, unless 18091d85d931Sdrh ** this is a temporary table or db->init.busy==1. When db->init.busy==1 1810f57b3399Sdrh ** it means we are reading the sqlite_master table because we just 1811f57b3399Sdrh ** connected to the database or because the sqlite_master table has 1812ddba9e54Sdrh ** recently changed, so the entry for this table already exists in 1813f57b3399Sdrh ** the sqlite_master table. We do not want to create it again. 1814969fa7c1Sdrh ** 1815969fa7c1Sdrh ** If the pSelect argument is not NULL, it means that this routine 1816969fa7c1Sdrh ** was called to create a table generated from a 1817969fa7c1Sdrh ** "CREATE TABLE ... AS SELECT ..." statement. The column names of 1818969fa7c1Sdrh ** the new table will match the result set of the SELECT. 181975897234Sdrh */ 182019a8e7e8Sdanielk1977 void sqlite3EndTable( 182119a8e7e8Sdanielk1977 Parse *pParse, /* Parse context */ 182219a8e7e8Sdanielk1977 Token *pCons, /* The ',' token after the last column defn. */ 18235969da4aSdrh Token *pEnd, /* The ')' before options in the CREATE TABLE */ 18245969da4aSdrh u8 tabOpts, /* Extra table options. Usually 0. */ 182519a8e7e8Sdanielk1977 Select *pSelect /* Select from a "CREATE ... AS SELECT" */ 182619a8e7e8Sdanielk1977 ){ 1827fdaac671Sdrh Table *p; /* The new table */ 1828fdaac671Sdrh sqlite3 *db = pParse->db; /* The database connection */ 1829fdaac671Sdrh int iDb; /* Database in which the table lives */ 1830fdaac671Sdrh Index *pIdx; /* An implied index of the table */ 183175897234Sdrh 1832027616d4Sdrh if( pEnd==0 && pSelect==0 ){ 18335969da4aSdrh return; 1834261919ccSdanielk1977 } 1835834f9971Sdrh assert( !db->mallocFailed ); 18362803757aSdrh p = pParse->pNewTable; 18375969da4aSdrh if( p==0 ) return; 183875897234Sdrh 1839517eb646Sdanielk1977 assert( !db->init.busy || !pSelect ); 1840517eb646Sdanielk1977 1841c6bd4e4aSdrh /* If the db->init.busy is 1 it means we are reading the SQL off the 1842c6bd4e4aSdrh ** "sqlite_master" or "sqlite_temp_master" table on the disk. 1843c6bd4e4aSdrh ** So do not write to the disk again. Extract the root page number 1844c6bd4e4aSdrh ** for the table from the db->init.newTnum field. (The page number 1845c6bd4e4aSdrh ** should have been put there by the sqliteOpenCb routine.) 1846c6bd4e4aSdrh */ 1847c6bd4e4aSdrh if( db->init.busy ){ 1848c6bd4e4aSdrh p->tnum = db->init.newTnum; 1849c6bd4e4aSdrh } 1850c6bd4e4aSdrh 1851c6bd4e4aSdrh /* Special processing for WITHOUT ROWID Tables */ 18525969da4aSdrh if( tabOpts & TF_WithoutRowid ){ 1853d2fe3358Sdrh if( (p->tabFlags & TF_Autoincrement) ){ 1854d2fe3358Sdrh sqlite3ErrorMsg(pParse, 1855d2fe3358Sdrh "AUTOINCREMENT not allowed on WITHOUT ROWID tables"); 1856d2fe3358Sdrh return; 1857d2fe3358Sdrh } 185881eba73eSdrh if( (p->tabFlags & TF_HasPrimaryKey)==0 ){ 1859d2fe3358Sdrh sqlite3ErrorMsg(pParse, "PRIMARY KEY missing on table %s", p->zName); 18607f9c5dbfSdrh }else{ 1861fccda8a1Sdrh p->tabFlags |= TF_WithoutRowid | TF_NoVisibleRowid; 18627f9c5dbfSdrh convertToWithoutRowidTable(pParse, p); 18637f9c5dbfSdrh } 186481eba73eSdrh } 186581eba73eSdrh 1866b9bb7c18Sdrh iDb = sqlite3SchemaToIndex(db, p->pSchema); 1867da184236Sdanielk1977 1868ffe07b2dSdrh #ifndef SQLITE_OMIT_CHECK 1869ffe07b2dSdrh /* Resolve names in all CHECK constraint expressions. 1870ffe07b2dSdrh */ 1871ffe07b2dSdrh if( p->pCheck ){ 18723780be11Sdrh sqlite3ResolveSelfReference(pParse, p, NC_IsCheck, 0, p->pCheck); 18732938f924Sdrh } 1874ffe07b2dSdrh #endif /* !defined(SQLITE_OMIT_CHECK) */ 1875ffe07b2dSdrh 1876e13e9f54Sdrh /* Estimate the average row size for the table and for all implied indices */ 1877e13e9f54Sdrh estimateTableWidth(p); 1878fdaac671Sdrh for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){ 1879e13e9f54Sdrh estimateIndexWidth(pIdx); 1880fdaac671Sdrh } 1881fdaac671Sdrh 1882e3c41372Sdrh /* If not initializing, then create a record for the new table 18830fa991b9Sdrh ** in the SQLITE_MASTER table of the database. 1884f57b3399Sdrh ** 1885e0bc4048Sdrh ** If this is a TEMPORARY table, write the entry into the auxiliary 1886e0bc4048Sdrh ** file instead of into the main database file. 188775897234Sdrh */ 18881d85d931Sdrh if( !db->init.busy ){ 18894ff6dfa7Sdrh int n; 1890d8bc7086Sdrh Vdbe *v; 18914794f735Sdrh char *zType; /* "view" or "table" */ 18924794f735Sdrh char *zType2; /* "VIEW" or "TABLE" */ 18934794f735Sdrh char *zStmt; /* Text of the CREATE TABLE or CREATE VIEW statement */ 189475897234Sdrh 18954adee20fSdanielk1977 v = sqlite3GetVdbe(pParse); 18965969da4aSdrh if( NEVER(v==0) ) return; 1897517eb646Sdanielk1977 189866a5167bSdrh sqlite3VdbeAddOp1(v, OP_Close, 0); 1899e6efa74bSdanielk1977 19000fa991b9Sdrh /* 19010fa991b9Sdrh ** Initialize zType for the new view or table. 19024794f735Sdrh */ 19034ff6dfa7Sdrh if( p->pSelect==0 ){ 19044ff6dfa7Sdrh /* A regular table */ 19054794f735Sdrh zType = "table"; 19064794f735Sdrh zType2 = "TABLE"; 1907576ec6b3Sdanielk1977 #ifndef SQLITE_OMIT_VIEW 19084ff6dfa7Sdrh }else{ 19094ff6dfa7Sdrh /* A view */ 19104794f735Sdrh zType = "view"; 19114794f735Sdrh zType2 = "VIEW"; 1912576ec6b3Sdanielk1977 #endif 19134ff6dfa7Sdrh } 1914517eb646Sdanielk1977 1915517eb646Sdanielk1977 /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT 1916517eb646Sdanielk1977 ** statement to populate the new table. The root-page number for the 19170fa991b9Sdrh ** new table is in register pParse->regRoot. 1918517eb646Sdanielk1977 ** 1919517eb646Sdanielk1977 ** Once the SELECT has been coded by sqlite3Select(), it is in a 1920517eb646Sdanielk1977 ** suitable state to query for the column names and types to be used 1921517eb646Sdanielk1977 ** by the new table. 1922c00da105Sdanielk1977 ** 1923c00da105Sdanielk1977 ** A shared-cache write-lock is not required to write to the new table, 1924c00da105Sdanielk1977 ** as a schema-lock must have already been obtained to create it. Since 1925c00da105Sdanielk1977 ** a schema-lock excludes all other database users, the write-lock would 1926c00da105Sdanielk1977 ** be redundant. 1927517eb646Sdanielk1977 */ 1928517eb646Sdanielk1977 if( pSelect ){ 192992632204Sdrh SelectDest dest; /* Where the SELECT should store results */ 19309df25c47Sdrh int regYield; /* Register holding co-routine entry-point */ 19319df25c47Sdrh int addrTop; /* Top of the co-routine */ 193292632204Sdrh int regRec; /* A record to be insert into the new table */ 193392632204Sdrh int regRowid; /* Rowid of the next row to insert */ 193492632204Sdrh int addrInsLoop; /* Top of the loop for inserting rows */ 193592632204Sdrh Table *pSelTab; /* A table that describes the SELECT results */ 19361013c932Sdrh 19379df25c47Sdrh regYield = ++pParse->nMem; 193892632204Sdrh regRec = ++pParse->nMem; 193992632204Sdrh regRowid = ++pParse->nMem; 19406ab3a2ecSdanielk1977 assert(pParse->nTab==1); 19410dd5cdaeSdrh sqlite3MayAbort(pParse); 1942b7654111Sdrh sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb); 1943428c218cSdan sqlite3VdbeChangeP5(v, OPFLAG_P2ISREG); 1944517eb646Sdanielk1977 pParse->nTab = 2; 19459df25c47Sdrh addrTop = sqlite3VdbeCurrentAddr(v) + 1; 19469df25c47Sdrh sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, addrTop); 19479df25c47Sdrh sqlite3SelectDestInit(&dest, SRT_Coroutine, regYield); 19487d10d5a6Sdrh sqlite3Select(pParse, pSelect, &dest); 19499df25c47Sdrh sqlite3VdbeAddOp1(v, OP_EndCoroutine, regYield); 19509df25c47Sdrh sqlite3VdbeJumpHere(v, addrTop - 1); 195192632204Sdrh if( pParse->nErr ) return; 19527d10d5a6Sdrh pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect); 19535969da4aSdrh if( pSelTab==0 ) return; 1954517eb646Sdanielk1977 assert( p->aCol==0 ); 1955517eb646Sdanielk1977 p->nCol = pSelTab->nCol; 1956517eb646Sdanielk1977 p->aCol = pSelTab->aCol; 1957517eb646Sdanielk1977 pSelTab->nCol = 0; 1958517eb646Sdanielk1977 pSelTab->aCol = 0; 19591feeaed2Sdan sqlite3DeleteTable(db, pSelTab); 19609df25c47Sdrh addrInsLoop = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm); 19619df25c47Sdrh VdbeCoverage(v); 19629df25c47Sdrh sqlite3VdbeAddOp3(v, OP_MakeRecord, dest.iSdst, dest.nSdst, regRec); 19639df25c47Sdrh sqlite3TableAffinity(v, p, 0); 19649df25c47Sdrh sqlite3VdbeAddOp2(v, OP_NewRowid, 1, regRowid); 19659df25c47Sdrh sqlite3VdbeAddOp3(v, OP_Insert, 1, regRec, regRowid); 19669df25c47Sdrh sqlite3VdbeAddOp2(v, OP_Goto, 0, addrInsLoop); 19679df25c47Sdrh sqlite3VdbeJumpHere(v, addrInsLoop); 19689df25c47Sdrh sqlite3VdbeAddOp1(v, OP_Close, 1); 1969517eb646Sdanielk1977 } 1970517eb646Sdanielk1977 19714794f735Sdrh /* Compute the complete text of the CREATE statement */ 19724794f735Sdrh if( pSelect ){ 19731d34fdecSdrh zStmt = createTableStmt(db, p); 19744794f735Sdrh }else{ 19758ea30bfcSdrh Token *pEnd2 = tabOpts ? &pParse->sLastToken : pEnd; 19768ea30bfcSdrh n = (int)(pEnd2->z - pParse->sNameToken.z); 19778ea30bfcSdrh if( pEnd2->z[0]!=';' ) n += pEnd2->n; 19781e536953Sdanielk1977 zStmt = sqlite3MPrintf(db, 19791e536953Sdanielk1977 "CREATE %s %.*s", zType2, n, pParse->sNameToken.z 19801e536953Sdanielk1977 ); 19814794f735Sdrh } 19824794f735Sdrh 19834794f735Sdrh /* A slot for the record has already been allocated in the 19844794f735Sdrh ** SQLITE_MASTER table. We just need to update that slot with all 19850fa991b9Sdrh ** the information we've collected. 19864794f735Sdrh */ 19874794f735Sdrh sqlite3NestedParse(pParse, 19884794f735Sdrh "UPDATE %Q.%s " 1989b7654111Sdrh "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q " 1990b7654111Sdrh "WHERE rowid=#%d", 1991da184236Sdanielk1977 db->aDb[iDb].zName, SCHEMA_TABLE(iDb), 19924794f735Sdrh zType, 19934794f735Sdrh p->zName, 19944794f735Sdrh p->zName, 1995b7654111Sdrh pParse->regRoot, 1996b7654111Sdrh zStmt, 1997b7654111Sdrh pParse->regRowid 19984794f735Sdrh ); 1999633e6d57Sdrh sqlite3DbFree(db, zStmt); 20009cbf3425Sdrh sqlite3ChangeCookie(pParse, iDb); 20012958a4e6Sdrh 20022958a4e6Sdrh #ifndef SQLITE_OMIT_AUTOINCREMENT 20032958a4e6Sdrh /* Check to see if we need to create an sqlite_sequence table for 20042958a4e6Sdrh ** keeping track of autoincrement keys. 20052958a4e6Sdrh */ 20067d10d5a6Sdrh if( p->tabFlags & TF_Autoincrement ){ 2007da184236Sdanielk1977 Db *pDb = &db->aDb[iDb]; 20082120608eSdrh assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); 2009da184236Sdanielk1977 if( pDb->pSchema->pSeqTab==0 ){ 20102958a4e6Sdrh sqlite3NestedParse(pParse, 2011f3388144Sdrh "CREATE TABLE %Q.sqlite_sequence(name,seq)", 2012f3388144Sdrh pDb->zName 20132958a4e6Sdrh ); 20142958a4e6Sdrh } 20152958a4e6Sdrh } 20162958a4e6Sdrh #endif 20174794f735Sdrh 20184794f735Sdrh /* Reparse everything to update our internal data structures */ 20195d9c9da6Sdrh sqlite3VdbeAddParseSchemaOp(v, iDb, 2020197bc20cSdan sqlite3MPrintf(db, "tbl_name='%q' AND type!='trigger'", p->zName)); 202175897234Sdrh } 202217e9e29dSdrh 20232958a4e6Sdrh 202417e9e29dSdrh /* Add the table to the in-memory representation of the database. 202517e9e29dSdrh */ 20268af73d41Sdrh if( db->init.busy ){ 202717e9e29dSdrh Table *pOld; 2028e501b89aSdanielk1977 Schema *pSchema = p->pSchema; 20292120608eSdrh assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); 2030acbcb7e0Sdrh pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName, p); 203117e9e29dSdrh if( pOld ){ 203217e9e29dSdrh assert( p==pOld ); /* Malloc must have failed inside HashInsert() */ 203317435752Sdrh db->mallocFailed = 1; 20345969da4aSdrh return; 203517e9e29dSdrh } 203617e9e29dSdrh pParse->pNewTable = 0; 203717e9e29dSdrh db->flags |= SQLITE_InternChanges; 203819a8e7e8Sdanielk1977 203919a8e7e8Sdanielk1977 #ifndef SQLITE_OMIT_ALTERTABLE 204019a8e7e8Sdanielk1977 if( !p->pSelect ){ 2041bab45c64Sdanielk1977 const char *zName = (const char *)pParse->sNameToken.z; 20429a087a99Sdrh int nName; 20435969da4aSdrh assert( !pSelect && pCons && pEnd ); 2044bab45c64Sdanielk1977 if( pCons->z==0 ){ 20455969da4aSdrh pCons = pEnd; 2046bab45c64Sdanielk1977 } 20471bd10f8aSdrh nName = (int)((const char *)pCons->z - zName); 20489a087a99Sdrh p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName); 204919a8e7e8Sdanielk1977 } 205019a8e7e8Sdanielk1977 #endif 205117e9e29dSdrh } 205275897234Sdrh } 205375897234Sdrh 2054b7f9164eSdrh #ifndef SQLITE_OMIT_VIEW 205575897234Sdrh /* 2056a76b5dfcSdrh ** The parser calls this routine in order to create a new VIEW 2057a76b5dfcSdrh */ 20584adee20fSdanielk1977 void sqlite3CreateView( 2059a76b5dfcSdrh Parse *pParse, /* The parsing context */ 2060a76b5dfcSdrh Token *pBegin, /* The CREATE token that begins the statement */ 206148dec7e2Sdanielk1977 Token *pName1, /* The token that holds the name of the view */ 206248dec7e2Sdanielk1977 Token *pName2, /* The token that holds the name of the view */ 20638981b904Sdrh ExprList *pCNames, /* Optional list of view column names */ 20646276c1cbSdrh Select *pSelect, /* A SELECT statement that will become the new view */ 2065fdd48a76Sdrh int isTemp, /* TRUE for a TEMPORARY view */ 2066fdd48a76Sdrh int noErr /* Suppress error messages if VIEW already exists */ 2067a76b5dfcSdrh ){ 2068a76b5dfcSdrh Table *p; 20694b59ab5eSdrh int n; 2070b7916a78Sdrh const char *z; 20714b59ab5eSdrh Token sEnd; 2072f26e09c8Sdrh DbFixer sFix; 207388caeac7Sdrh Token *pName = 0; 2074da184236Sdanielk1977 int iDb; 207517435752Sdrh sqlite3 *db = pParse->db; 2076a76b5dfcSdrh 20777c3d64f1Sdrh if( pParse->nVar>0 ){ 20787c3d64f1Sdrh sqlite3ErrorMsg(pParse, "parameters are not allowed in views"); 2079633e6d57Sdrh sqlite3SelectDelete(db, pSelect); 20807c3d64f1Sdrh return; 20817c3d64f1Sdrh } 2082fdd48a76Sdrh sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr); 2083a76b5dfcSdrh p = pParse->pNewTable; 20848981b904Sdrh if( p==0 || pParse->nErr ) goto create_view_fail; 2085ef2cb63eSdanielk1977 sqlite3TwoPartName(pParse, pName1, pName2, &pName); 208617435752Sdrh iDb = sqlite3SchemaToIndex(db, p->pSchema); 2087d100f691Sdrh sqlite3FixInit(&sFix, pParse, iDb, "view", pName); 20888981b904Sdrh if( sqlite3FixSelect(&sFix, pSelect) ) goto create_view_fail; 2089174b6195Sdrh 20904b59ab5eSdrh /* Make a copy of the entire SELECT statement that defines the view. 20914b59ab5eSdrh ** This will force all the Expr.token.z values to be dynamically 20924b59ab5eSdrh ** allocated rather than point to the input string - which means that 209324b03fd0Sdanielk1977 ** they will persist after the current sqlite3_exec() call returns. 20944b59ab5eSdrh */ 20956ab3a2ecSdanielk1977 p->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE); 20968981b904Sdrh p->pCheck = sqlite3ExprListDup(db, pCNames, EXPRDUP_REDUCE); 20978981b904Sdrh if( db->mallocFailed ) goto create_view_fail; 20984b59ab5eSdrh 20994b59ab5eSdrh /* Locate the end of the CREATE VIEW statement. Make sEnd point to 21004b59ab5eSdrh ** the end. 21014b59ab5eSdrh */ 2102a76b5dfcSdrh sEnd = pParse->sLastToken; 21038981b904Sdrh assert( sEnd.z[0]!=0 ); 21048981b904Sdrh if( sEnd.z[0]!=';' ){ 2105a76b5dfcSdrh sEnd.z += sEnd.n; 2106a76b5dfcSdrh } 2107a76b5dfcSdrh sEnd.n = 0; 21081bd10f8aSdrh n = (int)(sEnd.z - pBegin->z); 21098981b904Sdrh assert( n>0 ); 2110b7916a78Sdrh z = pBegin->z; 21118981b904Sdrh while( sqlite3Isspace(z[n-1]) ){ n--; } 21124ff6dfa7Sdrh sEnd.z = &z[n-1]; 21134ff6dfa7Sdrh sEnd.n = 1; 21144b59ab5eSdrh 21154adee20fSdanielk1977 /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */ 21165969da4aSdrh sqlite3EndTable(pParse, 0, &sEnd, 0, 0); 21178981b904Sdrh 21188981b904Sdrh create_view_fail: 21198981b904Sdrh sqlite3SelectDelete(db, pSelect); 21208981b904Sdrh sqlite3ExprListDelete(db, pCNames); 2121a76b5dfcSdrh return; 2122417be79cSdrh } 2123b7f9164eSdrh #endif /* SQLITE_OMIT_VIEW */ 2124a76b5dfcSdrh 2125fe3fcbe2Sdanielk1977 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) 2126417be79cSdrh /* 2127417be79cSdrh ** The Table structure pTable is really a VIEW. Fill in the names of 2128417be79cSdrh ** the columns of the view in the pTable structure. Return the number 2129cfa5684dSjplyon ** of errors. If an error is seen leave an error message in pParse->zErrMsg. 2130417be79cSdrh */ 21314adee20fSdanielk1977 int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){ 21329b3187e1Sdrh Table *pSelTab; /* A fake table from which we get the result set */ 21339b3187e1Sdrh Select *pSel; /* Copy of the SELECT that implements the view */ 21349b3187e1Sdrh int nErr = 0; /* Number of errors encountered */ 21359b3187e1Sdrh int n; /* Temporarily holds the number of cursors assigned */ 213617435752Sdrh sqlite3 *db = pParse->db; /* Database connection for malloc errors */ 213732c6a48bSdrh sqlite3_xauth xAuth; /* Saved xAuth pointer */ 21388981b904Sdrh u8 bEnabledLA; /* Saved db->lookaside.bEnabled state */ 2139417be79cSdrh 2140417be79cSdrh assert( pTable ); 2141417be79cSdrh 2142fe3fcbe2Sdanielk1977 #ifndef SQLITE_OMIT_VIRTUALTABLE 2143fe3fcbe2Sdanielk1977 if( sqlite3VtabCallConnect(pParse, pTable) ){ 2144fe3fcbe2Sdanielk1977 return SQLITE_ERROR; 2145fe3fcbe2Sdanielk1977 } 21464cbdda9eSdrh if( IsVirtual(pTable) ) return 0; 2147fe3fcbe2Sdanielk1977 #endif 2148fe3fcbe2Sdanielk1977 2149fe3fcbe2Sdanielk1977 #ifndef SQLITE_OMIT_VIEW 2150417be79cSdrh /* A positive nCol means the columns names for this view are 2151417be79cSdrh ** already known. 2152417be79cSdrh */ 2153417be79cSdrh if( pTable->nCol>0 ) return 0; 2154417be79cSdrh 2155417be79cSdrh /* A negative nCol is a special marker meaning that we are currently 2156417be79cSdrh ** trying to compute the column names. If we enter this routine with 2157417be79cSdrh ** a negative nCol, it means two or more views form a loop, like this: 2158417be79cSdrh ** 2159417be79cSdrh ** CREATE VIEW one AS SELECT * FROM two; 2160417be79cSdrh ** CREATE VIEW two AS SELECT * FROM one; 21613b167c75Sdrh ** 2162768578eeSdrh ** Actually, the error above is now caught prior to reaching this point. 2163768578eeSdrh ** But the following test is still important as it does come up 2164768578eeSdrh ** in the following: 2165768578eeSdrh ** 2166768578eeSdrh ** CREATE TABLE main.ex1(a); 2167768578eeSdrh ** CREATE TEMP VIEW ex1 AS SELECT a FROM ex1; 2168768578eeSdrh ** SELECT * FROM temp.ex1; 2169417be79cSdrh */ 2170417be79cSdrh if( pTable->nCol<0 ){ 21714adee20fSdanielk1977 sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName); 2172417be79cSdrh return 1; 2173417be79cSdrh } 217485c23c61Sdrh assert( pTable->nCol>=0 ); 2175417be79cSdrh 2176417be79cSdrh /* If we get this far, it means we need to compute the table names. 21779b3187e1Sdrh ** Note that the call to sqlite3ResultSetOfSelect() will expand any 21789b3187e1Sdrh ** "*" elements in the results set of the view and will assign cursors 21799b3187e1Sdrh ** to the elements of the FROM clause. But we do not want these changes 21809b3187e1Sdrh ** to be permanent. So the computation is done on a copy of the SELECT 21819b3187e1Sdrh ** statement that defines the view. 2182417be79cSdrh */ 21839b3187e1Sdrh assert( pTable->pSelect ); 21848981b904Sdrh bEnabledLA = db->lookaside.bEnabled; 21858981b904Sdrh if( pTable->pCheck ){ 21868981b904Sdrh db->lookaside.bEnabled = 0; 21878981b904Sdrh sqlite3ColumnsFromExprList(pParse, pTable->pCheck, 21888981b904Sdrh &pTable->nCol, &pTable->aCol); 21898981b904Sdrh }else{ 21906ab3a2ecSdanielk1977 pSel = sqlite3SelectDup(db, pTable->pSelect, 0); 2191261919ccSdanielk1977 if( pSel ){ 21929b3187e1Sdrh n = pParse->nTab; 21939b3187e1Sdrh sqlite3SrcListAssignCursors(pParse, pSel->pSrc); 2194417be79cSdrh pTable->nCol = -1; 2195d9da78a2Sdrh db->lookaside.bEnabled = 0; 2196db2d286bSdanielk1977 #ifndef SQLITE_OMIT_AUTHORIZATION 2197a6d0ffc3Sdrh xAuth = db->xAuth; 2198a6d0ffc3Sdrh db->xAuth = 0; 21997d10d5a6Sdrh pSelTab = sqlite3ResultSetOfSelect(pParse, pSel); 2200a6d0ffc3Sdrh db->xAuth = xAuth; 2201db2d286bSdanielk1977 #else 22027d10d5a6Sdrh pSelTab = sqlite3ResultSetOfSelect(pParse, pSel); 2203db2d286bSdanielk1977 #endif 22049b3187e1Sdrh pParse->nTab = n; 2205417be79cSdrh if( pSelTab ){ 2206417be79cSdrh assert( pTable->aCol==0 ); 2207417be79cSdrh pTable->nCol = pSelTab->nCol; 2208417be79cSdrh pTable->aCol = pSelTab->aCol; 2209417be79cSdrh pSelTab->nCol = 0; 2210417be79cSdrh pSelTab->aCol = 0; 22111feeaed2Sdan sqlite3DeleteTable(db, pSelTab); 22122120608eSdrh assert( sqlite3SchemaMutexHeld(db, 0, pTable->pSchema) ); 2213417be79cSdrh }else{ 2214417be79cSdrh pTable->nCol = 0; 2215417be79cSdrh nErr++; 2216417be79cSdrh } 2217633e6d57Sdrh sqlite3SelectDelete(db, pSel); 2218261919ccSdanielk1977 } else { 2219261919ccSdanielk1977 nErr++; 2220261919ccSdanielk1977 } 22218981b904Sdrh } 22228981b904Sdrh db->lookaside.bEnabled = bEnabledLA; 22238981b904Sdrh pTable->pSchema->schemaFlags |= DB_UnresetViews; 2224b7f9164eSdrh #endif /* SQLITE_OMIT_VIEW */ 22254b2688abSdanielk1977 return nErr; 2226fe3fcbe2Sdanielk1977 } 2227fe3fcbe2Sdanielk1977 #endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */ 2228417be79cSdrh 2229b7f9164eSdrh #ifndef SQLITE_OMIT_VIEW 2230417be79cSdrh /* 22318bf8dc92Sdrh ** Clear the column names from every VIEW in database idx. 2232417be79cSdrh */ 22339bb575fdSdrh static void sqliteViewResetAll(sqlite3 *db, int idx){ 2234417be79cSdrh HashElem *i; 22352120608eSdrh assert( sqlite3SchemaMutexHeld(db, idx, 0) ); 22368bf8dc92Sdrh if( !DbHasProperty(db, idx, DB_UnresetViews) ) return; 2237da184236Sdanielk1977 for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){ 2238417be79cSdrh Table *pTab = sqliteHashData(i); 2239417be79cSdrh if( pTab->pSelect ){ 224051be3873Sdrh sqlite3DeleteColumnNames(db, pTab); 2241d46def77Sdan pTab->aCol = 0; 2242d46def77Sdan pTab->nCol = 0; 2243417be79cSdrh } 2244417be79cSdrh } 22458bf8dc92Sdrh DbClearProperty(db, idx, DB_UnresetViews); 2246a76b5dfcSdrh } 2247b7f9164eSdrh #else 2248b7f9164eSdrh # define sqliteViewResetAll(A,B) 2249b7f9164eSdrh #endif /* SQLITE_OMIT_VIEW */ 2250a76b5dfcSdrh 225175897234Sdrh /* 2252a0bf2652Sdanielk1977 ** This function is called by the VDBE to adjust the internal schema 2253a0bf2652Sdanielk1977 ** used by SQLite when the btree layer moves a table root page. The 2254a0bf2652Sdanielk1977 ** root-page of a table or index in database iDb has changed from iFrom 2255a0bf2652Sdanielk1977 ** to iTo. 22566205d4a4Sdrh ** 22576205d4a4Sdrh ** Ticket #1728: The symbol table might still contain information 22586205d4a4Sdrh ** on tables and/or indices that are the process of being deleted. 22596205d4a4Sdrh ** If you are unlucky, one of those deleted indices or tables might 22606205d4a4Sdrh ** have the same rootpage number as the real table or index that is 22616205d4a4Sdrh ** being moved. So we cannot stop searching after the first match 22626205d4a4Sdrh ** because the first match might be for one of the deleted indices 22636205d4a4Sdrh ** or tables and not the table/index that is actually being moved. 22646205d4a4Sdrh ** We must continue looping until all tables and indices with 22656205d4a4Sdrh ** rootpage==iFrom have been converted to have a rootpage of iTo 22666205d4a4Sdrh ** in order to be certain that we got the right one. 2267a0bf2652Sdanielk1977 */ 2268a0bf2652Sdanielk1977 #ifndef SQLITE_OMIT_AUTOVACUUM 2269cdf011dcSdrh void sqlite3RootPageMoved(sqlite3 *db, int iDb, int iFrom, int iTo){ 2270a0bf2652Sdanielk1977 HashElem *pElem; 2271da184236Sdanielk1977 Hash *pHash; 2272cdf011dcSdrh Db *pDb; 2273a0bf2652Sdanielk1977 2274cdf011dcSdrh assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); 2275cdf011dcSdrh pDb = &db->aDb[iDb]; 2276da184236Sdanielk1977 pHash = &pDb->pSchema->tblHash; 2277da184236Sdanielk1977 for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){ 2278a0bf2652Sdanielk1977 Table *pTab = sqliteHashData(pElem); 2279a0bf2652Sdanielk1977 if( pTab->tnum==iFrom ){ 2280a0bf2652Sdanielk1977 pTab->tnum = iTo; 2281a0bf2652Sdanielk1977 } 2282a0bf2652Sdanielk1977 } 2283da184236Sdanielk1977 pHash = &pDb->pSchema->idxHash; 2284da184236Sdanielk1977 for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){ 2285a0bf2652Sdanielk1977 Index *pIdx = sqliteHashData(pElem); 2286a0bf2652Sdanielk1977 if( pIdx->tnum==iFrom ){ 2287a0bf2652Sdanielk1977 pIdx->tnum = iTo; 2288a0bf2652Sdanielk1977 } 2289a0bf2652Sdanielk1977 } 2290a0bf2652Sdanielk1977 } 2291a0bf2652Sdanielk1977 #endif 2292a0bf2652Sdanielk1977 2293a0bf2652Sdanielk1977 /* 2294a0bf2652Sdanielk1977 ** Write code to erase the table with root-page iTable from database iDb. 2295a0bf2652Sdanielk1977 ** Also write code to modify the sqlite_master table and internal schema 2296a0bf2652Sdanielk1977 ** if a root-page of another table is moved by the btree-layer whilst 2297a0bf2652Sdanielk1977 ** erasing iTable (this can happen with an auto-vacuum database). 2298a0bf2652Sdanielk1977 */ 22994e0cff60Sdrh static void destroyRootPage(Parse *pParse, int iTable, int iDb){ 23004e0cff60Sdrh Vdbe *v = sqlite3GetVdbe(pParse); 2301b7654111Sdrh int r1 = sqlite3GetTempReg(pParse); 2302b7654111Sdrh sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb); 2303e0af83acSdan sqlite3MayAbort(pParse); 230440e016e4Sdrh #ifndef SQLITE_OMIT_AUTOVACUUM 2305b7654111Sdrh /* OP_Destroy stores an in integer r1. If this integer 23064e0cff60Sdrh ** is non-zero, then it is the root page number of a table moved to 230781db88e6Sdrh ** location iTable. The following code modifies the sqlite_master table to 23084e0cff60Sdrh ** reflect this. 23094e0cff60Sdrh ** 23100fa991b9Sdrh ** The "#NNN" in the SQL is a special constant that means whatever value 2311b74b1017Sdrh ** is in register NNN. See grammar rules associated with the TK_REGISTER 2312b74b1017Sdrh ** token for additional information. 23134e0cff60Sdrh */ 231463e3e9f8Sdanielk1977 sqlite3NestedParse(pParse, 2315b7654111Sdrh "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d", 2316b7654111Sdrh pParse->db->aDb[iDb].zName, SCHEMA_TABLE(iDb), iTable, r1, r1); 2317a0bf2652Sdanielk1977 #endif 2318b7654111Sdrh sqlite3ReleaseTempReg(pParse, r1); 2319a0bf2652Sdanielk1977 } 2320a0bf2652Sdanielk1977 2321a0bf2652Sdanielk1977 /* 2322a0bf2652Sdanielk1977 ** Write VDBE code to erase table pTab and all associated indices on disk. 2323a0bf2652Sdanielk1977 ** Code to update the sqlite_master tables and internal schema definitions 2324a0bf2652Sdanielk1977 ** in case a root-page belonging to another table is moved by the btree layer 2325a0bf2652Sdanielk1977 ** is also added (this can happen with an auto-vacuum database). 2326a0bf2652Sdanielk1977 */ 23274e0cff60Sdrh static void destroyTable(Parse *pParse, Table *pTab){ 2328a0bf2652Sdanielk1977 #ifdef SQLITE_OMIT_AUTOVACUUM 2329eee46cf3Sdrh Index *pIdx; 233029c636bcSdrh int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema); 233129c636bcSdrh destroyRootPage(pParse, pTab->tnum, iDb); 2332a0bf2652Sdanielk1977 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ 233329c636bcSdrh destroyRootPage(pParse, pIdx->tnum, iDb); 2334a0bf2652Sdanielk1977 } 2335a0bf2652Sdanielk1977 #else 2336a0bf2652Sdanielk1977 /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM 2337a0bf2652Sdanielk1977 ** is not defined), then it is important to call OP_Destroy on the 2338a0bf2652Sdanielk1977 ** table and index root-pages in order, starting with the numerically 2339a0bf2652Sdanielk1977 ** largest root-page number. This guarantees that none of the root-pages 2340a0bf2652Sdanielk1977 ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the 2341a0bf2652Sdanielk1977 ** following were coded: 2342a0bf2652Sdanielk1977 ** 2343a0bf2652Sdanielk1977 ** OP_Destroy 4 0 2344a0bf2652Sdanielk1977 ** ... 2345a0bf2652Sdanielk1977 ** OP_Destroy 5 0 2346a0bf2652Sdanielk1977 ** 2347a0bf2652Sdanielk1977 ** and root page 5 happened to be the largest root-page number in the 2348a0bf2652Sdanielk1977 ** database, then root page 5 would be moved to page 4 by the 2349a0bf2652Sdanielk1977 ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit 2350a0bf2652Sdanielk1977 ** a free-list page. 2351a0bf2652Sdanielk1977 */ 2352a0bf2652Sdanielk1977 int iTab = pTab->tnum; 2353a0bf2652Sdanielk1977 int iDestroyed = 0; 2354a0bf2652Sdanielk1977 2355a0bf2652Sdanielk1977 while( 1 ){ 2356a0bf2652Sdanielk1977 Index *pIdx; 2357a0bf2652Sdanielk1977 int iLargest = 0; 2358a0bf2652Sdanielk1977 2359a0bf2652Sdanielk1977 if( iDestroyed==0 || iTab<iDestroyed ){ 2360a0bf2652Sdanielk1977 iLargest = iTab; 2361a0bf2652Sdanielk1977 } 2362a0bf2652Sdanielk1977 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ 2363a0bf2652Sdanielk1977 int iIdx = pIdx->tnum; 2364da184236Sdanielk1977 assert( pIdx->pSchema==pTab->pSchema ); 2365a0bf2652Sdanielk1977 if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){ 2366a0bf2652Sdanielk1977 iLargest = iIdx; 2367a0bf2652Sdanielk1977 } 2368a0bf2652Sdanielk1977 } 2369da184236Sdanielk1977 if( iLargest==0 ){ 2370da184236Sdanielk1977 return; 2371da184236Sdanielk1977 }else{ 2372da184236Sdanielk1977 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema); 23735a05be1bSdrh assert( iDb>=0 && iDb<pParse->db->nDb ); 2374da184236Sdanielk1977 destroyRootPage(pParse, iLargest, iDb); 2375a0bf2652Sdanielk1977 iDestroyed = iLargest; 2376a0bf2652Sdanielk1977 } 2377da184236Sdanielk1977 } 2378a0bf2652Sdanielk1977 #endif 2379a0bf2652Sdanielk1977 } 2380a0bf2652Sdanielk1977 2381a0bf2652Sdanielk1977 /* 238274e7c8f5Sdrh ** Remove entries from the sqlite_statN tables (for N in (1,2,3)) 2383a5ae4c33Sdrh ** after a DROP INDEX or DROP TABLE command. 2384a5ae4c33Sdrh */ 2385a5ae4c33Sdrh static void sqlite3ClearStatTables( 2386a5ae4c33Sdrh Parse *pParse, /* The parsing context */ 2387a5ae4c33Sdrh int iDb, /* The database number */ 2388a5ae4c33Sdrh const char *zType, /* "idx" or "tbl" */ 2389a5ae4c33Sdrh const char *zName /* Name of index or table */ 2390a5ae4c33Sdrh ){ 2391a5ae4c33Sdrh int i; 2392a5ae4c33Sdrh const char *zDbName = pParse->db->aDb[iDb].zName; 2393f52bb8d3Sdan for(i=1; i<=4; i++){ 239474e7c8f5Sdrh char zTab[24]; 239574e7c8f5Sdrh sqlite3_snprintf(sizeof(zTab),zTab,"sqlite_stat%d",i); 239674e7c8f5Sdrh if( sqlite3FindTable(pParse->db, zTab, zDbName) ){ 2397a5ae4c33Sdrh sqlite3NestedParse(pParse, 2398a5ae4c33Sdrh "DELETE FROM %Q.%s WHERE %s=%Q", 239974e7c8f5Sdrh zDbName, zTab, zType, zName 2400a5ae4c33Sdrh ); 2401a5ae4c33Sdrh } 2402a5ae4c33Sdrh } 2403a5ae4c33Sdrh } 2404a5ae4c33Sdrh 2405a5ae4c33Sdrh /* 2406faacf17cSdrh ** Generate code to drop a table. 2407faacf17cSdrh */ 2408faacf17cSdrh void sqlite3CodeDropTable(Parse *pParse, Table *pTab, int iDb, int isView){ 2409faacf17cSdrh Vdbe *v; 2410faacf17cSdrh sqlite3 *db = pParse->db; 2411faacf17cSdrh Trigger *pTrigger; 2412faacf17cSdrh Db *pDb = &db->aDb[iDb]; 2413faacf17cSdrh 2414faacf17cSdrh v = sqlite3GetVdbe(pParse); 2415faacf17cSdrh assert( v!=0 ); 2416faacf17cSdrh sqlite3BeginWriteOperation(pParse, 1, iDb); 2417faacf17cSdrh 2418faacf17cSdrh #ifndef SQLITE_OMIT_VIRTUALTABLE 2419faacf17cSdrh if( IsVirtual(pTab) ){ 2420faacf17cSdrh sqlite3VdbeAddOp0(v, OP_VBegin); 2421faacf17cSdrh } 2422faacf17cSdrh #endif 2423faacf17cSdrh 2424faacf17cSdrh /* Drop all triggers associated with the table being dropped. Code 2425faacf17cSdrh ** is generated to remove entries from sqlite_master and/or 2426faacf17cSdrh ** sqlite_temp_master if required. 2427faacf17cSdrh */ 2428faacf17cSdrh pTrigger = sqlite3TriggerList(pParse, pTab); 2429faacf17cSdrh while( pTrigger ){ 2430faacf17cSdrh assert( pTrigger->pSchema==pTab->pSchema || 2431faacf17cSdrh pTrigger->pSchema==db->aDb[1].pSchema ); 2432faacf17cSdrh sqlite3DropTriggerPtr(pParse, pTrigger); 2433faacf17cSdrh pTrigger = pTrigger->pNext; 2434faacf17cSdrh } 2435faacf17cSdrh 2436faacf17cSdrh #ifndef SQLITE_OMIT_AUTOINCREMENT 2437faacf17cSdrh /* Remove any entries of the sqlite_sequence table associated with 2438faacf17cSdrh ** the table being dropped. This is done before the table is dropped 2439faacf17cSdrh ** at the btree level, in case the sqlite_sequence table needs to 2440faacf17cSdrh ** move as a result of the drop (can happen in auto-vacuum mode). 2441faacf17cSdrh */ 2442faacf17cSdrh if( pTab->tabFlags & TF_Autoincrement ){ 2443faacf17cSdrh sqlite3NestedParse(pParse, 2444faacf17cSdrh "DELETE FROM %Q.sqlite_sequence WHERE name=%Q", 2445faacf17cSdrh pDb->zName, pTab->zName 2446faacf17cSdrh ); 2447faacf17cSdrh } 2448faacf17cSdrh #endif 2449faacf17cSdrh 2450faacf17cSdrh /* Drop all SQLITE_MASTER table and index entries that refer to the 2451faacf17cSdrh ** table. The program name loops through the master table and deletes 2452faacf17cSdrh ** every row that refers to a table of the same name as the one being 245348864df9Smistachkin ** dropped. Triggers are handled separately because a trigger can be 2454faacf17cSdrh ** created in the temp database that refers to a table in another 2455faacf17cSdrh ** database. 2456faacf17cSdrh */ 2457faacf17cSdrh sqlite3NestedParse(pParse, 2458faacf17cSdrh "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'", 2459faacf17cSdrh pDb->zName, SCHEMA_TABLE(iDb), pTab->zName); 2460faacf17cSdrh if( !isView && !IsVirtual(pTab) ){ 2461faacf17cSdrh destroyTable(pParse, pTab); 2462faacf17cSdrh } 2463faacf17cSdrh 2464faacf17cSdrh /* Remove the table entry from SQLite's internal schema and modify 2465faacf17cSdrh ** the schema cookie. 2466faacf17cSdrh */ 2467faacf17cSdrh if( IsVirtual(pTab) ){ 2468faacf17cSdrh sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0); 2469faacf17cSdrh } 2470faacf17cSdrh sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0); 2471faacf17cSdrh sqlite3ChangeCookie(pParse, iDb); 2472faacf17cSdrh sqliteViewResetAll(db, iDb); 2473faacf17cSdrh } 2474faacf17cSdrh 2475faacf17cSdrh /* 247675897234Sdrh ** This routine is called to do the work of a DROP TABLE statement. 2477d9b0257aSdrh ** pName is the name of the table to be dropped. 247875897234Sdrh */ 2479a073384fSdrh void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){ 2480a8858103Sdanielk1977 Table *pTab; 248175897234Sdrh Vdbe *v; 24829bb575fdSdrh sqlite3 *db = pParse->db; 2483d24cc427Sdrh int iDb; 248475897234Sdrh 24858af73d41Sdrh if( db->mallocFailed ){ 24866f7adc8aSdrh goto exit_drop_table; 24876f7adc8aSdrh } 24888af73d41Sdrh assert( pParse->nErr==0 ); 2489a8858103Sdanielk1977 assert( pName->nSrc==1 ); 249075209969Sdrh if( sqlite3ReadSchema(pParse) ) goto exit_drop_table; 2491a7564663Sdrh if( noErr ) db->suppressErr++; 249241fb5cd1Sdan pTab = sqlite3LocateTableItem(pParse, isView, &pName->a[0]); 2493a7564663Sdrh if( noErr ) db->suppressErr--; 2494a8858103Sdanielk1977 2495a073384fSdrh if( pTab==0 ){ 249657966753Sdan if( noErr ) sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase); 2497a073384fSdrh goto exit_drop_table; 2498a073384fSdrh } 2499da184236Sdanielk1977 iDb = sqlite3SchemaToIndex(db, pTab->pSchema); 2500e22a334bSdrh assert( iDb>=0 && iDb<db->nDb ); 2501b5258c3dSdanielk1977 2502b5258c3dSdanielk1977 /* If pTab is a virtual table, call ViewGetColumnNames() to ensure 2503b5258c3dSdanielk1977 ** it is initialized. 2504b5258c3dSdanielk1977 */ 2505b5258c3dSdanielk1977 if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){ 2506b5258c3dSdanielk1977 goto exit_drop_table; 2507b5258c3dSdanielk1977 } 2508e5f9c644Sdrh #ifndef SQLITE_OMIT_AUTHORIZATION 2509e5f9c644Sdrh { 2510e5f9c644Sdrh int code; 2511da184236Sdanielk1977 const char *zTab = SCHEMA_TABLE(iDb); 2512da184236Sdanielk1977 const char *zDb = db->aDb[iDb].zName; 2513f1a381e7Sdanielk1977 const char *zArg2 = 0; 25144adee20fSdanielk1977 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){ 2515a8858103Sdanielk1977 goto exit_drop_table; 2516e22a334bSdrh } 2517e5f9c644Sdrh if( isView ){ 251853c0f748Sdanielk1977 if( !OMIT_TEMPDB && iDb==1 ){ 2519e5f9c644Sdrh code = SQLITE_DROP_TEMP_VIEW; 2520e5f9c644Sdrh }else{ 2521e5f9c644Sdrh code = SQLITE_DROP_VIEW; 2522e5f9c644Sdrh } 25234b2688abSdanielk1977 #ifndef SQLITE_OMIT_VIRTUALTABLE 2524f1a381e7Sdanielk1977 }else if( IsVirtual(pTab) ){ 2525f1a381e7Sdanielk1977 code = SQLITE_DROP_VTABLE; 2526595a523aSdanielk1977 zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName; 25274b2688abSdanielk1977 #endif 2528e5f9c644Sdrh }else{ 252953c0f748Sdanielk1977 if( !OMIT_TEMPDB && iDb==1 ){ 2530e5f9c644Sdrh code = SQLITE_DROP_TEMP_TABLE; 2531e5f9c644Sdrh }else{ 2532e5f9c644Sdrh code = SQLITE_DROP_TABLE; 2533e5f9c644Sdrh } 2534e5f9c644Sdrh } 2535f1a381e7Sdanielk1977 if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){ 2536a8858103Sdanielk1977 goto exit_drop_table; 2537e5f9c644Sdrh } 2538a8858103Sdanielk1977 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){ 2539a8858103Sdanielk1977 goto exit_drop_table; 254077ad4e41Sdrh } 2541e5f9c644Sdrh } 2542e5f9c644Sdrh #endif 254308ccfaa1Sdrh if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 254408ccfaa1Sdrh && sqlite3StrNICmp(pTab->zName, "sqlite_stat", 11)!=0 ){ 2545a8858103Sdanielk1977 sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName); 2546a8858103Sdanielk1977 goto exit_drop_table; 254775897234Sdrh } 2548576ec6b3Sdanielk1977 2549576ec6b3Sdanielk1977 #ifndef SQLITE_OMIT_VIEW 2550576ec6b3Sdanielk1977 /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used 2551576ec6b3Sdanielk1977 ** on a table. 2552576ec6b3Sdanielk1977 */ 2553a8858103Sdanielk1977 if( isView && pTab->pSelect==0 ){ 2554a8858103Sdanielk1977 sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName); 2555a8858103Sdanielk1977 goto exit_drop_table; 25564ff6dfa7Sdrh } 2557a8858103Sdanielk1977 if( !isView && pTab->pSelect ){ 2558a8858103Sdanielk1977 sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName); 2559a8858103Sdanielk1977 goto exit_drop_table; 25604ff6dfa7Sdrh } 2561576ec6b3Sdanielk1977 #endif 256275897234Sdrh 25631ccde15dSdrh /* Generate code to remove the table from the master table 25641ccde15dSdrh ** on disk. 25651ccde15dSdrh */ 25664adee20fSdanielk1977 v = sqlite3GetVdbe(pParse); 256775897234Sdrh if( v ){ 256877658e2fSdrh sqlite3BeginWriteOperation(pParse, 1, iDb); 2569a5ae4c33Sdrh sqlite3ClearStatTables(pParse, iDb, "tbl", pTab->zName); 2570e0bc4048Sdrh sqlite3FkDropTable(pParse, pName, pTab); 2571faacf17cSdrh sqlite3CodeDropTable(pParse, pTab, iDb, isView); 25724ff6dfa7Sdrh } 25732958a4e6Sdrh 2574a8858103Sdanielk1977 exit_drop_table: 2575633e6d57Sdrh sqlite3SrcListDelete(db, pName); 257675897234Sdrh } 257775897234Sdrh 257875897234Sdrh /* 2579c2eef3b3Sdrh ** This routine is called to create a new foreign key on the table 2580c2eef3b3Sdrh ** currently under construction. pFromCol determines which columns 2581c2eef3b3Sdrh ** in the current table point to the foreign key. If pFromCol==0 then 2582c2eef3b3Sdrh ** connect the key to the last column inserted. pTo is the name of 2583bd50a926Sdrh ** the table referred to (a.k.a the "parent" table). pToCol is a list 2584bd50a926Sdrh ** of tables in the parent pTo table. flags contains all 2585c2eef3b3Sdrh ** information about the conflict resolution algorithms specified 2586c2eef3b3Sdrh ** in the ON DELETE, ON UPDATE and ON INSERT clauses. 2587c2eef3b3Sdrh ** 2588c2eef3b3Sdrh ** An FKey structure is created and added to the table currently 2589e61922a6Sdrh ** under construction in the pParse->pNewTable field. 2590c2eef3b3Sdrh ** 2591c2eef3b3Sdrh ** The foreign key is set for IMMEDIATE processing. A subsequent call 25924adee20fSdanielk1977 ** to sqlite3DeferForeignKey() might change this to DEFERRED. 2593c2eef3b3Sdrh */ 25944adee20fSdanielk1977 void sqlite3CreateForeignKey( 2595c2eef3b3Sdrh Parse *pParse, /* Parsing context */ 25960202b29eSdanielk1977 ExprList *pFromCol, /* Columns in this table that point to other table */ 2597c2eef3b3Sdrh Token *pTo, /* Name of the other table */ 25980202b29eSdanielk1977 ExprList *pToCol, /* Columns in the other table */ 2599c2eef3b3Sdrh int flags /* Conflict resolution algorithms. */ 2600c2eef3b3Sdrh ){ 26011857693dSdanielk1977 sqlite3 *db = pParse->db; 2602b7f9164eSdrh #ifndef SQLITE_OMIT_FOREIGN_KEY 260340e016e4Sdrh FKey *pFKey = 0; 26041da40a38Sdan FKey *pNextTo; 2605c2eef3b3Sdrh Table *p = pParse->pNewTable; 2606c2eef3b3Sdrh int nByte; 2607c2eef3b3Sdrh int i; 2608c2eef3b3Sdrh int nCol; 2609c2eef3b3Sdrh char *z; 2610c2eef3b3Sdrh 2611c2eef3b3Sdrh assert( pTo!=0 ); 26128af73d41Sdrh if( p==0 || IN_DECLARE_VTAB ) goto fk_end; 2613c2eef3b3Sdrh if( pFromCol==0 ){ 2614c2eef3b3Sdrh int iCol = p->nCol-1; 2615d3001711Sdrh if( NEVER(iCol<0) ) goto fk_end; 26160202b29eSdanielk1977 if( pToCol && pToCol->nExpr!=1 ){ 26174adee20fSdanielk1977 sqlite3ErrorMsg(pParse, "foreign key on %s" 2618f7a9e1acSdrh " should reference only one column of table %T", 2619f7a9e1acSdrh p->aCol[iCol].zName, pTo); 2620c2eef3b3Sdrh goto fk_end; 2621c2eef3b3Sdrh } 2622c2eef3b3Sdrh nCol = 1; 26230202b29eSdanielk1977 }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){ 26244adee20fSdanielk1977 sqlite3ErrorMsg(pParse, 2625c2eef3b3Sdrh "number of columns in foreign key does not match the number of " 2626f7a9e1acSdrh "columns in the referenced table"); 2627c2eef3b3Sdrh goto fk_end; 2628c2eef3b3Sdrh }else{ 26290202b29eSdanielk1977 nCol = pFromCol->nExpr; 2630c2eef3b3Sdrh } 2631e61922a6Sdrh nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1; 2632c2eef3b3Sdrh if( pToCol ){ 26330202b29eSdanielk1977 for(i=0; i<pToCol->nExpr; i++){ 2634ea678832Sdrh nByte += sqlite3Strlen30(pToCol->a[i].zName) + 1; 2635c2eef3b3Sdrh } 2636c2eef3b3Sdrh } 2637633e6d57Sdrh pFKey = sqlite3DbMallocZero(db, nByte ); 263817435752Sdrh if( pFKey==0 ){ 263917435752Sdrh goto fk_end; 264017435752Sdrh } 2641c2eef3b3Sdrh pFKey->pFrom = p; 2642c2eef3b3Sdrh pFKey->pNextFrom = p->pFKey; 2643e61922a6Sdrh z = (char*)&pFKey->aCol[nCol]; 2644df68f6b7Sdrh pFKey->zTo = z; 2645c2eef3b3Sdrh memcpy(z, pTo->z, pTo->n); 2646c2eef3b3Sdrh z[pTo->n] = 0; 264770d9e9ccSdanielk1977 sqlite3Dequote(z); 2648c2eef3b3Sdrh z += pTo->n+1; 2649c2eef3b3Sdrh pFKey->nCol = nCol; 2650c2eef3b3Sdrh if( pFromCol==0 ){ 2651c2eef3b3Sdrh pFKey->aCol[0].iFrom = p->nCol-1; 2652c2eef3b3Sdrh }else{ 2653c2eef3b3Sdrh for(i=0; i<nCol; i++){ 2654c2eef3b3Sdrh int j; 2655c2eef3b3Sdrh for(j=0; j<p->nCol; j++){ 26564adee20fSdanielk1977 if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){ 2657c2eef3b3Sdrh pFKey->aCol[i].iFrom = j; 2658c2eef3b3Sdrh break; 2659c2eef3b3Sdrh } 2660c2eef3b3Sdrh } 2661c2eef3b3Sdrh if( j>=p->nCol ){ 26624adee20fSdanielk1977 sqlite3ErrorMsg(pParse, 2663f7a9e1acSdrh "unknown column \"%s\" in foreign key definition", 2664f7a9e1acSdrh pFromCol->a[i].zName); 2665c2eef3b3Sdrh goto fk_end; 2666c2eef3b3Sdrh } 2667c2eef3b3Sdrh } 2668c2eef3b3Sdrh } 2669c2eef3b3Sdrh if( pToCol ){ 2670c2eef3b3Sdrh for(i=0; i<nCol; i++){ 2671ea678832Sdrh int n = sqlite3Strlen30(pToCol->a[i].zName); 2672c2eef3b3Sdrh pFKey->aCol[i].zCol = z; 2673c2eef3b3Sdrh memcpy(z, pToCol->a[i].zName, n); 2674c2eef3b3Sdrh z[n] = 0; 2675c2eef3b3Sdrh z += n+1; 2676c2eef3b3Sdrh } 2677c2eef3b3Sdrh } 2678c2eef3b3Sdrh pFKey->isDeferred = 0; 26798099ce6fSdan pFKey->aAction[0] = (u8)(flags & 0xff); /* ON DELETE action */ 26808099ce6fSdan pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff); /* ON UPDATE action */ 2681c2eef3b3Sdrh 26822120608eSdrh assert( sqlite3SchemaMutexHeld(db, 0, p->pSchema) ); 26831da40a38Sdan pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash, 2684acbcb7e0Sdrh pFKey->zTo, (void *)pFKey 26851da40a38Sdan ); 2686f59c5cacSdan if( pNextTo==pFKey ){ 2687f59c5cacSdan db->mallocFailed = 1; 2688f59c5cacSdan goto fk_end; 2689f59c5cacSdan } 26901da40a38Sdan if( pNextTo ){ 26911da40a38Sdan assert( pNextTo->pPrevTo==0 ); 26921da40a38Sdan pFKey->pNextTo = pNextTo; 26931da40a38Sdan pNextTo->pPrevTo = pFKey; 26941da40a38Sdan } 26951da40a38Sdan 2696c2eef3b3Sdrh /* Link the foreign key to the table as the last step. 2697c2eef3b3Sdrh */ 2698c2eef3b3Sdrh p->pFKey = pFKey; 2699c2eef3b3Sdrh pFKey = 0; 2700c2eef3b3Sdrh 2701c2eef3b3Sdrh fk_end: 2702633e6d57Sdrh sqlite3DbFree(db, pFKey); 2703b7f9164eSdrh #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */ 2704633e6d57Sdrh sqlite3ExprListDelete(db, pFromCol); 2705633e6d57Sdrh sqlite3ExprListDelete(db, pToCol); 2706c2eef3b3Sdrh } 2707c2eef3b3Sdrh 2708c2eef3b3Sdrh /* 2709c2eef3b3Sdrh ** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED 2710c2eef3b3Sdrh ** clause is seen as part of a foreign key definition. The isDeferred 2711c2eef3b3Sdrh ** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE. 2712c2eef3b3Sdrh ** The behavior of the most recently created foreign key is adjusted 2713c2eef3b3Sdrh ** accordingly. 2714c2eef3b3Sdrh */ 27154adee20fSdanielk1977 void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){ 2716b7f9164eSdrh #ifndef SQLITE_OMIT_FOREIGN_KEY 2717c2eef3b3Sdrh Table *pTab; 2718c2eef3b3Sdrh FKey *pFKey; 2719c2eef3b3Sdrh if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return; 27204c429839Sdrh assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */ 27211bd10f8aSdrh pFKey->isDeferred = (u8)isDeferred; 2722b7f9164eSdrh #endif 2723c2eef3b3Sdrh } 2724c2eef3b3Sdrh 2725c2eef3b3Sdrh /* 2726063336a5Sdrh ** Generate code that will erase and refill index *pIdx. This is 2727063336a5Sdrh ** used to initialize a newly created index or to recompute the 2728063336a5Sdrh ** content of an index in response to a REINDEX command. 2729063336a5Sdrh ** 2730063336a5Sdrh ** if memRootPage is not negative, it means that the index is newly 27311db639ceSdrh ** created. The register specified by memRootPage contains the 2732063336a5Sdrh ** root page number of the index. If memRootPage is negative, then 2733063336a5Sdrh ** the index already exists and must be cleared before being refilled and 2734063336a5Sdrh ** the root page number of the index is taken from pIndex->tnum. 2735063336a5Sdrh */ 2736063336a5Sdrh static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){ 2737063336a5Sdrh Table *pTab = pIndex->pTable; /* The table that is indexed */ 27386ab3a2ecSdanielk1977 int iTab = pParse->nTab++; /* Btree cursor used for pTab */ 27396ab3a2ecSdanielk1977 int iIdx = pParse->nTab++; /* Btree cursor used for pIndex */ 2740b07028f7Sdrh int iSorter; /* Cursor opened by OpenSorter (if in use) */ 2741063336a5Sdrh int addr1; /* Address of top of loop */ 27425134d135Sdan int addr2; /* Address to jump to for next iteration */ 2743063336a5Sdrh int tnum; /* Root page of index */ 2744b2b9d3d7Sdrh int iPartIdxLabel; /* Jump to this label to skip a row */ 2745063336a5Sdrh Vdbe *v; /* Generate code into this virtual machine */ 2746b3bf556eSdanielk1977 KeyInfo *pKey; /* KeyInfo for index */ 274760ec914cSpeter.d.reid int regRecord; /* Register holding assembled index record */ 274817435752Sdrh sqlite3 *db = pParse->db; /* The database connection */ 274917435752Sdrh int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema); 2750063336a5Sdrh 27511d54df88Sdanielk1977 #ifndef SQLITE_OMIT_AUTHORIZATION 27521d54df88Sdanielk1977 if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0, 275317435752Sdrh db->aDb[iDb].zName ) ){ 27541d54df88Sdanielk1977 return; 27551d54df88Sdanielk1977 } 27561d54df88Sdanielk1977 #endif 27571d54df88Sdanielk1977 2758c00da105Sdanielk1977 /* Require a write-lock on the table to perform this operation */ 2759c00da105Sdanielk1977 sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName); 2760c00da105Sdanielk1977 2761063336a5Sdrh v = sqlite3GetVdbe(pParse); 2762063336a5Sdrh if( v==0 ) return; 2763063336a5Sdrh if( memRootPage>=0 ){ 27641db639ceSdrh tnum = memRootPage; 2765063336a5Sdrh }else{ 2766063336a5Sdrh tnum = pIndex->tnum; 2767063336a5Sdrh } 27682ec2fb22Sdrh pKey = sqlite3KeyInfoOfIndex(pParse, pIndex); 2769a20fde64Sdan 2770689ab897Sdan /* Open the sorter cursor if we are to use one. */ 2771689ab897Sdan iSorter = pParse->nTab++; 2772fad9f9a8Sdan sqlite3VdbeAddOp4(v, OP_SorterOpen, iSorter, 0, pIndex->nKeyCol, (char*) 27732ec2fb22Sdrh sqlite3KeyInfoRef(pKey), P4_KEYINFO); 2774a20fde64Sdan 2775a20fde64Sdan /* Open the table. Loop through all rows of the table, inserting index 2776a20fde64Sdan ** records into the sorter. */ 2777c00da105Sdanielk1977 sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead); 2778688852abSdrh addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0); VdbeCoverage(v); 27792d401ab8Sdrh regRecord = sqlite3GetTempReg(pParse); 2780689ab897Sdan 27811c2c0b77Sdrh sqlite3GenerateIndexKey(pParse,pIndex,iTab,regRecord,0,&iPartIdxLabel,0,0); 27825134d135Sdan sqlite3VdbeAddOp2(v, OP_SorterInsert, iSorter, regRecord); 278387744513Sdrh sqlite3ResolvePartIdxLabel(pParse, iPartIdxLabel); 2784688852abSdrh sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1); VdbeCoverage(v); 2785a20fde64Sdan sqlite3VdbeJumpHere(v, addr1); 27864415628aSdrh if( memRootPage<0 ) sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb); 27874415628aSdrh sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb, 27882ec2fb22Sdrh (char *)pKey, P4_KEYINFO); 27894415628aSdrh sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR|((memRootPage>=0)?OPFLAG_P2ISREG:0)); 27904415628aSdrh 2791688852abSdrh addr1 = sqlite3VdbeAddOp2(v, OP_SorterSort, iSorter, 0); VdbeCoverage(v); 27921153c7b2Sdrh assert( pKey!=0 || db->mallocFailed || pParse->nErr ); 27935f1d1d9cSdrh if( IsUniqueIndex(pIndex) && pKey!=0 ){ 27945134d135Sdan int j2 = sqlite3VdbeCurrentAddr(v) + 3; 27955134d135Sdan sqlite3VdbeAddOp2(v, OP_Goto, 0, j2); 27965134d135Sdan addr2 = sqlite3VdbeCurrentAddr(v); 27971153c7b2Sdrh sqlite3VdbeAddOp4Int(v, OP_SorterCompare, iSorter, j2, regRecord, 2798ac50232dSdrh pIndex->nKeyCol); VdbeCoverage(v); 2799f9c8ce3cSdrh sqlite3UniqueConstraint(pParse, OE_Abort, pIndex); 28005134d135Sdan }else{ 28015134d135Sdan addr2 = sqlite3VdbeCurrentAddr(v); 2802689ab897Sdan } 28036cf4a7dfSdrh sqlite3VdbeAddOp3(v, OP_SorterData, iSorter, regRecord, iIdx); 2804b18e60b3Sdan sqlite3VdbeAddOp3(v, OP_Last, iIdx, 0, -1); 2805b18e60b3Sdan sqlite3VdbeAddOp3(v, OP_IdxInsert, iIdx, regRecord, 0); 2806ca892a72Sdrh sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT); 28072d401ab8Sdrh sqlite3ReleaseTempReg(pParse, regRecord); 2808688852abSdrh sqlite3VdbeAddOp2(v, OP_SorterNext, iSorter, addr2); VdbeCoverage(v); 2809d654be80Sdrh sqlite3VdbeJumpHere(v, addr1); 2810a20fde64Sdan 281166a5167bSdrh sqlite3VdbeAddOp1(v, OP_Close, iTab); 281266a5167bSdrh sqlite3VdbeAddOp1(v, OP_Close, iIdx); 2813689ab897Sdan sqlite3VdbeAddOp1(v, OP_Close, iSorter); 2814063336a5Sdrh } 2815063336a5Sdrh 2816063336a5Sdrh /* 281777e57dfbSdrh ** Allocate heap space to hold an Index object with nCol columns. 281877e57dfbSdrh ** 281977e57dfbSdrh ** Increase the allocation size to provide an extra nExtra bytes 282077e57dfbSdrh ** of 8-byte aligned space after the Index object and return a 282177e57dfbSdrh ** pointer to this extra space in *ppExtra. 282277e57dfbSdrh */ 282377e57dfbSdrh Index *sqlite3AllocateIndexObject( 282477e57dfbSdrh sqlite3 *db, /* Database connection */ 2825bbbdc83bSdrh i16 nCol, /* Total number of columns in the index */ 282677e57dfbSdrh int nExtra, /* Number of bytes of extra space to alloc */ 282777e57dfbSdrh char **ppExtra /* Pointer to the "extra" space */ 282877e57dfbSdrh ){ 282977e57dfbSdrh Index *p; /* Allocated index object */ 283077e57dfbSdrh int nByte; /* Bytes of space for Index object + arrays */ 283177e57dfbSdrh 283277e57dfbSdrh nByte = ROUND8(sizeof(Index)) + /* Index structure */ 283377e57dfbSdrh ROUND8(sizeof(char*)*nCol) + /* Index.azColl */ 2834cfc9df76Sdan ROUND8(sizeof(LogEst)*(nCol+1) + /* Index.aiRowLogEst */ 2835bbbdc83bSdrh sizeof(i16)*nCol + /* Index.aiColumn */ 283677e57dfbSdrh sizeof(u8)*nCol); /* Index.aSortOrder */ 283777e57dfbSdrh p = sqlite3DbMallocZero(db, nByte + nExtra); 283877e57dfbSdrh if( p ){ 283977e57dfbSdrh char *pExtra = ((char*)p)+ROUND8(sizeof(Index)); 284077e57dfbSdrh p->azColl = (char**)pExtra; pExtra += ROUND8(sizeof(char*)*nCol); 2841cfc9df76Sdan p->aiRowLogEst = (LogEst*)pExtra; pExtra += sizeof(LogEst)*(nCol+1); 2842bbbdc83bSdrh p->aiColumn = (i16*)pExtra; pExtra += sizeof(i16)*nCol; 284377e57dfbSdrh p->aSortOrder = (u8*)pExtra; 284477e57dfbSdrh p->nColumn = nCol; 2845bbbdc83bSdrh p->nKeyCol = nCol - 1; 284677e57dfbSdrh *ppExtra = ((char*)p) + nByte; 284777e57dfbSdrh } 284877e57dfbSdrh return p; 284977e57dfbSdrh } 285077e57dfbSdrh 285177e57dfbSdrh /* 285223bf66d6Sdrh ** Create a new index for an SQL table. pName1.pName2 is the name of the index 285323bf66d6Sdrh ** and pTblList is the name of the table that is to be indexed. Both will 2854adbca9cfSdrh ** be NULL for a primary key or an index that is created to satisfy a 2855adbca9cfSdrh ** UNIQUE constraint. If pTable and pIndex are NULL, use pParse->pNewTable 2856382c0247Sdrh ** as the table to be indexed. pParse->pNewTable is a table that is 2857382c0247Sdrh ** currently being constructed by a CREATE TABLE statement. 285875897234Sdrh ** 2859382c0247Sdrh ** pList is a list of columns to be indexed. pList will be NULL if this 2860382c0247Sdrh ** is a primary key or unique-constraint on the most recent column added 2861382c0247Sdrh ** to the table currently under construction. 28621da40a38Sdan ** 28631da40a38Sdan ** If the index is created successfully, return a pointer to the new Index 28641da40a38Sdan ** structure. This is used by sqlite3AddPrimaryKey() to mark the index 286548dd1d8eSdrh ** as the tables primary key (Index.idxType==SQLITE_IDXTYPE_PRIMARYKEY) 286675897234Sdrh */ 28671da40a38Sdan Index *sqlite3CreateIndex( 286875897234Sdrh Parse *pParse, /* All information about this parse */ 2869cbb18d22Sdanielk1977 Token *pName1, /* First part of index name. May be NULL */ 2870cbb18d22Sdanielk1977 Token *pName2, /* Second part of index name. May be NULL */ 28710202b29eSdanielk1977 SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */ 28720202b29eSdanielk1977 ExprList *pList, /* A list of columns to be indexed */ 28739cfcf5d4Sdrh int onError, /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */ 28741c55ba09Sdrh Token *pStart, /* The CREATE token that begins this statement */ 28751fe0537eSdrh Expr *pPIWhere, /* WHERE clause for partial indices */ 28764d91a701Sdrh int sortOrder, /* Sort order of primary key when pList==NULL */ 28774d91a701Sdrh int ifNotExist /* Omit error if index already exists */ 287875897234Sdrh ){ 28791da40a38Sdan Index *pRet = 0; /* Pointer to return */ 2880cbb18d22Sdanielk1977 Table *pTab = 0; /* Table to be indexed */ 2881d8123366Sdanielk1977 Index *pIndex = 0; /* The index to be created */ 2882fdd6e85aSdrh char *zName = 0; /* Name of the index */ 2883fdd6e85aSdrh int nName; /* Number of characters in zName */ 2884beae3194Sdrh int i, j; 2885f26e09c8Sdrh DbFixer sFix; /* For assigning database names to pTable */ 2886fdd6e85aSdrh int sortOrderMask; /* 1 to honor DESC in index. 0 to ignore. */ 28879bb575fdSdrh sqlite3 *db = pParse->db; 2888fdd6e85aSdrh Db *pDb; /* The specific table containing the indexed database */ 2889cbb18d22Sdanielk1977 int iDb; /* Index of the database that is being written */ 2890cbb18d22Sdanielk1977 Token *pName = 0; /* Unqualified name of the index to create */ 2891fdd6e85aSdrh struct ExprList_item *pListItem; /* For looping over pList */ 2892c28c4e50Sdrh int nExtra = 0; /* Space allocated for zExtra[] */ 28934415628aSdrh int nExtraCol; /* Number of extra columns needed */ 289447b927d2Sdrh char *zExtra = 0; /* Extra space after the Index object */ 28954415628aSdrh Index *pPk = 0; /* PRIMARY KEY index for WITHOUT ROWID tables */ 2896cbb18d22Sdanielk1977 28977088d501Sdrh if( db->mallocFailed || IN_DECLARE_VTAB || pParse->nErr>0 ){ 2898d3001711Sdrh goto exit_create_index; 2899d3001711Sdrh } 2900d3001711Sdrh if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){ 2901e501b89aSdanielk1977 goto exit_create_index; 2902e501b89aSdanielk1977 } 2903daffd0e5Sdrh 290475897234Sdrh /* 290575897234Sdrh ** Find the table that is to be indexed. Return early if not found. 290675897234Sdrh */ 2907cbb18d22Sdanielk1977 if( pTblName!=0 ){ 2908cbb18d22Sdanielk1977 2909cbb18d22Sdanielk1977 /* Use the two-part index name to determine the database 2910ef2cb63eSdanielk1977 ** to search for the table. 'Fix' the table name to this db 2911ef2cb63eSdanielk1977 ** before looking up the table. 2912cbb18d22Sdanielk1977 */ 2913cbb18d22Sdanielk1977 assert( pName1 && pName2 ); 2914ef2cb63eSdanielk1977 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName); 2915cbb18d22Sdanielk1977 if( iDb<0 ) goto exit_create_index; 2916b07028f7Sdrh assert( pName && pName->z ); 2917cbb18d22Sdanielk1977 291853c0f748Sdanielk1977 #ifndef SQLITE_OMIT_TEMPDB 2919d5578433Smistachkin /* If the index name was unqualified, check if the table 2920fe910339Sdanielk1977 ** is a temp table. If so, set the database to 1. Do not do this 2921fe910339Sdanielk1977 ** if initialising a database schema. 2922cbb18d22Sdanielk1977 */ 2923fe910339Sdanielk1977 if( !db->init.busy ){ 2924ef2cb63eSdanielk1977 pTab = sqlite3SrcListLookup(pParse, pTblName); 2925d3001711Sdrh if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){ 2926ef2cb63eSdanielk1977 iDb = 1; 2927ef2cb63eSdanielk1977 } 2928fe910339Sdanielk1977 } 292953c0f748Sdanielk1977 #endif 2930ef2cb63eSdanielk1977 2931d100f691Sdrh sqlite3FixInit(&sFix, pParse, iDb, "index", pName); 2932d100f691Sdrh if( sqlite3FixSrcList(&sFix, pTblName) ){ 293385c23c61Sdrh /* Because the parser constructs pTblName from a single identifier, 293485c23c61Sdrh ** sqlite3FixSrcList can never fail. */ 293585c23c61Sdrh assert(0); 2936cbb18d22Sdanielk1977 } 293741fb5cd1Sdan pTab = sqlite3LocateTableItem(pParse, 0, &pTblName->a[0]); 2938c31c7c1cSdrh assert( db->mallocFailed==0 || pTab==0 ); 2939c31c7c1cSdrh if( pTab==0 ) goto exit_create_index; 2940989b116aSdrh if( iDb==1 && db->aDb[iDb].pSchema!=pTab->pSchema ){ 2941989b116aSdrh sqlite3ErrorMsg(pParse, 2942989b116aSdrh "cannot create a TEMP index on non-TEMP table \"%s\"", 2943989b116aSdrh pTab->zName); 2944989b116aSdrh goto exit_create_index; 2945989b116aSdrh } 29464415628aSdrh if( !HasRowid(pTab) ) pPk = sqlite3PrimaryKeyIndex(pTab); 294775897234Sdrh }else{ 2948e3c41372Sdrh assert( pName==0 ); 2949b07028f7Sdrh assert( pStart==0 ); 295075897234Sdrh pTab = pParse->pNewTable; 2951a6370df1Sdrh if( !pTab ) goto exit_create_index; 2952da184236Sdanielk1977 iDb = sqlite3SchemaToIndex(db, pTab->pSchema); 295375897234Sdrh } 2954fdd6e85aSdrh pDb = &db->aDb[iDb]; 2955cbb18d22Sdanielk1977 2956d3001711Sdrh assert( pTab!=0 ); 2957d3001711Sdrh assert( pParse->nErr==0 ); 29580388123fSdrh if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 29593a3a03f2Sdrh && db->init.busy==0 2960d4530979Sdrh #if SQLITE_USER_AUTHENTICATION 2961d4530979Sdrh && sqlite3UserAuthTable(pTab->zName)==0 2962d4530979Sdrh #endif 2963503a686eSdrh && sqlite3StrNICmp(&pTab->zName[7],"altertab_",9)!=0 ){ 29644adee20fSdanielk1977 sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName); 29650be9df07Sdrh goto exit_create_index; 29660be9df07Sdrh } 2967576ec6b3Sdanielk1977 #ifndef SQLITE_OMIT_VIEW 2968a76b5dfcSdrh if( pTab->pSelect ){ 29694adee20fSdanielk1977 sqlite3ErrorMsg(pParse, "views may not be indexed"); 2970a76b5dfcSdrh goto exit_create_index; 2971a76b5dfcSdrh } 2972576ec6b3Sdanielk1977 #endif 29735ee9d697Sdanielk1977 #ifndef SQLITE_OMIT_VIRTUALTABLE 29745ee9d697Sdanielk1977 if( IsVirtual(pTab) ){ 29755ee9d697Sdanielk1977 sqlite3ErrorMsg(pParse, "virtual tables may not be indexed"); 29765ee9d697Sdanielk1977 goto exit_create_index; 29775ee9d697Sdanielk1977 } 29785ee9d697Sdanielk1977 #endif 297975897234Sdrh 298075897234Sdrh /* 298175897234Sdrh ** Find the name of the index. Make sure there is not already another 2982f57b3399Sdrh ** index or table with the same name. 2983f57b3399Sdrh ** 2984f57b3399Sdrh ** Exception: If we are reading the names of permanent indices from the 2985f57b3399Sdrh ** sqlite_master table (because some other process changed the schema) and 2986f57b3399Sdrh ** one of the index names collides with the name of a temporary table or 2987d24cc427Sdrh ** index, then we will continue to process this index. 2988f57b3399Sdrh ** 2989f57b3399Sdrh ** If pName==0 it means that we are 2990adbca9cfSdrh ** dealing with a primary key or UNIQUE constraint. We have to invent our 2991adbca9cfSdrh ** own name. 299275897234Sdrh */ 2993d8123366Sdanielk1977 if( pName ){ 299417435752Sdrh zName = sqlite3NameFromToken(db, pName); 2995d8123366Sdanielk1977 if( zName==0 ) goto exit_create_index; 2996b07028f7Sdrh assert( pName->z!=0 ); 2997d8123366Sdanielk1977 if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){ 2998d8123366Sdanielk1977 goto exit_create_index; 2999d8123366Sdanielk1977 } 3000d8123366Sdanielk1977 if( !db->init.busy ){ 3001d45a0315Sdanielk1977 if( sqlite3FindTable(db, zName, 0)!=0 ){ 3002d45a0315Sdanielk1977 sqlite3ErrorMsg(pParse, "there is already a table named %s", zName); 3003d45a0315Sdanielk1977 goto exit_create_index; 3004d45a0315Sdanielk1977 } 3005d45a0315Sdanielk1977 } 3006fdd6e85aSdrh if( sqlite3FindIndex(db, zName, pDb->zName)!=0 ){ 30074d91a701Sdrh if( !ifNotExist ){ 30084adee20fSdanielk1977 sqlite3ErrorMsg(pParse, "index %s already exists", zName); 30097687c83dSdan }else{ 30107687c83dSdan assert( !db->init.busy ); 30117687c83dSdan sqlite3CodeVerifySchema(pParse, iDb); 30124d91a701Sdrh } 301375897234Sdrh goto exit_create_index; 301475897234Sdrh } 3015a21c6b6fSdanielk1977 }else{ 3016adbca9cfSdrh int n; 3017adbca9cfSdrh Index *pLoop; 3018adbca9cfSdrh for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){} 3019f089aa45Sdrh zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n); 3020a1644fd8Sdanielk1977 if( zName==0 ){ 3021a1644fd8Sdanielk1977 goto exit_create_index; 3022a1644fd8Sdanielk1977 } 3023e3c41372Sdrh } 302475897234Sdrh 3025e5f9c644Sdrh /* Check for authorization to create an index. 3026e5f9c644Sdrh */ 3027e5f9c644Sdrh #ifndef SQLITE_OMIT_AUTHORIZATION 3028e22a334bSdrh { 3029fdd6e85aSdrh const char *zDb = pDb->zName; 303053c0f748Sdanielk1977 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){ 3031e5f9c644Sdrh goto exit_create_index; 3032e5f9c644Sdrh } 3033e5f9c644Sdrh i = SQLITE_CREATE_INDEX; 303453c0f748Sdanielk1977 if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX; 30354adee20fSdanielk1977 if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){ 3036e5f9c644Sdrh goto exit_create_index; 3037e5f9c644Sdrh } 3038e22a334bSdrh } 3039e5f9c644Sdrh #endif 3040e5f9c644Sdrh 304175897234Sdrh /* If pList==0, it means this routine was called to make a primary 30421ccde15dSdrh ** key out of the last column added to the table under construction. 304375897234Sdrh ** So create a fake list to simulate this. 304475897234Sdrh */ 304575897234Sdrh if( pList==0 ){ 3046108aa00aSdrh Token prevCol; 3047108aa00aSdrh prevCol.z = pTab->aCol[pTab->nCol-1].zName; 3048108aa00aSdrh prevCol.n = sqlite3Strlen30(prevCol.z); 3049108aa00aSdrh pList = sqlite3ExprListAppend(pParse, 0, 3050108aa00aSdrh sqlite3ExprAlloc(db, TK_ID, &prevCol, 0)); 305175897234Sdrh if( pList==0 ) goto exit_create_index; 3052bc622bc0Sdrh assert( pList->nExpr==1 ); 3053bc622bc0Sdrh sqlite3ExprListSetSortOrder(pList, sortOrder); 3054108aa00aSdrh }else{ 3055108aa00aSdrh sqlite3ExprListCheckLength(pParse, pList, "index"); 305675897234Sdrh } 305775897234Sdrh 3058b3bf556eSdanielk1977 /* Figure out how many bytes of space are required to store explicitly 3059b3bf556eSdanielk1977 ** specified collation sequence names. 3060b3bf556eSdanielk1977 */ 3061b3bf556eSdanielk1977 for(i=0; i<pList->nExpr; i++){ 3062d3001711Sdrh Expr *pExpr = pList->a[i].pExpr; 3063108aa00aSdrh if( pExpr && pExpr->op==TK_COLLATE ){ 3064911ce418Sdan nExtra += (1 + sqlite3Strlen30(pExpr->u.zToken)); 3065b3bf556eSdanielk1977 } 3066d3001711Sdrh } 3067b3bf556eSdanielk1977 306875897234Sdrh /* 306975897234Sdrh ** Allocate the index structure. 307075897234Sdrh */ 3071ea678832Sdrh nName = sqlite3Strlen30(zName); 30724415628aSdrh nExtraCol = pPk ? pPk->nKeyCol : 1; 30734415628aSdrh pIndex = sqlite3AllocateIndexObject(db, pList->nExpr + nExtraCol, 307477e57dfbSdrh nName + nExtra + 1, &zExtra); 307517435752Sdrh if( db->mallocFailed ){ 307617435752Sdrh goto exit_create_index; 307717435752Sdrh } 3078cfc9df76Sdan assert( EIGHT_BYTE_ALIGNMENT(pIndex->aiRowLogEst) ); 3079e09b84c5Sdrh assert( EIGHT_BYTE_ALIGNMENT(pIndex->azColl) ); 308077e57dfbSdrh pIndex->zName = zExtra; 308177e57dfbSdrh zExtra += nName + 1; 30825bb3eb9bSdrh memcpy(pIndex->zName, zName, nName+1); 308375897234Sdrh pIndex->pTable = pTab; 30841bd10f8aSdrh pIndex->onError = (u8)onError; 30859eade087Sdrh pIndex->uniqNotNull = onError!=OE_None; 308648dd1d8eSdrh pIndex->idxType = pName ? SQLITE_IDXTYPE_APPDEF : SQLITE_IDXTYPE_UNIQUE; 3087da184236Sdanielk1977 pIndex->pSchema = db->aDb[iDb].pSchema; 308872ffd091Sdrh pIndex->nKeyCol = pList->nExpr; 30893780be11Sdrh if( pPIWhere ){ 30903780be11Sdrh sqlite3ResolveSelfReference(pParse, pTab, NC_PartIdx, pPIWhere, 0); 30911fe0537eSdrh pIndex->pPartIdxWhere = pPIWhere; 30921fe0537eSdrh pPIWhere = 0; 30933780be11Sdrh } 30942120608eSdrh assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); 309575897234Sdrh 3096fdd6e85aSdrh /* Check to see if we should honor DESC requests on index columns 3097fdd6e85aSdrh */ 3098da184236Sdanielk1977 if( pDb->pSchema->file_format>=4 ){ 3099fdd6e85aSdrh sortOrderMask = -1; /* Honor DESC */ 3100fdd6e85aSdrh }else{ 3101fdd6e85aSdrh sortOrderMask = 0; /* Ignore DESC */ 3102fdd6e85aSdrh } 3103fdd6e85aSdrh 31041ccde15dSdrh /* Scan the names of the columns of the table to be indexed and 31051ccde15dSdrh ** load the column indices into the Index structure. Report an error 31061ccde15dSdrh ** if any column is not found. 3107d3001711Sdrh ** 3108d3001711Sdrh ** TODO: Add a test to make sure that the same column is not named 3109d3001711Sdrh ** more than once within the same index. Only the first instance of 3110d3001711Sdrh ** the column will ever be used by the optimizer. Note that using the 3111d3001711Sdrh ** same column more than once cannot be an error because that would 3112d3001711Sdrh ** break backwards compatibility - it needs to be a warning. 311375897234Sdrh */ 3114fdd6e85aSdrh for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){ 3115108aa00aSdrh Expr *pCExpr; 311685eeb692Sdrh int requestedSortOrder; 3117a34001c9Sdrh char *zColl; /* Collation sequence name */ 3118b3bf556eSdanielk1977 3119*a514b8ebSdrh sqlite3ResolveSelfReference(pParse, pTab, NC_IdxExpr, pListItem->pExpr, 0); 3120*a514b8ebSdrh if( pParse->nErr ) goto exit_create_index; 3121108aa00aSdrh pCExpr = sqlite3ExprSkipCollate(pListItem->pExpr); 3122*a514b8ebSdrh if( pCExpr->op!=TK_COLUMN ){ 3123108aa00aSdrh sqlite3ErrorMsg(pParse, "indexes on expressions not yet supported"); 3124108aa00aSdrh continue; 3125108aa00aSdrh } 3126*a514b8ebSdrh j = pCExpr->iColumn; 3127bf20a35dSdrh assert( j<=0x7fff ); 3128*a514b8ebSdrh if( j<0 ) j = pTab->iPKey; 3129bbbdc83bSdrh pIndex->aiColumn[i] = (i16)j; 3130*a514b8ebSdrh zColl = 0; 3131108aa00aSdrh if( pListItem->pExpr->op==TK_COLLATE ){ 3132d3001711Sdrh int nColl; 3133911ce418Sdan zColl = pListItem->pExpr->u.zToken; 3134d3001711Sdrh nColl = sqlite3Strlen30(zColl) + 1; 3135d3001711Sdrh assert( nExtra>=nColl ); 3136d3001711Sdrh memcpy(zExtra, zColl, nColl); 3137b3bf556eSdanielk1977 zColl = zExtra; 3138d3001711Sdrh zExtra += nColl; 3139d3001711Sdrh nExtra -= nColl; 3140*a514b8ebSdrh }else if( j>=0 ){ 3141b3bf556eSdanielk1977 zColl = pTab->aCol[j].zColl; 3142b3bf556eSdanielk1977 } 3143*a514b8ebSdrh if( !zColl ) zColl = "BINARY"; 3144b7f24de2Sdrh if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){ 31457cedc8d4Sdanielk1977 goto exit_create_index; 31467cedc8d4Sdanielk1977 } 3147b3bf556eSdanielk1977 pIndex->azColl[i] = zColl; 3148d946db00Sdrh requestedSortOrder = pListItem->sortOrder & sortOrderMask; 31491bd10f8aSdrh pIndex->aSortOrder[i] = (u8)requestedSortOrder; 31507699d1c4Sdrh if( pTab->aCol[j].notNull==0 ) pIndex->uniqNotNull = 0; 31510202b29eSdanielk1977 } 31524415628aSdrh if( pPk ){ 31537913e41fSdrh for(j=0; j<pPk->nKeyCol; j++){ 31547913e41fSdrh int x = pPk->aiColumn[j]; 31557913e41fSdrh if( hasColumn(pIndex->aiColumn, pIndex->nKeyCol, x) ){ 31567913e41fSdrh pIndex->nColumn--; 31577913e41fSdrh }else{ 31587913e41fSdrh pIndex->aiColumn[i] = x; 31594415628aSdrh pIndex->azColl[i] = pPk->azColl[j]; 31604415628aSdrh pIndex->aSortOrder[i] = pPk->aSortOrder[j]; 31617913e41fSdrh i++; 31624415628aSdrh } 31637913e41fSdrh } 31647913e41fSdrh assert( i==pIndex->nColumn ); 31654415628aSdrh }else{ 3166bbbdc83bSdrh pIndex->aiColumn[i] = -1; 3167bbbdc83bSdrh pIndex->azColl[i] = "BINARY"; 31684415628aSdrh } 316951147baaSdrh sqlite3DefaultRowEst(pIndex); 3170e13e9f54Sdrh if( pParse->pNewTable==0 ) estimateIndexWidth(pIndex); 317175897234Sdrh 3172d8123366Sdanielk1977 if( pTab==pParse->pNewTable ){ 3173d8123366Sdanielk1977 /* This routine has been called to create an automatic index as a 3174d8123366Sdanielk1977 ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or 3175d8123366Sdanielk1977 ** a PRIMARY KEY or UNIQUE clause following the column definitions. 3176d8123366Sdanielk1977 ** i.e. one of: 3177d8123366Sdanielk1977 ** 3178d8123366Sdanielk1977 ** CREATE TABLE t(x PRIMARY KEY, y); 3179d8123366Sdanielk1977 ** CREATE TABLE t(x, y, UNIQUE(x, y)); 3180d8123366Sdanielk1977 ** 3181d8123366Sdanielk1977 ** Either way, check to see if the table already has such an index. If 3182d8123366Sdanielk1977 ** so, don't bother creating this one. This only applies to 3183d8123366Sdanielk1977 ** automatically created indices. Users can do as they wish with 3184d8123366Sdanielk1977 ** explicit indices. 3185d3001711Sdrh ** 3186d3001711Sdrh ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent 3187d3001711Sdrh ** (and thus suppressing the second one) even if they have different 3188d3001711Sdrh ** sort orders. 3189d3001711Sdrh ** 3190d3001711Sdrh ** If there are different collating sequences or if the columns of 3191d3001711Sdrh ** the constraint occur in different orders, then the constraints are 3192d3001711Sdrh ** considered distinct and both result in separate indices. 3193d8123366Sdanielk1977 */ 3194d8123366Sdanielk1977 Index *pIdx; 3195d8123366Sdanielk1977 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ 3196d8123366Sdanielk1977 int k; 31975f1d1d9cSdrh assert( IsUniqueIndex(pIdx) ); 319848dd1d8eSdrh assert( pIdx->idxType!=SQLITE_IDXTYPE_APPDEF ); 31995f1d1d9cSdrh assert( IsUniqueIndex(pIndex) ); 3200d8123366Sdanielk1977 3201bbbdc83bSdrh if( pIdx->nKeyCol!=pIndex->nKeyCol ) continue; 3202bbbdc83bSdrh for(k=0; k<pIdx->nKeyCol; k++){ 3203d3001711Sdrh const char *z1; 3204d3001711Sdrh const char *z2; 3205d8123366Sdanielk1977 if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break; 3206d3001711Sdrh z1 = pIdx->azColl[k]; 3207d3001711Sdrh z2 = pIndex->azColl[k]; 3208b3bf556eSdanielk1977 if( z1!=z2 && sqlite3StrICmp(z1, z2) ) break; 3209d8123366Sdanielk1977 } 3210bbbdc83bSdrh if( k==pIdx->nKeyCol ){ 3211f736b771Sdanielk1977 if( pIdx->onError!=pIndex->onError ){ 3212f736b771Sdanielk1977 /* This constraint creates the same index as a previous 3213f736b771Sdanielk1977 ** constraint specified somewhere in the CREATE TABLE statement. 3214f736b771Sdanielk1977 ** However the ON CONFLICT clauses are different. If both this 3215f736b771Sdanielk1977 ** constraint and the previous equivalent constraint have explicit 3216f736b771Sdanielk1977 ** ON CONFLICT clauses this is an error. Otherwise, use the 321748864df9Smistachkin ** explicitly specified behavior for the index. 3218d8123366Sdanielk1977 */ 3219f736b771Sdanielk1977 if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){ 3220f736b771Sdanielk1977 sqlite3ErrorMsg(pParse, 3221f736b771Sdanielk1977 "conflicting ON CONFLICT clauses specified", 0); 3222f736b771Sdanielk1977 } 3223f736b771Sdanielk1977 if( pIdx->onError==OE_Default ){ 3224f736b771Sdanielk1977 pIdx->onError = pIndex->onError; 3225f736b771Sdanielk1977 } 3226f736b771Sdanielk1977 } 3227f0636850Sdrh pRet = pIdx; 3228d8123366Sdanielk1977 goto exit_create_index; 3229d8123366Sdanielk1977 } 3230d8123366Sdanielk1977 } 3231d8123366Sdanielk1977 } 3232d8123366Sdanielk1977 323375897234Sdrh /* Link the new Index structure to its table and to the other 3234adbca9cfSdrh ** in-memory database structures. 323575897234Sdrh */ 3236234c39dfSdrh if( db->init.busy ){ 32376d4abfbeSdrh Index *p; 32382120608eSdrh assert( sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) ); 3239da184236Sdanielk1977 p = sqlite3HashInsert(&pIndex->pSchema->idxHash, 3240acbcb7e0Sdrh pIndex->zName, pIndex); 32416d4abfbeSdrh if( p ){ 32426d4abfbeSdrh assert( p==pIndex ); /* Malloc must have failed */ 324317435752Sdrh db->mallocFailed = 1; 32446d4abfbeSdrh goto exit_create_index; 32456d4abfbeSdrh } 32465e00f6c7Sdrh db->flags |= SQLITE_InternChanges; 3247234c39dfSdrh if( pTblName!=0 ){ 32481d85d931Sdrh pIndex->tnum = db->init.newTnum; 3249d78eeee1Sdrh } 3250234c39dfSdrh } 3251d78eeee1Sdrh 32525838340bSdrh /* If this is the initial CREATE INDEX statement (or CREATE TABLE if the 32535838340bSdrh ** index is an implied index for a UNIQUE or PRIMARY KEY constraint) then 32545838340bSdrh ** emit code to allocate the index rootpage on disk and make an entry for 32555838340bSdrh ** the index in the sqlite_master table and populate the index with 32565838340bSdrh ** content. But, do not do this if we are simply reading the sqlite_master 32575838340bSdrh ** table to parse the schema, or if this index is the PRIMARY KEY index 32585838340bSdrh ** of a WITHOUT ROWID table. 325975897234Sdrh ** 32605838340bSdrh ** If pTblName==0 it means this index is generated as an implied PRIMARY KEY 32615838340bSdrh ** or UNIQUE index in a CREATE TABLE statement. Since the table 3262382c0247Sdrh ** has just been created, it contains no data and the index initialization 3263382c0247Sdrh ** step can be skipped. 326475897234Sdrh */ 32655838340bSdrh else if( pParse->nErr==0 && (HasRowid(pTab) || pTblName!=0) ){ 3266adbca9cfSdrh Vdbe *v; 3267063336a5Sdrh char *zStmt; 32680a07c107Sdrh int iMem = ++pParse->nMem; 326975897234Sdrh 32704adee20fSdanielk1977 v = sqlite3GetVdbe(pParse); 327175897234Sdrh if( v==0 ) goto exit_create_index; 3272063336a5Sdrh 3273aee128dcSdrh sqlite3BeginWriteOperation(pParse, 1, iDb); 3274c5b73585Sdan 3275c5b73585Sdan /* Create the rootpage for the index using CreateIndex. But before 3276c5b73585Sdan ** doing so, code a Noop instruction and store its address in 3277c5b73585Sdan ** Index.tnum. This is required in case this index is actually a 3278c5b73585Sdan ** PRIMARY KEY and the table is actually a WITHOUT ROWID table. In 3279c5b73585Sdan ** that case the convertToWithoutRowidTable() routine will replace 3280c5b73585Sdan ** the Noop with a Goto to jump over the VDBE code generated below. */ 3281c5b73585Sdan pIndex->tnum = sqlite3VdbeAddOp0(v, OP_Noop); 3282b7654111Sdrh sqlite3VdbeAddOp2(v, OP_CreateIndex, iDb, iMem); 3283063336a5Sdrh 3284063336a5Sdrh /* Gather the complete text of the CREATE INDEX statement into 3285063336a5Sdrh ** the zStmt variable 3286063336a5Sdrh */ 3287d3001711Sdrh if( pStart ){ 328877dfd5bbSdrh int n = (int)(pParse->sLastToken.z - pName->z) + pParse->sLastToken.n; 32898a9789b6Sdrh if( pName->z[n-1]==';' ) n--; 3290063336a5Sdrh /* A named index with an explicit CREATE INDEX statement */ 32911e536953Sdanielk1977 zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s", 32928a9789b6Sdrh onError==OE_None ? "" : " UNIQUE", n, pName->z); 32930202b29eSdanielk1977 }else{ 3294063336a5Sdrh /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */ 3295e497f005Sdrh /* zStmt = sqlite3MPrintf(""); */ 3296e497f005Sdrh zStmt = 0; 32970202b29eSdanielk1977 } 3298063336a5Sdrh 3299063336a5Sdrh /* Add an entry in sqlite_master for this index 3300063336a5Sdrh */ 3301063336a5Sdrh sqlite3NestedParse(pParse, 3302b7654111Sdrh "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);", 3303063336a5Sdrh db->aDb[iDb].zName, SCHEMA_TABLE(iDb), 3304063336a5Sdrh pIndex->zName, 3305063336a5Sdrh pTab->zName, 3306b7654111Sdrh iMem, 3307063336a5Sdrh zStmt 3308063336a5Sdrh ); 3309633e6d57Sdrh sqlite3DbFree(db, zStmt); 3310063336a5Sdrh 3311a21c6b6fSdanielk1977 /* Fill the index with data and reparse the schema. Code an OP_Expire 3312a21c6b6fSdanielk1977 ** to invalidate all pre-compiled statements. 3313063336a5Sdrh */ 3314cbb18d22Sdanielk1977 if( pTblName ){ 3315063336a5Sdrh sqlite3RefillIndex(pParse, pIndex, iMem); 33169cbf3425Sdrh sqlite3ChangeCookie(pParse, iDb); 33175d9c9da6Sdrh sqlite3VdbeAddParseSchemaOp(v, iDb, 33185d9c9da6Sdrh sqlite3MPrintf(db, "name='%q' AND type='index'", pIndex->zName)); 331966a5167bSdrh sqlite3VdbeAddOp1(v, OP_Expire, 0); 332075897234Sdrh } 3321c5b73585Sdan 3322c5b73585Sdan sqlite3VdbeJumpHere(v, pIndex->tnum); 332375897234Sdrh } 332475897234Sdrh 3325d8123366Sdanielk1977 /* When adding an index to the list of indices for a table, make 3326d8123366Sdanielk1977 ** sure all indices labeled OE_Replace come after all those labeled 3327d3001711Sdrh ** OE_Ignore. This is necessary for the correct constraint check 3328d3001711Sdrh ** processing (in sqlite3GenerateConstraintChecks()) as part of 3329d3001711Sdrh ** UPDATE and INSERT statements. 3330d8123366Sdanielk1977 */ 3331234c39dfSdrh if( db->init.busy || pTblName==0 ){ 3332d8123366Sdanielk1977 if( onError!=OE_Replace || pTab->pIndex==0 3333d8123366Sdanielk1977 || pTab->pIndex->onError==OE_Replace){ 3334d8123366Sdanielk1977 pIndex->pNext = pTab->pIndex; 3335d8123366Sdanielk1977 pTab->pIndex = pIndex; 3336d8123366Sdanielk1977 }else{ 3337d8123366Sdanielk1977 Index *pOther = pTab->pIndex; 3338d8123366Sdanielk1977 while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){ 3339d8123366Sdanielk1977 pOther = pOther->pNext; 3340d8123366Sdanielk1977 } 3341d8123366Sdanielk1977 pIndex->pNext = pOther->pNext; 3342d8123366Sdanielk1977 pOther->pNext = pIndex; 3343d8123366Sdanielk1977 } 33441da40a38Sdan pRet = pIndex; 3345d8123366Sdanielk1977 pIndex = 0; 3346234c39dfSdrh } 3347d8123366Sdanielk1977 334875897234Sdrh /* Clean up before exiting */ 334975897234Sdrh exit_create_index: 33501fe0537eSdrh if( pIndex ) freeIndex(db, pIndex); 33511fe0537eSdrh sqlite3ExprDelete(db, pPIWhere); 3352633e6d57Sdrh sqlite3ExprListDelete(db, pList); 3353633e6d57Sdrh sqlite3SrcListDelete(db, pTblName); 3354633e6d57Sdrh sqlite3DbFree(db, zName); 33551da40a38Sdan return pRet; 335675897234Sdrh } 335775897234Sdrh 335875897234Sdrh /* 335951147baaSdrh ** Fill the Index.aiRowEst[] array with default information - information 336091124b35Sdrh ** to be used when we have not run the ANALYZE command. 336128c4cf42Sdrh ** 336260ec914cSpeter.d.reid ** aiRowEst[0] is supposed to contain the number of elements in the index. 336328c4cf42Sdrh ** Since we do not know, guess 1 million. aiRowEst[1] is an estimate of the 336428c4cf42Sdrh ** number of rows in the table that match any particular value of the 336528c4cf42Sdrh ** first column of the index. aiRowEst[2] is an estimate of the number 3366cfc9df76Sdan ** of rows that match any particular combination of the first 2 columns 336728c4cf42Sdrh ** of the index. And so forth. It must always be the case that 336828c4cf42Sdrh * 336928c4cf42Sdrh ** aiRowEst[N]<=aiRowEst[N-1] 337028c4cf42Sdrh ** aiRowEst[N]>=1 337128c4cf42Sdrh ** 337228c4cf42Sdrh ** Apart from that, we have little to go on besides intuition as to 337328c4cf42Sdrh ** how aiRowEst[] should be initialized. The numbers generated here 337428c4cf42Sdrh ** are based on typical values found in actual indices. 337551147baaSdrh */ 337651147baaSdrh void sqlite3DefaultRowEst(Index *pIdx){ 3377264d2b97Sdan /* 10, 9, 8, 7, 6 */ 3378264d2b97Sdan LogEst aVal[] = { 33, 32, 30, 28, 26 }; 3379cfc9df76Sdan LogEst *a = pIdx->aiRowLogEst; 3380cfc9df76Sdan int nCopy = MIN(ArraySize(aVal), pIdx->nKeyCol); 338151147baaSdrh int i; 3382cfc9df76Sdan 3383264d2b97Sdan /* Set the first entry (number of rows in the index) to the estimated 3384264d2b97Sdan ** number of rows in the table. Or 10, if the estimated number of rows 3385264d2b97Sdan ** in the table is less than that. */ 3386cfc9df76Sdan a[0] = pIdx->pTable->nRowLogEst; 3387264d2b97Sdan if( a[0]<33 ) a[0] = 33; assert( 33==sqlite3LogEst(10) ); 3388264d2b97Sdan 3389264d2b97Sdan /* Estimate that a[1] is 10, a[2] is 9, a[3] is 8, a[4] is 7, a[5] is 3390264d2b97Sdan ** 6 and each subsequent value (if any) is 5. */ 3391cfc9df76Sdan memcpy(&a[1], aVal, nCopy*sizeof(LogEst)); 3392264d2b97Sdan for(i=nCopy+1; i<=pIdx->nKeyCol; i++){ 3393264d2b97Sdan a[i] = 23; assert( 23==sqlite3LogEst(5) ); 339428c4cf42Sdrh } 3395264d2b97Sdan 3396264d2b97Sdan assert( 0==sqlite3LogEst(1) ); 33975f1d1d9cSdrh if( IsUniqueIndex(pIdx) ) a[pIdx->nKeyCol] = 0; 339851147baaSdrh } 339951147baaSdrh 340051147baaSdrh /* 340174e24cd0Sdrh ** This routine will drop an existing named index. This routine 340274e24cd0Sdrh ** implements the DROP INDEX statement. 340375897234Sdrh */ 34044d91a701Sdrh void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){ 340575897234Sdrh Index *pIndex; 340675897234Sdrh Vdbe *v; 34079bb575fdSdrh sqlite3 *db = pParse->db; 3408da184236Sdanielk1977 int iDb; 340975897234Sdrh 34108af73d41Sdrh assert( pParse->nErr==0 ); /* Never called with prior errors */ 34118af73d41Sdrh if( db->mallocFailed ){ 3412d5d56523Sdanielk1977 goto exit_drop_index; 3413d5d56523Sdanielk1977 } 3414d24cc427Sdrh assert( pName->nSrc==1 ); 3415d5d56523Sdanielk1977 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){ 3416d5d56523Sdanielk1977 goto exit_drop_index; 3417d5d56523Sdanielk1977 } 34184adee20fSdanielk1977 pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase); 341975897234Sdrh if( pIndex==0 ){ 34204d91a701Sdrh if( !ifExists ){ 34214adee20fSdanielk1977 sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0); 342257966753Sdan }else{ 342357966753Sdan sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase); 34244d91a701Sdrh } 3425a6ecd338Sdrh pParse->checkSchema = 1; 3426d24cc427Sdrh goto exit_drop_index; 342775897234Sdrh } 342848dd1d8eSdrh if( pIndex->idxType!=SQLITE_IDXTYPE_APPDEF ){ 34294adee20fSdanielk1977 sqlite3ErrorMsg(pParse, "index associated with UNIQUE " 3430485b39b4Sdrh "or PRIMARY KEY constraint cannot be dropped", 0); 3431d24cc427Sdrh goto exit_drop_index; 3432d24cc427Sdrh } 3433da184236Sdanielk1977 iDb = sqlite3SchemaToIndex(db, pIndex->pSchema); 3434e5f9c644Sdrh #ifndef SQLITE_OMIT_AUTHORIZATION 3435e5f9c644Sdrh { 3436e5f9c644Sdrh int code = SQLITE_DROP_INDEX; 3437e5f9c644Sdrh Table *pTab = pIndex->pTable; 3438da184236Sdanielk1977 const char *zDb = db->aDb[iDb].zName; 3439da184236Sdanielk1977 const char *zTab = SCHEMA_TABLE(iDb); 34404adee20fSdanielk1977 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){ 3441d24cc427Sdrh goto exit_drop_index; 3442ed6c8671Sdrh } 3443da184236Sdanielk1977 if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX; 34444adee20fSdanielk1977 if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){ 3445d24cc427Sdrh goto exit_drop_index; 3446e5f9c644Sdrh } 3447e5f9c644Sdrh } 3448e5f9c644Sdrh #endif 344975897234Sdrh 345075897234Sdrh /* Generate code to remove the index and from the master table */ 34514adee20fSdanielk1977 v = sqlite3GetVdbe(pParse); 345275897234Sdrh if( v ){ 345377658e2fSdrh sqlite3BeginWriteOperation(pParse, 1, iDb); 3454b17131a0Sdrh sqlite3NestedParse(pParse, 345539f1bcb1Sdan "DELETE FROM %Q.%s WHERE name=%Q AND type='index'", 3456a5ae4c33Sdrh db->aDb[iDb].zName, SCHEMA_TABLE(iDb), pIndex->zName 3457b17131a0Sdrh ); 3458a5ae4c33Sdrh sqlite3ClearStatTables(pParse, iDb, "idx", pIndex->zName); 34599cbf3425Sdrh sqlite3ChangeCookie(pParse, iDb); 3460b17131a0Sdrh destroyRootPage(pParse, pIndex->tnum, iDb); 346166a5167bSdrh sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0); 346275897234Sdrh } 346375897234Sdrh 3464d24cc427Sdrh exit_drop_index: 3465633e6d57Sdrh sqlite3SrcListDelete(db, pName); 346675897234Sdrh } 346775897234Sdrh 346875897234Sdrh /* 3469cf643729Sdrh ** pArray is a pointer to an array of objects. Each object in the 34709ace112cSdan ** array is szEntry bytes in size. This routine uses sqlite3DbRealloc() 34719ace112cSdan ** to extend the array so that there is space for a new object at the end. 347213449892Sdrh ** 34739ace112cSdan ** When this function is called, *pnEntry contains the current size of 34749ace112cSdan ** the array (in entries - so the allocation is ((*pnEntry) * szEntry) bytes 34759ace112cSdan ** in total). 347613449892Sdrh ** 34779ace112cSdan ** If the realloc() is successful (i.e. if no OOM condition occurs), the 34789ace112cSdan ** space allocated for the new object is zeroed, *pnEntry updated to 34799ace112cSdan ** reflect the new size of the array and a pointer to the new allocation 34809ace112cSdan ** returned. *pIdx is set to the index of the new array entry in this case. 348113449892Sdrh ** 34829ace112cSdan ** Otherwise, if the realloc() fails, *pIdx is set to -1, *pnEntry remains 34839ace112cSdan ** unchanged and a copy of pArray returned. 348413449892Sdrh */ 3485cf643729Sdrh void *sqlite3ArrayAllocate( 348617435752Sdrh sqlite3 *db, /* Connection to notify of malloc failures */ 3487cf643729Sdrh void *pArray, /* Array of objects. Might be reallocated */ 3488cf643729Sdrh int szEntry, /* Size of each object in the array */ 3489cf643729Sdrh int *pnEntry, /* Number of objects currently in use */ 3490cf643729Sdrh int *pIdx /* Write the index of a new slot here */ 3491cf643729Sdrh ){ 3492cf643729Sdrh char *z; 34936c535158Sdrh int n = *pnEntry; 34946c535158Sdrh if( (n & (n-1))==0 ){ 34956c535158Sdrh int sz = (n==0) ? 1 : 2*n; 34966c535158Sdrh void *pNew = sqlite3DbRealloc(db, pArray, sz*szEntry); 349713449892Sdrh if( pNew==0 ){ 3498cf643729Sdrh *pIdx = -1; 3499cf643729Sdrh return pArray; 350013449892Sdrh } 3501cf643729Sdrh pArray = pNew; 350213449892Sdrh } 3503cf643729Sdrh z = (char*)pArray; 35046c535158Sdrh memset(&z[n * szEntry], 0, szEntry); 35056c535158Sdrh *pIdx = n; 3506cf643729Sdrh ++*pnEntry; 3507cf643729Sdrh return pArray; 350813449892Sdrh } 350913449892Sdrh 351013449892Sdrh /* 351175897234Sdrh ** Append a new element to the given IdList. Create a new IdList if 351275897234Sdrh ** need be. 3513daffd0e5Sdrh ** 3514daffd0e5Sdrh ** A new IdList is returned, or NULL if malloc() fails. 351575897234Sdrh */ 351617435752Sdrh IdList *sqlite3IdListAppend(sqlite3 *db, IdList *pList, Token *pToken){ 351713449892Sdrh int i; 351875897234Sdrh if( pList==0 ){ 351917435752Sdrh pList = sqlite3DbMallocZero(db, sizeof(IdList) ); 352075897234Sdrh if( pList==0 ) return 0; 352175897234Sdrh } 3522cf643729Sdrh pList->a = sqlite3ArrayAllocate( 352317435752Sdrh db, 3524cf643729Sdrh pList->a, 3525cf643729Sdrh sizeof(pList->a[0]), 3526cf643729Sdrh &pList->nId, 3527cf643729Sdrh &i 3528cf643729Sdrh ); 352913449892Sdrh if( i<0 ){ 3530633e6d57Sdrh sqlite3IdListDelete(db, pList); 3531daffd0e5Sdrh return 0; 353275897234Sdrh } 353317435752Sdrh pList->a[i].zName = sqlite3NameFromToken(db, pToken); 353475897234Sdrh return pList; 353575897234Sdrh } 353675897234Sdrh 353775897234Sdrh /* 3538fe05af87Sdrh ** Delete an IdList. 3539fe05af87Sdrh */ 3540633e6d57Sdrh void sqlite3IdListDelete(sqlite3 *db, IdList *pList){ 3541fe05af87Sdrh int i; 3542fe05af87Sdrh if( pList==0 ) return; 3543fe05af87Sdrh for(i=0; i<pList->nId; i++){ 3544633e6d57Sdrh sqlite3DbFree(db, pList->a[i].zName); 3545fe05af87Sdrh } 3546633e6d57Sdrh sqlite3DbFree(db, pList->a); 3547633e6d57Sdrh sqlite3DbFree(db, pList); 3548fe05af87Sdrh } 3549fe05af87Sdrh 3550fe05af87Sdrh /* 3551fe05af87Sdrh ** Return the index in pList of the identifier named zId. Return -1 3552fe05af87Sdrh ** if not found. 3553fe05af87Sdrh */ 3554fe05af87Sdrh int sqlite3IdListIndex(IdList *pList, const char *zName){ 3555fe05af87Sdrh int i; 3556fe05af87Sdrh if( pList==0 ) return -1; 3557fe05af87Sdrh for(i=0; i<pList->nId; i++){ 3558fe05af87Sdrh if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i; 3559fe05af87Sdrh } 3560fe05af87Sdrh return -1; 3561fe05af87Sdrh } 3562fe05af87Sdrh 3563fe05af87Sdrh /* 3564a78c22c4Sdrh ** Expand the space allocated for the given SrcList object by 3565a78c22c4Sdrh ** creating nExtra new slots beginning at iStart. iStart is zero based. 3566a78c22c4Sdrh ** New slots are zeroed. 3567a78c22c4Sdrh ** 3568a78c22c4Sdrh ** For example, suppose a SrcList initially contains two entries: A,B. 3569a78c22c4Sdrh ** To append 3 new entries onto the end, do this: 3570a78c22c4Sdrh ** 3571a78c22c4Sdrh ** sqlite3SrcListEnlarge(db, pSrclist, 3, 2); 3572a78c22c4Sdrh ** 3573a78c22c4Sdrh ** After the call above it would contain: A, B, nil, nil, nil. 3574a78c22c4Sdrh ** If the iStart argument had been 1 instead of 2, then the result 3575a78c22c4Sdrh ** would have been: A, nil, nil, nil, B. To prepend the new slots, 3576a78c22c4Sdrh ** the iStart value would be 0. The result then would 3577a78c22c4Sdrh ** be: nil, nil, nil, A, B. 3578a78c22c4Sdrh ** 3579a78c22c4Sdrh ** If a memory allocation fails the SrcList is unchanged. The 3580a78c22c4Sdrh ** db->mallocFailed flag will be set to true. 3581a78c22c4Sdrh */ 3582a78c22c4Sdrh SrcList *sqlite3SrcListEnlarge( 3583a78c22c4Sdrh sqlite3 *db, /* Database connection to notify of OOM errors */ 3584a78c22c4Sdrh SrcList *pSrc, /* The SrcList to be enlarged */ 3585a78c22c4Sdrh int nExtra, /* Number of new slots to add to pSrc->a[] */ 3586a78c22c4Sdrh int iStart /* Index in pSrc->a[] of first new slot */ 3587a78c22c4Sdrh ){ 3588a78c22c4Sdrh int i; 3589a78c22c4Sdrh 3590a78c22c4Sdrh /* Sanity checking on calling parameters */ 3591a78c22c4Sdrh assert( iStart>=0 ); 3592a78c22c4Sdrh assert( nExtra>=1 ); 35938af73d41Sdrh assert( pSrc!=0 ); 35948af73d41Sdrh assert( iStart<=pSrc->nSrc ); 3595a78c22c4Sdrh 3596a78c22c4Sdrh /* Allocate additional space if needed */ 3597fc5717ccSdrh if( (u32)pSrc->nSrc+nExtra>pSrc->nAlloc ){ 3598a78c22c4Sdrh SrcList *pNew; 3599a78c22c4Sdrh int nAlloc = pSrc->nSrc+nExtra; 36006a1e071fSdrh int nGot; 3601a78c22c4Sdrh pNew = sqlite3DbRealloc(db, pSrc, 3602a78c22c4Sdrh sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) ); 3603a78c22c4Sdrh if( pNew==0 ){ 3604a78c22c4Sdrh assert( db->mallocFailed ); 3605a78c22c4Sdrh return pSrc; 3606a78c22c4Sdrh } 3607a78c22c4Sdrh pSrc = pNew; 36086a1e071fSdrh nGot = (sqlite3DbMallocSize(db, pNew) - sizeof(*pSrc))/sizeof(pSrc->a[0])+1; 36096d1626ebSdrh pSrc->nAlloc = nGot; 3610a78c22c4Sdrh } 3611a78c22c4Sdrh 3612a78c22c4Sdrh /* Move existing slots that come after the newly inserted slots 3613a78c22c4Sdrh ** out of the way */ 3614a78c22c4Sdrh for(i=pSrc->nSrc-1; i>=iStart; i--){ 3615a78c22c4Sdrh pSrc->a[i+nExtra] = pSrc->a[i]; 3616a78c22c4Sdrh } 36176d1626ebSdrh pSrc->nSrc += nExtra; 3618a78c22c4Sdrh 3619a78c22c4Sdrh /* Zero the newly allocated slots */ 3620a78c22c4Sdrh memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra); 3621a78c22c4Sdrh for(i=iStart; i<iStart+nExtra; i++){ 3622a78c22c4Sdrh pSrc->a[i].iCursor = -1; 3623a78c22c4Sdrh } 3624a78c22c4Sdrh 3625a78c22c4Sdrh /* Return a pointer to the enlarged SrcList */ 3626a78c22c4Sdrh return pSrc; 3627a78c22c4Sdrh } 3628a78c22c4Sdrh 3629a78c22c4Sdrh 3630a78c22c4Sdrh /* 3631ad3cab52Sdrh ** Append a new table name to the given SrcList. Create a new SrcList if 3632b7916a78Sdrh ** need be. A new entry is created in the SrcList even if pTable is NULL. 3633ad3cab52Sdrh ** 3634a78c22c4Sdrh ** A SrcList is returned, or NULL if there is an OOM error. The returned 3635a78c22c4Sdrh ** SrcList might be the same as the SrcList that was input or it might be 3636a78c22c4Sdrh ** a new one. If an OOM error does occurs, then the prior value of pList 3637a78c22c4Sdrh ** that is input to this routine is automatically freed. 3638113088ecSdrh ** 3639113088ecSdrh ** If pDatabase is not null, it means that the table has an optional 3640113088ecSdrh ** database name prefix. Like this: "database.table". The pDatabase 3641113088ecSdrh ** points to the table name and the pTable points to the database name. 3642113088ecSdrh ** The SrcList.a[].zName field is filled with the table name which might 3643113088ecSdrh ** come from pTable (if pDatabase is NULL) or from pDatabase. 3644113088ecSdrh ** SrcList.a[].zDatabase is filled with the database name from pTable, 3645113088ecSdrh ** or with NULL if no database is specified. 3646113088ecSdrh ** 3647113088ecSdrh ** In other words, if call like this: 3648113088ecSdrh ** 364917435752Sdrh ** sqlite3SrcListAppend(D,A,B,0); 3650113088ecSdrh ** 3651113088ecSdrh ** Then B is a table name and the database name is unspecified. If called 3652113088ecSdrh ** like this: 3653113088ecSdrh ** 365417435752Sdrh ** sqlite3SrcListAppend(D,A,B,C); 3655113088ecSdrh ** 3656d3001711Sdrh ** Then C is the table name and B is the database name. If C is defined 3657d3001711Sdrh ** then so is B. In other words, we never have a case where: 3658d3001711Sdrh ** 3659d3001711Sdrh ** sqlite3SrcListAppend(D,A,0,C); 3660b7916a78Sdrh ** 3661b7916a78Sdrh ** Both pTable and pDatabase are assumed to be quoted. They are dequoted 3662b7916a78Sdrh ** before being added to the SrcList. 3663ad3cab52Sdrh */ 366417435752Sdrh SrcList *sqlite3SrcListAppend( 366517435752Sdrh sqlite3 *db, /* Connection to notify of malloc failures */ 366617435752Sdrh SrcList *pList, /* Append to this SrcList. NULL creates a new SrcList */ 366717435752Sdrh Token *pTable, /* Table to append */ 366817435752Sdrh Token *pDatabase /* Database of the table */ 366917435752Sdrh ){ 3670a99db3b6Sdrh struct SrcList_item *pItem; 3671d3001711Sdrh assert( pDatabase==0 || pTable!=0 ); /* Cannot have C without B */ 3672ad3cab52Sdrh if( pList==0 ){ 367317435752Sdrh pList = sqlite3DbMallocZero(db, sizeof(SrcList) ); 3674ad3cab52Sdrh if( pList==0 ) return 0; 36754305d103Sdrh pList->nAlloc = 1; 3676ad3cab52Sdrh } 3677a78c22c4Sdrh pList = sqlite3SrcListEnlarge(db, pList, 1, pList->nSrc); 3678a78c22c4Sdrh if( db->mallocFailed ){ 3679633e6d57Sdrh sqlite3SrcListDelete(db, pList); 3680ad3cab52Sdrh return 0; 3681ad3cab52Sdrh } 3682a78c22c4Sdrh pItem = &pList->a[pList->nSrc-1]; 3683113088ecSdrh if( pDatabase && pDatabase->z==0 ){ 3684113088ecSdrh pDatabase = 0; 3685113088ecSdrh } 3686d3001711Sdrh if( pDatabase ){ 3687113088ecSdrh Token *pTemp = pDatabase; 3688113088ecSdrh pDatabase = pTable; 3689113088ecSdrh pTable = pTemp; 3690113088ecSdrh } 369117435752Sdrh pItem->zName = sqlite3NameFromToken(db, pTable); 369217435752Sdrh pItem->zDatabase = sqlite3NameFromToken(db, pDatabase); 3693ad3cab52Sdrh return pList; 3694ad3cab52Sdrh } 3695ad3cab52Sdrh 3696ad3cab52Sdrh /* 3697dfe88eceSdrh ** Assign VdbeCursor index numbers to all tables in a SrcList 369863eb5f29Sdrh */ 36994adee20fSdanielk1977 void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){ 370063eb5f29Sdrh int i; 37019b3187e1Sdrh struct SrcList_item *pItem; 370217435752Sdrh assert(pList || pParse->db->mallocFailed ); 3703261919ccSdanielk1977 if( pList ){ 37049b3187e1Sdrh for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){ 37059b3187e1Sdrh if( pItem->iCursor>=0 ) break; 37069b3187e1Sdrh pItem->iCursor = pParse->nTab++; 37079b3187e1Sdrh if( pItem->pSelect ){ 37089b3187e1Sdrh sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc); 370963eb5f29Sdrh } 371063eb5f29Sdrh } 371163eb5f29Sdrh } 3712261919ccSdanielk1977 } 371363eb5f29Sdrh 371463eb5f29Sdrh /* 3715ad3cab52Sdrh ** Delete an entire SrcList including all its substructure. 3716ad3cab52Sdrh */ 3717633e6d57Sdrh void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){ 3718ad3cab52Sdrh int i; 3719be5c89acSdrh struct SrcList_item *pItem; 3720ad3cab52Sdrh if( pList==0 ) return; 3721be5c89acSdrh for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){ 3722633e6d57Sdrh sqlite3DbFree(db, pItem->zDatabase); 3723633e6d57Sdrh sqlite3DbFree(db, pItem->zName); 3724633e6d57Sdrh sqlite3DbFree(db, pItem->zAlias); 37258a48b9c0Sdrh if( pItem->fg.isIndexedBy ) sqlite3DbFree(db, pItem->u1.zIndexedBy); 37268a48b9c0Sdrh if( pItem->fg.isTabFunc ) sqlite3ExprListDelete(db, pItem->u1.pFuncArg); 37271feeaed2Sdan sqlite3DeleteTable(db, pItem->pTab); 3728633e6d57Sdrh sqlite3SelectDelete(db, pItem->pSelect); 3729633e6d57Sdrh sqlite3ExprDelete(db, pItem->pOn); 3730633e6d57Sdrh sqlite3IdListDelete(db, pItem->pUsing); 373175897234Sdrh } 3732633e6d57Sdrh sqlite3DbFree(db, pList); 373375897234Sdrh } 373475897234Sdrh 3735982cef7eSdrh /* 373661dfc31dSdrh ** This routine is called by the parser to add a new term to the 373761dfc31dSdrh ** end of a growing FROM clause. The "p" parameter is the part of 373861dfc31dSdrh ** the FROM clause that has already been constructed. "p" is NULL 373961dfc31dSdrh ** if this is the first term of the FROM clause. pTable and pDatabase 374061dfc31dSdrh ** are the name of the table and database named in the FROM clause term. 374161dfc31dSdrh ** pDatabase is NULL if the database name qualifier is missing - the 374260ec914cSpeter.d.reid ** usual case. If the term has an alias, then pAlias points to the 374361dfc31dSdrh ** alias token. If the term is a subquery, then pSubquery is the 374461dfc31dSdrh ** SELECT statement that the subquery encodes. The pTable and 374561dfc31dSdrh ** pDatabase parameters are NULL for subqueries. The pOn and pUsing 374661dfc31dSdrh ** parameters are the content of the ON and USING clauses. 374761dfc31dSdrh ** 374861dfc31dSdrh ** Return a new SrcList which encodes is the FROM with the new 374961dfc31dSdrh ** term added. 375061dfc31dSdrh */ 375161dfc31dSdrh SrcList *sqlite3SrcListAppendFromTerm( 375217435752Sdrh Parse *pParse, /* Parsing context */ 375361dfc31dSdrh SrcList *p, /* The left part of the FROM clause already seen */ 375461dfc31dSdrh Token *pTable, /* Name of the table to add to the FROM clause */ 375561dfc31dSdrh Token *pDatabase, /* Name of the database containing pTable */ 375661dfc31dSdrh Token *pAlias, /* The right-hand side of the AS subexpression */ 375761dfc31dSdrh Select *pSubquery, /* A subquery used in place of a table name */ 375861dfc31dSdrh Expr *pOn, /* The ON clause of a join */ 375961dfc31dSdrh IdList *pUsing /* The USING clause of a join */ 376061dfc31dSdrh ){ 376161dfc31dSdrh struct SrcList_item *pItem; 376217435752Sdrh sqlite3 *db = pParse->db; 3763bd1a0a4fSdanielk1977 if( !p && (pOn || pUsing) ){ 3764bd1a0a4fSdanielk1977 sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s", 3765bd1a0a4fSdanielk1977 (pOn ? "ON" : "USING") 3766bd1a0a4fSdanielk1977 ); 3767bd1a0a4fSdanielk1977 goto append_from_error; 3768bd1a0a4fSdanielk1977 } 376917435752Sdrh p = sqlite3SrcListAppend(db, p, pTable, pDatabase); 37708af73d41Sdrh if( p==0 || NEVER(p->nSrc==0) ){ 3771bd1a0a4fSdanielk1977 goto append_from_error; 377261dfc31dSdrh } 377361dfc31dSdrh pItem = &p->a[p->nSrc-1]; 37748af73d41Sdrh assert( pAlias!=0 ); 37758af73d41Sdrh if( pAlias->n ){ 377617435752Sdrh pItem->zAlias = sqlite3NameFromToken(db, pAlias); 377761dfc31dSdrh } 377861dfc31dSdrh pItem->pSelect = pSubquery; 377961dfc31dSdrh pItem->pOn = pOn; 378061dfc31dSdrh pItem->pUsing = pUsing; 3781bd1a0a4fSdanielk1977 return p; 3782bd1a0a4fSdanielk1977 3783bd1a0a4fSdanielk1977 append_from_error: 3784bd1a0a4fSdanielk1977 assert( p==0 ); 37859b87d7b9Sdanielk1977 sqlite3ExprDelete(db, pOn); 37869b87d7b9Sdanielk1977 sqlite3IdListDelete(db, pUsing); 3787bd1a0a4fSdanielk1977 sqlite3SelectDelete(db, pSubquery); 3788bd1a0a4fSdanielk1977 return 0; 378961dfc31dSdrh } 379061dfc31dSdrh 379161dfc31dSdrh /* 3792b1c685b0Sdanielk1977 ** Add an INDEXED BY or NOT INDEXED clause to the most recently added 3793b1c685b0Sdanielk1977 ** element of the source-list passed as the second argument. 3794b1c685b0Sdanielk1977 */ 3795b1c685b0Sdanielk1977 void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){ 37968af73d41Sdrh assert( pIndexedBy!=0 ); 37978af73d41Sdrh if( p && ALWAYS(p->nSrc>0) ){ 3798b1c685b0Sdanielk1977 struct SrcList_item *pItem = &p->a[p->nSrc-1]; 37998a48b9c0Sdrh assert( pItem->fg.notIndexed==0 ); 38008a48b9c0Sdrh assert( pItem->fg.isIndexedBy==0 ); 38018a48b9c0Sdrh assert( pItem->fg.isTabFunc==0 ); 3802b1c685b0Sdanielk1977 if( pIndexedBy->n==1 && !pIndexedBy->z ){ 3803b1c685b0Sdanielk1977 /* A "NOT INDEXED" clause was supplied. See parse.y 3804b1c685b0Sdanielk1977 ** construct "indexed_opt" for details. */ 38058a48b9c0Sdrh pItem->fg.notIndexed = 1; 3806b1c685b0Sdanielk1977 }else{ 38078a48b9c0Sdrh pItem->u1.zIndexedBy = sqlite3NameFromToken(pParse->db, pIndexedBy); 38088a48b9c0Sdrh pItem->fg.isIndexedBy = (pItem->u1.zIndexedBy!=0); 3809b1c685b0Sdanielk1977 } 3810b1c685b0Sdanielk1977 } 3811b1c685b0Sdanielk1977 } 3812b1c685b0Sdanielk1977 3813b1c685b0Sdanielk1977 /* 381401d230ceSdrh ** Add the list of function arguments to the SrcList entry for a 381501d230ceSdrh ** table-valued-function. 381601d230ceSdrh */ 381701d230ceSdrh void sqlite3SrcListFuncArgs(Parse *pParse, SrcList *p, ExprList *pList){ 3818d8b1bfc6Sdrh if( p && pList ){ 381901d230ceSdrh struct SrcList_item *pItem = &p->a[p->nSrc-1]; 382001d230ceSdrh assert( pItem->fg.notIndexed==0 ); 382101d230ceSdrh assert( pItem->fg.isIndexedBy==0 ); 382201d230ceSdrh assert( pItem->fg.isTabFunc==0 ); 382301d230ceSdrh pItem->u1.pFuncArg = pList; 382401d230ceSdrh pItem->fg.isTabFunc = 1; 3825d8b1bfc6Sdrh }else{ 3826d8b1bfc6Sdrh sqlite3ExprListDelete(pParse->db, pList); 382701d230ceSdrh } 382801d230ceSdrh } 382901d230ceSdrh 383001d230ceSdrh /* 383161dfc31dSdrh ** When building up a FROM clause in the parser, the join operator 383261dfc31dSdrh ** is initially attached to the left operand. But the code generator 383361dfc31dSdrh ** expects the join operator to be on the right operand. This routine 383461dfc31dSdrh ** Shifts all join operators from left to right for an entire FROM 383561dfc31dSdrh ** clause. 383661dfc31dSdrh ** 383761dfc31dSdrh ** Example: Suppose the join is like this: 383861dfc31dSdrh ** 383961dfc31dSdrh ** A natural cross join B 384061dfc31dSdrh ** 384161dfc31dSdrh ** The operator is "natural cross join". The A and B operands are stored 384261dfc31dSdrh ** in p->a[0] and p->a[1], respectively. The parser initially stores the 384361dfc31dSdrh ** operator with A. This routine shifts that operator over to B. 384461dfc31dSdrh */ 384561dfc31dSdrh void sqlite3SrcListShiftJoinType(SrcList *p){ 3846d017ab99Sdrh if( p ){ 384761dfc31dSdrh int i; 384861dfc31dSdrh for(i=p->nSrc-1; i>0; i--){ 38498a48b9c0Sdrh p->a[i].fg.jointype = p->a[i-1].fg.jointype; 385061dfc31dSdrh } 38518a48b9c0Sdrh p->a[0].fg.jointype = 0; 385261dfc31dSdrh } 385361dfc31dSdrh } 385461dfc31dSdrh 385561dfc31dSdrh /* 3856c4a3c779Sdrh ** Begin a transaction 3857c4a3c779Sdrh */ 3858684917c2Sdrh void sqlite3BeginTransaction(Parse *pParse, int type){ 38599bb575fdSdrh sqlite3 *db; 38601d850a72Sdanielk1977 Vdbe *v; 3861684917c2Sdrh int i; 38625e00f6c7Sdrh 3863d3001711Sdrh assert( pParse!=0 ); 3864d3001711Sdrh db = pParse->db; 3865d3001711Sdrh assert( db!=0 ); 38660449171eSdrh /* if( db->aDb[0].pBt==0 ) return; */ 3867d3001711Sdrh if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){ 3868d3001711Sdrh return; 3869d3001711Sdrh } 38701d850a72Sdanielk1977 v = sqlite3GetVdbe(pParse); 38711d850a72Sdanielk1977 if( !v ) return; 3872684917c2Sdrh if( type!=TK_DEFERRED ){ 3873684917c2Sdrh for(i=0; i<db->nDb; i++){ 387466a5167bSdrh sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1); 3875fb98264aSdrh sqlite3VdbeUsesBtree(v, i); 3876684917c2Sdrh } 3877684917c2Sdrh } 387866a5167bSdrh sqlite3VdbeAddOp2(v, OP_AutoCommit, 0, 0); 387902f75f19Sdrh } 3880c4a3c779Sdrh 3881c4a3c779Sdrh /* 3882c4a3c779Sdrh ** Commit a transaction 3883c4a3c779Sdrh */ 38844adee20fSdanielk1977 void sqlite3CommitTransaction(Parse *pParse){ 38851d850a72Sdanielk1977 Vdbe *v; 38865e00f6c7Sdrh 3887d3001711Sdrh assert( pParse!=0 ); 3888b07028f7Sdrh assert( pParse->db!=0 ); 3889d3001711Sdrh if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ){ 3890d3001711Sdrh return; 3891d3001711Sdrh } 38921d850a72Sdanielk1977 v = sqlite3GetVdbe(pParse); 38931d850a72Sdanielk1977 if( v ){ 389466a5167bSdrh sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 0); 3895c4a3c779Sdrh } 389602f75f19Sdrh } 3897c4a3c779Sdrh 3898c4a3c779Sdrh /* 3899c4a3c779Sdrh ** Rollback a transaction 3900c4a3c779Sdrh */ 39014adee20fSdanielk1977 void sqlite3RollbackTransaction(Parse *pParse){ 39025e00f6c7Sdrh Vdbe *v; 39035e00f6c7Sdrh 3904d3001711Sdrh assert( pParse!=0 ); 3905b07028f7Sdrh assert( pParse->db!=0 ); 3906d3001711Sdrh if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ){ 3907d3001711Sdrh return; 3908d3001711Sdrh } 39094adee20fSdanielk1977 v = sqlite3GetVdbe(pParse); 39105e00f6c7Sdrh if( v ){ 391166a5167bSdrh sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 1); 3912c4a3c779Sdrh } 391302f75f19Sdrh } 3914f57b14a6Sdrh 3915f57b14a6Sdrh /* 3916fd7f0452Sdanielk1977 ** This function is called by the parser when it parses a command to create, 3917fd7f0452Sdanielk1977 ** release or rollback an SQL savepoint. 3918fd7f0452Sdanielk1977 */ 3919fd7f0452Sdanielk1977 void sqlite3Savepoint(Parse *pParse, int op, Token *pName){ 3920ab9b703fSdanielk1977 char *zName = sqlite3NameFromToken(pParse->db, pName); 3921ab9b703fSdanielk1977 if( zName ){ 3922ab9b703fSdanielk1977 Vdbe *v = sqlite3GetVdbe(pParse); 3923ab9b703fSdanielk1977 #ifndef SQLITE_OMIT_AUTHORIZATION 3924558814f8Sdan static const char * const az[] = { "BEGIN", "RELEASE", "ROLLBACK" }; 3925ab9b703fSdanielk1977 assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 ); 3926ab9b703fSdanielk1977 #endif 3927ab9b703fSdanielk1977 if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){ 3928ab9b703fSdanielk1977 sqlite3DbFree(pParse->db, zName); 3929ab9b703fSdanielk1977 return; 3930ab9b703fSdanielk1977 } 3931ab9b703fSdanielk1977 sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC); 3932fd7f0452Sdanielk1977 } 3933fd7f0452Sdanielk1977 } 3934fd7f0452Sdanielk1977 3935fd7f0452Sdanielk1977 /* 3936dc3ff9c3Sdrh ** Make sure the TEMP database is open and available for use. Return 3937dc3ff9c3Sdrh ** the number of errors. Leave any error messages in the pParse structure. 3938dc3ff9c3Sdrh */ 3939ddfb2f03Sdanielk1977 int sqlite3OpenTempDatabase(Parse *pParse){ 3940dc3ff9c3Sdrh sqlite3 *db = pParse->db; 3941dc3ff9c3Sdrh if( db->aDb[1].pBt==0 && !pParse->explain ){ 394233f4e02aSdrh int rc; 394310a76c90Sdrh Btree *pBt; 394433f4e02aSdrh static const int flags = 394533f4e02aSdrh SQLITE_OPEN_READWRITE | 394633f4e02aSdrh SQLITE_OPEN_CREATE | 394733f4e02aSdrh SQLITE_OPEN_EXCLUSIVE | 394833f4e02aSdrh SQLITE_OPEN_DELETEONCLOSE | 394933f4e02aSdrh SQLITE_OPEN_TEMP_DB; 395033f4e02aSdrh 39513a6d8aecSdan rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pBt, 0, flags); 3952dc3ff9c3Sdrh if( rc!=SQLITE_OK ){ 3953dc3ff9c3Sdrh sqlite3ErrorMsg(pParse, "unable to open a temporary database " 3954dc3ff9c3Sdrh "file for storing temporary tables"); 3955dc3ff9c3Sdrh pParse->rc = rc; 3956dc3ff9c3Sdrh return 1; 3957dc3ff9c3Sdrh } 395810a76c90Sdrh db->aDb[1].pBt = pBt; 395914db2665Sdanielk1977 assert( db->aDb[1].pSchema ); 396010a76c90Sdrh if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){ 396110a76c90Sdrh db->mallocFailed = 1; 39627c9c9868Sdrh return 1; 396310a76c90Sdrh } 3964dc3ff9c3Sdrh } 3965dc3ff9c3Sdrh return 0; 3966dc3ff9c3Sdrh } 3967dc3ff9c3Sdrh 3968dc3ff9c3Sdrh /* 3969aceb31b1Sdrh ** Record the fact that the schema cookie will need to be verified 3970aceb31b1Sdrh ** for database iDb. The code to actually verify the schema cookie 3971aceb31b1Sdrh ** will occur at the end of the top-level VDBE and will be generated 3972aceb31b1Sdrh ** later, by sqlite3FinishCoding(). 3973001bbcbbSdrh */ 39744adee20fSdanielk1977 void sqlite3CodeVerifySchema(Parse *pParse, int iDb){ 397565a7cd16Sdan Parse *pToplevel = sqlite3ParseToplevel(pParse); 397665a7cd16Sdan sqlite3 *db = pToplevel->db; 397765a7cd16Sdan 3978aceb31b1Sdrh assert( iDb>=0 && iDb<db->nDb ); 397980242055Sdrh assert( db->aDb[iDb].pBt!=0 || iDb==1 ); 3980c797d4dcSdrh assert( iDb<SQLITE_MAX_ATTACHED+2 ); 39812120608eSdrh assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); 3982a7ab6d81Sdrh if( DbMaskTest(pToplevel->cookieMask, iDb)==0 ){ 3983a7ab6d81Sdrh DbMaskSet(pToplevel->cookieMask, iDb); 398465a7cd16Sdan pToplevel->cookieValue[iDb] = db->aDb[iDb].pSchema->schema_cookie; 398553c0f748Sdanielk1977 if( !OMIT_TEMPDB && iDb==1 ){ 398665a7cd16Sdan sqlite3OpenTempDatabase(pToplevel); 3987dc3ff9c3Sdrh } 3988001bbcbbSdrh } 3989c275b4eaSdrh } 3990001bbcbbSdrh 3991001bbcbbSdrh /* 399257966753Sdan ** If argument zDb is NULL, then call sqlite3CodeVerifySchema() for each 399357966753Sdan ** attached database. Otherwise, invoke it for the database named zDb only. 399457966753Sdan */ 399557966753Sdan void sqlite3CodeVerifyNamedSchema(Parse *pParse, const char *zDb){ 399657966753Sdan sqlite3 *db = pParse->db; 399757966753Sdan int i; 399857966753Sdan for(i=0; i<db->nDb; i++){ 399957966753Sdan Db *pDb = &db->aDb[i]; 400057966753Sdan if( pDb->pBt && (!zDb || 0==sqlite3StrICmp(zDb, pDb->zName)) ){ 400157966753Sdan sqlite3CodeVerifySchema(pParse, i); 400257966753Sdan } 400357966753Sdan } 400457966753Sdan } 400557966753Sdan 400657966753Sdan /* 40071c92853dSdrh ** Generate VDBE code that prepares for doing an operation that 4008c977f7f5Sdrh ** might change the database. 4009c977f7f5Sdrh ** 4010c977f7f5Sdrh ** This routine starts a new transaction if we are not already within 4011c977f7f5Sdrh ** a transaction. If we are already within a transaction, then a checkpoint 40127f0f12e3Sdrh ** is set if the setStatement parameter is true. A checkpoint should 4013c977f7f5Sdrh ** be set for operations that might fail (due to a constraint) part of 4014c977f7f5Sdrh ** the way through and which will need to undo some writes without having to 4015c977f7f5Sdrh ** rollback the whole transaction. For operations where all constraints 4016c977f7f5Sdrh ** can be checked before any changes are made to the database, it is never 4017c977f7f5Sdrh ** necessary to undo a write and the checkpoint should not be set. 40181c92853dSdrh */ 40197f0f12e3Sdrh void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){ 402065a7cd16Sdan Parse *pToplevel = sqlite3ParseToplevel(pParse); 402180242055Sdrh sqlite3CodeVerifySchema(pParse, iDb); 4022a7ab6d81Sdrh DbMaskSet(pToplevel->writeMask, iDb); 4023e0af83acSdan pToplevel->isMultiWrite |= setStatement; 40241d850a72Sdanielk1977 } 4025e0af83acSdan 4026e0af83acSdan /* 4027ff738bceSdrh ** Indicate that the statement currently under construction might write 4028ff738bceSdrh ** more than one entry (example: deleting one row then inserting another, 4029ff738bceSdrh ** inserting multiple rows in a table, or inserting a row and index entries.) 4030ff738bceSdrh ** If an abort occurs after some of these writes have completed, then it will 4031ff738bceSdrh ** be necessary to undo the completed writes. 4032ff738bceSdrh */ 4033ff738bceSdrh void sqlite3MultiWrite(Parse *pParse){ 4034ff738bceSdrh Parse *pToplevel = sqlite3ParseToplevel(pParse); 4035ff738bceSdrh pToplevel->isMultiWrite = 1; 4036ff738bceSdrh } 4037ff738bceSdrh 4038ff738bceSdrh /* 4039ff738bceSdrh ** The code generator calls this routine if is discovers that it is 4040ff738bceSdrh ** possible to abort a statement prior to completion. In order to 4041ff738bceSdrh ** perform this abort without corrupting the database, we need to make 4042ff738bceSdrh ** sure that the statement is protected by a statement transaction. 4043ff738bceSdrh ** 4044ff738bceSdrh ** Technically, we only need to set the mayAbort flag if the 4045ff738bceSdrh ** isMultiWrite flag was previously set. There is a time dependency 4046ff738bceSdrh ** such that the abort must occur after the multiwrite. This makes 4047ff738bceSdrh ** some statements involving the REPLACE conflict resolution algorithm 4048ff738bceSdrh ** go a little faster. But taking advantage of this time dependency 4049ff738bceSdrh ** makes it more difficult to prove that the code is correct (in 4050ff738bceSdrh ** particular, it prevents us from writing an effective 4051ff738bceSdrh ** implementation of sqlite3AssertMayAbort()) and so we have chosen 4052ff738bceSdrh ** to take the safe route and skip the optimization. 4053e0af83acSdan */ 4054e0af83acSdan void sqlite3MayAbort(Parse *pParse){ 4055e0af83acSdan Parse *pToplevel = sqlite3ParseToplevel(pParse); 4056e0af83acSdan pToplevel->mayAbort = 1; 4057e0af83acSdan } 4058e0af83acSdan 4059e0af83acSdan /* 4060e0af83acSdan ** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT 4061e0af83acSdan ** error. The onError parameter determines which (if any) of the statement 4062e0af83acSdan ** and/or current transaction is rolled back. 4063e0af83acSdan */ 4064d91c1a17Sdrh void sqlite3HaltConstraint( 4065d91c1a17Sdrh Parse *pParse, /* Parsing context */ 4066d91c1a17Sdrh int errCode, /* extended error code */ 4067d91c1a17Sdrh int onError, /* Constraint type */ 4068d91c1a17Sdrh char *p4, /* Error message */ 4069f9c8ce3cSdrh i8 p4type, /* P4_STATIC or P4_TRANSIENT */ 4070f9c8ce3cSdrh u8 p5Errmsg /* P5_ErrMsg type */ 4071d91c1a17Sdrh ){ 4072e0af83acSdan Vdbe *v = sqlite3GetVdbe(pParse); 4073d91c1a17Sdrh assert( (errCode&0xff)==SQLITE_CONSTRAINT ); 4074e0af83acSdan if( onError==OE_Abort ){ 4075e0af83acSdan sqlite3MayAbort(pParse); 4076e0af83acSdan } 4077d91c1a17Sdrh sqlite3VdbeAddOp4(v, OP_Halt, errCode, onError, 0, p4, p4type); 4078f9c8ce3cSdrh if( p5Errmsg ) sqlite3VdbeChangeP5(v, p5Errmsg); 4079f9c8ce3cSdrh } 4080f9c8ce3cSdrh 4081f9c8ce3cSdrh /* 4082f9c8ce3cSdrh ** Code an OP_Halt due to UNIQUE or PRIMARY KEY constraint violation. 4083f9c8ce3cSdrh */ 4084f9c8ce3cSdrh void sqlite3UniqueConstraint( 4085f9c8ce3cSdrh Parse *pParse, /* Parsing context */ 4086f9c8ce3cSdrh int onError, /* Constraint type */ 4087f9c8ce3cSdrh Index *pIdx /* The index that triggers the constraint */ 4088f9c8ce3cSdrh ){ 4089f9c8ce3cSdrh char *zErr; 4090f9c8ce3cSdrh int j; 4091f9c8ce3cSdrh StrAccum errMsg; 4092f9c8ce3cSdrh Table *pTab = pIdx->pTable; 4093f9c8ce3cSdrh 4094c0490572Sdrh sqlite3StrAccumInit(&errMsg, pParse->db, 0, 0, 200); 4095f9c8ce3cSdrh for(j=0; j<pIdx->nKeyCol; j++){ 4096f9c8ce3cSdrh char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName; 4097f9c8ce3cSdrh if( j ) sqlite3StrAccumAppend(&errMsg, ", ", 2); 4098a6353a3fSdrh sqlite3StrAccumAppendAll(&errMsg, pTab->zName); 4099f9c8ce3cSdrh sqlite3StrAccumAppend(&errMsg, ".", 1); 4100a6353a3fSdrh sqlite3StrAccumAppendAll(&errMsg, zCol); 4101f9c8ce3cSdrh } 4102f9c8ce3cSdrh zErr = sqlite3StrAccumFinish(&errMsg); 4103f9c8ce3cSdrh sqlite3HaltConstraint(pParse, 410448dd1d8eSdrh IsPrimaryKeyIndex(pIdx) ? SQLITE_CONSTRAINT_PRIMARYKEY 410548dd1d8eSdrh : SQLITE_CONSTRAINT_UNIQUE, 410693889d93Sdan onError, zErr, P4_DYNAMIC, P5_ConstraintUnique); 4107f9c8ce3cSdrh } 4108f9c8ce3cSdrh 4109f9c8ce3cSdrh 4110f9c8ce3cSdrh /* 4111f9c8ce3cSdrh ** Code an OP_Halt due to non-unique rowid. 4112f9c8ce3cSdrh */ 4113f9c8ce3cSdrh void sqlite3RowidConstraint( 4114f9c8ce3cSdrh Parse *pParse, /* Parsing context */ 4115f9c8ce3cSdrh int onError, /* Conflict resolution algorithm */ 4116f9c8ce3cSdrh Table *pTab /* The table with the non-unique rowid */ 4117f9c8ce3cSdrh ){ 4118f9c8ce3cSdrh char *zMsg; 4119f9c8ce3cSdrh int rc; 4120f9c8ce3cSdrh if( pTab->iPKey>=0 ){ 4121f9c8ce3cSdrh zMsg = sqlite3MPrintf(pParse->db, "%s.%s", pTab->zName, 4122f9c8ce3cSdrh pTab->aCol[pTab->iPKey].zName); 4123f9c8ce3cSdrh rc = SQLITE_CONSTRAINT_PRIMARYKEY; 4124f9c8ce3cSdrh }else{ 4125f9c8ce3cSdrh zMsg = sqlite3MPrintf(pParse->db, "%s.rowid", pTab->zName); 4126f9c8ce3cSdrh rc = SQLITE_CONSTRAINT_ROWID; 4127f9c8ce3cSdrh } 4128f9c8ce3cSdrh sqlite3HaltConstraint(pParse, rc, onError, zMsg, P4_DYNAMIC, 4129f9c8ce3cSdrh P5_ConstraintUnique); 4130663fc63aSdrh } 4131663fc63aSdrh 41324343fea2Sdrh /* 41334343fea2Sdrh ** Check to see if pIndex uses the collating sequence pColl. Return 41344343fea2Sdrh ** true if it does and false if it does not. 41354343fea2Sdrh */ 41364343fea2Sdrh #ifndef SQLITE_OMIT_REINDEX 4137b3bf556eSdanielk1977 static int collationMatch(const char *zColl, Index *pIndex){ 4138b3bf556eSdanielk1977 int i; 41390449171eSdrh assert( zColl!=0 ); 4140b3bf556eSdanielk1977 for(i=0; i<pIndex->nColumn; i++){ 4141b3bf556eSdanielk1977 const char *z = pIndex->azColl[i]; 4142bbbdc83bSdrh assert( z!=0 || pIndex->aiColumn[i]<0 ); 4143bbbdc83bSdrh if( pIndex->aiColumn[i]>=0 && 0==sqlite3StrICmp(z, zColl) ){ 4144b3bf556eSdanielk1977 return 1; 4145b3bf556eSdanielk1977 } 41464343fea2Sdrh } 41474343fea2Sdrh return 0; 41484343fea2Sdrh } 41494343fea2Sdrh #endif 41504343fea2Sdrh 41514343fea2Sdrh /* 41524343fea2Sdrh ** Recompute all indices of pTab that use the collating sequence pColl. 41534343fea2Sdrh ** If pColl==0 then recompute all indices of pTab. 41544343fea2Sdrh */ 41554343fea2Sdrh #ifndef SQLITE_OMIT_REINDEX 4156b3bf556eSdanielk1977 static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){ 41574343fea2Sdrh Index *pIndex; /* An index associated with pTab */ 41584343fea2Sdrh 41594343fea2Sdrh for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){ 4160b3bf556eSdanielk1977 if( zColl==0 || collationMatch(zColl, pIndex) ){ 4161da184236Sdanielk1977 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema); 4162da184236Sdanielk1977 sqlite3BeginWriteOperation(pParse, 0, iDb); 41634343fea2Sdrh sqlite3RefillIndex(pParse, pIndex, -1); 41644343fea2Sdrh } 41654343fea2Sdrh } 41664343fea2Sdrh } 41674343fea2Sdrh #endif 41684343fea2Sdrh 41694343fea2Sdrh /* 41704343fea2Sdrh ** Recompute all indices of all tables in all databases where the 41714343fea2Sdrh ** indices use the collating sequence pColl. If pColl==0 then recompute 41724343fea2Sdrh ** all indices everywhere. 41734343fea2Sdrh */ 41744343fea2Sdrh #ifndef SQLITE_OMIT_REINDEX 4175b3bf556eSdanielk1977 static void reindexDatabases(Parse *pParse, char const *zColl){ 41764343fea2Sdrh Db *pDb; /* A single database */ 41774343fea2Sdrh int iDb; /* The database index number */ 41784343fea2Sdrh sqlite3 *db = pParse->db; /* The database connection */ 41794343fea2Sdrh HashElem *k; /* For looping over tables in pDb */ 41804343fea2Sdrh Table *pTab; /* A table in the database */ 41814343fea2Sdrh 41822120608eSdrh assert( sqlite3BtreeHoldsAllMutexes(db) ); /* Needed for schema access */ 41834343fea2Sdrh for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){ 418443617e9aSdrh assert( pDb!=0 ); 4185da184236Sdanielk1977 for(k=sqliteHashFirst(&pDb->pSchema->tblHash); k; k=sqliteHashNext(k)){ 41864343fea2Sdrh pTab = (Table*)sqliteHashData(k); 4187b3bf556eSdanielk1977 reindexTable(pParse, pTab, zColl); 41884343fea2Sdrh } 41894343fea2Sdrh } 41904343fea2Sdrh } 41914343fea2Sdrh #endif 41924343fea2Sdrh 41934343fea2Sdrh /* 4194eee46cf3Sdrh ** Generate code for the REINDEX command. 4195eee46cf3Sdrh ** 4196eee46cf3Sdrh ** REINDEX -- 1 4197eee46cf3Sdrh ** REINDEX <collation> -- 2 4198eee46cf3Sdrh ** REINDEX ?<database>.?<tablename> -- 3 4199eee46cf3Sdrh ** REINDEX ?<database>.?<indexname> -- 4 4200eee46cf3Sdrh ** 4201eee46cf3Sdrh ** Form 1 causes all indices in all attached databases to be rebuilt. 4202eee46cf3Sdrh ** Form 2 rebuilds all indices in all databases that use the named 4203eee46cf3Sdrh ** collating function. Forms 3 and 4 rebuild the named index or all 4204eee46cf3Sdrh ** indices associated with the named table. 42054343fea2Sdrh */ 42064343fea2Sdrh #ifndef SQLITE_OMIT_REINDEX 42074343fea2Sdrh void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){ 42084343fea2Sdrh CollSeq *pColl; /* Collating sequence to be reindexed, or NULL */ 42094343fea2Sdrh char *z; /* Name of a table or index */ 42104343fea2Sdrh const char *zDb; /* Name of the database */ 42114343fea2Sdrh Table *pTab; /* A table in the database */ 42124343fea2Sdrh Index *pIndex; /* An index associated with pTab */ 42134343fea2Sdrh int iDb; /* The database index number */ 42144343fea2Sdrh sqlite3 *db = pParse->db; /* The database connection */ 42154343fea2Sdrh Token *pObjName; /* Name of the table or index to be reindexed */ 42164343fea2Sdrh 421733a5edc3Sdanielk1977 /* Read the database schema. If an error occurs, leave an error message 421833a5edc3Sdanielk1977 ** and code in pParse and return NULL. */ 421933a5edc3Sdanielk1977 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){ 4220e63739a8Sdanielk1977 return; 422133a5edc3Sdanielk1977 } 422233a5edc3Sdanielk1977 42238af73d41Sdrh if( pName1==0 ){ 42244343fea2Sdrh reindexDatabases(pParse, 0); 42254343fea2Sdrh return; 4226d3001711Sdrh }else if( NEVER(pName2==0) || pName2->z==0 ){ 422739002505Sdanielk1977 char *zColl; 4228b3bf556eSdanielk1977 assert( pName1->z ); 422939002505Sdanielk1977 zColl = sqlite3NameFromToken(pParse->db, pName1); 423039002505Sdanielk1977 if( !zColl ) return; 4231c4a64facSdrh pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0); 42324343fea2Sdrh if( pColl ){ 4233f0113000Sdanielk1977 reindexDatabases(pParse, zColl); 4234633e6d57Sdrh sqlite3DbFree(db, zColl); 42354343fea2Sdrh return; 42364343fea2Sdrh } 4237633e6d57Sdrh sqlite3DbFree(db, zColl); 42384343fea2Sdrh } 42394343fea2Sdrh iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName); 42404343fea2Sdrh if( iDb<0 ) return; 424117435752Sdrh z = sqlite3NameFromToken(db, pObjName); 424284f31128Sdrh if( z==0 ) return; 42434343fea2Sdrh zDb = db->aDb[iDb].zName; 42444343fea2Sdrh pTab = sqlite3FindTable(db, z, zDb); 42454343fea2Sdrh if( pTab ){ 42464343fea2Sdrh reindexTable(pParse, pTab, 0); 4247633e6d57Sdrh sqlite3DbFree(db, z); 42484343fea2Sdrh return; 42494343fea2Sdrh } 42504343fea2Sdrh pIndex = sqlite3FindIndex(db, z, zDb); 4251633e6d57Sdrh sqlite3DbFree(db, z); 42524343fea2Sdrh if( pIndex ){ 42534343fea2Sdrh sqlite3BeginWriteOperation(pParse, 0, iDb); 42544343fea2Sdrh sqlite3RefillIndex(pParse, pIndex, -1); 42554343fea2Sdrh return; 42564343fea2Sdrh } 42574343fea2Sdrh sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed"); 42584343fea2Sdrh } 42594343fea2Sdrh #endif 4260b3bf556eSdanielk1977 4261b3bf556eSdanielk1977 /* 42622ec2fb22Sdrh ** Return a KeyInfo structure that is appropriate for the given Index. 4263b3bf556eSdanielk1977 ** 42642ec2fb22Sdrh ** The KeyInfo structure for an index is cached in the Index object. 42652ec2fb22Sdrh ** So there might be multiple references to the returned pointer. The 42662ec2fb22Sdrh ** caller should not try to modify the KeyInfo object. 42672ec2fb22Sdrh ** 42682ec2fb22Sdrh ** The caller should invoke sqlite3KeyInfoUnref() on the returned object 42692ec2fb22Sdrh ** when it has finished using it. 4270b3bf556eSdanielk1977 */ 42712ec2fb22Sdrh KeyInfo *sqlite3KeyInfoOfIndex(Parse *pParse, Index *pIdx){ 4272b3bf556eSdanielk1977 int i; 4273ad124329Sdrh int nCol = pIdx->nColumn; 4274ad124329Sdrh int nKey = pIdx->nKeyCol; 4275323df790Sdrh KeyInfo *pKey; 427618b67f3fSdrh if( pParse->nErr ) return 0; 42771153c7b2Sdrh if( pIdx->uniqNotNull ){ 4278ad124329Sdrh pKey = sqlite3KeyInfoAlloc(pParse->db, nKey, nCol-nKey); 42791153c7b2Sdrh }else{ 42801153c7b2Sdrh pKey = sqlite3KeyInfoAlloc(pParse->db, nCol, 0); 42811153c7b2Sdrh } 4282b3bf556eSdanielk1977 if( pKey ){ 42832ec2fb22Sdrh assert( sqlite3KeyInfoIsWriteable(pKey) ); 4284b3bf556eSdanielk1977 for(i=0; i<nCol; i++){ 4285b3bf556eSdanielk1977 char *zColl = pIdx->azColl[i]; 4286b8a9bb4fSdrh assert( zColl!=0 ); 4287b8a9bb4fSdrh pKey->aColl[i] = strcmp(zColl,"BINARY")==0 ? 0 : 4288b8a9bb4fSdrh sqlite3LocateCollSeq(pParse, zColl); 4289b3bf556eSdanielk1977 pKey->aSortOrder[i] = pIdx->aSortOrder[i]; 4290b3bf556eSdanielk1977 } 4291b3bf556eSdanielk1977 if( pParse->nErr ){ 42922ec2fb22Sdrh sqlite3KeyInfoUnref(pKey); 429318b67f3fSdrh pKey = 0; 4294b3bf556eSdanielk1977 } 42952ec2fb22Sdrh } 429618b67f3fSdrh return pKey; 4297b3bf556eSdanielk1977 } 42988b471863Sdrh 42998b471863Sdrh #ifndef SQLITE_OMIT_CTE 43007d562dbeSdan /* 43017d562dbeSdan ** This routine is invoked once per CTE by the parser while parsing a 43027d562dbeSdan ** WITH clause. 43038b471863Sdrh */ 43047d562dbeSdan With *sqlite3WithAdd( 43058b471863Sdrh Parse *pParse, /* Parsing context */ 43067d562dbeSdan With *pWith, /* Existing WITH clause, or NULL */ 43078b471863Sdrh Token *pName, /* Name of the common-table */ 43084e9119d9Sdan ExprList *pArglist, /* Optional column name list for the table */ 43098b471863Sdrh Select *pQuery /* Query used to initialize the table */ 43108b471863Sdrh ){ 43114e9119d9Sdan sqlite3 *db = pParse->db; 43124e9119d9Sdan With *pNew; 43134e9119d9Sdan char *zName; 43144e9119d9Sdan 43154e9119d9Sdan /* Check that the CTE name is unique within this WITH clause. If 43164e9119d9Sdan ** not, store an error in the Parse structure. */ 43174e9119d9Sdan zName = sqlite3NameFromToken(pParse->db, pName); 43184e9119d9Sdan if( zName && pWith ){ 43194e9119d9Sdan int i; 43204e9119d9Sdan for(i=0; i<pWith->nCte; i++){ 43214e9119d9Sdan if( sqlite3StrICmp(zName, pWith->a[i].zName)==0 ){ 4322727a99f1Sdrh sqlite3ErrorMsg(pParse, "duplicate WITH table name: %s", zName); 43234e9119d9Sdan } 43244e9119d9Sdan } 43254e9119d9Sdan } 43264e9119d9Sdan 43274e9119d9Sdan if( pWith ){ 43284e9119d9Sdan int nByte = sizeof(*pWith) + (sizeof(pWith->a[1]) * pWith->nCte); 43294e9119d9Sdan pNew = sqlite3DbRealloc(db, pWith, nByte); 43304e9119d9Sdan }else{ 43314e9119d9Sdan pNew = sqlite3DbMallocZero(db, sizeof(*pWith)); 43324e9119d9Sdan } 43334e9119d9Sdan assert( zName!=0 || pNew==0 ); 4334a9f5c13dSdan assert( db->mallocFailed==0 || pNew==0 ); 43354e9119d9Sdan 43364e9119d9Sdan if( pNew==0 ){ 43374e9119d9Sdan sqlite3ExprListDelete(db, pArglist); 43384e9119d9Sdan sqlite3SelectDelete(db, pQuery); 43394e9119d9Sdan sqlite3DbFree(db, zName); 4340a9f5c13dSdan pNew = pWith; 43414e9119d9Sdan }else{ 43424e9119d9Sdan pNew->a[pNew->nCte].pSelect = pQuery; 43434e9119d9Sdan pNew->a[pNew->nCte].pCols = pArglist; 43444e9119d9Sdan pNew->a[pNew->nCte].zName = zName; 4345f2655fe8Sdan pNew->a[pNew->nCte].zErr = 0; 43464e9119d9Sdan pNew->nCte++; 43474e9119d9Sdan } 43484e9119d9Sdan 43494e9119d9Sdan return pNew; 43508b471863Sdrh } 43518b471863Sdrh 43527d562dbeSdan /* 43537d562dbeSdan ** Free the contents of the With object passed as the second argument. 43548b471863Sdrh */ 43557d562dbeSdan void sqlite3WithDelete(sqlite3 *db, With *pWith){ 43564e9119d9Sdan if( pWith ){ 43574e9119d9Sdan int i; 43584e9119d9Sdan for(i=0; i<pWith->nCte; i++){ 43594e9119d9Sdan struct Cte *pCte = &pWith->a[i]; 43604e9119d9Sdan sqlite3ExprListDelete(db, pCte->pCols); 43614e9119d9Sdan sqlite3SelectDelete(db, pCte->pSelect); 43624e9119d9Sdan sqlite3DbFree(db, pCte->zName); 43634e9119d9Sdan } 43644e9119d9Sdan sqlite3DbFree(db, pWith); 43654e9119d9Sdan } 43668b471863Sdrh } 43678b471863Sdrh #endif /* !defined(SQLITE_OMIT_CTE) */ 4368