AryaWu/sqlite
0
1/*2** 2001 September 153**4** The author disclaims copyright to this source code. In place of5** a legal notice, here is a blessing:6**7** May you do good and not evil.8** May you find forgiveness for yourself and forgive others.9** May you share freely, never taking more than you give.10**11*************************************************************************12** This file contains C code routines that are called by the SQLite parser13** when syntax rules are reduced. The routines in this file handle the14** following kinds of SQL syntax:15**16** CREATE TABLE17** DROP TABLE18** CREATE INDEX19** DROP INDEX20** creating ID lists21** BEGIN TRANSACTION22** COMMIT23** ROLLBACK24*/25#include "sqliteInt.h"26 27#ifndef SQLITE_OMIT_SHARED_CACHE28/*29** The TableLock structure is only used by the sqlite3TableLock() and30** codeTableLocks() functions.31*/32struct TableLock {33 int iDb; /* The database containing the table to be locked */34 Pgno iTab; /* The root page of the table to be locked */35 u8 isWriteLock; /* True for write lock. False for a read lock */36 const char *zLockName; /* Name of the table */37};38 39/*40** Record the fact that we want to lock a table at run-time. 41**42** The table to be locked has root page iTab and is found in database iDb.43** A read or a write lock can be taken depending on isWritelock.44**45** This routine just records the fact that the lock is desired. The46** code to make the lock occur is generated by a later call to47** codeTableLocks() which occurs during sqlite3FinishCoding().48*/49static SQLITE_NOINLINE void lockTable(50 Parse *pParse, /* Parsing context */51 int iDb, /* Index of the database containing the table to lock */52 Pgno iTab, /* Root page number of the table to be locked */53 u8 isWriteLock, /* True for a write lock */54 const char *zName /* Name of the table to be locked */55){56 Parse *pToplevel;57 int i;58 int nBytes;59 TableLock *p;60 assert( iDb>=0 );61 62 pToplevel = sqlite3ParseToplevel(pParse);63 for(i=0; i<pToplevel->nTableLock; i++){64 p = &pToplevel->aTableLock[i];65 if( p->iDb==iDb && p->iTab==iTab ){66 p->isWriteLock = (p->isWriteLock || isWriteLock);67 return;68 }69 }70 71 assert( pToplevel->nTableLock < 0x7fff0000 );72 nBytes = sizeof(TableLock) * (pToplevel->nTableLock+1);73 pToplevel->aTableLock =74 sqlite3DbReallocOrFree(pToplevel->db, pToplevel->aTableLock, nBytes);75 if( pToplevel->aTableLock ){76 p = &pToplevel->aTableLock[pToplevel->nTableLock++];77 p->iDb = iDb;78 p->iTab = iTab;79 p->isWriteLock = isWriteLock;80 p->zLockName = zName;81 }else{82 pToplevel->nTableLock = 0;83 sqlite3OomFault(pToplevel->db);84 }85}86void sqlite3TableLock(87 Parse *pParse, /* Parsing context */88 int iDb, /* Index of the database containing the table to lock */89 Pgno iTab, /* Root page number of the table to be locked */90 u8 isWriteLock, /* True for a write lock */91 const char *zName /* Name of the table to be locked */92){93 if( iDb==1 ) return;94 if( !sqlite3BtreeSharable(pParse->db->aDb[iDb].pBt) ) return;95 lockTable(pParse, iDb, iTab, isWriteLock, zName);96}97 98/*99** Code an OP_TableLock instruction for each table locked by the100** statement (configured by calls to sqlite3TableLock()).101*/102static void codeTableLocks(Parse *pParse){103 int i;104 Vdbe *pVdbe = pParse->pVdbe;105 assert( pVdbe!=0 );106 107 for(i=0; i<pParse->nTableLock; i++){108 TableLock *p = &pParse->aTableLock[i];109 int p1 = p->iDb;110 sqlite3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, p->isWriteLock,111 p->zLockName, P4_STATIC);112 }113}114#else115 #define codeTableLocks(x)116#endif117 118/*119** Return TRUE if the given yDbMask object is empty - if it contains no120** 1 bits. This routine is used by the DbMaskAllZero() and DbMaskNotZero()121** macros when SQLITE_MAX_ATTACHED is greater than 30.122*/123#if SQLITE_MAX_ATTACHED>30124int sqlite3DbMaskAllZero(yDbMask m){125 int i;126 for(i=0; i<sizeof(yDbMask); i++) if( m[i] ) return 0;127 return 1;128}129#endif130 131/*132** This routine is called after a single SQL statement has been133** parsed and a VDBE program to execute that statement has been134** prepared. This routine puts the finishing touches on the135** VDBE program and resets the pParse structure for the next136** parse.137**138** Note that if an error occurred, it might be the case that139** no VDBE code was generated.140*/141void sqlite3FinishCoding(Parse *pParse){142 sqlite3 *db;143 Vdbe *v;144 int iDb, i;145 146 assert( pParse->pToplevel==0 );147 db = pParse->db;148 assert( db->pParse==pParse );149 if( pParse->nested ) return;150 if( pParse->nErr ){151 if( db->mallocFailed ) pParse->rc = SQLITE_NOMEM;152 return;153 }154 assert( db->mallocFailed==0 );155 156 /* Begin by generating some termination code at the end of the157 ** vdbe program158 */159 v = pParse->pVdbe;160 if( v==0 ){161 if( db->init.busy ){162 pParse->rc = SQLITE_DONE;163 return;164 }165 v = sqlite3GetVdbe(pParse);166 if( v==0 ) pParse->rc = SQLITE_ERROR;167 }168 assert( !pParse->isMultiWrite169 || sqlite3VdbeAssertMayAbort(v, pParse->mayAbort));170 if( v ){171 if( pParse->bReturning ){172 Returning *pReturning;173 int addrRewind;174 int reg;175 176 assert( !pParse->isCreate );177 pReturning = pParse->u1.d.pReturning;178 if( pReturning->nRetCol ){179 sqlite3VdbeAddOp0(v, OP_FkCheck);180 addrRewind =181 sqlite3VdbeAddOp1(v, OP_Rewind, pReturning->iRetCur);182 VdbeCoverage(v);183 reg = pReturning->iRetReg;184 for(i=0; i<pReturning->nRetCol; i++){185 sqlite3VdbeAddOp3(v, OP_Column, pReturning->iRetCur, i, reg+i);186 }187 sqlite3VdbeAddOp2(v, OP_ResultRow, reg, i);188 sqlite3VdbeAddOp2(v, OP_Next, pReturning->iRetCur, addrRewind+1);189 VdbeCoverage(v);190 sqlite3VdbeJumpHere(v, addrRewind);191 }192 }193 sqlite3VdbeAddOp0(v, OP_Halt);194 195 /* The cookie mask contains one bit for each database file open.196 ** (Bit 0 is for main, bit 1 is for temp, and so forth.) Bits are197 ** set for each database that is used. Generate code to start a198 ** transaction on each used database and to verify the schema cookie199 ** on each used database.200 */201 assert( pParse->nErr>0 || sqlite3VdbeGetOp(v, 0)->opcode==OP_Init );202 sqlite3VdbeJumpHere(v, 0);203 assert( db->nDb>0 );204 iDb = 0;205 do{206 Schema *pSchema;207 if( DbMaskTest(pParse->cookieMask, iDb)==0 ) continue;208 sqlite3VdbeUsesBtree(v, iDb);209 pSchema = db->aDb[iDb].pSchema;210 sqlite3VdbeAddOp4Int(v,211 OP_Transaction, /* Opcode */212 iDb, /* P1 */213 DbMaskTest(pParse->writeMask,iDb), /* P2 */214 pSchema->schema_cookie, /* P3 */215 pSchema->iGeneration /* P4 */216 );217 if( db->init.busy==0 ) sqlite3VdbeChangeP5(v, 1);218 VdbeComment((v,219 "usesStmtJournal=%d", pParse->mayAbort && pParse->isMultiWrite));220 }while( ++iDb<db->nDb );221#ifndef SQLITE_OMIT_VIRTUALTABLE222 for(i=0; i<pParse->nVtabLock; i++){223 char *vtab = (char *)sqlite3GetVTable(db, pParse->apVtabLock[i]);224 sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB);225 }226 pParse->nVtabLock = 0;227#endif228 229#ifndef SQLITE_OMIT_SHARED_CACHE230 /* Once all the cookies have been verified and transactions opened,231 ** obtain the required table-locks. This is a no-op unless the232 ** shared-cache feature is enabled.233 */234 if( pParse->nTableLock ) codeTableLocks(pParse);235#endif236 237 /* Initialize any AUTOINCREMENT data structures required.238 */239 if( pParse->pAinc ) sqlite3AutoincrementBegin(pParse);240 241 /* Code constant expressions that were factored out of inner loops. 242 */243 if( pParse->pConstExpr ){244 ExprList *pEL = pParse->pConstExpr;245 pParse->okConstFactor = 0;246 for(i=0; i<pEL->nExpr; i++){247 assert( pEL->a[i].u.iConstExprReg>0 );248 sqlite3ExprCode(pParse, pEL->a[i].pExpr, pEL->a[i].u.iConstExprReg);249 }250 }251 252 if( pParse->bReturning ){253 Returning *pRet;254 assert( !pParse->isCreate );255 pRet = pParse->u1.d.pReturning;256 if( pRet->nRetCol ){257 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pRet->iRetCur, pRet->nRetCol);258 }259 }260 261 /* Finally, jump back to the beginning of the executable code. */262 sqlite3VdbeGoto(v, 1);263 }264 265 /* Get the VDBE program ready for execution266 */267 assert( v!=0 || pParse->nErr );268 assert( db->mallocFailed==0 || pParse->nErr );269 if( pParse->nErr==0 ){270 /* A minimum of one cursor is required if autoincrement is used271 * See ticket [a696379c1f08866] */272 assert( pParse->pAinc==0 || pParse->nTab>0 );273 sqlite3VdbeMakeReady(v, pParse);274 pParse->rc = SQLITE_DONE;275 }else{276 pParse->rc = SQLITE_ERROR;277 }278}279 280/*281** Run the parser and code generator recursively in order to generate282** code for the SQL statement given onto the end of the pParse context283** currently under construction. Notes:284**285** * The final OP_Halt is not appended and other initialization286** and finalization steps are omitted because those are handling by the287** outermost parser.288**289** * Built-in SQL functions always take precedence over application-defined290** SQL functions. In other words, it is not possible to override a291** built-in function.292*/293void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){294 va_list ap;295 char *zSql;296 sqlite3 *db = pParse->db;297 u32 savedDbFlags = db->mDbFlags;298 char saveBuf[PARSE_TAIL_SZ];299 300 if( pParse->nErr ) return;301 if( pParse->eParseMode ) return;302 assert( pParse->nested<10 ); /* Nesting should only be of limited depth */303 va_start(ap, zFormat);304 zSql = sqlite3VMPrintf(db, zFormat, ap);305 va_end(ap);306 if( zSql==0 ){307 /* This can result either from an OOM or because the formatted string308 ** exceeds SQLITE_LIMIT_LENGTH. In the latter case, we need to set309 ** an error */310 if( !db->mallocFailed ) pParse->rc = SQLITE_TOOBIG;311 pParse->nErr++;312 return;313 }314 pParse->nested++;315 memcpy(saveBuf, PARSE_TAIL(pParse), PARSE_TAIL_SZ);316 memset(PARSE_TAIL(pParse), 0, PARSE_TAIL_SZ);317 db->mDbFlags |= DBFLAG_PreferBuiltin;318 sqlite3RunParser(pParse, zSql);319 db->mDbFlags = savedDbFlags;320 sqlite3DbFree(db, zSql);321 memcpy(PARSE_TAIL(pParse), saveBuf, PARSE_TAIL_SZ);322 pParse->nested--;323}324 325/*326** Locate the in-memory structure that describes a particular database327** table given the name of that table and (optionally) the name of the328** database containing the table. Return NULL if not found.329**330** If zDatabase is 0, all databases are searched for the table and the331** first matching table is returned. (No checking for duplicate table332** names is done.) The search order is TEMP first, then MAIN, then any333** auxiliary databases added using the ATTACH command.334**335** See also sqlite3LocateTable().336*/337Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){338 Table *p = 0;339 int i;340 341 /* All mutexes are required for schema access. Make sure we hold them. */342 assert( zDatabase!=0 || sqlite3BtreeHoldsAllMutexes(db) );343 if( zDatabase ){344 for(i=0; i<db->nDb; i++){345 if( sqlite3StrICmp(zDatabase, db->aDb[i].zDbSName)==0 ) break;346 }347 if( i>=db->nDb ){348 /* No match against the official names. But always match "main"349 ** to schema 0 as a legacy fallback. */350 if( sqlite3StrICmp(zDatabase,"main")==0 ){351 i = 0;352 }else{353 return 0;354 }355 }356 p = sqlite3HashFind(&db->aDb[i].pSchema->tblHash, zName);357 if( p==0 && sqlite3StrNICmp(zName, "sqlite_", 7)==0 ){358 if( i==1 ){359 if( sqlite3StrICmp(zName+7, &PREFERRED_TEMP_SCHEMA_TABLE[7])==0360 || sqlite3StrICmp(zName+7, &PREFERRED_SCHEMA_TABLE[7])==0361 || sqlite3StrICmp(zName+7, &LEGACY_SCHEMA_TABLE[7])==0362 ){363 p = sqlite3HashFind(&db->aDb[1].pSchema->tblHash,364 LEGACY_TEMP_SCHEMA_TABLE);365 }366 }else{367 if( sqlite3StrICmp(zName+7, &PREFERRED_SCHEMA_TABLE[7])==0 ){368 p = sqlite3HashFind(&db->aDb[i].pSchema->tblHash,369 LEGACY_SCHEMA_TABLE);370 }371 }372 }373 }else{374 /* Match against TEMP first */375 p = sqlite3HashFind(&db->aDb[1].pSchema->tblHash, zName);376 if( p ) return p;377 /* The main database is second */378 p = sqlite3HashFind(&db->aDb[0].pSchema->tblHash, zName);379 if( p ) return p;380 /* Attached databases are in order of attachment */381 for(i=2; i<db->nDb; i++){382 assert( sqlite3SchemaMutexHeld(db, i, 0) );383 p = sqlite3HashFind(&db->aDb[i].pSchema->tblHash, zName);384 if( p ) break;385 }386 if( p==0 && sqlite3StrNICmp(zName, "sqlite_", 7)==0 ){387 if( sqlite3StrICmp(zName+7, &PREFERRED_SCHEMA_TABLE[7])==0 ){388 p = sqlite3HashFind(&db->aDb[0].pSchema->tblHash, LEGACY_SCHEMA_TABLE);389 }else if( sqlite3StrICmp(zName+7, &PREFERRED_TEMP_SCHEMA_TABLE[7])==0 ){390 p = sqlite3HashFind(&db->aDb[1].pSchema->tblHash,391 LEGACY_TEMP_SCHEMA_TABLE);392 }393 }394 }395 return p;396}397 398/*399** Locate the in-memory structure that describes a particular database400** table given the name of that table and (optionally) the name of the401** database containing the table. Return NULL if not found. Also leave an402** error message in pParse->zErrMsg.403**404** The difference between this routine and sqlite3FindTable() is that this405** routine leaves an error message in pParse->zErrMsg where406** sqlite3FindTable() does not.407*/408Table *sqlite3LocateTable(409 Parse *pParse, /* context in which to report errors */410 u32 flags, /* LOCATE_VIEW or LOCATE_NOERR */411 const char *zName, /* Name of the table we are looking for */412 const char *zDbase /* Name of the database. Might be NULL */413){414 Table *p;415 sqlite3 *db = pParse->db;416 417 /* Read the database schema. If an error occurs, leave an error message418 ** and code in pParse and return NULL. */419 if( (db->mDbFlags & DBFLAG_SchemaKnownOk)==0420 && SQLITE_OK!=sqlite3ReadSchema(pParse)421 ){422 return 0;423 }424 425 p = sqlite3FindTable(db, zName, zDbase);426 if( p==0 ){427#ifndef SQLITE_OMIT_VIRTUALTABLE428 /* If zName is the not the name of a table in the schema created using429 ** CREATE, then check to see if it is the name of an virtual table that430 ** can be an eponymous virtual table. */431 if( (pParse->prepFlags & SQLITE_PREPARE_NO_VTAB)==0 && db->init.busy==0 ){432 Module *pMod = (Module*)sqlite3HashFind(&db->aModule, zName);433 if( pMod==0 && sqlite3_strnicmp(zName, "pragma_", 7)==0 ){434 pMod = sqlite3PragmaVtabRegister(db, zName);435 }436#ifndef SQLITE_OMIT_JSON437 if( pMod==0 && sqlite3_strnicmp(zName, "json", 4)==0 ){438 pMod = sqlite3JsonVtabRegister(db, zName);439 }440#endif441#ifdef SQLITE_ENABLE_CARRAY442 if( pMod==0 && sqlite3_stricmp(zName, "carray")==0 ){443 pMod = sqlite3CarrayRegister(db);444 }445#endif446 if( pMod && sqlite3VtabEponymousTableInit(pParse, pMod) ){447 testcase( pMod->pEpoTab==0 );448 return pMod->pEpoTab;449 }450 }451#endif452 if( flags & LOCATE_NOERR ) return 0;453 pParse->checkSchema = 1;454 }else if( IsVirtual(p) && (pParse->prepFlags & SQLITE_PREPARE_NO_VTAB)!=0 ){455 p = 0;456 }457 458 if( p==0 ){459 const char *zMsg = flags & LOCATE_VIEW ? "no such view" : "no such table";460 if( zDbase ){461 sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName);462 }else{463 sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName);464 }465 }else{466 assert( HasRowid(p) || p->iPKey<0 );467 }468 469 return p;470}471 472/*473** Locate the table identified by *p.474**475** This is a wrapper around sqlite3LocateTable(). The difference between476** sqlite3LocateTable() and this function is that this function restricts477** the search to schema (p->pSchema) if it is not NULL. p->pSchema may be478** non-NULL if it is part of a view or trigger program definition. See479** sqlite3FixSrcList() for details.480*/481Table *sqlite3LocateTableItem(482 Parse *pParse,483 u32 flags,484 SrcItem *p485){486 const char *zDb;487 if( p->fg.fixedSchema ){488 int iDb = sqlite3SchemaToIndex(pParse->db, p->u4.pSchema);489 zDb = pParse->db->aDb[iDb].zDbSName;490 }else{491 assert( !p->fg.isSubquery );492 zDb = p->u4.zDatabase;493 }494 return sqlite3LocateTable(pParse, flags, p->zName, zDb);495}496 497/*498** Return the preferred table name for system tables. Translate legacy499** names into the new preferred names, as appropriate.500*/501const char *sqlite3PreferredTableName(const char *zName){502 if( sqlite3StrNICmp(zName, "sqlite_", 7)==0 ){503 if( sqlite3StrICmp(zName+7, &LEGACY_SCHEMA_TABLE[7])==0 ){504 return PREFERRED_SCHEMA_TABLE;505 }506 if( sqlite3StrICmp(zName+7, &LEGACY_TEMP_SCHEMA_TABLE[7])==0 ){507 return PREFERRED_TEMP_SCHEMA_TABLE;508 }509 }510 return zName;511}512 513/*514** Locate the in-memory structure that describes515** a particular index given the name of that index516** and the name of the database that contains the index.517** Return NULL if not found.518**519** If zDatabase is 0, all databases are searched for the520** table and the first matching index is returned. (No checking521** for duplicate index names is done.) The search order is522** TEMP first, then MAIN, then any auxiliary databases added523** using the ATTACH command.524*/525Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){526 Index *p = 0;527 int i;528 /* All mutexes are required for schema access. Make sure we hold them. */529 assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );530 for(i=OMIT_TEMPDB; i<db->nDb; i++){531 int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */532 Schema *pSchema = db->aDb[j].pSchema;533 assert( pSchema );534 if( zDb && sqlite3DbIsNamed(db, j, zDb)==0 ) continue;535 assert( sqlite3SchemaMutexHeld(db, j, 0) );536 p = sqlite3HashFind(&pSchema->idxHash, zName);537 if( p ) break;538 }539 return p;540}541 542/*543** Reclaim the memory used by an index544*/545void sqlite3FreeIndex(sqlite3 *db, Index *p){546#ifndef SQLITE_OMIT_ANALYZE547 sqlite3DeleteIndexSamples(db, p);548#endif549 sqlite3ExprDelete(db, p->pPartIdxWhere);550 sqlite3ExprListDelete(db, p->aColExpr);551 sqlite3DbFree(db, p->zColAff);552 if( p->isResized ) sqlite3DbFree(db, (void *)p->azColl);553#ifdef SQLITE_ENABLE_STAT4554 sqlite3_free(p->aiRowEst);555#endif556 sqlite3DbFree(db, p);557}558 559/*560** For the index called zIdxName which is found in the database iDb,561** unlike that index from its Table then remove the index from562** the index hash table and free all memory structures associated563** with the index.564*/565void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){566 Index *pIndex;567 Hash *pHash;568 569 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );570 pHash = &db->aDb[iDb].pSchema->idxHash;571 pIndex = sqlite3HashInsert(pHash, zIdxName, 0);572 if( ALWAYS(pIndex) ){573 if( pIndex->pTable->pIndex==pIndex ){574 pIndex->pTable->pIndex = pIndex->pNext;575 }else{576 Index *p;577 /* Justification of ALWAYS(); The index must be on the list of578 ** indices. */579 p = pIndex->pTable->pIndex;580 while( ALWAYS(p) && p->pNext!=pIndex ){ p = p->pNext; }581 if( ALWAYS(p && p->pNext==pIndex) ){582 p->pNext = pIndex->pNext;583 }584 }585 sqlite3FreeIndex(db, pIndex);586 }587 db->mDbFlags |= DBFLAG_SchemaChange;588}589 590/*591** Look through the list of open database files in db->aDb[] and if592** any have been closed, remove them from the list. Reallocate the593** db->aDb[] structure to a smaller size, if possible.594**595** Entry 0 (the "main" database) and entry 1 (the "temp" database)596** are never candidates for being collapsed.597*/598void sqlite3CollapseDatabaseArray(sqlite3 *db){599 int i, j;600 for(i=j=2; i<db->nDb; i++){601 struct Db *pDb = &db->aDb[i];602 if( pDb->pBt==0 ){603 sqlite3DbFree(db, pDb->zDbSName);604 pDb->zDbSName = 0;605 continue;606 }607 if( j<i ){608 db->aDb[j] = db->aDb[i];609 }610 j++;611 }612 db->nDb = j;613 if( db->nDb<=2 && db->aDb!=db->aDbStatic ){614 memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));615 sqlite3DbFree(db, db->aDb);616 db->aDb = db->aDbStatic;617 }618}619 620/*621** Reset the schema for the database at index iDb. Also reset the622** TEMP schema. The reset is deferred if db->nSchemaLock is not zero.623** Deferred resets may be run by calling with iDb<0.624*/625void sqlite3ResetOneSchema(sqlite3 *db, int iDb){626 int i;627 assert( iDb<db->nDb );628 629 if( iDb>=0 ){630 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );631 DbSetProperty(db, iDb, DB_ResetWanted);632 DbSetProperty(db, 1, DB_ResetWanted);633 db->mDbFlags &= ~DBFLAG_SchemaKnownOk;634 }635 636 if( db->nSchemaLock==0 ){637 for(i=0; i<db->nDb; i++){638 if( DbHasProperty(db, i, DB_ResetWanted) ){639 sqlite3SchemaClear(db->aDb[i].pSchema);640 }641 }642 }643}644 645/*646** Erase all schema information from all attached databases (including647** "main" and "temp") for a single database connection.648*/649void sqlite3ResetAllSchemasOfConnection(sqlite3 *db){650 int i;651 sqlite3BtreeEnterAll(db);652 for(i=0; i<db->nDb; i++){653 Db *pDb = &db->aDb[i];654 if( pDb->pSchema ){655 if( db->nSchemaLock==0 ){656 sqlite3SchemaClear(pDb->pSchema);657 }else{658 DbSetProperty(db, i, DB_ResetWanted);659 }660 }661 }662 db->mDbFlags &= ~(DBFLAG_SchemaChange|DBFLAG_SchemaKnownOk);663 sqlite3VtabUnlockList(db);664 sqlite3BtreeLeaveAll(db);665 if( db->nSchemaLock==0 ){666 sqlite3CollapseDatabaseArray(db);667 }668}669 670/*671** This routine is called when a commit occurs.672*/673void sqlite3CommitInternalChanges(sqlite3 *db){674 db->mDbFlags &= ~DBFLAG_SchemaChange;675}676 677/*678** Set the expression associated with a column. This is usually679** the DEFAULT value, but might also be the expression that computes680** the value for a generated column.681*/682void sqlite3ColumnSetExpr(683 Parse *pParse, /* Parsing context */684 Table *pTab, /* The table containing the column */685 Column *pCol, /* The column to receive the new DEFAULT expression */686 Expr *pExpr /* The new default expression */687){688 ExprList *pList;689 assert( IsOrdinaryTable(pTab) );690 pList = pTab->u.tab.pDfltList;691 if( pCol->iDflt==0692 || NEVER(pList==0)693 || NEVER(pList->nExpr<pCol->iDflt)694 ){695 pCol->iDflt = pList==0 ? 1 : pList->nExpr+1;696 pTab->u.tab.pDfltList = sqlite3ExprListAppend(pParse, pList, pExpr);697 }else{698 sqlite3ExprDelete(pParse->db, pList->a[pCol->iDflt-1].pExpr);699 pList->a[pCol->iDflt-1].pExpr = pExpr;700 }701}702 703/*704** Return the expression associated with a column. The expression might be705** the DEFAULT clause or the AS clause of a generated column.706** Return NULL if the column has no associated expression.707*/708Expr *sqlite3ColumnExpr(Table *pTab, Column *pCol){709 if( pCol->iDflt==0 ) return 0;710 if( !IsOrdinaryTable(pTab) ) return 0;711 if( NEVER(pTab->u.tab.pDfltList==0) ) return 0;712 if( NEVER(pTab->u.tab.pDfltList->nExpr<pCol->iDflt) ) return 0;713 return pTab->u.tab.pDfltList->a[pCol->iDflt-1].pExpr;714}715 716/*717** Set the collating sequence name for a column.718*/719void sqlite3ColumnSetColl(720 sqlite3 *db,721 Column *pCol,722 const char *zColl723){724 i64 nColl;725 i64 n;726 char *zNew;727 assert( zColl!=0 );728 n = sqlite3Strlen30(pCol->zCnName) + 1;729 if( pCol->colFlags & COLFLAG_HASTYPE ){730 n += sqlite3Strlen30(pCol->zCnName+n) + 1;731 }732 nColl = sqlite3Strlen30(zColl) + 1;733 zNew = sqlite3DbRealloc(db, pCol->zCnName, nColl+n);734 if( zNew ){735 pCol->zCnName = zNew;736 memcpy(pCol->zCnName + n, zColl, nColl);737 pCol->colFlags |= COLFLAG_HASCOLL;738 }739}740 741/*742** Return the collating sequence name for a column743*/744const char *sqlite3ColumnColl(Column *pCol){745 const char *z;746 if( (pCol->colFlags & COLFLAG_HASCOLL)==0 ) return 0;747 z = pCol->zCnName;748 while( *z ){ z++; }749 if( pCol->colFlags & COLFLAG_HASTYPE ){750 do{ z++; }while( *z );751 }752 return z+1;753}754 755/*756** Delete memory allocated for the column names of a table or view (the757** Table.aCol[] array).758*/759void sqlite3DeleteColumnNames(sqlite3 *db, Table *pTable){760 int i;761 Column *pCol;762 assert( pTable!=0 );763 assert( db!=0 );764 if( (pCol = pTable->aCol)!=0 ){765 for(i=0; i<pTable->nCol; i++, pCol++){766 assert( pCol->zCnName==0 || pCol->hName==sqlite3StrIHash(pCol->zCnName) );767 sqlite3DbFree(db, pCol->zCnName);768 }769 sqlite3DbNNFreeNN(db, pTable->aCol);770 if( IsOrdinaryTable(pTable) ){771 sqlite3ExprListDelete(db, pTable->u.tab.pDfltList);772 }773 if( db->pnBytesFreed==0 ){774 pTable->aCol = 0;775 pTable->nCol = 0;776 if( IsOrdinaryTable(pTable) ){777 pTable->u.tab.pDfltList = 0;778 }779 }780 }781}782 783/*784** Remove the memory data structures associated with the given785** Table. No changes are made to disk by this routine.786**787** This routine just deletes the data structure. It does not unlink788** the table data structure from the hash table. But it does destroy789** memory structures of the indices and foreign keys associated with790** the table.791**792** The db parameter is optional. It is needed if the Table object793** contains lookaside memory. (Table objects in the schema do not use794** lookaside memory, but some ephemeral Table objects do.) Or the795** db parameter can be used with db->pnBytesFreed to measure the memory796** used by the Table object.797*/798static void SQLITE_NOINLINE deleteTable(sqlite3 *db, Table *pTable){799 Index *pIndex, *pNext;800 801#ifdef SQLITE_DEBUG802 /* Record the number of outstanding lookaside allocations in schema Tables803 ** prior to doing any free() operations. Since schema Tables do not use804 ** lookaside, this number should not change.805 **806 ** If malloc has already failed, it may be that it failed while allocating807 ** a Table object that was going to be marked ephemeral. So do not check808 ** that no lookaside memory is used in this case either. */809 int nLookaside = 0;810 assert( db!=0 );811 if( !db->mallocFailed && (pTable->tabFlags & TF_Ephemeral)==0 ){812 nLookaside = sqlite3LookasideUsed(db, 0);813 }814#endif815 816 /* Delete all indices associated with this table. */817 for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){818 pNext = pIndex->pNext;819 assert( pIndex->pSchema==pTable->pSchema820 || (IsVirtual(pTable) && pIndex->idxType!=SQLITE_IDXTYPE_APPDEF) );821 if( db->pnBytesFreed==0 && !IsVirtual(pTable) ){822 char *zName = pIndex->zName;823 TESTONLY ( Index *pOld = ) sqlite3HashInsert(824 &pIndex->pSchema->idxHash, zName, 0825 );826 assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );827 assert( pOld==pIndex || pOld==0 );828 }829 sqlite3FreeIndex(db, pIndex);830 }831 832 if( IsOrdinaryTable(pTable) ){833 sqlite3FkDelete(db, pTable);834 }835#ifndef SQLITE_OMIT_VIRTUALTABLE836 else if( IsVirtual(pTable) ){837 sqlite3VtabClear(db, pTable);838 }839#endif840 else{841 assert( IsView(pTable) );842 sqlite3SelectDelete(db, pTable->u.view.pSelect);843 }844 845 /* Delete the Table structure itself.846 */847 sqlite3DeleteColumnNames(db, pTable);848 sqlite3DbFree(db, pTable->zName);849 sqlite3DbFree(db, pTable->zColAff);850 sqlite3ExprListDelete(db, pTable->pCheck);851 sqlite3DbFree(db, pTable);852 853 /* Verify that no lookaside memory was used by schema tables */854 assert( nLookaside==0 || nLookaside==sqlite3LookasideUsed(db,0) );855}856void sqlite3DeleteTable(sqlite3 *db, Table *pTable){857 /* Do not delete the table until the reference count reaches zero. */858 assert( db!=0 );859 if( !pTable ) return;860 if( db->pnBytesFreed==0 && (--pTable->nTabRef)>0 ) return;861 deleteTable(db, pTable);862}863void sqlite3DeleteTableGeneric(sqlite3 *db, void *pTable){864 sqlite3DeleteTable(db, (Table*)pTable);865}866 867 868/*869** Unlink the given table from the hash tables and the delete the870** table structure with all its indices and foreign keys.871*/872void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){873 Table *p;874 Db *pDb;875 876 assert( db!=0 );877 assert( iDb>=0 && iDb<db->nDb );878 assert( zTabName );879 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );880 testcase( zTabName[0]==0 ); /* Zero-length table names are allowed */881 pDb = &db->aDb[iDb];882 p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName, 0);883 sqlite3DeleteTable(db, p);884 db->mDbFlags |= DBFLAG_SchemaChange;885}886 887/*888** Given a token, return a string that consists of the text of that889** token. Space to hold the returned string890** is obtained from sqliteMalloc() and must be freed by the calling891** function.892**893** Any quotation marks (ex: "name", 'name', [name], or `name`) that894** surround the body of the token are removed.895**896** Tokens are often just pointers into the original SQL text and so897** are not \000 terminated and are not persistent. The returned string898** is \000 terminated and is persistent.899*/900char *sqlite3NameFromToken(sqlite3 *db, const Token *pName){901 char *zName;902 if( pName ){903 zName = sqlite3DbStrNDup(db, (const char*)pName->z, pName->n);904 sqlite3Dequote(zName);905 }else{906 zName = 0;907 }908 return zName;909}910 911/*912** Open the sqlite_schema table stored in database number iDb for913** writing. The table is opened using cursor 0.914*/915void sqlite3OpenSchemaTable(Parse *p, int iDb){916 Vdbe *v = sqlite3GetVdbe(p);917 sqlite3TableLock(p, iDb, SCHEMA_ROOT, 1, LEGACY_SCHEMA_TABLE);918 sqlite3VdbeAddOp4Int(v, OP_OpenWrite, 0, SCHEMA_ROOT, iDb, 5);919 if( p->nTab==0 ){920 p->nTab = 1;921 }922}923 924/*925** Parameter zName points to a nul-terminated buffer containing the name926** of a database ("main", "temp" or the name of an attached db). This927** function returns the index of the named database in db->aDb[], or928** -1 if the named db cannot be found.929*/930int sqlite3FindDbName(sqlite3 *db, const char *zName){931 int i = -1; /* Database number */932 if( zName ){933 Db *pDb;934 for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){935 if( 0==sqlite3_stricmp(pDb->zDbSName, zName) ) break;936 /* "main" is always an acceptable alias for the primary database937 ** even if it has been renamed using SQLITE_DBCONFIG_MAINDBNAME. */938 if( i==0 && 0==sqlite3_stricmp("main", zName) ) break;939 }940 }941 return i;942}943 944/*945** The token *pName contains the name of a database (either "main" or946** "temp" or the name of an attached db). This routine returns the947** index of the named database in db->aDb[], or -1 if the named db948** does not exist.949*/950int sqlite3FindDb(sqlite3 *db, Token *pName){951 int i; /* Database number */952 char *zName; /* Name we are searching for */953 zName = sqlite3NameFromToken(db, pName);954 i = sqlite3FindDbName(db, zName);955 sqlite3DbFree(db, zName);956 return i;957}958 959/* The table or view or trigger name is passed to this routine via tokens960** pName1 and pName2. If the table name was fully qualified, for example:961**962** CREATE TABLE xxx.yyy (...);963**964** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if965** the table name is not fully qualified, i.e.:966**967** CREATE TABLE yyy(...);968**969** Then pName1 is set to "yyy" and pName2 is "".970**971** This routine sets the *ppUnqual pointer to point at the token (pName1 or972** pName2) that stores the unqualified table name. The index of the973** database "xxx" is returned.974*/975int sqlite3TwoPartName(976 Parse *pParse, /* Parsing and code generating context */977 Token *pName1, /* The "xxx" in the name "xxx.yyy" or "xxx" */978 Token *pName2, /* The "yyy" in the name "xxx.yyy" */979 Token **pUnqual /* Write the unqualified object name here */980){981 int iDb; /* Database holding the object */982 sqlite3 *db = pParse->db;983 984 assert( pName2!=0 );985 if( pName2->n>0 ){986 if( db->init.busy ) {987 sqlite3ErrorMsg(pParse, "corrupt database");988 return -1;989 }990 *pUnqual = pName2;991 iDb = sqlite3FindDb(db, pName1);992 if( iDb<0 ){993 sqlite3ErrorMsg(pParse, "unknown database %T", pName1);994 return -1;995 }996 }else{997 assert( db->init.iDb==0 || db->init.busy || IN_SPECIAL_PARSE998 || (db->mDbFlags & DBFLAG_Vacuum)!=0);999 iDb = db->init.iDb;1000 *pUnqual = pName1;1001 }1002 return iDb;1003}1004 1005/*1006** True if PRAGMA writable_schema is ON1007*/1008int sqlite3WritableSchema(sqlite3 *db){1009 testcase( (db->flags&(SQLITE_WriteSchema|SQLITE_Defensive))==0 );1010 testcase( (db->flags&(SQLITE_WriteSchema|SQLITE_Defensive))==1011 SQLITE_WriteSchema );1012 testcase( (db->flags&(SQLITE_WriteSchema|SQLITE_Defensive))==1013 SQLITE_Defensive );1014 testcase( (db->flags&(SQLITE_WriteSchema|SQLITE_Defensive))==1015 (SQLITE_WriteSchema|SQLITE_Defensive) );1016 return (db->flags&(SQLITE_WriteSchema|SQLITE_Defensive))==SQLITE_WriteSchema;1017}1018 1019/*1020** This routine is used to check if the UTF-8 string zName is a legal1021** unqualified name for a new schema object (table, index, view or1022** trigger). All names are legal except those that begin with the string1023** "sqlite_" (in upper, lower or mixed case). This portion of the namespace1024** is reserved for internal use.1025**1026** When parsing the sqlite_schema table, this routine also checks to1027** make sure the "type", "name", and "tbl_name" columns are consistent1028** with the SQL.1029*/1030int sqlite3CheckObjectName(1031 Parse *pParse, /* Parsing context */1032 const char *zName, /* Name of the object to check */1033 const char *zType, /* Type of this object */1034 const char *zTblName /* Parent table name for triggers and indexes */1035){1036 sqlite3 *db = pParse->db;1037 if( sqlite3WritableSchema(db)1038 || db->init.imposterTable1039 || !sqlite3Config.bExtraSchemaChecks1040 ){1041 /* Skip these error checks for writable_schema=ON */1042 return SQLITE_OK;1043 }1044 if( db->init.busy ){1045 if( sqlite3_stricmp(zType, db->init.azInit[0])1046 || sqlite3_stricmp(zName, db->init.azInit[1])1047 || sqlite3_stricmp(zTblName, db->init.azInit[2])1048 ){1049 sqlite3ErrorMsg(pParse, ""); /* corruptSchema() will supply the error */1050 return SQLITE_ERROR;1051 }1052 }else{1053 if( (pParse->nested==0 && 0==sqlite3StrNICmp(zName, "sqlite_", 7))1054 || (sqlite3ReadOnlyShadowTables(db) && sqlite3ShadowTableName(db, zName))1055 ){1056 sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s",1057 zName);1058 return SQLITE_ERROR;1059 }1060 1061 }1062 return SQLITE_OK;1063}1064 1065/*1066** Return the PRIMARY KEY index of a table1067*/1068Index *sqlite3PrimaryKeyIndex(Table *pTab){1069 Index *p;1070 for(p=pTab->pIndex; p && !IsPrimaryKeyIndex(p); p=p->pNext){}1071 return p;1072}1073 1074/*1075** Convert an table column number into a index column number. That is,1076** for the column iCol in the table (as defined by the CREATE TABLE statement)1077** find the (first) offset of that column in index pIdx. Or return -11078** if column iCol is not used in index pIdx.1079*/1080int sqlite3TableColumnToIndex(Index *pIdx, int iCol){1081 int i;1082 i16 iCol16;1083 assert( iCol>=(-1) && iCol<=SQLITE_MAX_COLUMN );1084 assert( pIdx->nColumn<=SQLITE_MAX_COLUMN*2 );1085 iCol16 = iCol;1086 for(i=0; i<pIdx->nColumn; i++){1087 if( iCol16==pIdx->aiColumn[i] ){1088 return i;1089 }1090 }1091 return -1;1092}1093 1094#ifndef SQLITE_OMIT_GENERATED_COLUMNS1095/* Convert a storage column number into a table column number.1096**1097** The storage column number (0,1,2,....) is the index of the value1098** as it appears in the record on disk. The true column number1099** is the index (0,1,2,...) of the column in the CREATE TABLE statement.1100**1101** The storage column number is less than the table column number if1102** and only there are VIRTUAL columns to the left.1103**1104** If SQLITE_OMIT_GENERATED_COLUMNS, this routine is a no-op macro.1105*/1106i16 sqlite3StorageColumnToTable(Table *pTab, i16 iCol){1107 if( pTab->tabFlags & TF_HasVirtual ){1108 int i;1109 for(i=0; i<=iCol; i++){1110 if( pTab->aCol[i].colFlags & COLFLAG_VIRTUAL ) iCol++;1111 }1112 }1113 return iCol;1114}1115#endif1116 1117#ifndef SQLITE_OMIT_GENERATED_COLUMNS1118/* Convert a table column number into a storage column number.1119**1120** The storage column number (0,1,2,....) is the index of the value1121** as it appears in the record on disk. Or, if the input column is1122** the N-th virtual column (zero-based) then the storage number is1123** the number of non-virtual columns in the table plus N. 1124**1125** The true column number is the index (0,1,2,...) of the column in1126** the CREATE TABLE statement.1127**1128** If the input column is a VIRTUAL column, then it should not appear1129** in storage. But the value sometimes is cached in registers that1130** follow the range of registers used to construct storage. This1131** avoids computing the same VIRTUAL column multiple times, and provides1132** values for use by OP_Param opcodes in triggers. Hence, if the1133** input column is a VIRTUAL table, put it after all the other columns.1134**1135** In the following, N means "normal column", S means STORED, and1136** V means VIRTUAL. Suppose the CREATE TABLE has columns like this:1137**1138** CREATE TABLE ex(N,S,V,N,S,V,N,S,V);1139** -- 0 1 2 3 4 5 6 7 81140**1141** Then the mapping from this function is as follows:1142**1143** INPUTS: 0 1 2 3 4 5 6 7 81144** OUTPUTS: 0 1 6 2 3 7 4 5 81145**1146** So, in other words, this routine shifts all the virtual columns to1147** the end.1148**1149** If SQLITE_OMIT_GENERATED_COLUMNS then there are no virtual columns and1150** this routine is a no-op macro. If the pTab does not have any virtual1151** columns, then this routine is no-op that always return iCol. If iCol1152** is negative (indicating the ROWID column) then this routine return iCol.1153*/1154i16 sqlite3TableColumnToStorage(Table *pTab, i16 iCol){1155 int i;1156 i16 n;1157 assert( iCol<pTab->nCol );1158 if( (pTab->tabFlags & TF_HasVirtual)==0 || iCol<0 ) return iCol;1159 for(i=0, n=0; i<iCol; i++){1160 if( (pTab->aCol[i].colFlags & COLFLAG_VIRTUAL)==0 ) n++;1161 }1162 if( pTab->aCol[i].colFlags & COLFLAG_VIRTUAL ){1163 /* iCol is a virtual column itself */1164 return pTab->nNVCol + i - n;1165 }else{1166 /* iCol is a normal or stored column */1167 return n;1168 }1169}1170#endif1171 1172/*1173** Insert a single OP_JournalMode query opcode in order to force the1174** prepared statement to return false for sqlite3_stmt_readonly(). This1175** is used by CREATE TABLE IF NOT EXISTS and similar if the table already1176** exists, so that the prepared statement for CREATE TABLE IF NOT EXISTS1177** will return false for sqlite3_stmt_readonly() even if that statement1178** is a read-only no-op.1179*/1180static void sqlite3ForceNotReadOnly(Parse *pParse){1181 int iReg = ++pParse->nMem;1182 Vdbe *v = sqlite3GetVdbe(pParse);1183 if( v ){1184 sqlite3VdbeAddOp3(v, OP_JournalMode, 0, iReg, PAGER_JOURNALMODE_QUERY);1185 sqlite3VdbeUsesBtree(v, 0);1186 }1187}1188 1189/*1190** Begin constructing a new table representation in memory. This is1191** the first of several action routines that get called in response1192** to a CREATE TABLE statement. In particular, this routine is called1193** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp1194** flag is true if the table should be stored in the auxiliary database1195** file instead of in the main database file. This is normally the case1196** when the "TEMP" or "TEMPORARY" keyword occurs in between1197** CREATE and TABLE.1198**1199** The new table record is initialized and put in pParse->pNewTable.1200** As more of the CREATE TABLE statement is parsed, additional action