ds@1952: /* ds@1952: ** 2001 September 15 ds@1952: ** ds@1952: ** The author disclaims copyright to this source code. In place of ds@1952: ** a legal notice, here is a blessing: ds@1952: ** ds@1952: ** May you do good and not evil. ds@1952: ** May you find forgiveness for yourself and forgive others. ds@1952: ** May you share freely, never taking more than you give. ds@1952: ** ds@1952: ************************************************************************* ds@1952: ** This file contains C code routines that are called by the SQLite parser ds@1952: ** when syntax rules are reduced. The routines in this file handle the ds@1952: ** following kinds of SQL syntax: ds@1952: ** ds@1952: ** CREATE TABLE ds@1952: ** DROP TABLE ds@1952: ** CREATE INDEX ds@1952: ** DROP INDEX ds@1952: ** creating ID lists ds@1952: ** BEGIN TRANSACTION ds@1952: ** COMMIT ds@1952: ** ROLLBACK ds@1952: ** ds@1952: ** $Id$ ds@1952: */ ds@1952: #include "sqliteInt.h" ds@1952: #include ds@1952: ds@1952: /* ds@1952: ** This routine is called when a new SQL statement is beginning to ds@1952: ** be parsed. Initialize the pParse structure as needed. ds@1952: */ ds@1952: void sqlite3BeginParse(Parse *pParse, int explainFlag){ ds@1952: pParse->explain = explainFlag; ds@1952: pParse->nVar = 0; ds@1952: } ds@1952: ds@1952: #ifndef SQLITE_OMIT_SHARED_CACHE ds@1952: /* ds@1952: ** The TableLock structure is only used by the sqlite3TableLock() and ds@1952: ** codeTableLocks() functions. ds@1952: */ ds@1952: struct TableLock { ds@1952: int iDb; /* The database containing the table to be locked */ ds@1952: int iTab; /* The root page of the table to be locked */ ds@1952: u8 isWriteLock; /* True for write lock. False for a read lock */ ds@1952: const char *zName; /* Name of the table */ ds@1952: }; ds@1952: ds@1952: /* ds@1952: ** Record the fact that we want to lock a table at run-time. ds@1952: ** ds@1952: ** The table to be locked has root page iTab and is found in database iDb. ds@1952: ** A read or a write lock can be taken depending on isWritelock. ds@1952: ** ds@1952: ** This routine just records the fact that the lock is desired. The ds@1952: ** code to make the lock occur is generated by a later call to ds@1952: ** codeTableLocks() which occurs during sqlite3FinishCoding(). ds@1952: */ ds@1952: void sqlite3TableLock( ds@1952: Parse *pParse, /* Parsing context */ ds@1952: int iDb, /* Index of the database containing the table to lock */ ds@1952: int iTab, /* Root page number of the table to be locked */ ds@1952: u8 isWriteLock, /* True for a write lock */ ds@1952: const char *zName /* Name of the table to be locked */ ds@1952: ){ ds@1952: int i; ds@1952: int nBytes; ds@1952: TableLock *p; ds@1952: ds@1952: if( iDb<0 ){ ds@1952: return; ds@1952: } ds@1952: ds@1952: for(i=0; inTableLock; i++){ ds@1952: p = &pParse->aTableLock[i]; ds@1952: if( p->iDb==iDb && p->iTab==iTab ){ ds@1952: p->isWriteLock = (p->isWriteLock || isWriteLock); ds@1952: return; ds@1952: } ds@1952: } ds@1952: ds@1952: nBytes = sizeof(TableLock) * (pParse->nTableLock+1); ds@1952: pParse->aTableLock = ds@1952: sqlite3DbReallocOrFree(pParse->db, pParse->aTableLock, nBytes); ds@1952: if( pParse->aTableLock ){ ds@1952: p = &pParse->aTableLock[pParse->nTableLock++]; ds@1952: p->iDb = iDb; ds@1952: p->iTab = iTab; ds@1952: p->isWriteLock = isWriteLock; ds@1952: p->zName = zName; ds@1952: }else{ ds@1952: pParse->nTableLock = 0; ds@1952: pParse->db->mallocFailed = 1; ds@1952: } ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Code an OP_TableLock instruction for each table locked by the ds@1952: ** statement (configured by calls to sqlite3TableLock()). ds@1952: */ ds@1952: static void codeTableLocks(Parse *pParse){ ds@1952: int i; ds@1952: Vdbe *pVdbe; ds@1952: ds@1952: if( 0==(pVdbe = sqlite3GetVdbe(pParse)) ){ ds@1952: return; ds@1952: } ds@1952: ds@1952: for(i=0; inTableLock; i++){ ds@1952: TableLock *p = &pParse->aTableLock[i]; ds@1952: int p1 = p->iDb; ds@1952: if( p->isWriteLock ){ ds@1952: p1 = -1*(p1+1); ds@1952: } ds@1952: sqlite3VdbeOp3(pVdbe, OP_TableLock, p1, p->iTab, p->zName, P3_STATIC); ds@1952: } ds@1952: } ds@1952: #else ds@1952: #define codeTableLocks(x) ds@1952: #endif ds@1952: ds@1952: /* ds@1952: ** This routine is called after a single SQL statement has been ds@1952: ** parsed and a VDBE program to execute that statement has been ds@1952: ** prepared. This routine puts the finishing touches on the ds@1952: ** VDBE program and resets the pParse structure for the next ds@1952: ** parse. ds@1952: ** ds@1952: ** Note that if an error occurred, it might be the case that ds@1952: ** no VDBE code was generated. ds@1952: */ ds@1952: void sqlite3FinishCoding(Parse *pParse){ ds@1952: sqlite3 *db; ds@1952: Vdbe *v; ds@1952: ds@1952: db = pParse->db; ds@1952: if( db->mallocFailed ) return; ds@1952: if( pParse->nested ) return; ds@1952: if( !pParse->pVdbe ){ ds@1952: if( pParse->rc==SQLITE_OK && pParse->nErr ){ ds@1952: pParse->rc = SQLITE_ERROR; ds@1952: return; ds@1952: } ds@1952: } ds@1952: ds@1952: /* Begin by generating some termination code at the end of the ds@1952: ** vdbe program ds@1952: */ ds@1952: v = sqlite3GetVdbe(pParse); ds@1952: if( v ){ ds@1952: sqlite3VdbeAddOp(v, OP_Halt, 0, 0); ds@1952: ds@1952: /* The cookie mask contains one bit for each database file open. ds@1952: ** (Bit 0 is for main, bit 1 is for temp, and so forth.) Bits are ds@1952: ** set for each database that is used. Generate code to start a ds@1952: ** transaction on each used database and to verify the schema cookie ds@1952: ** on each used database. ds@1952: */ ds@1952: if( pParse->cookieGoto>0 ){ ds@1952: u32 mask; ds@1952: int iDb; ds@1952: sqlite3VdbeJumpHere(v, pParse->cookieGoto-1); ds@1952: for(iDb=0, mask=1; iDbnDb; mask<<=1, iDb++){ ds@1952: if( (mask & pParse->cookieMask)==0 ) continue; ds@1952: sqlite3VdbeUsesBtree(v, iDb); ds@1952: sqlite3VdbeAddOp(v, OP_Transaction, iDb, (mask & pParse->writeMask)!=0); ds@1952: sqlite3VdbeAddOp(v, OP_VerifyCookie, iDb, pParse->cookieValue[iDb]); ds@1952: } ds@1952: #ifndef SQLITE_OMIT_VIRTUALTABLE ds@1952: if( pParse->pVirtualLock ){ ds@1952: char *vtab = (char *)pParse->pVirtualLock->pVtab; ds@1952: sqlite3VdbeOp3(v, OP_VBegin, 0, 0, vtab, P3_VTAB); ds@1952: } ds@1952: #endif ds@1952: ds@1952: /* Once all the cookies have been verified and transactions opened, ds@1952: ** obtain the required table-locks. This is a no-op unless the ds@1952: ** shared-cache feature is enabled. ds@1952: */ ds@1952: codeTableLocks(pParse); ds@1952: sqlite3VdbeAddOp(v, OP_Goto, 0, pParse->cookieGoto); ds@1952: } ds@1952: ds@1952: #ifndef SQLITE_OMIT_TRACE ds@1952: /* Add a No-op that contains the complete text of the compiled SQL ds@1952: ** statement as its P3 argument. This does not change the functionality ds@1952: ** of the program. ds@1952: ** ds@1952: ** This is used to implement sqlite3_trace(). ds@1952: */ ds@1952: sqlite3VdbeOp3(v, OP_Noop, 0, 0, pParse->zSql, pParse->zTail-pParse->zSql); ds@1952: #endif /* SQLITE_OMIT_TRACE */ ds@1952: } ds@1952: ds@1952: ds@1952: /* Get the VDBE program ready for execution ds@1952: */ ds@1952: if( v && pParse->nErr==0 && !db->mallocFailed ){ ds@1952: #ifdef SQLITE_DEBUG ds@1952: FILE *trace = (db->flags & SQLITE_VdbeTrace)!=0 ? stdout : 0; ds@1952: sqlite3VdbeTrace(v, trace); ds@1952: #endif ds@1952: sqlite3VdbeMakeReady(v, pParse->nVar, pParse->nMem+3, ds@1952: pParse->nTab+3, pParse->explain); ds@1952: pParse->rc = SQLITE_DONE; ds@1952: pParse->colNamesSet = 0; ds@1952: }else if( pParse->rc==SQLITE_OK ){ ds@1952: pParse->rc = SQLITE_ERROR; ds@1952: } ds@1952: pParse->nTab = 0; ds@1952: pParse->nMem = 0; ds@1952: pParse->nSet = 0; ds@1952: pParse->nVar = 0; ds@1952: pParse->cookieMask = 0; ds@1952: pParse->cookieGoto = 0; ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Run the parser and code generator recursively in order to generate ds@1952: ** code for the SQL statement given onto the end of the pParse context ds@1952: ** currently under construction. When the parser is run recursively ds@1952: ** this way, the final OP_Halt is not appended and other initialization ds@1952: ** and finalization steps are omitted because those are handling by the ds@1952: ** outermost parser. ds@1952: ** ds@1952: ** Not everything is nestable. This facility is designed to permit ds@1952: ** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER. Use ds@1952: ** care if you decide to try to use this routine for some other purposes. ds@1952: */ ds@1952: void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){ ds@1952: va_list ap; ds@1952: char *zSql; ds@1952: # define SAVE_SZ (sizeof(Parse) - offsetof(Parse,nVar)) ds@1952: char saveBuf[SAVE_SZ]; ds@1952: ds@1952: if( pParse->nErr ) return; ds@1952: assert( pParse->nested<10 ); /* Nesting should only be of limited depth */ ds@1952: va_start(ap, zFormat); ds@1952: zSql = sqlite3VMPrintf(pParse->db, zFormat, ap); ds@1952: va_end(ap); ds@1952: if( zSql==0 ){ ds@1952: pParse->db->mallocFailed = 1; ds@1952: return; /* A malloc must have failed */ ds@1952: } ds@1952: pParse->nested++; ds@1952: memcpy(saveBuf, &pParse->nVar, SAVE_SZ); ds@1952: memset(&pParse->nVar, 0, SAVE_SZ); ds@1952: sqlite3RunParser(pParse, zSql, 0); ds@1952: sqlite3_free(zSql); ds@1952: memcpy(&pParse->nVar, saveBuf, SAVE_SZ); ds@1952: pParse->nested--; ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Locate the in-memory structure that describes a particular database ds@1952: ** table given the name of that table and (optionally) the name of the ds@1952: ** database containing the table. Return NULL if not found. ds@1952: ** ds@1952: ** If zDatabase is 0, all databases are searched for the table and the ds@1952: ** first matching table is returned. (No checking for duplicate table ds@1952: ** names is done.) The search order is TEMP first, then MAIN, then any ds@1952: ** auxiliary databases added using the ATTACH command. ds@1952: ** ds@1952: ** See also sqlite3LocateTable(). ds@1952: */ ds@1952: Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){ ds@1952: Table *p = 0; ds@1952: int i; ds@1952: assert( zName!=0 ); ds@1952: for(i=OMIT_TEMPDB; inDb; i++){ ds@1952: int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */ ds@1952: if( zDatabase!=0 && sqlite3StrICmp(zDatabase, db->aDb[j].zName) ) continue; ds@1952: p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName, strlen(zName)+1); ds@1952: if( p ) break; ds@1952: } ds@1952: return p; ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Locate the in-memory structure that describes a particular database ds@1952: ** table given the name of that table and (optionally) the name of the ds@1952: ** database containing the table. Return NULL if not found. Also leave an ds@1952: ** error message in pParse->zErrMsg. ds@1952: ** ds@1952: ** The difference between this routine and sqlite3FindTable() is that this ds@1952: ** routine leaves an error message in pParse->zErrMsg where ds@1952: ** sqlite3FindTable() does not. ds@1952: */ ds@1952: Table *sqlite3LocateTable(Parse *pParse, const char *zName, const char *zDbase){ ds@1952: Table *p; ds@1952: ds@1952: /* Read the database schema. If an error occurs, leave an error message ds@1952: ** and code in pParse and return NULL. */ ds@1952: if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){ ds@1952: return 0; ds@1952: } ds@1952: ds@1952: p = sqlite3FindTable(pParse->db, zName, zDbase); ds@1952: if( p==0 ){ ds@1952: if( zDbase ){ ds@1952: sqlite3ErrorMsg(pParse, "no such table: %s.%s", zDbase, zName); ds@1952: }else{ ds@1952: sqlite3ErrorMsg(pParse, "no such table: %s", zName); ds@1952: } ds@1952: pParse->checkSchema = 1; ds@1952: } ds@1952: return p; ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Locate the in-memory structure that describes ds@1952: ** a particular index given the name of that index ds@1952: ** and the name of the database that contains the index. ds@1952: ** Return NULL if not found. ds@1952: ** ds@1952: ** If zDatabase is 0, all databases are searched for the ds@1952: ** table and the first matching index is returned. (No checking ds@1952: ** for duplicate index names is done.) The search order is ds@1952: ** TEMP first, then MAIN, then any auxiliary databases added ds@1952: ** using the ATTACH command. ds@1952: */ ds@1952: Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){ ds@1952: Index *p = 0; ds@1952: int i; ds@1952: for(i=OMIT_TEMPDB; inDb; i++){ ds@1952: int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */ ds@1952: Schema *pSchema = db->aDb[j].pSchema; ds@1952: if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zName) ) continue; ds@1952: assert( pSchema || (j==1 && !db->aDb[1].pBt) ); ds@1952: if( pSchema ){ ds@1952: p = sqlite3HashFind(&pSchema->idxHash, zName, strlen(zName)+1); ds@1952: } ds@1952: if( p ) break; ds@1952: } ds@1952: return p; ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Reclaim the memory used by an index ds@1952: */ ds@1952: static void freeIndex(Index *p){ ds@1952: sqlite3_free(p->zColAff); ds@1952: sqlite3_free(p); ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Remove the given index from the index hash table, and free ds@1952: ** its memory structures. ds@1952: ** ds@1952: ** The index is removed from the database hash tables but ds@1952: ** it is not unlinked from the Table that it indexes. ds@1952: ** Unlinking from the Table must be done by the calling function. ds@1952: */ ds@1952: static void sqliteDeleteIndex(Index *p){ ds@1952: Index *pOld; ds@1952: const char *zName = p->zName; ds@1952: ds@1952: pOld = sqlite3HashInsert(&p->pSchema->idxHash, zName, strlen( zName)+1, 0); ds@1952: assert( pOld==0 || pOld==p ); ds@1952: freeIndex(p); ds@1952: } ds@1952: ds@1952: /* ds@1952: ** For the index called zIdxName which is found in the database iDb, ds@1952: ** unlike that index from its Table then remove the index from ds@1952: ** the index hash table and free all memory structures associated ds@1952: ** with the index. ds@1952: */ ds@1952: void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){ ds@1952: Index *pIndex; ds@1952: int len; ds@1952: Hash *pHash = &db->aDb[iDb].pSchema->idxHash; ds@1952: ds@1952: len = strlen(zIdxName); ds@1952: pIndex = sqlite3HashInsert(pHash, zIdxName, len+1, 0); ds@1952: if( pIndex ){ ds@1952: if( pIndex->pTable->pIndex==pIndex ){ ds@1952: pIndex->pTable->pIndex = pIndex->pNext; ds@1952: }else{ ds@1952: Index *p; ds@1952: for(p=pIndex->pTable->pIndex; p && p->pNext!=pIndex; p=p->pNext){} ds@1952: if( p && p->pNext==pIndex ){ ds@1952: p->pNext = pIndex->pNext; ds@1952: } ds@1952: } ds@1952: freeIndex(pIndex); ds@1952: } ds@1952: db->flags |= SQLITE_InternChanges; ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Erase all schema information from the in-memory hash tables of ds@1952: ** a single database. This routine is called to reclaim memory ds@1952: ** before the database closes. It is also called during a rollback ds@1952: ** if there were schema changes during the transaction or if a ds@1952: ** schema-cookie mismatch occurs. ds@1952: ** ds@1952: ** If iDb<=0 then reset the internal schema tables for all database ds@1952: ** files. If iDb>=2 then reset the internal schema for only the ds@1952: ** single file indicated. ds@1952: */ ds@1952: void sqlite3ResetInternalSchema(sqlite3 *db, int iDb){ ds@1952: int i, j; ds@1952: ds@1952: assert( iDb>=0 && iDbnDb ); ds@1952: for(i=iDb; inDb; i++){ ds@1952: Db *pDb = &db->aDb[i]; ds@1952: if( pDb->pSchema ){ ds@1952: sqlite3SchemaFree(pDb->pSchema); ds@1952: } ds@1952: if( iDb>0 ) return; ds@1952: } ds@1952: assert( iDb==0 ); ds@1952: db->flags &= ~SQLITE_InternChanges; ds@1952: ds@1952: /* If one or more of the auxiliary database files has been closed, ds@1952: ** then remove them from the auxiliary database list. We take the ds@1952: ** opportunity to do this here since we have just deleted all of the ds@1952: ** schema hash tables and therefore do not have to make any changes ds@1952: ** to any of those tables. ds@1952: */ ds@1952: for(i=0; inDb; i++){ ds@1952: struct Db *pDb = &db->aDb[i]; ds@1952: if( pDb->pBt==0 ){ ds@1952: if( pDb->pAux && pDb->xFreeAux ) pDb->xFreeAux(pDb->pAux); ds@1952: pDb->pAux = 0; ds@1952: } ds@1952: } ds@1952: for(i=j=2; inDb; i++){ ds@1952: struct Db *pDb = &db->aDb[i]; ds@1952: if( pDb->pBt==0 ){ ds@1952: sqlite3_free(pDb->zName); ds@1952: pDb->zName = 0; ds@1952: continue; ds@1952: } ds@1952: if( jaDb[j] = db->aDb[i]; ds@1952: } ds@1952: j++; ds@1952: } ds@1952: memset(&db->aDb[j], 0, (db->nDb-j)*sizeof(db->aDb[j])); ds@1952: db->nDb = j; ds@1952: if( db->nDb<=2 && db->aDb!=db->aDbStatic ){ ds@1952: memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0])); ds@1952: sqlite3_free(db->aDb); ds@1952: db->aDb = db->aDbStatic; ds@1952: } ds@1952: } ds@1952: ds@1952: /* ds@1952: ** This routine is called when a commit occurs. ds@1952: */ ds@1952: void sqlite3CommitInternalChanges(sqlite3 *db){ ds@1952: db->flags &= ~SQLITE_InternChanges; ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Clear the column names from a table or view. ds@1952: */ ds@1952: static void sqliteResetColumnNames(Table *pTable){ ds@1952: int i; ds@1952: Column *pCol; ds@1952: assert( pTable!=0 ); ds@1952: if( (pCol = pTable->aCol)!=0 ){ ds@1952: for(i=0; inCol; i++, pCol++){ ds@1952: sqlite3_free(pCol->zName); ds@1952: sqlite3ExprDelete(pCol->pDflt); ds@1952: sqlite3_free(pCol->zType); ds@1952: sqlite3_free(pCol->zColl); ds@1952: } ds@1952: sqlite3_free(pTable->aCol); ds@1952: } ds@1952: pTable->aCol = 0; ds@1952: pTable->nCol = 0; ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Remove the memory data structures associated with the given ds@1952: ** Table. No changes are made to disk by this routine. ds@1952: ** ds@1952: ** This routine just deletes the data structure. It does not unlink ds@1952: ** the table data structure from the hash table. Nor does it remove ds@1952: ** foreign keys from the sqlite.aFKey hash table. But it does destroy ds@1952: ** memory structures of the indices and foreign keys associated with ds@1952: ** the table. ds@1952: */ ds@1952: void sqlite3DeleteTable(Table *pTable){ ds@1952: Index *pIndex, *pNext; ds@1952: FKey *pFKey, *pNextFKey; ds@1952: ds@1952: if( pTable==0 ) return; ds@1952: ds@1952: /* Do not delete the table until the reference count reaches zero. */ ds@1952: pTable->nRef--; ds@1952: if( pTable->nRef>0 ){ ds@1952: return; ds@1952: } ds@1952: assert( pTable->nRef==0 ); ds@1952: ds@1952: /* Delete all indices associated with this table ds@1952: */ ds@1952: for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){ ds@1952: pNext = pIndex->pNext; ds@1952: assert( pIndex->pSchema==pTable->pSchema ); ds@1952: sqliteDeleteIndex(pIndex); ds@1952: } ds@1952: ds@1952: #ifndef SQLITE_OMIT_FOREIGN_KEY ds@1952: /* Delete all foreign keys associated with this table. The keys ds@1952: ** should have already been unlinked from the pSchema->aFKey hash table ds@1952: */ ds@1952: for(pFKey=pTable->pFKey; pFKey; pFKey=pNextFKey){ ds@1952: pNextFKey = pFKey->pNextFrom; ds@1952: assert( sqlite3HashFind(&pTable->pSchema->aFKey, ds@1952: pFKey->zTo, strlen(pFKey->zTo)+1)!=pFKey ); ds@1952: sqlite3_free(pFKey); ds@1952: } ds@1952: #endif ds@1952: ds@1952: /* Delete the Table structure itself. ds@1952: */ ds@1952: sqliteResetColumnNames(pTable); ds@1952: sqlite3_free(pTable->zName); ds@1952: sqlite3_free(pTable->zColAff); ds@1952: sqlite3SelectDelete(pTable->pSelect); ds@1952: #ifndef SQLITE_OMIT_CHECK ds@1952: sqlite3ExprDelete(pTable->pCheck); ds@1952: #endif ds@1952: sqlite3VtabClear(pTable); ds@1952: sqlite3_free(pTable); ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Unlink the given table from the hash tables and the delete the ds@1952: ** table structure with all its indices and foreign keys. ds@1952: */ ds@1952: void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){ ds@1952: Table *p; ds@1952: FKey *pF1, *pF2; ds@1952: Db *pDb; ds@1952: ds@1952: assert( db!=0 ); ds@1952: assert( iDb>=0 && iDbnDb ); ds@1952: assert( zTabName && zTabName[0] ); ds@1952: pDb = &db->aDb[iDb]; ds@1952: p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName, strlen(zTabName)+1,0); ds@1952: if( p ){ ds@1952: #ifndef SQLITE_OMIT_FOREIGN_KEY ds@1952: for(pF1=p->pFKey; pF1; pF1=pF1->pNextFrom){ ds@1952: int nTo = strlen(pF1->zTo) + 1; ds@1952: pF2 = sqlite3HashFind(&pDb->pSchema->aFKey, pF1->zTo, nTo); ds@1952: if( pF2==pF1 ){ ds@1952: sqlite3HashInsert(&pDb->pSchema->aFKey, pF1->zTo, nTo, pF1->pNextTo); ds@1952: }else{ ds@1952: while( pF2 && pF2->pNextTo!=pF1 ){ pF2=pF2->pNextTo; } ds@1952: if( pF2 ){ ds@1952: pF2->pNextTo = pF1->pNextTo; ds@1952: } ds@1952: } ds@1952: } ds@1952: #endif ds@1952: sqlite3DeleteTable(p); ds@1952: } ds@1952: db->flags |= SQLITE_InternChanges; ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Given a token, return a string that consists of the text of that ds@1952: ** token with any quotations removed. Space to hold the returned string ds@1952: ** is obtained from sqliteMalloc() and must be freed by the calling ds@1952: ** function. ds@1952: ** ds@1952: ** Tokens are often just pointers into the original SQL text and so ds@1952: ** are not \000 terminated and are not persistent. The returned string ds@1952: ** is \000 terminated and is persistent. ds@1952: */ ds@1952: char *sqlite3NameFromToken(sqlite3 *db, Token *pName){ ds@1952: char *zName; ds@1952: if( pName ){ ds@1952: zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n); ds@1952: sqlite3Dequote(zName); ds@1952: }else{ ds@1952: zName = 0; ds@1952: } ds@1952: return zName; ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Open the sqlite_master table stored in database number iDb for ds@1952: ** writing. The table is opened using cursor 0. ds@1952: */ ds@1952: void sqlite3OpenMasterTable(Parse *p, int iDb){ ds@1952: Vdbe *v = sqlite3GetVdbe(p); ds@1952: sqlite3TableLock(p, iDb, MASTER_ROOT, 1, SCHEMA_TABLE(iDb)); ds@1952: sqlite3VdbeAddOp(v, OP_Integer, iDb, 0); ds@1952: sqlite3VdbeAddOp(v, OP_OpenWrite, 0, MASTER_ROOT); ds@1952: sqlite3VdbeAddOp(v, OP_SetNumColumns, 0, 5); /* sqlite_master has 5 columns */ ds@1952: } ds@1952: ds@1952: /* ds@1952: ** The token *pName contains the name of a database (either "main" or ds@1952: ** "temp" or the name of an attached db). This routine returns the ds@1952: ** index of the named database in db->aDb[], or -1 if the named db ds@1952: ** does not exist. ds@1952: */ ds@1952: int sqlite3FindDb(sqlite3 *db, Token *pName){ ds@1952: int i = -1; /* Database number */ ds@1952: int n; /* Number of characters in the name */ ds@1952: Db *pDb; /* A database whose name space is being searched */ ds@1952: char *zName; /* Name we are searching for */ ds@1952: ds@1952: zName = sqlite3NameFromToken(db, pName); ds@1952: if( zName ){ ds@1952: n = strlen(zName); ds@1952: for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){ ds@1952: if( (!OMIT_TEMPDB || i!=1 ) && n==strlen(pDb->zName) && ds@1952: 0==sqlite3StrICmp(pDb->zName, zName) ){ ds@1952: break; ds@1952: } ds@1952: } ds@1952: sqlite3_free(zName); ds@1952: } ds@1952: return i; ds@1952: } ds@1952: ds@1952: /* The table or view or trigger name is passed to this routine via tokens ds@1952: ** pName1 and pName2. If the table name was fully qualified, for example: ds@1952: ** ds@1952: ** CREATE TABLE xxx.yyy (...); ds@1952: ** ds@1952: ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if ds@1952: ** the table name is not fully qualified, i.e.: ds@1952: ** ds@1952: ** CREATE TABLE yyy(...); ds@1952: ** ds@1952: ** Then pName1 is set to "yyy" and pName2 is "". ds@1952: ** ds@1952: ** This routine sets the *ppUnqual pointer to point at the token (pName1 or ds@1952: ** pName2) that stores the unqualified table name. The index of the ds@1952: ** database "xxx" is returned. ds@1952: */ ds@1952: int sqlite3TwoPartName( ds@1952: Parse *pParse, /* Parsing and code generating context */ ds@1952: Token *pName1, /* The "xxx" in the name "xxx.yyy" or "xxx" */ ds@1952: Token *pName2, /* The "yyy" in the name "xxx.yyy" */ ds@1952: Token **pUnqual /* Write the unqualified object name here */ ds@1952: ){ ds@1952: int iDb; /* Database holding the object */ ds@1952: sqlite3 *db = pParse->db; ds@1952: ds@1952: if( pName2 && pName2->n>0 ){ ds@1952: assert( !db->init.busy ); ds@1952: *pUnqual = pName2; ds@1952: iDb = sqlite3FindDb(db, pName1); ds@1952: if( iDb<0 ){ ds@1952: sqlite3ErrorMsg(pParse, "unknown database %T", pName1); ds@1952: pParse->nErr++; ds@1952: return -1; ds@1952: } ds@1952: }else{ ds@1952: assert( db->init.iDb==0 || db->init.busy ); ds@1952: iDb = db->init.iDb; ds@1952: *pUnqual = pName1; ds@1952: } ds@1952: return iDb; ds@1952: } ds@1952: ds@1952: /* ds@1952: ** This routine is used to check if the UTF-8 string zName is a legal ds@1952: ** unqualified name for a new schema object (table, index, view or ds@1952: ** trigger). All names are legal except those that begin with the string ds@1952: ** "sqlite_" (in upper, lower or mixed case). This portion of the namespace ds@1952: ** is reserved for internal use. ds@1952: */ ds@1952: int sqlite3CheckObjectName(Parse *pParse, const char *zName){ ds@1952: if( !pParse->db->init.busy && pParse->nested==0 ds@1952: && (pParse->db->flags & SQLITE_WriteSchema)==0 ds@1952: && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){ ds@1952: sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName); ds@1952: return SQLITE_ERROR; ds@1952: } ds@1952: return SQLITE_OK; ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Begin constructing a new table representation in memory. This is ds@1952: ** the first of several action routines that get called in response ds@1952: ** to a CREATE TABLE statement. In particular, this routine is called ds@1952: ** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp ds@1952: ** flag is true if the table should be stored in the auxiliary database ds@1952: ** file instead of in the main database file. This is normally the case ds@1952: ** when the "TEMP" or "TEMPORARY" keyword occurs in between ds@1952: ** CREATE and TABLE. ds@1952: ** ds@1952: ** The new table record is initialized and put in pParse->pNewTable. ds@1952: ** As more of the CREATE TABLE statement is parsed, additional action ds@1952: ** routines will be called to add more information to this record. ds@1952: ** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine ds@1952: ** is called to complete the construction of the new table record. ds@1952: */ ds@1952: void sqlite3StartTable( ds@1952: Parse *pParse, /* Parser context */ ds@1952: Token *pName1, /* First part of the name of the table or view */ ds@1952: Token *pName2, /* Second part of the name of the table or view */ ds@1952: int isTemp, /* True if this is a TEMP table */ ds@1952: int isView, /* True if this is a VIEW */ ds@1952: int isVirtual, /* True if this is a VIRTUAL table */ ds@1952: int noErr /* Do nothing if table already exists */ ds@1952: ){ ds@1952: Table *pTable; ds@1952: char *zName = 0; /* The name of the new table */ ds@1952: sqlite3 *db = pParse->db; ds@1952: Vdbe *v; ds@1952: int iDb; /* Database number to create the table in */ ds@1952: Token *pName; /* Unqualified name of the table to create */ ds@1952: ds@1952: /* The table or view name to create is passed to this routine via tokens ds@1952: ** pName1 and pName2. If the table name was fully qualified, for example: ds@1952: ** ds@1952: ** CREATE TABLE xxx.yyy (...); ds@1952: ** ds@1952: ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if ds@1952: ** the table name is not fully qualified, i.e.: ds@1952: ** ds@1952: ** CREATE TABLE yyy(...); ds@1952: ** ds@1952: ** Then pName1 is set to "yyy" and pName2 is "". ds@1952: ** ds@1952: ** The call below sets the pName pointer to point at the token (pName1 or ds@1952: ** pName2) that stores the unqualified table name. The variable iDb is ds@1952: ** set to the index of the database that the table or view is to be ds@1952: ** created in. ds@1952: */ ds@1952: iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName); ds@1952: if( iDb<0 ) return; ds@1952: if( !OMIT_TEMPDB && isTemp && iDb>1 ){ ds@1952: /* If creating a temp table, the name may not be qualified */ ds@1952: sqlite3ErrorMsg(pParse, "temporary table name must be unqualified"); ds@1952: return; ds@1952: } ds@1952: if( !OMIT_TEMPDB && isTemp ) iDb = 1; ds@1952: ds@1952: pParse->sNameToken = *pName; ds@1952: zName = sqlite3NameFromToken(db, pName); ds@1952: if( zName==0 ) return; ds@1952: if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){ ds@1952: goto begin_table_error; ds@1952: } ds@1952: if( db->init.iDb==1 ) isTemp = 1; ds@1952: #ifndef SQLITE_OMIT_AUTHORIZATION ds@1952: assert( (isTemp & 1)==isTemp ); ds@1952: { ds@1952: int code; ds@1952: char *zDb = db->aDb[iDb].zName; ds@1952: if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){ ds@1952: goto begin_table_error; ds@1952: } ds@1952: if( isView ){ ds@1952: if( !OMIT_TEMPDB && isTemp ){ ds@1952: code = SQLITE_CREATE_TEMP_VIEW; ds@1952: }else{ ds@1952: code = SQLITE_CREATE_VIEW; ds@1952: } ds@1952: }else{ ds@1952: if( !OMIT_TEMPDB && isTemp ){ ds@1952: code = SQLITE_CREATE_TEMP_TABLE; ds@1952: }else{ ds@1952: code = SQLITE_CREATE_TABLE; ds@1952: } ds@1952: } ds@1952: if( !isVirtual && sqlite3AuthCheck(pParse, code, zName, 0, zDb) ){ ds@1952: goto begin_table_error; ds@1952: } ds@1952: } ds@1952: #endif ds@1952: ds@1952: /* Make sure the new table name does not collide with an existing ds@1952: ** index or table name in the same database. Issue an error message if ds@1952: ** it does. The exception is if the statement being parsed was passed ds@1952: ** to an sqlite3_declare_vtab() call. In that case only the column names ds@1952: ** and types will be used, so there is no need to test for namespace ds@1952: ** collisions. ds@1952: */ ds@1952: if( !IN_DECLARE_VTAB ){ ds@1952: if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){ ds@1952: goto begin_table_error; ds@1952: } ds@1952: pTable = sqlite3FindTable(db, zName, db->aDb[iDb].zName); ds@1952: if( pTable ){ ds@1952: if( !noErr ){ ds@1952: sqlite3ErrorMsg(pParse, "table %T already exists", pName); ds@1952: } ds@1952: goto begin_table_error; ds@1952: } ds@1952: if( sqlite3FindIndex(db, zName, 0)!=0 && (iDb==0 || !db->init.busy) ){ ds@1952: sqlite3ErrorMsg(pParse, "there is already an index named %s", zName); ds@1952: goto begin_table_error; ds@1952: } ds@1952: } ds@1952: ds@1952: pTable = sqlite3DbMallocZero(db, sizeof(Table)); ds@1952: if( pTable==0 ){ ds@1952: db->mallocFailed = 1; ds@1952: pParse->rc = SQLITE_NOMEM; ds@1952: pParse->nErr++; ds@1952: goto begin_table_error; ds@1952: } ds@1952: pTable->zName = zName; ds@1952: pTable->iPKey = -1; ds@1952: pTable->pSchema = db->aDb[iDb].pSchema; ds@1952: pTable->nRef = 1; ds@1952: if( pParse->pNewTable ) sqlite3DeleteTable(pParse->pNewTable); ds@1952: pParse->pNewTable = pTable; ds@1952: ds@1952: /* If this is the magic sqlite_sequence table used by autoincrement, ds@1952: ** then record a pointer to this table in the main database structure ds@1952: ** so that INSERT can find the table easily. ds@1952: */ ds@1952: #ifndef SQLITE_OMIT_AUTOINCREMENT ds@1952: if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){ ds@1952: pTable->pSchema->pSeqTab = pTable; ds@1952: } ds@1952: #endif ds@1952: ds@1952: /* Begin generating the code that will insert the table record into ds@1952: ** the SQLITE_MASTER table. Note in particular that we must go ahead ds@1952: ** and allocate the record number for the table entry now. Before any ds@1952: ** PRIMARY KEY or UNIQUE keywords are parsed. Those keywords will cause ds@1952: ** indices to be created and the table record must come before the ds@1952: ** indices. Hence, the record number for the table must be allocated ds@1952: ** now. ds@1952: */ ds@1952: if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){ ds@1952: int lbl; ds@1952: int fileFormat; ds@1952: sqlite3BeginWriteOperation(pParse, 0, iDb); ds@1952: ds@1952: #ifndef SQLITE_OMIT_VIRTUALTABLE ds@1952: if( isVirtual ){ ds@1952: sqlite3VdbeAddOp(v, OP_VBegin, 0, 0); ds@1952: } ds@1952: #endif ds@1952: ds@1952: /* If the file format and encoding in the database have not been set, ds@1952: ** set them now. ds@1952: */ ds@1952: sqlite3VdbeAddOp(v, OP_ReadCookie, iDb, 1); /* file_format */ ds@1952: sqlite3VdbeUsesBtree(v, iDb); ds@1952: lbl = sqlite3VdbeMakeLabel(v); ds@1952: sqlite3VdbeAddOp(v, OP_If, 0, lbl); ds@1952: fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ? ds@1952: 1 : SQLITE_MAX_FILE_FORMAT; ds@1952: sqlite3VdbeAddOp(v, OP_Integer, fileFormat, 0); ds@1952: sqlite3VdbeAddOp(v, OP_SetCookie, iDb, 1); ds@1952: sqlite3VdbeAddOp(v, OP_Integer, ENC(db), 0); ds@1952: sqlite3VdbeAddOp(v, OP_SetCookie, iDb, 4); ds@1952: sqlite3VdbeResolveLabel(v, lbl); ds@1952: ds@1952: /* This just creates a place-holder record in the sqlite_master table. ds@1952: ** The record created does not contain anything yet. It will be replaced ds@1952: ** by the real entry in code generated at sqlite3EndTable(). ds@1952: ** ds@1952: ** The rowid for the new entry is left on the top of the stack. ds@1952: ** The rowid value is needed by the code that sqlite3EndTable will ds@1952: ** generate. ds@1952: */ ds@1952: #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) ds@1952: if( isView || isVirtual ){ ds@1952: sqlite3VdbeAddOp(v, OP_Integer, 0, 0); ds@1952: }else ds@1952: #endif ds@1952: { ds@1952: sqlite3VdbeAddOp(v, OP_CreateTable, iDb, 0); ds@1952: } ds@1952: sqlite3OpenMasterTable(pParse, iDb); ds@1952: sqlite3VdbeAddOp(v, OP_NewRowid, 0, 0); ds@1952: sqlite3VdbeAddOp(v, OP_Dup, 0, 0); ds@1952: sqlite3VdbeAddOp(v, OP_Null, 0, 0); ds@1952: sqlite3VdbeAddOp(v, OP_Insert, 0, OPFLAG_APPEND); ds@1952: sqlite3VdbeAddOp(v, OP_Close, 0, 0); ds@1952: sqlite3VdbeAddOp(v, OP_Pull, 1, 0); ds@1952: } ds@1952: ds@1952: /* Normal (non-error) return. */ ds@1952: return; ds@1952: ds@1952: /* If an error occurs, we jump here */ ds@1952: begin_table_error: ds@1952: sqlite3_free(zName); ds@1952: return; ds@1952: } ds@1952: ds@1952: /* ds@1952: ** This macro is used to compare two strings in a case-insensitive manner. ds@1952: ** It is slightly faster than calling sqlite3StrICmp() directly, but ds@1952: ** produces larger code. ds@1952: ** ds@1952: ** WARNING: This macro is not compatible with the strcmp() family. It ds@1952: ** returns true if the two strings are equal, otherwise false. ds@1952: */ ds@1952: #define STRICMP(x, y) (\ ds@1952: sqlite3UpperToLower[*(unsigned char *)(x)]== \ ds@1952: sqlite3UpperToLower[*(unsigned char *)(y)] \ ds@1952: && sqlite3StrICmp((x)+1,(y)+1)==0 ) ds@1952: ds@1952: /* ds@1952: ** Add a new column to the table currently being constructed. ds@1952: ** ds@1952: ** The parser calls this routine once for each column declaration ds@1952: ** in a CREATE TABLE statement. sqlite3StartTable() gets called ds@1952: ** first to get things going. Then this routine is called for each ds@1952: ** column. ds@1952: */ ds@1952: void sqlite3AddColumn(Parse *pParse, Token *pName){ ds@1952: Table *p; ds@1952: int i; ds@1952: char *z; ds@1952: Column *pCol; ds@1952: if( (p = pParse->pNewTable)==0 ) return; ds@1952: if( p->nCol+1>SQLITE_MAX_COLUMN ){ ds@1952: sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName); ds@1952: return; ds@1952: } ds@1952: z = sqlite3NameFromToken(pParse->db, pName); ds@1952: if( z==0 ) return; ds@1952: for(i=0; inCol; i++){ ds@1952: if( STRICMP(z, p->aCol[i].zName) ){ ds@1952: sqlite3ErrorMsg(pParse, "duplicate column name: %s", z); ds@1952: sqlite3_free(z); ds@1952: return; ds@1952: } ds@1952: } ds@1952: if( (p->nCol & 0x7)==0 ){ ds@1952: Column *aNew; ds@1952: aNew = sqlite3DbRealloc(pParse->db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0])); ds@1952: if( aNew==0 ){ ds@1952: sqlite3_free(z); ds@1952: return; ds@1952: } ds@1952: p->aCol = aNew; ds@1952: } ds@1952: pCol = &p->aCol[p->nCol]; ds@1952: memset(pCol, 0, sizeof(p->aCol[0])); ds@1952: pCol->zName = z; ds@1952: ds@1952: /* If there is no type specified, columns have the default affinity ds@1952: ** 'NONE'. If there is a type specified, then sqlite3AddColumnType() will ds@1952: ** be called next to set pCol->affinity correctly. ds@1952: */ ds@1952: pCol->affinity = SQLITE_AFF_NONE; ds@1952: p->nCol++; ds@1952: } ds@1952: ds@1952: /* ds@1952: ** This routine is called by the parser while in the middle of ds@1952: ** parsing a CREATE TABLE statement. A "NOT NULL" constraint has ds@1952: ** been seen on a column. This routine sets the notNull flag on ds@1952: ** the column currently under construction. ds@1952: */ ds@1952: void sqlite3AddNotNull(Parse *pParse, int onError){ ds@1952: Table *p; ds@1952: int i; ds@1952: if( (p = pParse->pNewTable)==0 ) return; ds@1952: i = p->nCol-1; ds@1952: if( i>=0 ) p->aCol[i].notNull = onError; ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Scan the column type name zType (length nType) and return the ds@1952: ** associated affinity type. ds@1952: ** ds@1952: ** This routine does a case-independent search of zType for the ds@1952: ** substrings in the following table. If one of the substrings is ds@1952: ** found, the corresponding affinity is returned. If zType contains ds@1952: ** more than one of the substrings, entries toward the top of ds@1952: ** the table take priority. For example, if zType is 'BLOBINT', ds@1952: ** SQLITE_AFF_INTEGER is returned. ds@1952: ** ds@1952: ** Substring | Affinity ds@1952: ** -------------------------------- ds@1952: ** 'INT' | SQLITE_AFF_INTEGER ds@1952: ** 'CHAR' | SQLITE_AFF_TEXT ds@1952: ** 'CLOB' | SQLITE_AFF_TEXT ds@1952: ** 'TEXT' | SQLITE_AFF_TEXT ds@1952: ** 'BLOB' | SQLITE_AFF_NONE ds@1952: ** 'REAL' | SQLITE_AFF_REAL ds@1952: ** 'FLOA' | SQLITE_AFF_REAL ds@1952: ** 'DOUB' | SQLITE_AFF_REAL ds@1952: ** ds@1952: ** If none of the substrings in the above table are found, ds@1952: ** SQLITE_AFF_NUMERIC is returned. ds@1952: */ ds@1952: char sqlite3AffinityType(const Token *pType){ ds@1952: u32 h = 0; ds@1952: char aff = SQLITE_AFF_NUMERIC; ds@1952: const unsigned char *zIn = pType->z; ds@1952: const unsigned char *zEnd = &pType->z[pType->n]; ds@1952: ds@1952: while( zIn!=zEnd ){ ds@1952: h = (h<<8) + sqlite3UpperToLower[*zIn]; ds@1952: zIn++; ds@1952: if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){ /* CHAR */ ds@1952: aff = SQLITE_AFF_TEXT; ds@1952: }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){ /* CLOB */ ds@1952: aff = SQLITE_AFF_TEXT; ds@1952: }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){ /* TEXT */ ds@1952: aff = SQLITE_AFF_TEXT; ds@1952: }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b') /* BLOB */ ds@1952: && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){ ds@1952: aff = SQLITE_AFF_NONE; ds@1952: #ifndef SQLITE_OMIT_FLOATING_POINT ds@1952: }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l') /* REAL */ ds@1952: && aff==SQLITE_AFF_NUMERIC ){ ds@1952: aff = SQLITE_AFF_REAL; ds@1952: }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a') /* FLOA */ ds@1952: && aff==SQLITE_AFF_NUMERIC ){ ds@1952: aff = SQLITE_AFF_REAL; ds@1952: }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b') /* DOUB */ ds@1952: && aff==SQLITE_AFF_NUMERIC ){ ds@1952: aff = SQLITE_AFF_REAL; ds@1952: #endif ds@1952: }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){ /* INT */ ds@1952: aff = SQLITE_AFF_INTEGER; ds@1952: break; ds@1952: } ds@1952: } ds@1952: ds@1952: return aff; ds@1952: } ds@1952: ds@1952: /* ds@1952: ** This routine is called by the parser while in the middle of ds@1952: ** parsing a CREATE TABLE statement. The pFirst token is the first ds@1952: ** token in the sequence of tokens that describe the type of the ds@1952: ** column currently under construction. pLast is the last token ds@1952: ** in the sequence. Use this information to construct a string ds@1952: ** that contains the typename of the column and store that string ds@1952: ** in zType. ds@1952: */ ds@1952: void sqlite3AddColumnType(Parse *pParse, Token *pType){ ds@1952: Table *p; ds@1952: int i; ds@1952: Column *pCol; ds@1952: ds@1952: if( (p = pParse->pNewTable)==0 ) return; ds@1952: i = p->nCol-1; ds@1952: if( i<0 ) return; ds@1952: pCol = &p->aCol[i]; ds@1952: sqlite3_free(pCol->zType); ds@1952: pCol->zType = sqlite3NameFromToken(pParse->db, pType); ds@1952: pCol->affinity = sqlite3AffinityType(pType); ds@1952: } ds@1952: ds@1952: /* ds@1952: ** The expression is the default value for the most recently added column ds@1952: ** of the table currently under construction. ds@1952: ** ds@1952: ** Default value expressions must be constant. Raise an exception if this ds@1952: ** is not the case. ds@1952: ** ds@1952: ** This routine is called by the parser while in the middle of ds@1952: ** parsing a CREATE TABLE statement. ds@1952: */ ds@1952: void sqlite3AddDefaultValue(Parse *pParse, Expr *pExpr){ ds@1952: Table *p; ds@1952: Column *pCol; ds@1952: if( (p = pParse->pNewTable)!=0 ){ ds@1952: pCol = &(p->aCol[p->nCol-1]); ds@1952: if( !sqlite3ExprIsConstantOrFunction(pExpr) ){ ds@1952: sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant", ds@1952: pCol->zName); ds@1952: }else{ ds@1952: Expr *pCopy; ds@1952: sqlite3 *db = pParse->db; ds@1952: sqlite3ExprDelete(pCol->pDflt); ds@1952: pCol->pDflt = pCopy = sqlite3ExprDup(db, pExpr); ds@1952: if( pCopy ){ ds@1952: sqlite3TokenCopy(db, &pCopy->span, &pExpr->span); ds@1952: } ds@1952: } ds@1952: } ds@1952: sqlite3ExprDelete(pExpr); ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Designate the PRIMARY KEY for the table. pList is a list of names ds@1952: ** of columns that form the primary key. If pList is NULL, then the ds@1952: ** most recently added column of the table is the primary key. ds@1952: ** ds@1952: ** A table can have at most one primary key. If the table already has ds@1952: ** a primary key (and this is the second primary key) then create an ds@1952: ** error. ds@1952: ** ds@1952: ** If the PRIMARY KEY is on a single column whose datatype is INTEGER, ds@1952: ** then we will try to use that column as the rowid. Set the Table.iPKey ds@1952: ** field of the table under construction to be the index of the ds@1952: ** INTEGER PRIMARY KEY column. Table.iPKey is set to -1 if there is ds@1952: ** no INTEGER PRIMARY KEY. ds@1952: ** ds@1952: ** If the key is not an INTEGER PRIMARY KEY, then create a unique ds@1952: ** index for the key. No index is created for INTEGER PRIMARY KEYs. ds@1952: */ ds@1952: void sqlite3AddPrimaryKey( ds@1952: Parse *pParse, /* Parsing context */ ds@1952: ExprList *pList, /* List of field names to be indexed */ ds@1952: int onError, /* What to do with a uniqueness conflict */ ds@1952: int autoInc, /* True if the AUTOINCREMENT keyword is present */ ds@1952: int sortOrder /* SQLITE_SO_ASC or SQLITE_SO_DESC */ ds@1952: ){ ds@1952: Table *pTab = pParse->pNewTable; ds@1952: char *zType = 0; ds@1952: int iCol = -1, i; ds@1952: if( pTab==0 || IN_DECLARE_VTAB ) goto primary_key_exit; ds@1952: if( pTab->hasPrimKey ){ ds@1952: sqlite3ErrorMsg(pParse, ds@1952: "table \"%s\" has more than one primary key", pTab->zName); ds@1952: goto primary_key_exit; ds@1952: } ds@1952: pTab->hasPrimKey = 1; ds@1952: if( pList==0 ){ ds@1952: iCol = pTab->nCol - 1; ds@1952: pTab->aCol[iCol].isPrimKey = 1; ds@1952: }else{ ds@1952: for(i=0; inExpr; i++){ ds@1952: for(iCol=0; iColnCol; iCol++){ ds@1952: if( sqlite3StrICmp(pList->a[i].zName, pTab->aCol[iCol].zName)==0 ){ ds@1952: break; ds@1952: } ds@1952: } ds@1952: if( iColnCol ){ ds@1952: pTab->aCol[iCol].isPrimKey = 1; ds@1952: } ds@1952: } ds@1952: if( pList->nExpr>1 ) iCol = -1; ds@1952: } ds@1952: if( iCol>=0 && iColnCol ){ ds@1952: zType = pTab->aCol[iCol].zType; ds@1952: } ds@1952: if( zType && sqlite3StrICmp(zType, "INTEGER")==0 ds@1952: && sortOrder==SQLITE_SO_ASC ){ ds@1952: pTab->iPKey = iCol; ds@1952: pTab->keyConf = onError; ds@1952: pTab->autoInc = autoInc; ds@1952: }else if( autoInc ){ ds@1952: #ifndef SQLITE_OMIT_AUTOINCREMENT ds@1952: sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an " ds@1952: "INTEGER PRIMARY KEY"); ds@1952: #endif ds@1952: }else{ ds@1952: sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0, 0, sortOrder, 0); ds@1952: pList = 0; ds@1952: } ds@1952: ds@1952: primary_key_exit: ds@1952: sqlite3ExprListDelete(pList); ds@1952: return; ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Add a new CHECK constraint to the table currently under construction. ds@1952: */ ds@1952: void sqlite3AddCheckConstraint( ds@1952: Parse *pParse, /* Parsing context */ ds@1952: Expr *pCheckExpr /* The check expression */ ds@1952: ){ ds@1952: #ifndef SQLITE_OMIT_CHECK ds@1952: Table *pTab = pParse->pNewTable; ds@1952: sqlite3 *db = pParse->db; ds@1952: if( pTab && !IN_DECLARE_VTAB ){ ds@1952: /* The CHECK expression must be duplicated so that tokens refer ds@1952: ** to malloced space and not the (ephemeral) text of the CREATE TABLE ds@1952: ** statement */ ds@1952: pTab->pCheck = sqlite3ExprAnd(db, pTab->pCheck, ds@1952: sqlite3ExprDup(db, pCheckExpr)); ds@1952: } ds@1952: #endif ds@1952: sqlite3ExprDelete(pCheckExpr); ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Set the collation function of the most recently parsed table column ds@1952: ** to the CollSeq given. ds@1952: */ ds@1952: void sqlite3AddCollateType(Parse *pParse, const char *zType, int nType){ ds@1952: Table *p; ds@1952: int i; ds@1952: ds@1952: if( (p = pParse->pNewTable)==0 ) return; ds@1952: i = p->nCol-1; ds@1952: ds@1952: if( sqlite3LocateCollSeq(pParse, zType, nType) ){ ds@1952: Index *pIdx; ds@1952: p->aCol[i].zColl = sqlite3DbStrNDup(pParse->db, zType, nType); ds@1952: ds@1952: /* If the column is declared as " PRIMARY KEY COLLATE ", ds@1952: ** then an index may have been created on this column before the ds@1952: ** collation type was added. Correct this if it is the case. ds@1952: */ ds@1952: for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){ ds@1952: assert( pIdx->nColumn==1 ); ds@1952: if( pIdx->aiColumn[0]==i ){ ds@1952: pIdx->azColl[0] = p->aCol[i].zColl; ds@1952: } ds@1952: } ds@1952: } ds@1952: } ds@1952: ds@1952: /* ds@1952: ** This function returns the collation sequence for database native text ds@1952: ** encoding identified by the string zName, length nName. ds@1952: ** ds@1952: ** If the requested collation sequence is not available, or not available ds@1952: ** in the database native encoding, the collation factory is invoked to ds@1952: ** request it. If the collation factory does not supply such a sequence, ds@1952: ** and the sequence is available in another text encoding, then that is ds@1952: ** returned instead. ds@1952: ** ds@1952: ** If no versions of the requested collations sequence are available, or ds@1952: ** another error occurs, NULL is returned and an error message written into ds@1952: ** pParse. ds@1952: ** ds@1952: ** This routine is a wrapper around sqlite3FindCollSeq(). This routine ds@1952: ** invokes the collation factory if the named collation cannot be found ds@1952: ** and generates an error message. ds@1952: */ ds@1952: CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName, int nName){ ds@1952: sqlite3 *db = pParse->db; ds@1952: u8 enc = ENC(db); ds@1952: u8 initbusy = db->init.busy; ds@1952: CollSeq *pColl; ds@1952: ds@1952: pColl = sqlite3FindCollSeq(db, enc, zName, nName, initbusy); ds@1952: if( !initbusy && (!pColl || !pColl->xCmp) ){ ds@1952: pColl = sqlite3GetCollSeq(db, pColl, zName, nName); ds@1952: if( !pColl ){ ds@1952: if( nName<0 ){ ds@1952: nName = strlen(zName); ds@1952: } ds@1952: sqlite3ErrorMsg(pParse, "no such collation sequence: %.*s", nName, zName); ds@1952: pColl = 0; ds@1952: } ds@1952: } ds@1952: ds@1952: return pColl; ds@1952: } ds@1952: ds@1952: ds@1952: /* ds@1952: ** Generate code that will increment the schema cookie. ds@1952: ** ds@1952: ** The schema cookie is used to determine when the schema for the ds@1952: ** database changes. After each schema change, the cookie value ds@1952: ** changes. When a process first reads the schema it records the ds@1952: ** cookie. Thereafter, whenever it goes to access the database, ds@1952: ** it checks the cookie to make sure the schema has not changed ds@1952: ** since it was last read. ds@1952: ** ds@1952: ** This plan is not completely bullet-proof. It is possible for ds@1952: ** the schema to change multiple times and for the cookie to be ds@1952: ** set back to prior value. But schema changes are infrequent ds@1952: ** and the probability of hitting the same cookie value is only ds@1952: ** 1 chance in 2^32. So we're safe enough. ds@1952: */ ds@1952: void sqlite3ChangeCookie(sqlite3 *db, Vdbe *v, int iDb){ ds@1952: sqlite3VdbeAddOp(v, OP_Integer, db->aDb[iDb].pSchema->schema_cookie+1, 0); ds@1952: sqlite3VdbeAddOp(v, OP_SetCookie, iDb, 0); ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Measure the number of characters needed to output the given ds@1952: ** identifier. The number returned includes any quotes used ds@1952: ** but does not include the null terminator. ds@1952: ** ds@1952: ** The estimate is conservative. It might be larger that what is ds@1952: ** really needed. ds@1952: */ ds@1952: static int identLength(const char *z){ ds@1952: int n; ds@1952: for(n=0; *z; n++, z++){ ds@1952: if( *z=='"' ){ n++; } ds@1952: } ds@1952: return n + 2; ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Write an identifier onto the end of the given string. Add ds@1952: ** quote characters as needed. ds@1952: */ ds@1952: static void identPut(char *z, int *pIdx, char *zSignedIdent){ ds@1952: unsigned char *zIdent = (unsigned char*)zSignedIdent; ds@1952: int i, j, needQuote; ds@1952: i = *pIdx; ds@1952: for(j=0; zIdent[j]; j++){ ds@1952: if( !isalnum(zIdent[j]) && zIdent[j]!='_' ) break; ds@1952: } ds@1952: needQuote = zIdent[j]!=0 || isdigit(zIdent[0]) ds@1952: || sqlite3KeywordCode(zIdent, j)!=TK_ID; ds@1952: if( needQuote ) z[i++] = '"'; ds@1952: for(j=0; zIdent[j]; j++){ ds@1952: z[i++] = zIdent[j]; ds@1952: if( zIdent[j]=='"' ) z[i++] = '"'; ds@1952: } ds@1952: if( needQuote ) z[i++] = '"'; ds@1952: z[i] = 0; ds@1952: *pIdx = i; ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Generate a CREATE TABLE statement appropriate for the given ds@1952: ** table. Memory to hold the text of the statement is obtained ds@1952: ** from sqliteMalloc() and must be freed by the calling function. ds@1952: */ ds@1952: static char *createTableStmt(Table *p, int isTemp){ ds@1952: int i, k, n; ds@1952: char *zStmt; ds@1952: char *zSep, *zSep2, *zEnd, *z; ds@1952: Column *pCol; ds@1952: n = 0; ds@1952: for(pCol = p->aCol, i=0; inCol; i++, pCol++){ ds@1952: n += identLength(pCol->zName); ds@1952: z = pCol->zType; ds@1952: if( z ){ ds@1952: n += (strlen(z) + 1); ds@1952: } ds@1952: } ds@1952: n += identLength(p->zName); ds@1952: if( n<50 ){ ds@1952: zSep = ""; ds@1952: zSep2 = ","; ds@1952: zEnd = ")"; ds@1952: }else{ ds@1952: zSep = "\n "; ds@1952: zSep2 = ",\n "; ds@1952: zEnd = "\n)"; ds@1952: } ds@1952: n += 35 + 6*p->nCol; ds@1952: zStmt = sqlite3_malloc( n ); ds@1952: if( zStmt==0 ) return 0; ds@1952: sqlite3_snprintf(n, zStmt, ds@1952: !OMIT_TEMPDB&&isTemp ? "CREATE TEMP TABLE ":"CREATE TABLE "); ds@1952: k = strlen(zStmt); ds@1952: identPut(zStmt, &k, p->zName); ds@1952: zStmt[k++] = '('; ds@1952: for(pCol=p->aCol, i=0; inCol; i++, pCol++){ ds@1952: sqlite3_snprintf(n-k, &zStmt[k], zSep); ds@1952: k += strlen(&zStmt[k]); ds@1952: zSep = zSep2; ds@1952: identPut(zStmt, &k, pCol->zName); ds@1952: if( (z = pCol->zType)!=0 ){ ds@1952: zStmt[k++] = ' '; ds@1952: assert( strlen(z)+k+1<=n ); ds@1952: sqlite3_snprintf(n-k, &zStmt[k], "%s", z); ds@1952: k += strlen(z); ds@1952: } ds@1952: } ds@1952: sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd); ds@1952: return zStmt; ds@1952: } ds@1952: ds@1952: /* ds@1952: ** This routine is called to report the final ")" that terminates ds@1952: ** a CREATE TABLE statement. ds@1952: ** ds@1952: ** The table structure that other action routines have been building ds@1952: ** is added to the internal hash tables, assuming no errors have ds@1952: ** occurred. ds@1952: ** ds@1952: ** An entry for the table is made in the master table on disk, unless ds@1952: ** this is a temporary table or db->init.busy==1. When db->init.busy==1 ds@1952: ** it means we are reading the sqlite_master table because we just ds@1952: ** connected to the database or because the sqlite_master table has ds@1952: ** recently changed, so the entry for this table already exists in ds@1952: ** the sqlite_master table. We do not want to create it again. ds@1952: ** ds@1952: ** If the pSelect argument is not NULL, it means that this routine ds@1952: ** was called to create a table generated from a ds@1952: ** "CREATE TABLE ... AS SELECT ..." statement. The column names of ds@1952: ** the new table will match the result set of the SELECT. ds@1952: */ ds@1952: void sqlite3EndTable( ds@1952: Parse *pParse, /* Parse context */ ds@1952: Token *pCons, /* The ',' token after the last column defn. */ ds@1952: Token *pEnd, /* The final ')' token in the CREATE TABLE */ ds@1952: Select *pSelect /* Select from a "CREATE ... AS SELECT" */ ds@1952: ){ ds@1952: Table *p; ds@1952: sqlite3 *db = pParse->db; ds@1952: int iDb; ds@1952: ds@1952: if( (pEnd==0 && pSelect==0) || pParse->nErr || db->mallocFailed ) { ds@1952: return; ds@1952: } ds@1952: p = pParse->pNewTable; ds@1952: if( p==0 ) return; ds@1952: ds@1952: assert( !db->init.busy || !pSelect ); ds@1952: ds@1952: iDb = sqlite3SchemaToIndex(db, p->pSchema); ds@1952: ds@1952: #ifndef SQLITE_OMIT_CHECK ds@1952: /* Resolve names in all CHECK constraint expressions. ds@1952: */ ds@1952: if( p->pCheck ){ ds@1952: SrcList sSrc; /* Fake SrcList for pParse->pNewTable */ ds@1952: NameContext sNC; /* Name context for pParse->pNewTable */ ds@1952: ds@1952: memset(&sNC, 0, sizeof(sNC)); ds@1952: memset(&sSrc, 0, sizeof(sSrc)); ds@1952: sSrc.nSrc = 1; ds@1952: sSrc.a[0].zName = p->zName; ds@1952: sSrc.a[0].pTab = p; ds@1952: sSrc.a[0].iCursor = -1; ds@1952: sNC.pParse = pParse; ds@1952: sNC.pSrcList = &sSrc; ds@1952: sNC.isCheck = 1; ds@1952: if( sqlite3ExprResolveNames(&sNC, p->pCheck) ){ ds@1952: return; ds@1952: } ds@1952: } ds@1952: #endif /* !defined(SQLITE_OMIT_CHECK) */ ds@1952: ds@1952: /* If the db->init.busy is 1 it means we are reading the SQL off the ds@1952: ** "sqlite_master" or "sqlite_temp_master" table on the disk. ds@1952: ** So do not write to the disk again. Extract the root page number ds@1952: ** for the table from the db->init.newTnum field. (The page number ds@1952: ** should have been put there by the sqliteOpenCb routine.) ds@1952: */ ds@1952: if( db->init.busy ){ ds@1952: p->tnum = db->init.newTnum; ds@1952: } ds@1952: ds@1952: /* If not initializing, then create a record for the new table ds@1952: ** in the SQLITE_MASTER table of the database. The record number ds@1952: ** for the new table entry should already be on the stack. ds@1952: ** ds@1952: ** If this is a TEMPORARY table, write the entry into the auxiliary ds@1952: ** file instead of into the main database file. ds@1952: */ ds@1952: if( !db->init.busy ){ ds@1952: int n; ds@1952: Vdbe *v; ds@1952: char *zType; /* "view" or "table" */ ds@1952: char *zType2; /* "VIEW" or "TABLE" */ ds@1952: char *zStmt; /* Text of the CREATE TABLE or CREATE VIEW statement */ ds@1952: ds@1952: v = sqlite3GetVdbe(pParse); ds@1952: if( v==0 ) return; ds@1952: ds@1952: sqlite3VdbeAddOp(v, OP_Close, 0, 0); ds@1952: ds@1952: /* Create the rootpage for the new table and push it onto the stack. ds@1952: ** A view has no rootpage, so just push a zero onto the stack for ds@1952: ** views. Initialize zType at the same time. ds@1952: */ ds@1952: if( p->pSelect==0 ){ ds@1952: /* A regular table */ ds@1952: zType = "table"; ds@1952: zType2 = "TABLE"; ds@1952: #ifndef SQLITE_OMIT_VIEW ds@1952: }else{ ds@1952: /* A view */ ds@1952: zType = "view"; ds@1952: zType2 = "VIEW"; ds@1952: #endif ds@1952: } ds@1952: ds@1952: /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT ds@1952: ** statement to populate the new table. The root-page number for the ds@1952: ** new table is on the top of the vdbe stack. ds@1952: ** ds@1952: ** Once the SELECT has been coded by sqlite3Select(), it is in a ds@1952: ** suitable state to query for the column names and types to be used ds@1952: ** by the new table. ds@1952: ** ds@1952: ** A shared-cache write-lock is not required to write to the new table, ds@1952: ** as a schema-lock must have already been obtained to create it. Since ds@1952: ** a schema-lock excludes all other database users, the write-lock would ds@1952: ** be redundant. ds@1952: */ ds@1952: if( pSelect ){ ds@1952: Table *pSelTab; ds@1952: sqlite3VdbeAddOp(v, OP_Dup, 0, 0); ds@1952: sqlite3VdbeAddOp(v, OP_Integer, iDb, 0); ds@1952: sqlite3VdbeAddOp(v, OP_OpenWrite, 1, 0); ds@1952: pParse->nTab = 2; ds@1952: sqlite3Select(pParse, pSelect, SRT_Table, 1, 0, 0, 0, 0); ds@1952: sqlite3VdbeAddOp(v, OP_Close, 1, 0); ds@1952: if( pParse->nErr==0 ){ ds@1952: pSelTab = sqlite3ResultSetOfSelect(pParse, 0, pSelect); ds@1952: if( pSelTab==0 ) return; ds@1952: assert( p->aCol==0 ); ds@1952: p->nCol = pSelTab->nCol; ds@1952: p->aCol = pSelTab->aCol; ds@1952: pSelTab->nCol = 0; ds@1952: pSelTab->aCol = 0; ds@1952: sqlite3DeleteTable(pSelTab); ds@1952: } ds@1952: } ds@1952: ds@1952: /* Compute the complete text of the CREATE statement */ ds@1952: if( pSelect ){ ds@1952: zStmt = createTableStmt(p, p->pSchema==db->aDb[1].pSchema); ds@1952: }else{ ds@1952: n = pEnd->z - pParse->sNameToken.z + 1; ds@1952: zStmt = sqlite3MPrintf(db, ds@1952: "CREATE %s %.*s", zType2, n, pParse->sNameToken.z ds@1952: ); ds@1952: } ds@1952: ds@1952: /* A slot for the record has already been allocated in the ds@1952: ** SQLITE_MASTER table. We just need to update that slot with all ds@1952: ** the information we've collected. The rowid for the preallocated ds@1952: ** slot is the 2nd item on the stack. The top of the stack is the ds@1952: ** root page for the new table (or a 0 if this is a view). ds@1952: */ ds@1952: sqlite3NestedParse(pParse, ds@1952: "UPDATE %Q.%s " ds@1952: "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#0, sql=%Q " ds@1952: "WHERE rowid=#1", ds@1952: db->aDb[iDb].zName, SCHEMA_TABLE(iDb), ds@1952: zType, ds@1952: p->zName, ds@1952: p->zName, ds@1952: zStmt ds@1952: ); ds@1952: sqlite3_free(zStmt); ds@1952: sqlite3ChangeCookie(db, v, iDb); ds@1952: ds@1952: #ifndef SQLITE_OMIT_AUTOINCREMENT ds@1952: /* Check to see if we need to create an sqlite_sequence table for ds@1952: ** keeping track of autoincrement keys. ds@1952: */ ds@1952: if( p->autoInc ){ ds@1952: Db *pDb = &db->aDb[iDb]; ds@1952: if( pDb->pSchema->pSeqTab==0 ){ ds@1952: sqlite3NestedParse(pParse, ds@1952: "CREATE TABLE %Q.sqlite_sequence(name,seq)", ds@1952: pDb->zName ds@1952: ); ds@1952: } ds@1952: } ds@1952: #endif ds@1952: ds@1952: /* Reparse everything to update our internal data structures */ ds@1952: sqlite3VdbeOp3(v, OP_ParseSchema, iDb, 0, ds@1952: sqlite3MPrintf(db, "tbl_name='%q'",p->zName), P3_DYNAMIC); ds@1952: } ds@1952: ds@1952: ds@1952: /* Add the table to the in-memory representation of the database. ds@1952: */ ds@1952: if( db->init.busy && pParse->nErr==0 ){ ds@1952: Table *pOld; ds@1952: FKey *pFKey; ds@1952: Schema *pSchema = p->pSchema; ds@1952: pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName, strlen(p->zName)+1,p); ds@1952: if( pOld ){ ds@1952: assert( p==pOld ); /* Malloc must have failed inside HashInsert() */ ds@1952: db->mallocFailed = 1; ds@1952: return; ds@1952: } ds@1952: #ifndef SQLITE_OMIT_FOREIGN_KEY ds@1952: for(pFKey=p->pFKey; pFKey; pFKey=pFKey->pNextFrom){ ds@1952: void *data; ds@1952: int nTo = strlen(pFKey->zTo) + 1; ds@1952: pFKey->pNextTo = sqlite3HashFind(&pSchema->aFKey, pFKey->zTo, nTo); ds@1952: data = sqlite3HashInsert(&pSchema->aFKey, pFKey->zTo, nTo, pFKey); ds@1952: if( data==(void *)pFKey ){ ds@1952: db->mallocFailed = 1; ds@1952: } ds@1952: } ds@1952: #endif ds@1952: pParse->pNewTable = 0; ds@1952: db->nTable++; ds@1952: db->flags |= SQLITE_InternChanges; ds@1952: ds@1952: #ifndef SQLITE_OMIT_ALTERTABLE ds@1952: if( !p->pSelect ){ ds@1952: const char *zName = (const char *)pParse->sNameToken.z; ds@1952: int nName; ds@1952: assert( !pSelect && pCons && pEnd ); ds@1952: if( pCons->z==0 ){ ds@1952: pCons = pEnd; ds@1952: } ds@1952: nName = (const char *)pCons->z - zName; ds@1952: p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName); ds@1952: } ds@1952: #endif ds@1952: } ds@1952: } ds@1952: ds@1952: #ifndef SQLITE_OMIT_VIEW ds@1952: /* ds@1952: ** The parser calls this routine in order to create a new VIEW ds@1952: */ ds@1952: void sqlite3CreateView( ds@1952: Parse *pParse, /* The parsing context */ ds@1952: Token *pBegin, /* The CREATE token that begins the statement */ ds@1952: Token *pName1, /* The token that holds the name of the view */ ds@1952: Token *pName2, /* The token that holds the name of the view */ ds@1952: Select *pSelect, /* A SELECT statement that will become the new view */ ds@1952: int isTemp, /* TRUE for a TEMPORARY view */ ds@1952: int noErr /* Suppress error messages if VIEW already exists */ ds@1952: ){ ds@1952: Table *p; ds@1952: int n; ds@1952: const unsigned char *z; ds@1952: Token sEnd; ds@1952: DbFixer sFix; ds@1952: Token *pName; ds@1952: int iDb; ds@1952: sqlite3 *db = pParse->db; ds@1952: ds@1952: if( pParse->nVar>0 ){ ds@1952: sqlite3ErrorMsg(pParse, "parameters are not allowed in views"); ds@1952: sqlite3SelectDelete(pSelect); ds@1952: return; ds@1952: } ds@1952: sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr); ds@1952: p = pParse->pNewTable; ds@1952: if( p==0 || pParse->nErr ){ ds@1952: sqlite3SelectDelete(pSelect); ds@1952: return; ds@1952: } ds@1952: sqlite3TwoPartName(pParse, pName1, pName2, &pName); ds@1952: iDb = sqlite3SchemaToIndex(db, p->pSchema); ds@1952: if( sqlite3FixInit(&sFix, pParse, iDb, "view", pName) ds@1952: && sqlite3FixSelect(&sFix, pSelect) ds@1952: ){ ds@1952: sqlite3SelectDelete(pSelect); ds@1952: return; ds@1952: } ds@1952: ds@1952: /* Make a copy of the entire SELECT statement that defines the view. ds@1952: ** This will force all the Expr.token.z values to be dynamically ds@1952: ** allocated rather than point to the input string - which means that ds@1952: ** they will persist after the current sqlite3_exec() call returns. ds@1952: */ ds@1952: p->pSelect = sqlite3SelectDup(db, pSelect); ds@1952: sqlite3SelectDelete(pSelect); ds@1952: if( db->mallocFailed ){ ds@1952: return; ds@1952: } ds@1952: if( !db->init.busy ){ ds@1952: sqlite3ViewGetColumnNames(pParse, p); ds@1952: } ds@1952: ds@1952: /* Locate the end of the CREATE VIEW statement. Make sEnd point to ds@1952: ** the end. ds@1952: */ ds@1952: sEnd = pParse->sLastToken; ds@1952: if( sEnd.z[0]!=0 && sEnd.z[0]!=';' ){ ds@1952: sEnd.z += sEnd.n; ds@1952: } ds@1952: sEnd.n = 0; ds@1952: n = sEnd.z - pBegin->z; ds@1952: z = (const unsigned char*)pBegin->z; ds@1952: while( n>0 && (z[n-1]==';' || isspace(z[n-1])) ){ n--; } ds@1952: sEnd.z = &z[n-1]; ds@1952: sEnd.n = 1; ds@1952: ds@1952: /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */ ds@1952: sqlite3EndTable(pParse, 0, &sEnd, 0); ds@1952: return; ds@1952: } ds@1952: #endif /* SQLITE_OMIT_VIEW */ ds@1952: ds@1952: #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) ds@1952: /* ds@1952: ** The Table structure pTable is really a VIEW. Fill in the names of ds@1952: ** the columns of the view in the pTable structure. Return the number ds@1952: ** of errors. If an error is seen leave an error message in pParse->zErrMsg. ds@1952: */ ds@1952: int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){ ds@1952: Table *pSelTab; /* A fake table from which we get the result set */ ds@1952: Select *pSel; /* Copy of the SELECT that implements the view */ ds@1952: int nErr = 0; /* Number of errors encountered */ ds@1952: int n; /* Temporarily holds the number of cursors assigned */ ds@1952: sqlite3 *db = pParse->db; /* Database connection for malloc errors */ ds@1952: ds@1952: assert( pTable ); ds@1952: ds@1952: #ifndef SQLITE_OMIT_VIRTUALTABLE ds@1952: if( sqlite3VtabCallConnect(pParse, pTable) ){ ds@1952: return SQLITE_ERROR; ds@1952: } ds@1952: if( IsVirtual(pTable) ) return 0; ds@1952: #endif ds@1952: ds@1952: #ifndef SQLITE_OMIT_VIEW ds@1952: /* A positive nCol means the columns names for this view are ds@1952: ** already known. ds@1952: */ ds@1952: if( pTable->nCol>0 ) return 0; ds@1952: ds@1952: /* A negative nCol is a special marker meaning that we are currently ds@1952: ** trying to compute the column names. If we enter this routine with ds@1952: ** a negative nCol, it means two or more views form a loop, like this: ds@1952: ** ds@1952: ** CREATE VIEW one AS SELECT * FROM two; ds@1952: ** CREATE VIEW two AS SELECT * FROM one; ds@1952: ** ds@1952: ** Actually, this error is caught previously and so the following test ds@1952: ** should always fail. But we will leave it in place just to be safe. ds@1952: */ ds@1952: if( pTable->nCol<0 ){ ds@1952: sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName); ds@1952: return 1; ds@1952: } ds@1952: assert( pTable->nCol>=0 ); ds@1952: ds@1952: /* If we get this far, it means we need to compute the table names. ds@1952: ** Note that the call to sqlite3ResultSetOfSelect() will expand any ds@1952: ** "*" elements in the results set of the view and will assign cursors ds@1952: ** to the elements of the FROM clause. But we do not want these changes ds@1952: ** to be permanent. So the computation is done on a copy of the SELECT ds@1952: ** statement that defines the view. ds@1952: */ ds@1952: assert( pTable->pSelect ); ds@1952: pSel = sqlite3SelectDup(db, pTable->pSelect); ds@1952: if( pSel ){ ds@1952: n = pParse->nTab; ds@1952: sqlite3SrcListAssignCursors(pParse, pSel->pSrc); ds@1952: pTable->nCol = -1; ds@1952: pSelTab = sqlite3ResultSetOfSelect(pParse, 0, pSel); ds@1952: pParse->nTab = n; ds@1952: if( pSelTab ){ ds@1952: assert( pTable->aCol==0 ); ds@1952: pTable->nCol = pSelTab->nCol; ds@1952: pTable->aCol = pSelTab->aCol; ds@1952: pSelTab->nCol = 0; ds@1952: pSelTab->aCol = 0; ds@1952: sqlite3DeleteTable(pSelTab); ds@1952: pTable->pSchema->flags |= DB_UnresetViews; ds@1952: }else{ ds@1952: pTable->nCol = 0; ds@1952: nErr++; ds@1952: } ds@1952: sqlite3SelectDelete(pSel); ds@1952: } else { ds@1952: nErr++; ds@1952: } ds@1952: #endif /* SQLITE_OMIT_VIEW */ ds@1952: return nErr; ds@1952: } ds@1952: #endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */ ds@1952: ds@1952: #ifndef SQLITE_OMIT_VIEW ds@1952: /* ds@1952: ** Clear the column names from every VIEW in database idx. ds@1952: */ ds@1952: static void sqliteViewResetAll(sqlite3 *db, int idx){ ds@1952: HashElem *i; ds@1952: if( !DbHasProperty(db, idx, DB_UnresetViews) ) return; ds@1952: for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){ ds@1952: Table *pTab = sqliteHashData(i); ds@1952: if( pTab->pSelect ){ ds@1952: sqliteResetColumnNames(pTab); ds@1952: } ds@1952: } ds@1952: DbClearProperty(db, idx, DB_UnresetViews); ds@1952: } ds@1952: #else ds@1952: # define sqliteViewResetAll(A,B) ds@1952: #endif /* SQLITE_OMIT_VIEW */ ds@1952: ds@1952: /* ds@1952: ** This function is called by the VDBE to adjust the internal schema ds@1952: ** used by SQLite when the btree layer moves a table root page. The ds@1952: ** root-page of a table or index in database iDb has changed from iFrom ds@1952: ** to iTo. ds@1952: ** ds@1952: ** Ticket #1728: The symbol table might still contain information ds@1952: ** on tables and/or indices that are the process of being deleted. ds@1952: ** If you are unlucky, one of those deleted indices or tables might ds@1952: ** have the same rootpage number as the real table or index that is ds@1952: ** being moved. So we cannot stop searching after the first match ds@1952: ** because the first match might be for one of the deleted indices ds@1952: ** or tables and not the table/index that is actually being moved. ds@1952: ** We must continue looping until all tables and indices with ds@1952: ** rootpage==iFrom have been converted to have a rootpage of iTo ds@1952: ** in order to be certain that we got the right one. ds@1952: */ ds@1952: #ifndef SQLITE_OMIT_AUTOVACUUM ds@1952: void sqlite3RootPageMoved(Db *pDb, int iFrom, int iTo){ ds@1952: HashElem *pElem; ds@1952: Hash *pHash; ds@1952: ds@1952: pHash = &pDb->pSchema->tblHash; ds@1952: for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){ ds@1952: Table *pTab = sqliteHashData(pElem); ds@1952: if( pTab->tnum==iFrom ){ ds@1952: pTab->tnum = iTo; ds@1952: } ds@1952: } ds@1952: pHash = &pDb->pSchema->idxHash; ds@1952: for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){ ds@1952: Index *pIdx = sqliteHashData(pElem); ds@1952: if( pIdx->tnum==iFrom ){ ds@1952: pIdx->tnum = iTo; ds@1952: } ds@1952: } ds@1952: } ds@1952: #endif ds@1952: ds@1952: /* ds@1952: ** Write code to erase the table with root-page iTable from database iDb. ds@1952: ** Also write code to modify the sqlite_master table and internal schema ds@1952: ** if a root-page of another table is moved by the btree-layer whilst ds@1952: ** erasing iTable (this can happen with an auto-vacuum database). ds@1952: */ ds@1952: static void destroyRootPage(Parse *pParse, int iTable, int iDb){ ds@1952: Vdbe *v = sqlite3GetVdbe(pParse); ds@1952: sqlite3VdbeAddOp(v, OP_Destroy, iTable, iDb); ds@1952: #ifndef SQLITE_OMIT_AUTOVACUUM ds@1952: /* OP_Destroy pushes an integer onto the stack. If this integer ds@1952: ** is non-zero, then it is the root page number of a table moved to ds@1952: ** location iTable. The following code modifies the sqlite_master table to ds@1952: ** reflect this. ds@1952: ** ds@1952: ** The "#0" in the SQL is a special constant that means whatever value ds@1952: ** is on the top of the stack. See sqlite3RegisterExpr(). ds@1952: */ ds@1952: sqlite3NestedParse(pParse, ds@1952: "UPDATE %Q.%s SET rootpage=%d WHERE #0 AND rootpage=#0", ds@1952: pParse->db->aDb[iDb].zName, SCHEMA_TABLE(iDb), iTable); ds@1952: #endif ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Write VDBE code to erase table pTab and all associated indices on disk. ds@1952: ** Code to update the sqlite_master tables and internal schema definitions ds@1952: ** in case a root-page belonging to another table is moved by the btree layer ds@1952: ** is also added (this can happen with an auto-vacuum database). ds@1952: */ ds@1952: static void destroyTable(Parse *pParse, Table *pTab){ ds@1952: #ifdef SQLITE_OMIT_AUTOVACUUM ds@1952: Index *pIdx; ds@1952: int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema); ds@1952: destroyRootPage(pParse, pTab->tnum, iDb); ds@1952: for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ ds@1952: destroyRootPage(pParse, pIdx->tnum, iDb); ds@1952: } ds@1952: #else ds@1952: /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM ds@1952: ** is not defined), then it is important to call OP_Destroy on the ds@1952: ** table and index root-pages in order, starting with the numerically ds@1952: ** largest root-page number. This guarantees that none of the root-pages ds@1952: ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the ds@1952: ** following were coded: ds@1952: ** ds@1952: ** OP_Destroy 4 0 ds@1952: ** ... ds@1952: ** OP_Destroy 5 0 ds@1952: ** ds@1952: ** and root page 5 happened to be the largest root-page number in the ds@1952: ** database, then root page 5 would be moved to page 4 by the ds@1952: ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit ds@1952: ** a free-list page. ds@1952: */ ds@1952: int iTab = pTab->tnum; ds@1952: int iDestroyed = 0; ds@1952: ds@1952: while( 1 ){ ds@1952: Index *pIdx; ds@1952: int iLargest = 0; ds@1952: ds@1952: if( iDestroyed==0 || iTabpIndex; pIdx; pIdx=pIdx->pNext){ ds@1952: int iIdx = pIdx->tnum; ds@1952: assert( pIdx->pSchema==pTab->pSchema ); ds@1952: if( (iDestroyed==0 || (iIdxiLargest ){ ds@1952: iLargest = iIdx; ds@1952: } ds@1952: } ds@1952: if( iLargest==0 ){ ds@1952: return; ds@1952: }else{ ds@1952: int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema); ds@1952: destroyRootPage(pParse, iLargest, iDb); ds@1952: iDestroyed = iLargest; ds@1952: } ds@1952: } ds@1952: #endif ds@1952: } ds@1952: ds@1952: /* ds@1952: ** This routine is called to do the work of a DROP TABLE statement. ds@1952: ** pName is the name of the table to be dropped. ds@1952: */ ds@1952: void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){ ds@1952: Table *pTab; ds@1952: Vdbe *v; ds@1952: sqlite3 *db = pParse->db; ds@1952: int iDb; ds@1952: ds@1952: if( pParse->nErr || db->mallocFailed ){ ds@1952: goto exit_drop_table; ds@1952: } ds@1952: assert( pName->nSrc==1 ); ds@1952: pTab = sqlite3LocateTable(pParse, pName->a[0].zName, pName->a[0].zDatabase); ds@1952: ds@1952: if( pTab==0 ){ ds@1952: if( noErr ){ ds@1952: sqlite3ErrorClear(pParse); ds@1952: } ds@1952: goto exit_drop_table; ds@1952: } ds@1952: iDb = sqlite3SchemaToIndex(db, pTab->pSchema); ds@1952: assert( iDb>=0 && iDbnDb ); ds@1952: #ifndef SQLITE_OMIT_AUTHORIZATION ds@1952: { ds@1952: int code; ds@1952: const char *zTab = SCHEMA_TABLE(iDb); ds@1952: const char *zDb = db->aDb[iDb].zName; ds@1952: const char *zArg2 = 0; ds@1952: if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){ ds@1952: goto exit_drop_table; ds@1952: } ds@1952: if( isView ){ ds@1952: if( !OMIT_TEMPDB && iDb==1 ){ ds@1952: code = SQLITE_DROP_TEMP_VIEW; ds@1952: }else{ ds@1952: code = SQLITE_DROP_VIEW; ds@1952: } ds@1952: #ifndef SQLITE_OMIT_VIRTUALTABLE ds@1952: }else if( IsVirtual(pTab) ){ ds@1952: if( sqlite3ViewGetColumnNames(pParse, pTab) ){ ds@1952: goto exit_drop_table; ds@1952: } ds@1952: code = SQLITE_DROP_VTABLE; ds@1952: zArg2 = pTab->pMod->zName; ds@1952: #endif ds@1952: }else{ ds@1952: if( !OMIT_TEMPDB && iDb==1 ){ ds@1952: code = SQLITE_DROP_TEMP_TABLE; ds@1952: }else{ ds@1952: code = SQLITE_DROP_TABLE; ds@1952: } ds@1952: } ds@1952: if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){ ds@1952: goto exit_drop_table; ds@1952: } ds@1952: if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){ ds@1952: goto exit_drop_table; ds@1952: } ds@1952: } ds@1952: #endif ds@1952: if( pTab->readOnly || pTab==db->aDb[iDb].pSchema->pSeqTab ){ ds@1952: sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName); ds@1952: goto exit_drop_table; ds@1952: } ds@1952: ds@1952: #ifndef SQLITE_OMIT_VIEW ds@1952: /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used ds@1952: ** on a table. ds@1952: */ ds@1952: if( isView && pTab->pSelect==0 ){ ds@1952: sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName); ds@1952: goto exit_drop_table; ds@1952: } ds@1952: if( !isView && pTab->pSelect ){ ds@1952: sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName); ds@1952: goto exit_drop_table; ds@1952: } ds@1952: #endif ds@1952: ds@1952: /* Generate code to remove the table from the master table ds@1952: ** on disk. ds@1952: */ ds@1952: v = sqlite3GetVdbe(pParse); ds@1952: if( v ){ ds@1952: Trigger *pTrigger; ds@1952: Db *pDb = &db->aDb[iDb]; ds@1952: sqlite3BeginWriteOperation(pParse, 0, iDb); ds@1952: ds@1952: #ifndef SQLITE_OMIT_VIRTUALTABLE ds@1952: if( IsVirtual(pTab) ){ ds@1952: Vdbe *v = sqlite3GetVdbe(pParse); ds@1952: if( v ){ ds@1952: sqlite3VdbeAddOp(v, OP_VBegin, 0, 0); ds@1952: } ds@1952: } ds@1952: #endif ds@1952: ds@1952: /* Drop all triggers associated with the table being dropped. Code ds@1952: ** is generated to remove entries from sqlite_master and/or ds@1952: ** sqlite_temp_master if required. ds@1952: */ ds@1952: pTrigger = pTab->pTrigger; ds@1952: while( pTrigger ){ ds@1952: assert( pTrigger->pSchema==pTab->pSchema || ds@1952: pTrigger->pSchema==db->aDb[1].pSchema ); ds@1952: sqlite3DropTriggerPtr(pParse, pTrigger); ds@1952: pTrigger = pTrigger->pNext; ds@1952: } ds@1952: ds@1952: #ifndef SQLITE_OMIT_AUTOINCREMENT ds@1952: /* Remove any entries of the sqlite_sequence table associated with ds@1952: ** the table being dropped. This is done before the table is dropped ds@1952: ** at the btree level, in case the sqlite_sequence table needs to ds@1952: ** move as a result of the drop (can happen in auto-vacuum mode). ds@1952: */ ds@1952: if( pTab->autoInc ){ ds@1952: sqlite3NestedParse(pParse, ds@1952: "DELETE FROM %s.sqlite_sequence WHERE name=%Q", ds@1952: pDb->zName, pTab->zName ds@1952: ); ds@1952: } ds@1952: #endif ds@1952: ds@1952: /* Drop all SQLITE_MASTER table and index entries that refer to the ds@1952: ** table. The program name loops through the master table and deletes ds@1952: ** every row that refers to a table of the same name as the one being ds@1952: ** dropped. Triggers are handled seperately because a trigger can be ds@1952: ** created in the temp database that refers to a table in another ds@1952: ** database. ds@1952: */ ds@1952: sqlite3NestedParse(pParse, ds@1952: "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'", ds@1952: pDb->zName, SCHEMA_TABLE(iDb), pTab->zName); ds@1952: if( !isView && !IsVirtual(pTab) ){ ds@1952: destroyTable(pParse, pTab); ds@1952: } ds@1952: ds@1952: /* Remove the table entry from SQLite's internal schema and modify ds@1952: ** the schema cookie. ds@1952: */ ds@1952: if( IsVirtual(pTab) ){ ds@1952: sqlite3VdbeOp3(v, OP_VDestroy, iDb, 0, pTab->zName, 0); ds@1952: } ds@1952: sqlite3VdbeOp3(v, OP_DropTable, iDb, 0, pTab->zName, 0); ds@1952: sqlite3ChangeCookie(db, v, iDb); ds@1952: } ds@1952: sqliteViewResetAll(db, iDb); ds@1952: ds@1952: exit_drop_table: ds@1952: sqlite3SrcListDelete(pName); ds@1952: } ds@1952: ds@1952: /* ds@1952: ** This routine is called to create a new foreign key on the table ds@1952: ** currently under construction. pFromCol determines which columns ds@1952: ** in the current table point to the foreign key. If pFromCol==0 then ds@1952: ** connect the key to the last column inserted. pTo is the name of ds@1952: ** the table referred to. pToCol is a list of tables in the other ds@1952: ** pTo table that the foreign key points to. flags contains all ds@1952: ** information about the conflict resolution algorithms specified ds@1952: ** in the ON DELETE, ON UPDATE and ON INSERT clauses. ds@1952: ** ds@1952: ** An FKey structure is created and added to the table currently ds@1952: ** under construction in the pParse->pNewTable field. The new FKey ds@1952: ** is not linked into db->aFKey at this point - that does not happen ds@1952: ** until sqlite3EndTable(). ds@1952: ** ds@1952: ** The foreign key is set for IMMEDIATE processing. A subsequent call ds@1952: ** to sqlite3DeferForeignKey() might change this to DEFERRED. ds@1952: */ ds@1952: void sqlite3CreateForeignKey( ds@1952: Parse *pParse, /* Parsing context */ ds@1952: ExprList *pFromCol, /* Columns in this table that point to other table */ ds@1952: Token *pTo, /* Name of the other table */ ds@1952: ExprList *pToCol, /* Columns in the other table */ ds@1952: int flags /* Conflict resolution algorithms. */ ds@1952: ){ ds@1952: #ifndef SQLITE_OMIT_FOREIGN_KEY ds@1952: FKey *pFKey = 0; ds@1952: Table *p = pParse->pNewTable; ds@1952: int nByte; ds@1952: int i; ds@1952: int nCol; ds@1952: char *z; ds@1952: ds@1952: assert( pTo!=0 ); ds@1952: if( p==0 || pParse->nErr || IN_DECLARE_VTAB ) goto fk_end; ds@1952: if( pFromCol==0 ){ ds@1952: int iCol = p->nCol-1; ds@1952: if( iCol<0 ) goto fk_end; ds@1952: if( pToCol && pToCol->nExpr!=1 ){ ds@1952: sqlite3ErrorMsg(pParse, "foreign key on %s" ds@1952: " should reference only one column of table %T", ds@1952: p->aCol[iCol].zName, pTo); ds@1952: goto fk_end; ds@1952: } ds@1952: nCol = 1; ds@1952: }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){ ds@1952: sqlite3ErrorMsg(pParse, ds@1952: "number of columns in foreign key does not match the number of " ds@1952: "columns in the referenced table"); ds@1952: goto fk_end; ds@1952: }else{ ds@1952: nCol = pFromCol->nExpr; ds@1952: } ds@1952: nByte = sizeof(*pFKey) + nCol*sizeof(pFKey->aCol[0]) + pTo->n + 1; ds@1952: if( pToCol ){ ds@1952: for(i=0; inExpr; i++){ ds@1952: nByte += strlen(pToCol->a[i].zName) + 1; ds@1952: } ds@1952: } ds@1952: pFKey = sqlite3DbMallocZero(pParse->db, nByte ); ds@1952: if( pFKey==0 ){ ds@1952: goto fk_end; ds@1952: } ds@1952: pFKey->pFrom = p; ds@1952: pFKey->pNextFrom = p->pFKey; ds@1952: z = (char*)&pFKey[1]; ds@1952: pFKey->aCol = (struct sColMap*)z; ds@1952: z += sizeof(struct sColMap)*nCol; ds@1952: pFKey->zTo = z; ds@1952: memcpy(z, pTo->z, pTo->n); ds@1952: z[pTo->n] = 0; ds@1952: z += pTo->n+1; ds@1952: pFKey->pNextTo = 0; ds@1952: pFKey->nCol = nCol; ds@1952: if( pFromCol==0 ){ ds@1952: pFKey->aCol[0].iFrom = p->nCol-1; ds@1952: }else{ ds@1952: for(i=0; inCol; j++){ ds@1952: if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){ ds@1952: pFKey->aCol[i].iFrom = j; ds@1952: break; ds@1952: } ds@1952: } ds@1952: if( j>=p->nCol ){ ds@1952: sqlite3ErrorMsg(pParse, ds@1952: "unknown column \"%s\" in foreign key definition", ds@1952: pFromCol->a[i].zName); ds@1952: goto fk_end; ds@1952: } ds@1952: } ds@1952: } ds@1952: if( pToCol ){ ds@1952: for(i=0; ia[i].zName); ds@1952: pFKey->aCol[i].zCol = z; ds@1952: memcpy(z, pToCol->a[i].zName, n); ds@1952: z[n] = 0; ds@1952: z += n+1; ds@1952: } ds@1952: } ds@1952: pFKey->isDeferred = 0; ds@1952: pFKey->deleteConf = flags & 0xff; ds@1952: pFKey->updateConf = (flags >> 8 ) & 0xff; ds@1952: pFKey->insertConf = (flags >> 16 ) & 0xff; ds@1952: ds@1952: /* Link the foreign key to the table as the last step. ds@1952: */ ds@1952: p->pFKey = pFKey; ds@1952: pFKey = 0; ds@1952: ds@1952: fk_end: ds@1952: sqlite3_free(pFKey); ds@1952: #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */ ds@1952: sqlite3ExprListDelete(pFromCol); ds@1952: sqlite3ExprListDelete(pToCol); ds@1952: } ds@1952: ds@1952: /* ds@1952: ** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED ds@1952: ** clause is seen as part of a foreign key definition. The isDeferred ds@1952: ** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE. ds@1952: ** The behavior of the most recently created foreign key is adjusted ds@1952: ** accordingly. ds@1952: */ ds@1952: void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){ ds@1952: #ifndef SQLITE_OMIT_FOREIGN_KEY ds@1952: Table *pTab; ds@1952: FKey *pFKey; ds@1952: if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return; ds@1952: pFKey->isDeferred = isDeferred; ds@1952: #endif ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Generate code that will erase and refill index *pIdx. This is ds@1952: ** used to initialize a newly created index or to recompute the ds@1952: ** content of an index in response to a REINDEX command. ds@1952: ** ds@1952: ** if memRootPage is not negative, it means that the index is newly ds@1952: ** created. The memory cell specified by memRootPage contains the ds@1952: ** root page number of the index. If memRootPage is negative, then ds@1952: ** the index already exists and must be cleared before being refilled and ds@1952: ** the root page number of the index is taken from pIndex->tnum. ds@1952: */ ds@1952: static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){ ds@1952: Table *pTab = pIndex->pTable; /* The table that is indexed */ ds@1952: int iTab = pParse->nTab; /* Btree cursor used for pTab */ ds@1952: int iIdx = pParse->nTab+1; /* Btree cursor used for pIndex */ ds@1952: int addr1; /* Address of top of loop */ ds@1952: int tnum; /* Root page of index */ ds@1952: Vdbe *v; /* Generate code into this virtual machine */ ds@1952: KeyInfo *pKey; /* KeyInfo for index */ ds@1952: sqlite3 *db = pParse->db; /* The database connection */ ds@1952: int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema); ds@1952: ds@1952: #ifndef SQLITE_OMIT_AUTHORIZATION ds@1952: if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0, ds@1952: db->aDb[iDb].zName ) ){ ds@1952: return; ds@1952: } ds@1952: #endif ds@1952: ds@1952: /* Require a write-lock on the table to perform this operation */ ds@1952: sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName); ds@1952: ds@1952: v = sqlite3GetVdbe(pParse); ds@1952: if( v==0 ) return; ds@1952: if( memRootPage>=0 ){ ds@1952: sqlite3VdbeAddOp(v, OP_MemLoad, memRootPage, 0); ds@1952: tnum = 0; ds@1952: }else{ ds@1952: tnum = pIndex->tnum; ds@1952: sqlite3VdbeAddOp(v, OP_Clear, tnum, iDb); ds@1952: } ds@1952: sqlite3VdbeAddOp(v, OP_Integer, iDb, 0); ds@1952: pKey = sqlite3IndexKeyinfo(pParse, pIndex); ds@1952: sqlite3VdbeOp3(v, OP_OpenWrite, iIdx, tnum, (char *)pKey, P3_KEYINFO_HANDOFF); ds@1952: sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead); ds@1952: addr1 = sqlite3VdbeAddOp(v, OP_Rewind, iTab, 0); ds@1952: sqlite3GenerateIndexKey(v, pIndex, iTab); ds@1952: if( pIndex->onError!=OE_None ){ ds@1952: int curaddr = sqlite3VdbeCurrentAddr(v); ds@1952: int addr2 = curaddr+4; ds@1952: sqlite3VdbeChangeP2(v, curaddr-1, addr2); ds@1952: sqlite3VdbeAddOp(v, OP_Rowid, iTab, 0); ds@1952: sqlite3VdbeAddOp(v, OP_AddImm, 1, 0); ds@1952: sqlite3VdbeAddOp(v, OP_IsUnique, iIdx, addr2); ds@1952: sqlite3VdbeOp3(v, OP_Halt, SQLITE_CONSTRAINT, OE_Abort, ds@1952: "indexed columns are not unique", P3_STATIC); ds@1952: assert( db->mallocFailed || addr2==sqlite3VdbeCurrentAddr(v) ); ds@1952: } ds@1952: sqlite3VdbeAddOp(v, OP_IdxInsert, iIdx, 0); ds@1952: sqlite3VdbeAddOp(v, OP_Next, iTab, addr1+1); ds@1952: sqlite3VdbeJumpHere(v, addr1); ds@1952: sqlite3VdbeAddOp(v, OP_Close, iTab, 0); ds@1952: sqlite3VdbeAddOp(v, OP_Close, iIdx, 0); ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Create a new index for an SQL table. pName1.pName2 is the name of the index ds@1952: ** and pTblList is the name of the table that is to be indexed. Both will ds@1952: ** be NULL for a primary key or an index that is created to satisfy a ds@1952: ** UNIQUE constraint. If pTable and pIndex are NULL, use pParse->pNewTable ds@1952: ** as the table to be indexed. pParse->pNewTable is a table that is ds@1952: ** currently being constructed by a CREATE TABLE statement. ds@1952: ** ds@1952: ** pList is a list of columns to be indexed. pList will be NULL if this ds@1952: ** is a primary key or unique-constraint on the most recent column added ds@1952: ** to the table currently under construction. ds@1952: */ ds@1952: void sqlite3CreateIndex( ds@1952: Parse *pParse, /* All information about this parse */ ds@1952: Token *pName1, /* First part of index name. May be NULL */ ds@1952: Token *pName2, /* Second part of index name. May be NULL */ ds@1952: SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */ ds@1952: ExprList *pList, /* A list of columns to be indexed */ ds@1952: int onError, /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */ ds@1952: Token *pStart, /* The CREATE token that begins this statement */ ds@1952: Token *pEnd, /* The ")" that closes the CREATE INDEX statement */ ds@1952: int sortOrder, /* Sort order of primary key when pList==NULL */ ds@1952: int ifNotExist /* Omit error if index already exists */ ds@1952: ){ ds@1952: Table *pTab = 0; /* Table to be indexed */ ds@1952: Index *pIndex = 0; /* The index to be created */ ds@1952: char *zName = 0; /* Name of the index */ ds@1952: int nName; /* Number of characters in zName */ ds@1952: int i, j; ds@1952: Token nullId; /* Fake token for an empty ID list */ ds@1952: DbFixer sFix; /* For assigning database names to pTable */ ds@1952: int sortOrderMask; /* 1 to honor DESC in index. 0 to ignore. */ ds@1952: sqlite3 *db = pParse->db; ds@1952: Db *pDb; /* The specific table containing the indexed database */ ds@1952: int iDb; /* Index of the database that is being written */ ds@1952: Token *pName = 0; /* Unqualified name of the index to create */ ds@1952: struct ExprList_item *pListItem; /* For looping over pList */ ds@1952: int nCol; ds@1952: int nExtra = 0; ds@1952: char *zExtra; ds@1952: ds@1952: if( pParse->nErr || db->mallocFailed || IN_DECLARE_VTAB ){ ds@1952: goto exit_create_index; ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Find the table that is to be indexed. Return early if not found. ds@1952: */ ds@1952: if( pTblName!=0 ){ ds@1952: ds@1952: /* Use the two-part index name to determine the database ds@1952: ** to search for the table. 'Fix' the table name to this db ds@1952: ** before looking up the table. ds@1952: */ ds@1952: assert( pName1 && pName2 ); ds@1952: iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName); ds@1952: if( iDb<0 ) goto exit_create_index; ds@1952: ds@1952: #ifndef SQLITE_OMIT_TEMPDB ds@1952: /* If the index name was unqualified, check if the the table ds@1952: ** is a temp table. If so, set the database to 1. ds@1952: */ ds@1952: pTab = sqlite3SrcListLookup(pParse, pTblName); ds@1952: if( pName2 && pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){ ds@1952: iDb = 1; ds@1952: } ds@1952: #endif ds@1952: ds@1952: if( sqlite3FixInit(&sFix, pParse, iDb, "index", pName) && ds@1952: sqlite3FixSrcList(&sFix, pTblName) ds@1952: ){ ds@1952: /* Because the parser constructs pTblName from a single identifier, ds@1952: ** sqlite3FixSrcList can never fail. */ ds@1952: assert(0); ds@1952: } ds@1952: pTab = sqlite3LocateTable(pParse, pTblName->a[0].zName, ds@1952: pTblName->a[0].zDatabase); ds@1952: if( !pTab ) goto exit_create_index; ds@1952: assert( db->aDb[iDb].pSchema==pTab->pSchema ); ds@1952: }else{ ds@1952: assert( pName==0 ); ds@1952: pTab = pParse->pNewTable; ds@1952: if( !pTab ) goto exit_create_index; ds@1952: iDb = sqlite3SchemaToIndex(db, pTab->pSchema); ds@1952: } ds@1952: pDb = &db->aDb[iDb]; ds@1952: ds@1952: if( pTab==0 || pParse->nErr ) goto exit_create_index; ds@1952: if( pTab->readOnly ){ ds@1952: sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName); ds@1952: goto exit_create_index; ds@1952: } ds@1952: #ifndef SQLITE_OMIT_VIEW ds@1952: if( pTab->pSelect ){ ds@1952: sqlite3ErrorMsg(pParse, "views may not be indexed"); ds@1952: goto exit_create_index; ds@1952: } ds@1952: #endif ds@1952: #ifndef SQLITE_OMIT_VIRTUALTABLE ds@1952: if( IsVirtual(pTab) ){ ds@1952: sqlite3ErrorMsg(pParse, "virtual tables may not be indexed"); ds@1952: goto exit_create_index; ds@1952: } ds@1952: #endif ds@1952: ds@1952: /* ds@1952: ** Find the name of the index. Make sure there is not already another ds@1952: ** index or table with the same name. ds@1952: ** ds@1952: ** Exception: If we are reading the names of permanent indices from the ds@1952: ** sqlite_master table (because some other process changed the schema) and ds@1952: ** one of the index names collides with the name of a temporary table or ds@1952: ** index, then we will continue to process this index. ds@1952: ** ds@1952: ** If pName==0 it means that we are ds@1952: ** dealing with a primary key or UNIQUE constraint. We have to invent our ds@1952: ** own name. ds@1952: */ ds@1952: if( pName ){ ds@1952: zName = sqlite3NameFromToken(db, pName); ds@1952: if( SQLITE_OK!=sqlite3ReadSchema(pParse) ) goto exit_create_index; ds@1952: if( zName==0 ) goto exit_create_index; ds@1952: if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){ ds@1952: goto exit_create_index; ds@1952: } ds@1952: if( !db->init.busy ){ ds@1952: if( SQLITE_OK!=sqlite3ReadSchema(pParse) ) goto exit_create_index; ds@1952: if( sqlite3FindTable(db, zName, 0)!=0 ){ ds@1952: sqlite3ErrorMsg(pParse, "there is already a table named %s", zName); ds@1952: goto exit_create_index; ds@1952: } ds@1952: } ds@1952: if( sqlite3FindIndex(db, zName, pDb->zName)!=0 ){ ds@1952: if( !ifNotExist ){ ds@1952: sqlite3ErrorMsg(pParse, "index %s already exists", zName); ds@1952: } ds@1952: goto exit_create_index; ds@1952: } ds@1952: }else{ ds@1952: char zBuf[30]; ds@1952: int n; ds@1952: Index *pLoop; ds@1952: for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){} ds@1952: sqlite3_snprintf(sizeof(zBuf),zBuf,"_%d",n); ds@1952: zName = 0; ds@1952: sqlite3SetString(&zName, "sqlite_autoindex_", pTab->zName, zBuf, (char*)0); ds@1952: if( zName==0 ){ ds@1952: db->mallocFailed = 1; ds@1952: goto exit_create_index; ds@1952: } ds@1952: } ds@1952: ds@1952: /* Check for authorization to create an index. ds@1952: */ ds@1952: #ifndef SQLITE_OMIT_AUTHORIZATION ds@1952: { ds@1952: const char *zDb = pDb->zName; ds@1952: if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){ ds@1952: goto exit_create_index; ds@1952: } ds@1952: i = SQLITE_CREATE_INDEX; ds@1952: if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX; ds@1952: if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){ ds@1952: goto exit_create_index; ds@1952: } ds@1952: } ds@1952: #endif ds@1952: ds@1952: /* If pList==0, it means this routine was called to make a primary ds@1952: ** key out of the last column added to the table under construction. ds@1952: ** So create a fake list to simulate this. ds@1952: */ ds@1952: if( pList==0 ){ ds@1952: nullId.z = (u8*)pTab->aCol[pTab->nCol-1].zName; ds@1952: nullId.n = strlen((char*)nullId.z); ds@1952: pList = sqlite3ExprListAppend(pParse, 0, 0, &nullId); ds@1952: if( pList==0 ) goto exit_create_index; ds@1952: pList->a[0].sortOrder = sortOrder; ds@1952: } ds@1952: ds@1952: /* Figure out how many bytes of space are required to store explicitly ds@1952: ** specified collation sequence names. ds@1952: */ ds@1952: for(i=0; inExpr; i++){ ds@1952: Expr *pExpr = pList->a[i].pExpr; ds@1952: if( pExpr ){ ds@1952: nExtra += (1 + strlen(pExpr->pColl->zName)); ds@1952: } ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Allocate the index structure. ds@1952: */ ds@1952: nName = strlen(zName); ds@1952: nCol = pList->nExpr; ds@1952: pIndex = sqlite3DbMallocZero(db, ds@1952: sizeof(Index) + /* Index structure */ ds@1952: sizeof(int)*nCol + /* Index.aiColumn */ ds@1952: sizeof(int)*(nCol+1) + /* Index.aiRowEst */ ds@1952: sizeof(char *)*nCol + /* Index.azColl */ ds@1952: sizeof(u8)*nCol + /* Index.aSortOrder */ ds@1952: nName + 1 + /* Index.zName */ ds@1952: nExtra /* Collation sequence names */ ds@1952: ); ds@1952: if( db->mallocFailed ){ ds@1952: goto exit_create_index; ds@1952: } ds@1952: pIndex->azColl = (char**)(&pIndex[1]); ds@1952: pIndex->aiColumn = (int *)(&pIndex->azColl[nCol]); ds@1952: pIndex->aiRowEst = (unsigned *)(&pIndex->aiColumn[nCol]); ds@1952: pIndex->aSortOrder = (u8 *)(&pIndex->aiRowEst[nCol+1]); ds@1952: pIndex->zName = (char *)(&pIndex->aSortOrder[nCol]); ds@1952: zExtra = (char *)(&pIndex->zName[nName+1]); ds@1952: memcpy(pIndex->zName, zName, nName+1); ds@1952: pIndex->pTable = pTab; ds@1952: pIndex->nColumn = pList->nExpr; ds@1952: pIndex->onError = onError; ds@1952: pIndex->autoIndex = pName==0; ds@1952: pIndex->pSchema = db->aDb[iDb].pSchema; ds@1952: ds@1952: /* Check to see if we should honor DESC requests on index columns ds@1952: */ ds@1952: if( pDb->pSchema->file_format>=4 ){ ds@1952: sortOrderMask = -1; /* Honor DESC */ ds@1952: }else{ ds@1952: sortOrderMask = 0; /* Ignore DESC */ ds@1952: } ds@1952: ds@1952: /* Scan the names of the columns of the table to be indexed and ds@1952: ** load the column indices into the Index structure. Report an error ds@1952: ** if any column is not found. ds@1952: */ ds@1952: for(i=0, pListItem=pList->a; inExpr; i++, pListItem++){ ds@1952: const char *zColName = pListItem->zName; ds@1952: Column *pTabCol; ds@1952: int requestedSortOrder; ds@1952: char *zColl; /* Collation sequence name */ ds@1952: ds@1952: for(j=0, pTabCol=pTab->aCol; jnCol; j++, pTabCol++){ ds@1952: if( sqlite3StrICmp(zColName, pTabCol->zName)==0 ) break; ds@1952: } ds@1952: if( j>=pTab->nCol ){ ds@1952: sqlite3ErrorMsg(pParse, "table %s has no column named %s", ds@1952: pTab->zName, zColName); ds@1952: goto exit_create_index; ds@1952: } ds@1952: /* TODO: Add a test to make sure that the same column is not named ds@1952: ** more than once within the same index. Only the first instance of ds@1952: ** the column will ever be used by the optimizer. Note that using the ds@1952: ** same column more than once cannot be an error because that would ds@1952: ** break backwards compatibility - it needs to be a warning. ds@1952: */ ds@1952: pIndex->aiColumn[i] = j; ds@1952: if( pListItem->pExpr ){ ds@1952: assert( pListItem->pExpr->pColl ); ds@1952: zColl = zExtra; ds@1952: sqlite3_snprintf(nExtra, zExtra, "%s", pListItem->pExpr->pColl->zName); ds@1952: zExtra += (strlen(zColl) + 1); ds@1952: }else{ ds@1952: zColl = pTab->aCol[j].zColl; ds@1952: if( !zColl ){ ds@1952: zColl = db->pDfltColl->zName; ds@1952: } ds@1952: } ds@1952: if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl, -1) ){ ds@1952: goto exit_create_index; ds@1952: } ds@1952: pIndex->azColl[i] = zColl; ds@1952: requestedSortOrder = pListItem->sortOrder & sortOrderMask; ds@1952: pIndex->aSortOrder[i] = requestedSortOrder; ds@1952: } ds@1952: sqlite3DefaultRowEst(pIndex); ds@1952: ds@1952: if( pTab==pParse->pNewTable ){ ds@1952: /* This routine has been called to create an automatic index as a ds@1952: ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or ds@1952: ** a PRIMARY KEY or UNIQUE clause following the column definitions. ds@1952: ** i.e. one of: ds@1952: ** ds@1952: ** CREATE TABLE t(x PRIMARY KEY, y); ds@1952: ** CREATE TABLE t(x, y, UNIQUE(x, y)); ds@1952: ** ds@1952: ** Either way, check to see if the table already has such an index. If ds@1952: ** so, don't bother creating this one. This only applies to ds@1952: ** automatically created indices. Users can do as they wish with ds@1952: ** explicit indices. ds@1952: */ ds@1952: Index *pIdx; ds@1952: for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ ds@1952: int k; ds@1952: assert( pIdx->onError!=OE_None ); ds@1952: assert( pIdx->autoIndex ); ds@1952: assert( pIndex->onError!=OE_None ); ds@1952: ds@1952: if( pIdx->nColumn!=pIndex->nColumn ) continue; ds@1952: for(k=0; knColumn; k++){ ds@1952: const char *z1 = pIdx->azColl[k]; ds@1952: const char *z2 = pIndex->azColl[k]; ds@1952: if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break; ds@1952: if( pIdx->aSortOrder[k]!=pIndex->aSortOrder[k] ) break; ds@1952: if( z1!=z2 && sqlite3StrICmp(z1, z2) ) break; ds@1952: } ds@1952: if( k==pIdx->nColumn ){ ds@1952: if( pIdx->onError!=pIndex->onError ){ ds@1952: /* This constraint creates the same index as a previous ds@1952: ** constraint specified somewhere in the CREATE TABLE statement. ds@1952: ** However the ON CONFLICT clauses are different. If both this ds@1952: ** constraint and the previous equivalent constraint have explicit ds@1952: ** ON CONFLICT clauses this is an error. Otherwise, use the ds@1952: ** explicitly specified behaviour for the index. ds@1952: */ ds@1952: if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){ ds@1952: sqlite3ErrorMsg(pParse, ds@1952: "conflicting ON CONFLICT clauses specified", 0); ds@1952: } ds@1952: if( pIdx->onError==OE_Default ){ ds@1952: pIdx->onError = pIndex->onError; ds@1952: } ds@1952: } ds@1952: goto exit_create_index; ds@1952: } ds@1952: } ds@1952: } ds@1952: ds@1952: /* Link the new Index structure to its table and to the other ds@1952: ** in-memory database structures. ds@1952: */ ds@1952: if( db->init.busy ){ ds@1952: Index *p; ds@1952: p = sqlite3HashInsert(&pIndex->pSchema->idxHash, ds@1952: pIndex->zName, strlen(pIndex->zName)+1, pIndex); ds@1952: if( p ){ ds@1952: assert( p==pIndex ); /* Malloc must have failed */ ds@1952: db->mallocFailed = 1; ds@1952: goto exit_create_index; ds@1952: } ds@1952: db->flags |= SQLITE_InternChanges; ds@1952: if( pTblName!=0 ){ ds@1952: pIndex->tnum = db->init.newTnum; ds@1952: } ds@1952: } ds@1952: ds@1952: /* If the db->init.busy is 0 then create the index on disk. This ds@1952: ** involves writing the index into the master table and filling in the ds@1952: ** index with the current table contents. ds@1952: ** ds@1952: ** The db->init.busy is 0 when the user first enters a CREATE INDEX ds@1952: ** command. db->init.busy is 1 when a database is opened and ds@1952: ** CREATE INDEX statements are read out of the master table. In ds@1952: ** the latter case the index already exists on disk, which is why ds@1952: ** we don't want to recreate it. ds@1952: ** ds@1952: ** If pTblName==0 it means this index is generated as a primary key ds@1952: ** or UNIQUE constraint of a CREATE TABLE statement. Since the table ds@1952: ** has just been created, it contains no data and the index initialization ds@1952: ** step can be skipped. ds@1952: */ ds@1952: else if( db->init.busy==0 ){ ds@1952: Vdbe *v; ds@1952: char *zStmt; ds@1952: int iMem = pParse->nMem++; ds@1952: ds@1952: v = sqlite3GetVdbe(pParse); ds@1952: if( v==0 ) goto exit_create_index; ds@1952: ds@1952: ds@1952: /* Create the rootpage for the index ds@1952: */ ds@1952: sqlite3BeginWriteOperation(pParse, 1, iDb); ds@1952: sqlite3VdbeAddOp(v, OP_CreateIndex, iDb, 0); ds@1952: sqlite3VdbeAddOp(v, OP_MemStore, iMem, 0); ds@1952: ds@1952: /* Gather the complete text of the CREATE INDEX statement into ds@1952: ** the zStmt variable ds@1952: */ ds@1952: if( pStart && pEnd ){ ds@1952: /* A named index with an explicit CREATE INDEX statement */ ds@1952: zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s", ds@1952: onError==OE_None ? "" : " UNIQUE", ds@1952: pEnd->z - pName->z + 1, ds@1952: pName->z); ds@1952: }else{ ds@1952: /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */ ds@1952: /* zStmt = sqlite3MPrintf(""); */ ds@1952: zStmt = 0; ds@1952: } ds@1952: ds@1952: /* Add an entry in sqlite_master for this index ds@1952: */ ds@1952: sqlite3NestedParse(pParse, ds@1952: "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#0,%Q);", ds@1952: db->aDb[iDb].zName, SCHEMA_TABLE(iDb), ds@1952: pIndex->zName, ds@1952: pTab->zName, ds@1952: zStmt ds@1952: ); ds@1952: sqlite3VdbeAddOp(v, OP_Pop, 1, 0); ds@1952: sqlite3_free(zStmt); ds@1952: ds@1952: /* Fill the index with data and reparse the schema. Code an OP_Expire ds@1952: ** to invalidate all pre-compiled statements. ds@1952: */ ds@1952: if( pTblName ){ ds@1952: sqlite3RefillIndex(pParse, pIndex, iMem); ds@1952: sqlite3ChangeCookie(db, v, iDb); ds@1952: sqlite3VdbeOp3(v, OP_ParseSchema, iDb, 0, ds@1952: sqlite3MPrintf(db, "name='%q'", pIndex->zName), P3_DYNAMIC); ds@1952: sqlite3VdbeAddOp(v, OP_Expire, 0, 0); ds@1952: } ds@1952: } ds@1952: ds@1952: /* When adding an index to the list of indices for a table, make ds@1952: ** sure all indices labeled OE_Replace come after all those labeled ds@1952: ** OE_Ignore. This is necessary for the correct operation of UPDATE ds@1952: ** and INSERT. ds@1952: */ ds@1952: if( db->init.busy || pTblName==0 ){ ds@1952: if( onError!=OE_Replace || pTab->pIndex==0 ds@1952: || pTab->pIndex->onError==OE_Replace){ ds@1952: pIndex->pNext = pTab->pIndex; ds@1952: pTab->pIndex = pIndex; ds@1952: }else{ ds@1952: Index *pOther = pTab->pIndex; ds@1952: while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){ ds@1952: pOther = pOther->pNext; ds@1952: } ds@1952: pIndex->pNext = pOther->pNext; ds@1952: pOther->pNext = pIndex; ds@1952: } ds@1952: pIndex = 0; ds@1952: } ds@1952: ds@1952: /* Clean up before exiting */ ds@1952: exit_create_index: ds@1952: if( pIndex ){ ds@1952: freeIndex(pIndex); ds@1952: } ds@1952: sqlite3ExprListDelete(pList); ds@1952: sqlite3SrcListDelete(pTblName); ds@1952: sqlite3_free(zName); ds@1952: return; ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Generate code to make sure the file format number is at least minFormat. ds@1952: ** The generated code will increase the file format number if necessary. ds@1952: */ ds@1952: void sqlite3MinimumFileFormat(Parse *pParse, int iDb, int minFormat){ ds@1952: Vdbe *v; ds@1952: v = sqlite3GetVdbe(pParse); ds@1952: if( v ){ ds@1952: sqlite3VdbeAddOp(v, OP_ReadCookie, iDb, 1); ds@1952: sqlite3VdbeUsesBtree(v, iDb); ds@1952: sqlite3VdbeAddOp(v, OP_Integer, minFormat, 0); ds@1952: sqlite3VdbeAddOp(v, OP_Ge, 0, sqlite3VdbeCurrentAddr(v)+3); ds@1952: sqlite3VdbeAddOp(v, OP_Integer, minFormat, 0); ds@1952: sqlite3VdbeAddOp(v, OP_SetCookie, iDb, 1); ds@1952: } ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Fill the Index.aiRowEst[] array with default information - information ds@1952: ** to be used when we have not run the ANALYZE command. ds@1952: ** ds@1952: ** aiRowEst[0] is suppose to contain the number of elements in the index. ds@1952: ** Since we do not know, guess 1 million. aiRowEst[1] is an estimate of the ds@1952: ** number of rows in the table that match any particular value of the ds@1952: ** first column of the index. aiRowEst[2] is an estimate of the number ds@1952: ** of rows that match any particular combiniation of the first 2 columns ds@1952: ** of the index. And so forth. It must always be the case that ds@1952: * ds@1952: ** aiRowEst[N]<=aiRowEst[N-1] ds@1952: ** aiRowEst[N]>=1 ds@1952: ** ds@1952: ** Apart from that, we have little to go on besides intuition as to ds@1952: ** how aiRowEst[] should be initialized. The numbers generated here ds@1952: ** are based on typical values found in actual indices. ds@1952: */ ds@1952: void sqlite3DefaultRowEst(Index *pIdx){ ds@1952: unsigned *a = pIdx->aiRowEst; ds@1952: int i; ds@1952: assert( a!=0 ); ds@1952: a[0] = 1000000; ds@1952: for(i=pIdx->nColumn; i>=5; i--){ ds@1952: a[i] = 5; ds@1952: } ds@1952: while( i>=1 ){ ds@1952: a[i] = 11 - i; ds@1952: i--; ds@1952: } ds@1952: if( pIdx->onError!=OE_None ){ ds@1952: a[pIdx->nColumn] = 1; ds@1952: } ds@1952: } ds@1952: ds@1952: /* ds@1952: ** This routine will drop an existing named index. This routine ds@1952: ** implements the DROP INDEX statement. ds@1952: */ ds@1952: void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){ ds@1952: Index *pIndex; ds@1952: Vdbe *v; ds@1952: sqlite3 *db = pParse->db; ds@1952: int iDb; ds@1952: ds@1952: if( pParse->nErr || db->mallocFailed ){ ds@1952: goto exit_drop_index; ds@1952: } ds@1952: assert( pName->nSrc==1 ); ds@1952: if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){ ds@1952: goto exit_drop_index; ds@1952: } ds@1952: pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase); ds@1952: if( pIndex==0 ){ ds@1952: if( !ifExists ){ ds@1952: sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0); ds@1952: } ds@1952: pParse->checkSchema = 1; ds@1952: goto exit_drop_index; ds@1952: } ds@1952: if( pIndex->autoIndex ){ ds@1952: sqlite3ErrorMsg(pParse, "index associated with UNIQUE " ds@1952: "or PRIMARY KEY constraint cannot be dropped", 0); ds@1952: goto exit_drop_index; ds@1952: } ds@1952: iDb = sqlite3SchemaToIndex(db, pIndex->pSchema); ds@1952: #ifndef SQLITE_OMIT_AUTHORIZATION ds@1952: { ds@1952: int code = SQLITE_DROP_INDEX; ds@1952: Table *pTab = pIndex->pTable; ds@1952: const char *zDb = db->aDb[iDb].zName; ds@1952: const char *zTab = SCHEMA_TABLE(iDb); ds@1952: if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){ ds@1952: goto exit_drop_index; ds@1952: } ds@1952: if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX; ds@1952: if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){ ds@1952: goto exit_drop_index; ds@1952: } ds@1952: } ds@1952: #endif ds@1952: ds@1952: /* Generate code to remove the index and from the master table */ ds@1952: v = sqlite3GetVdbe(pParse); ds@1952: if( v ){ ds@1952: sqlite3NestedParse(pParse, ds@1952: "DELETE FROM %Q.%s WHERE name=%Q", ds@1952: db->aDb[iDb].zName, SCHEMA_TABLE(iDb), ds@1952: pIndex->zName ds@1952: ); ds@1952: sqlite3ChangeCookie(db, v, iDb); ds@1952: destroyRootPage(pParse, pIndex->tnum, iDb); ds@1952: sqlite3VdbeOp3(v, OP_DropIndex, iDb, 0, pIndex->zName, 0); ds@1952: } ds@1952: ds@1952: exit_drop_index: ds@1952: sqlite3SrcListDelete(pName); ds@1952: } ds@1952: ds@1952: /* ds@1952: ** pArray is a pointer to an array of objects. Each object in the ds@1952: ** array is szEntry bytes in size. This routine allocates a new ds@1952: ** object on the end of the array. ds@1952: ** ds@1952: ** *pnEntry is the number of entries already in use. *pnAlloc is ds@1952: ** the previously allocated size of the array. initSize is the ds@1952: ** suggested initial array size allocation. ds@1952: ** ds@1952: ** The index of the new entry is returned in *pIdx. ds@1952: ** ds@1952: ** This routine returns a pointer to the array of objects. This ds@1952: ** might be the same as the pArray parameter or it might be a different ds@1952: ** pointer if the array was resized. ds@1952: */ ds@1952: void *sqlite3ArrayAllocate( ds@1952: sqlite3 *db, /* Connection to notify of malloc failures */ ds@1952: void *pArray, /* Array of objects. Might be reallocated */ ds@1952: int szEntry, /* Size of each object in the array */ ds@1952: int initSize, /* Suggested initial allocation, in elements */ ds@1952: int *pnEntry, /* Number of objects currently in use */ ds@1952: int *pnAlloc, /* Current size of the allocation, in elements */ ds@1952: int *pIdx /* Write the index of a new slot here */ ds@1952: ){ ds@1952: char *z; ds@1952: if( *pnEntry >= *pnAlloc ){ ds@1952: void *pNew; ds@1952: int newSize; ds@1952: newSize = (*pnAlloc)*2 + initSize; ds@1952: pNew = sqlite3DbRealloc(db, pArray, newSize*szEntry); ds@1952: if( pNew==0 ){ ds@1952: *pIdx = -1; ds@1952: return pArray; ds@1952: } ds@1952: *pnAlloc = newSize; ds@1952: pArray = pNew; ds@1952: } ds@1952: z = (char*)pArray; ds@1952: memset(&z[*pnEntry * szEntry], 0, szEntry); ds@1952: *pIdx = *pnEntry; ds@1952: ++*pnEntry; ds@1952: return pArray; ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Append a new element to the given IdList. Create a new IdList if ds@1952: ** need be. ds@1952: ** ds@1952: ** A new IdList is returned, or NULL if malloc() fails. ds@1952: */ ds@1952: IdList *sqlite3IdListAppend(sqlite3 *db, IdList *pList, Token *pToken){ ds@1952: int i; ds@1952: if( pList==0 ){ ds@1952: pList = sqlite3DbMallocZero(db, sizeof(IdList) ); ds@1952: if( pList==0 ) return 0; ds@1952: pList->nAlloc = 0; ds@1952: } ds@1952: pList->a = sqlite3ArrayAllocate( ds@1952: db, ds@1952: pList->a, ds@1952: sizeof(pList->a[0]), ds@1952: 5, ds@1952: &pList->nId, ds@1952: &pList->nAlloc, ds@1952: &i ds@1952: ); ds@1952: if( i<0 ){ ds@1952: sqlite3IdListDelete(pList); ds@1952: return 0; ds@1952: } ds@1952: pList->a[i].zName = sqlite3NameFromToken(db, pToken); ds@1952: return pList; ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Delete an IdList. ds@1952: */ ds@1952: void sqlite3IdListDelete(IdList *pList){ ds@1952: int i; ds@1952: if( pList==0 ) return; ds@1952: for(i=0; inId; i++){ ds@1952: sqlite3_free(pList->a[i].zName); ds@1952: } ds@1952: sqlite3_free(pList->a); ds@1952: sqlite3_free(pList); ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Return the index in pList of the identifier named zId. Return -1 ds@1952: ** if not found. ds@1952: */ ds@1952: int sqlite3IdListIndex(IdList *pList, const char *zName){ ds@1952: int i; ds@1952: if( pList==0 ) return -1; ds@1952: for(i=0; inId; i++){ ds@1952: if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i; ds@1952: } ds@1952: return -1; ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Append a new table name to the given SrcList. Create a new SrcList if ds@1952: ** need be. A new entry is created in the SrcList even if pToken is NULL. ds@1952: ** ds@1952: ** A new SrcList is returned, or NULL if malloc() fails. ds@1952: ** ds@1952: ** If pDatabase is not null, it means that the table has an optional ds@1952: ** database name prefix. Like this: "database.table". The pDatabase ds@1952: ** points to the table name and the pTable points to the database name. ds@1952: ** The SrcList.a[].zName field is filled with the table name which might ds@1952: ** come from pTable (if pDatabase is NULL) or from pDatabase. ds@1952: ** SrcList.a[].zDatabase is filled with the database name from pTable, ds@1952: ** or with NULL if no database is specified. ds@1952: ** ds@1952: ** In other words, if call like this: ds@1952: ** ds@1952: ** sqlite3SrcListAppend(D,A,B,0); ds@1952: ** ds@1952: ** Then B is a table name and the database name is unspecified. If called ds@1952: ** like this: ds@1952: ** ds@1952: ** sqlite3SrcListAppend(D,A,B,C); ds@1952: ** ds@1952: ** Then C is the table name and B is the database name. ds@1952: */ ds@1952: SrcList *sqlite3SrcListAppend( ds@1952: sqlite3 *db, /* Connection to notify of malloc failures */ ds@1952: SrcList *pList, /* Append to this SrcList. NULL creates a new SrcList */ ds@1952: Token *pTable, /* Table to append */ ds@1952: Token *pDatabase /* Database of the table */ ds@1952: ){ ds@1952: struct SrcList_item *pItem; ds@1952: if( pList==0 ){ ds@1952: pList = sqlite3DbMallocZero(db, sizeof(SrcList) ); ds@1952: if( pList==0 ) return 0; ds@1952: pList->nAlloc = 1; ds@1952: } ds@1952: if( pList->nSrc>=pList->nAlloc ){ ds@1952: SrcList *pNew; ds@1952: pList->nAlloc *= 2; ds@1952: pNew = sqlite3DbRealloc(db, pList, ds@1952: sizeof(*pList) + (pList->nAlloc-1)*sizeof(pList->a[0]) ); ds@1952: if( pNew==0 ){ ds@1952: sqlite3SrcListDelete(pList); ds@1952: return 0; ds@1952: } ds@1952: pList = pNew; ds@1952: } ds@1952: pItem = &pList->a[pList->nSrc]; ds@1952: memset(pItem, 0, sizeof(pList->a[0])); ds@1952: if( pDatabase && pDatabase->z==0 ){ ds@1952: pDatabase = 0; ds@1952: } ds@1952: if( pDatabase && pTable ){ ds@1952: Token *pTemp = pDatabase; ds@1952: pDatabase = pTable; ds@1952: pTable = pTemp; ds@1952: } ds@1952: pItem->zName = sqlite3NameFromToken(db, pTable); ds@1952: pItem->zDatabase = sqlite3NameFromToken(db, pDatabase); ds@1952: pItem->iCursor = -1; ds@1952: pItem->isPopulated = 0; ds@1952: pList->nSrc++; ds@1952: return pList; ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Assign cursors to all tables in a SrcList ds@1952: */ ds@1952: void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){ ds@1952: int i; ds@1952: struct SrcList_item *pItem; ds@1952: assert(pList || pParse->db->mallocFailed ); ds@1952: if( pList ){ ds@1952: for(i=0, pItem=pList->a; inSrc; i++, pItem++){ ds@1952: if( pItem->iCursor>=0 ) break; ds@1952: pItem->iCursor = pParse->nTab++; ds@1952: if( pItem->pSelect ){ ds@1952: sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc); ds@1952: } ds@1952: } ds@1952: } ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Delete an entire SrcList including all its substructure. ds@1952: */ ds@1952: void sqlite3SrcListDelete(SrcList *pList){ ds@1952: int i; ds@1952: struct SrcList_item *pItem; ds@1952: if( pList==0 ) return; ds@1952: for(pItem=pList->a, i=0; inSrc; i++, pItem++){ ds@1952: sqlite3_free(pItem->zDatabase); ds@1952: sqlite3_free(pItem->zName); ds@1952: sqlite3_free(pItem->zAlias); ds@1952: sqlite3DeleteTable(pItem->pTab); ds@1952: sqlite3SelectDelete(pItem->pSelect); ds@1952: sqlite3ExprDelete(pItem->pOn); ds@1952: sqlite3IdListDelete(pItem->pUsing); ds@1952: } ds@1952: sqlite3_free(pList); ds@1952: } ds@1952: ds@1952: /* ds@1952: ** This routine is called by the parser to add a new term to the ds@1952: ** end of a growing FROM clause. The "p" parameter is the part of ds@1952: ** the FROM clause that has already been constructed. "p" is NULL ds@1952: ** if this is the first term of the FROM clause. pTable and pDatabase ds@1952: ** are the name of the table and database named in the FROM clause term. ds@1952: ** pDatabase is NULL if the database name qualifier is missing - the ds@1952: ** usual case. If the term has a alias, then pAlias points to the ds@1952: ** alias token. If the term is a subquery, then pSubquery is the ds@1952: ** SELECT statement that the subquery encodes. The pTable and ds@1952: ** pDatabase parameters are NULL for subqueries. The pOn and pUsing ds@1952: ** parameters are the content of the ON and USING clauses. ds@1952: ** ds@1952: ** Return a new SrcList which encodes is the FROM with the new ds@1952: ** term added. ds@1952: */ ds@1952: SrcList *sqlite3SrcListAppendFromTerm( ds@1952: Parse *pParse, /* Parsing context */ ds@1952: SrcList *p, /* The left part of the FROM clause already seen */ ds@1952: Token *pTable, /* Name of the table to add to the FROM clause */ ds@1952: Token *pDatabase, /* Name of the database containing pTable */ ds@1952: Token *pAlias, /* The right-hand side of the AS subexpression */ ds@1952: Select *pSubquery, /* A subquery used in place of a table name */ ds@1952: Expr *pOn, /* The ON clause of a join */ ds@1952: IdList *pUsing /* The USING clause of a join */ ds@1952: ){ ds@1952: struct SrcList_item *pItem; ds@1952: sqlite3 *db = pParse->db; ds@1952: p = sqlite3SrcListAppend(db, p, pTable, pDatabase); ds@1952: if( p==0 || p->nSrc==0 ){ ds@1952: sqlite3ExprDelete(pOn); ds@1952: sqlite3IdListDelete(pUsing); ds@1952: sqlite3SelectDelete(pSubquery); ds@1952: return p; ds@1952: } ds@1952: pItem = &p->a[p->nSrc-1]; ds@1952: if( pAlias && pAlias->n ){ ds@1952: pItem->zAlias = sqlite3NameFromToken(db, pAlias); ds@1952: } ds@1952: pItem->pSelect = pSubquery; ds@1952: pItem->pOn = pOn; ds@1952: pItem->pUsing = pUsing; ds@1952: return p; ds@1952: } ds@1952: ds@1952: /* ds@1952: ** When building up a FROM clause in the parser, the join operator ds@1952: ** is initially attached to the left operand. But the code generator ds@1952: ** expects the join operator to be on the right operand. This routine ds@1952: ** Shifts all join operators from left to right for an entire FROM ds@1952: ** clause. ds@1952: ** ds@1952: ** Example: Suppose the join is like this: ds@1952: ** ds@1952: ** A natural cross join B ds@1952: ** ds@1952: ** The operator is "natural cross join". The A and B operands are stored ds@1952: ** in p->a[0] and p->a[1], respectively. The parser initially stores the ds@1952: ** operator with A. This routine shifts that operator over to B. ds@1952: */ ds@1952: void sqlite3SrcListShiftJoinType(SrcList *p){ ds@1952: if( p && p->a ){ ds@1952: int i; ds@1952: for(i=p->nSrc-1; i>0; i--){ ds@1952: p->a[i].jointype = p->a[i-1].jointype; ds@1952: } ds@1952: p->a[0].jointype = 0; ds@1952: } ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Begin a transaction ds@1952: */ ds@1952: void sqlite3BeginTransaction(Parse *pParse, int type){ ds@1952: sqlite3 *db; ds@1952: Vdbe *v; ds@1952: int i; ds@1952: ds@1952: if( pParse==0 || (db=pParse->db)==0 || db->aDb[0].pBt==0 ) return; ds@1952: if( pParse->nErr || db->mallocFailed ) return; ds@1952: if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ) return; ds@1952: ds@1952: v = sqlite3GetVdbe(pParse); ds@1952: if( !v ) return; ds@1952: if( type!=TK_DEFERRED ){ ds@1952: for(i=0; inDb; i++){ ds@1952: sqlite3VdbeAddOp(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1); ds@1952: sqlite3VdbeUsesBtree(v, i); ds@1952: } ds@1952: } ds@1952: sqlite3VdbeAddOp(v, OP_AutoCommit, 0, 0); ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Commit a transaction ds@1952: */ ds@1952: void sqlite3CommitTransaction(Parse *pParse){ ds@1952: sqlite3 *db; ds@1952: Vdbe *v; ds@1952: ds@1952: if( pParse==0 || (db=pParse->db)==0 || db->aDb[0].pBt==0 ) return; ds@1952: if( pParse->nErr || db->mallocFailed ) return; ds@1952: if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ) return; ds@1952: ds@1952: v = sqlite3GetVdbe(pParse); ds@1952: if( v ){ ds@1952: sqlite3VdbeAddOp(v, OP_AutoCommit, 1, 0); ds@1952: } ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Rollback a transaction ds@1952: */ ds@1952: void sqlite3RollbackTransaction(Parse *pParse){ ds@1952: sqlite3 *db; ds@1952: Vdbe *v; ds@1952: ds@1952: if( pParse==0 || (db=pParse->db)==0 || db->aDb[0].pBt==0 ) return; ds@1952: if( pParse->nErr || db->mallocFailed ) return; ds@1952: if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ) return; ds@1952: ds@1952: v = sqlite3GetVdbe(pParse); ds@1952: if( v ){ ds@1952: sqlite3VdbeAddOp(v, OP_AutoCommit, 1, 1); ds@1952: } ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Make sure the TEMP database is open and available for use. Return ds@1952: ** the number of errors. Leave any error messages in the pParse structure. ds@1952: */ ds@1952: int sqlite3OpenTempDatabase(Parse *pParse){ ds@1952: sqlite3 *db = pParse->db; ds@1952: if( db->aDb[1].pBt==0 && !pParse->explain ){ ds@1952: int rc; ds@1952: static const int flags = ds@1952: SQLITE_OPEN_READWRITE | ds@1952: SQLITE_OPEN_CREATE | ds@1952: SQLITE_OPEN_EXCLUSIVE | ds@1952: SQLITE_OPEN_DELETEONCLOSE | ds@1952: SQLITE_OPEN_TEMP_DB; ds@1952: ds@1952: rc = sqlite3BtreeFactory(db, 0, 0, SQLITE_DEFAULT_CACHE_SIZE, flags, ds@1952: &db->aDb[1].pBt); ds@1952: if( rc!=SQLITE_OK ){ ds@1952: sqlite3ErrorMsg(pParse, "unable to open a temporary database " ds@1952: "file for storing temporary tables"); ds@1952: pParse->rc = rc; ds@1952: return 1; ds@1952: } ds@1952: if( db->flags & !db->autoCommit ){ ds@1952: rc = sqlite3BtreeBeginTrans(db->aDb[1].pBt, 1); ds@1952: if( rc!=SQLITE_OK ){ ds@1952: sqlite3ErrorMsg(pParse, "unable to get a write lock on " ds@1952: "the temporary database file"); ds@1952: pParse->rc = rc; ds@1952: return 1; ds@1952: } ds@1952: } ds@1952: assert( db->aDb[1].pSchema ); ds@1952: } ds@1952: return 0; ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Generate VDBE code that will verify the schema cookie and start ds@1952: ** a read-transaction for all named database files. ds@1952: ** ds@1952: ** It is important that all schema cookies be verified and all ds@1952: ** read transactions be started before anything else happens in ds@1952: ** the VDBE program. But this routine can be called after much other ds@1952: ** code has been generated. So here is what we do: ds@1952: ** ds@1952: ** The first time this routine is called, we code an OP_Goto that ds@1952: ** will jump to a subroutine at the end of the program. Then we ds@1952: ** record every database that needs its schema verified in the ds@1952: ** pParse->cookieMask field. Later, after all other code has been ds@1952: ** generated, the subroutine that does the cookie verifications and ds@1952: ** starts the transactions will be coded and the OP_Goto P2 value ds@1952: ** will be made to point to that subroutine. The generation of the ds@1952: ** cookie verification subroutine code happens in sqlite3FinishCoding(). ds@1952: ** ds@1952: ** If iDb<0 then code the OP_Goto only - don't set flag to verify the ds@1952: ** schema on any databases. This can be used to position the OP_Goto ds@1952: ** early in the code, before we know if any database tables will be used. ds@1952: */ ds@1952: void sqlite3CodeVerifySchema(Parse *pParse, int iDb){ ds@1952: sqlite3 *db; ds@1952: Vdbe *v; ds@1952: int mask; ds@1952: ds@1952: v = sqlite3GetVdbe(pParse); ds@1952: if( v==0 ) return; /* This only happens if there was a prior error */ ds@1952: db = pParse->db; ds@1952: if( pParse->cookieGoto==0 ){ ds@1952: pParse->cookieGoto = sqlite3VdbeAddOp(v, OP_Goto, 0, 0)+1; ds@1952: } ds@1952: if( iDb>=0 ){ ds@1952: assert( iDbnDb ); ds@1952: assert( db->aDb[iDb].pBt!=0 || iDb==1 ); ds@1952: assert( iDbcookieMask & mask)==0 ){ ds@1952: pParse->cookieMask |= mask; ds@1952: pParse->cookieValue[iDb] = db->aDb[iDb].pSchema->schema_cookie; ds@1952: if( !OMIT_TEMPDB && iDb==1 ){ ds@1952: sqlite3OpenTempDatabase(pParse); ds@1952: } ds@1952: } ds@1952: } ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Generate VDBE code that prepares for doing an operation that ds@1952: ** might change the database. ds@1952: ** ds@1952: ** This routine starts a new transaction if we are not already within ds@1952: ** a transaction. If we are already within a transaction, then a checkpoint ds@1952: ** is set if the setStatement parameter is true. A checkpoint should ds@1952: ** be set for operations that might fail (due to a constraint) part of ds@1952: ** the way through and which will need to undo some writes without having to ds@1952: ** rollback the whole transaction. For operations where all constraints ds@1952: ** can be checked before any changes are made to the database, it is never ds@1952: ** necessary to undo a write and the checkpoint should not be set. ds@1952: ** ds@1952: ** Only database iDb and the temp database are made writable by this call. ds@1952: ** If iDb==0, then the main and temp databases are made writable. If ds@1952: ** iDb==1 then only the temp database is made writable. If iDb>1 then the ds@1952: ** specified auxiliary database and the temp database are made writable. ds@1952: */ ds@1952: void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){ ds@1952: Vdbe *v = sqlite3GetVdbe(pParse); ds@1952: if( v==0 ) return; ds@1952: sqlite3CodeVerifySchema(pParse, iDb); ds@1952: pParse->writeMask |= 1<nested==0 ){ ds@1952: sqlite3VdbeAddOp(v, OP_Statement, iDb, 0); ds@1952: } ds@1952: if( (OMIT_TEMPDB || iDb!=1) && pParse->db->aDb[1].pBt!=0 ){ ds@1952: sqlite3BeginWriteOperation(pParse, setStatement, 1); ds@1952: } ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Check to see if pIndex uses the collating sequence pColl. Return ds@1952: ** true if it does and false if it does not. ds@1952: */ ds@1952: #ifndef SQLITE_OMIT_REINDEX ds@1952: static int collationMatch(const char *zColl, Index *pIndex){ ds@1952: int i; ds@1952: for(i=0; inColumn; i++){ ds@1952: const char *z = pIndex->azColl[i]; ds@1952: if( z==zColl || (z && zColl && 0==sqlite3StrICmp(z, zColl)) ){ ds@1952: return 1; ds@1952: } ds@1952: } ds@1952: return 0; ds@1952: } ds@1952: #endif ds@1952: ds@1952: /* ds@1952: ** Recompute all indices of pTab that use the collating sequence pColl. ds@1952: ** If pColl==0 then recompute all indices of pTab. ds@1952: */ ds@1952: #ifndef SQLITE_OMIT_REINDEX ds@1952: static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){ ds@1952: Index *pIndex; /* An index associated with pTab */ ds@1952: ds@1952: for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){ ds@1952: if( zColl==0 || collationMatch(zColl, pIndex) ){ ds@1952: int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema); ds@1952: sqlite3BeginWriteOperation(pParse, 0, iDb); ds@1952: sqlite3RefillIndex(pParse, pIndex, -1); ds@1952: } ds@1952: } ds@1952: } ds@1952: #endif ds@1952: ds@1952: /* ds@1952: ** Recompute all indices of all tables in all databases where the ds@1952: ** indices use the collating sequence pColl. If pColl==0 then recompute ds@1952: ** all indices everywhere. ds@1952: */ ds@1952: #ifndef SQLITE_OMIT_REINDEX ds@1952: static void reindexDatabases(Parse *pParse, char const *zColl){ ds@1952: Db *pDb; /* A single database */ ds@1952: int iDb; /* The database index number */ ds@1952: sqlite3 *db = pParse->db; /* The database connection */ ds@1952: HashElem *k; /* For looping over tables in pDb */ ds@1952: Table *pTab; /* A table in the database */ ds@1952: ds@1952: for(iDb=0, pDb=db->aDb; iDbnDb; iDb++, pDb++){ ds@1952: assert( pDb!=0 ); ds@1952: for(k=sqliteHashFirst(&pDb->pSchema->tblHash); k; k=sqliteHashNext(k)){ ds@1952: pTab = (Table*)sqliteHashData(k); ds@1952: reindexTable(pParse, pTab, zColl); ds@1952: } ds@1952: } ds@1952: } ds@1952: #endif ds@1952: ds@1952: /* ds@1952: ** Generate code for the REINDEX command. ds@1952: ** ds@1952: ** REINDEX -- 1 ds@1952: ** REINDEX -- 2 ds@1952: ** REINDEX ?.? -- 3 ds@1952: ** REINDEX ?.? -- 4 ds@1952: ** ds@1952: ** Form 1 causes all indices in all attached databases to be rebuilt. ds@1952: ** Form 2 rebuilds all indices in all databases that use the named ds@1952: ** collating function. Forms 3 and 4 rebuild the named index or all ds@1952: ** indices associated with the named table. ds@1952: */ ds@1952: #ifndef SQLITE_OMIT_REINDEX ds@1952: void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){ ds@1952: CollSeq *pColl; /* Collating sequence to be reindexed, or NULL */ ds@1952: char *z; /* Name of a table or index */ ds@1952: const char *zDb; /* Name of the database */ ds@1952: Table *pTab; /* A table in the database */ ds@1952: Index *pIndex; /* An index associated with pTab */ ds@1952: int iDb; /* The database index number */ ds@1952: sqlite3 *db = pParse->db; /* The database connection */ ds@1952: Token *pObjName; /* Name of the table or index to be reindexed */ ds@1952: ds@1952: /* Read the database schema. If an error occurs, leave an error message ds@1952: ** and code in pParse and return NULL. */ ds@1952: if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){ ds@1952: return; ds@1952: } ds@1952: ds@1952: if( pName1==0 || pName1->z==0 ){ ds@1952: reindexDatabases(pParse, 0); ds@1952: return; ds@1952: }else if( pName2==0 || pName2->z==0 ){ ds@1952: assert( pName1->z ); ds@1952: pColl = sqlite3FindCollSeq(db, ENC(db), (char*)pName1->z, pName1->n, 0); ds@1952: if( pColl ){ ds@1952: char *zColl = sqlite3DbStrNDup(db, (const char *)pName1->z, pName1->n); ds@1952: if( zColl ){ ds@1952: reindexDatabases(pParse, zColl); ds@1952: sqlite3_free(zColl); ds@1952: } ds@1952: return; ds@1952: } ds@1952: } ds@1952: iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName); ds@1952: if( iDb<0 ) return; ds@1952: z = sqlite3NameFromToken(db, pObjName); ds@1952: if( z==0 ) return; ds@1952: zDb = db->aDb[iDb].zName; ds@1952: pTab = sqlite3FindTable(db, z, zDb); ds@1952: if( pTab ){ ds@1952: reindexTable(pParse, pTab, 0); ds@1952: sqlite3_free(z); ds@1952: return; ds@1952: } ds@1952: pIndex = sqlite3FindIndex(db, z, zDb); ds@1952: sqlite3_free(z); ds@1952: if( pIndex ){ ds@1952: sqlite3BeginWriteOperation(pParse, 0, iDb); ds@1952: sqlite3RefillIndex(pParse, pIndex, -1); ds@1952: return; ds@1952: } ds@1952: sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed"); ds@1952: } ds@1952: #endif ds@1952: ds@1952: /* ds@1952: ** Return a dynamicly allocated KeyInfo structure that can be used ds@1952: ** with OP_OpenRead or OP_OpenWrite to access database index pIdx. ds@1952: ** ds@1952: ** If successful, a pointer to the new structure is returned. In this case ds@1952: ** the caller is responsible for calling sqlite3_free() on the returned ds@1952: ** pointer. If an error occurs (out of memory or missing collation ds@1952: ** sequence), NULL is returned and the state of pParse updated to reflect ds@1952: ** the error. ds@1952: */ ds@1952: KeyInfo *sqlite3IndexKeyinfo(Parse *pParse, Index *pIdx){ ds@1952: int i; ds@1952: int nCol = pIdx->nColumn; ds@1952: int nBytes = sizeof(KeyInfo) + (nCol-1)*sizeof(CollSeq*) + nCol; ds@1952: KeyInfo *pKey = (KeyInfo *)sqlite3DbMallocZero(pParse->db, nBytes); ds@1952: ds@1952: if( pKey ){ ds@1952: pKey->db = pParse->db; ds@1952: pKey->aSortOrder = (u8 *)&(pKey->aColl[nCol]); ds@1952: assert( &pKey->aSortOrder[nCol]==&(((u8 *)pKey)[nBytes]) ); ds@1952: for(i=0; iazColl[i]; ds@1952: assert( zColl ); ds@1952: pKey->aColl[i] = sqlite3LocateCollSeq(pParse, zColl, -1); ds@1952: pKey->aSortOrder[i] = pIdx->aSortOrder[i]; ds@1952: } ds@1952: pKey->nField = nCol; ds@1952: } ds@1952: ds@1952: if( pParse->nErr ){ ds@1952: sqlite3_free(pKey); ds@1952: pKey = 0; ds@1952: } ds@1952: return pKey; ds@1952: }