4 ** The author disclaims copyright to this source code. In place of
5 ** a legal notice, here is a blessing:
7 ** May you do good and not evil.
8 ** May you find forgiveness for yourself and forgive others.
9 ** May you share freely, never taking more than you give.
11 *************************************************************************
12 ** This file contains C code routines that are called by the SQLite parser
13 ** when syntax rules are reduced. The routines in this file handle the
14 ** following kinds of SQL syntax:
27 #include "sqliteInt.h"
31 ** This routine is called when a new SQL statement is beginning to
32 ** be parsed. Initialize the pParse structure as needed.
34 void sqlite3BeginParse(Parse *pParse, int explainFlag){
35 pParse->explain = explainFlag;
39 #ifndef SQLITE_OMIT_SHARED_CACHE
41 ** The TableLock structure is only used by the sqlite3TableLock() and
42 ** codeTableLocks() functions.
45 int iDb; /* The database containing the table to be locked */
46 int iTab; /* The root page of the table to be locked */
47 u8 isWriteLock; /* True for write lock. False for a read lock */
48 const char *zName; /* Name of the table */
52 ** Record the fact that we want to lock a table at run-time.
54 ** The table to be locked has root page iTab and is found in database iDb.
55 ** A read or a write lock can be taken depending on isWritelock.
57 ** This routine just records the fact that the lock is desired. The
58 ** code to make the lock occur is generated by a later call to
59 ** codeTableLocks() which occurs during sqlite3FinishCoding().
61 void sqlite3TableLock(
62 Parse *pParse, /* Parsing context */
63 int iDb, /* Index of the database containing the table to lock */
64 int iTab, /* Root page number of the table to be locked */
65 u8 isWriteLock, /* True for a write lock */
66 const char *zName /* Name of the table to be locked */
76 for(i=0; i<pParse->nTableLock; i++){
77 p = &pParse->aTableLock[i];
78 if( p->iDb==iDb && p->iTab==iTab ){
79 p->isWriteLock = (p->isWriteLock || isWriteLock);
84 nBytes = sizeof(TableLock) * (pParse->nTableLock+1);
86 sqlite3DbReallocOrFree(pParse->db, pParse->aTableLock, nBytes);
87 if( pParse->aTableLock ){
88 p = &pParse->aTableLock[pParse->nTableLock++];
91 p->isWriteLock = isWriteLock;
94 pParse->nTableLock = 0;
95 pParse->db->mallocFailed = 1;
100 ** Code an OP_TableLock instruction for each table locked by the
101 ** statement (configured by calls to sqlite3TableLock()).
103 static void codeTableLocks(Parse *pParse){
107 if( 0==(pVdbe = sqlite3GetVdbe(pParse)) ){
111 for(i=0; i<pParse->nTableLock; i++){
112 TableLock *p = &pParse->aTableLock[i];
114 if( p->isWriteLock ){
117 sqlite3VdbeOp3(pVdbe, OP_TableLock, p1, p->iTab, p->zName, P3_STATIC);
121 #define codeTableLocks(x)
125 ** This routine is called after a single SQL statement has been
126 ** parsed and a VDBE program to execute that statement has been
127 ** prepared. This routine puts the finishing touches on the
128 ** VDBE program and resets the pParse structure for the next
131 ** Note that if an error occurred, it might be the case that
132 ** no VDBE code was generated.
134 void sqlite3FinishCoding(Parse *pParse){
139 if( db->mallocFailed ) return;
140 if( pParse->nested ) return;
141 if( !pParse->pVdbe ){
142 if( pParse->rc==SQLITE_OK && pParse->nErr ){
143 pParse->rc = SQLITE_ERROR;
148 /* Begin by generating some termination code at the end of the
151 v = sqlite3GetVdbe(pParse);
153 sqlite3VdbeAddOp(v, OP_Halt, 0, 0);
155 /* The cookie mask contains one bit for each database file open.
156 ** (Bit 0 is for main, bit 1 is for temp, and so forth.) Bits are
157 ** set for each database that is used. Generate code to start a
158 ** transaction on each used database and to verify the schema cookie
159 ** on each used database.
161 if( pParse->cookieGoto>0 ){
164 sqlite3VdbeJumpHere(v, pParse->cookieGoto-1);
165 for(iDb=0, mask=1; iDb<db->nDb; mask<<=1, iDb++){
166 if( (mask & pParse->cookieMask)==0 ) continue;
167 sqlite3VdbeUsesBtree(v, iDb);
168 sqlite3VdbeAddOp(v, OP_Transaction, iDb, (mask & pParse->writeMask)!=0);
169 sqlite3VdbeAddOp(v, OP_VerifyCookie, iDb, pParse->cookieValue[iDb]);
171 #ifndef SQLITE_OMIT_VIRTUALTABLE
172 if( pParse->pVirtualLock ){
173 char *vtab = (char *)pParse->pVirtualLock->pVtab;
174 sqlite3VdbeOp3(v, OP_VBegin, 0, 0, vtab, P3_VTAB);
178 /* Once all the cookies have been verified and transactions opened,
179 ** obtain the required table-locks. This is a no-op unless the
180 ** shared-cache feature is enabled.
182 codeTableLocks(pParse);
183 sqlite3VdbeAddOp(v, OP_Goto, 0, pParse->cookieGoto);
186 #ifndef SQLITE_OMIT_TRACE
187 /* Add a No-op that contains the complete text of the compiled SQL
188 ** statement as its P3 argument. This does not change the functionality
191 ** This is used to implement sqlite3_trace().
193 sqlite3VdbeOp3(v, OP_Noop, 0, 0, pParse->zSql, pParse->zTail-pParse->zSql);
194 #endif /* SQLITE_OMIT_TRACE */
198 /* Get the VDBE program ready for execution
200 if( v && pParse->nErr==0 && !db->mallocFailed ){
202 FILE *trace = (db->flags & SQLITE_VdbeTrace)!=0 ? stdout : 0;
203 sqlite3VdbeTrace(v, trace);
205 sqlite3VdbeMakeReady(v, pParse->nVar, pParse->nMem+3,
206 pParse->nTab+3, pParse->explain);
207 pParse->rc = SQLITE_DONE;
208 pParse->colNamesSet = 0;
209 }else if( pParse->rc==SQLITE_OK ){
210 pParse->rc = SQLITE_ERROR;
216 pParse->cookieMask = 0;
217 pParse->cookieGoto = 0;
221 ** Run the parser and code generator recursively in order to generate
222 ** code for the SQL statement given onto the end of the pParse context
223 ** currently under construction. When the parser is run recursively
224 ** this way, the final OP_Halt is not appended and other initialization
225 ** and finalization steps are omitted because those are handling by the
228 ** Not everything is nestable. This facility is designed to permit
229 ** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER. Use
230 ** care if you decide to try to use this routine for some other purposes.
232 void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
235 # define SAVE_SZ (sizeof(Parse) - offsetof(Parse,nVar))
236 char saveBuf[SAVE_SZ];
238 if( pParse->nErr ) return;
239 assert( pParse->nested<10 ); /* Nesting should only be of limited depth */
240 va_start(ap, zFormat);
241 zSql = sqlite3VMPrintf(pParse->db, zFormat, ap);
244 pParse->db->mallocFailed = 1;
245 return; /* A malloc must have failed */
248 memcpy(saveBuf, &pParse->nVar, SAVE_SZ);
249 memset(&pParse->nVar, 0, SAVE_SZ);
250 sqlite3RunParser(pParse, zSql, 0);
252 memcpy(&pParse->nVar, saveBuf, SAVE_SZ);
257 ** Locate the in-memory structure that describes a particular database
258 ** table given the name of that table and (optionally) the name of the
259 ** database containing the table. Return NULL if not found.
261 ** If zDatabase is 0, all databases are searched for the table and the
262 ** first matching table is returned. (No checking for duplicate table
263 ** names is done.) The search order is TEMP first, then MAIN, then any
264 ** auxiliary databases added using the ATTACH command.
266 ** See also sqlite3LocateTable().
268 Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
272 for(i=OMIT_TEMPDB; i<db->nDb; i++){
273 int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
274 if( zDatabase!=0 && sqlite3StrICmp(zDatabase, db->aDb[j].zName) ) continue;
275 p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName, strlen(zName)+1);
282 ** Locate the in-memory structure that describes a particular database
283 ** table given the name of that table and (optionally) the name of the
284 ** database containing the table. Return NULL if not found. Also leave an
285 ** error message in pParse->zErrMsg.
287 ** The difference between this routine and sqlite3FindTable() is that this
288 ** routine leaves an error message in pParse->zErrMsg where
289 ** sqlite3FindTable() does not.
291 Table *sqlite3LocateTable(Parse *pParse, const char *zName, const char *zDbase){
294 /* Read the database schema. If an error occurs, leave an error message
295 ** and code in pParse and return NULL. */
296 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
300 p = sqlite3FindTable(pParse->db, zName, zDbase);
303 sqlite3ErrorMsg(pParse, "no such table: %s.%s", zDbase, zName);
305 sqlite3ErrorMsg(pParse, "no such table: %s", zName);
307 pParse->checkSchema = 1;
313 ** Locate the in-memory structure that describes
314 ** a particular index given the name of that index
315 ** and the name of the database that contains the index.
316 ** Return NULL if not found.
318 ** If zDatabase is 0, all databases are searched for the
319 ** table and the first matching index is returned. (No checking
320 ** for duplicate index names is done.) The search order is
321 ** TEMP first, then MAIN, then any auxiliary databases added
322 ** using the ATTACH command.
324 Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
327 for(i=OMIT_TEMPDB; i<db->nDb; i++){
328 int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
329 Schema *pSchema = db->aDb[j].pSchema;
330 if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zName) ) continue;
331 assert( pSchema || (j==1 && !db->aDb[1].pBt) );
333 p = sqlite3HashFind(&pSchema->idxHash, zName, strlen(zName)+1);
341 ** Reclaim the memory used by an index
343 static void freeIndex(Index *p){
344 sqlite3_free(p->zColAff);
349 ** Remove the given index from the index hash table, and free
350 ** its memory structures.
352 ** The index is removed from the database hash tables but
353 ** it is not unlinked from the Table that it indexes.
354 ** Unlinking from the Table must be done by the calling function.
356 static void sqliteDeleteIndex(Index *p){
358 const char *zName = p->zName;
360 pOld = sqlite3HashInsert(&p->pSchema->idxHash, zName, strlen( zName)+1, 0);
361 assert( pOld==0 || pOld==p );
366 ** For the index called zIdxName which is found in the database iDb,
367 ** unlike that index from its Table then remove the index from
368 ** the index hash table and free all memory structures associated
371 void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
374 Hash *pHash = &db->aDb[iDb].pSchema->idxHash;
376 len = strlen(zIdxName);
377 pIndex = sqlite3HashInsert(pHash, zIdxName, len+1, 0);
379 if( pIndex->pTable->pIndex==pIndex ){
380 pIndex->pTable->pIndex = pIndex->pNext;
383 for(p=pIndex->pTable->pIndex; p && p->pNext!=pIndex; p=p->pNext){}
384 if( p && p->pNext==pIndex ){
385 p->pNext = pIndex->pNext;
390 db->flags |= SQLITE_InternChanges;
394 ** Erase all schema information from the in-memory hash tables of
395 ** a single database. This routine is called to reclaim memory
396 ** before the database closes. It is also called during a rollback
397 ** if there were schema changes during the transaction or if a
398 ** schema-cookie mismatch occurs.
400 ** If iDb<=0 then reset the internal schema tables for all database
401 ** files. If iDb>=2 then reset the internal schema for only the
402 ** single file indicated.
404 void sqlite3ResetInternalSchema(sqlite3 *db, int iDb){
407 assert( iDb>=0 && iDb<db->nDb );
408 for(i=iDb; i<db->nDb; i++){
409 Db *pDb = &db->aDb[i];
411 sqlite3SchemaFree(pDb->pSchema);
416 db->flags &= ~SQLITE_InternChanges;
418 /* If one or more of the auxiliary database files has been closed,
419 ** then remove them from the auxiliary database list. We take the
420 ** opportunity to do this here since we have just deleted all of the
421 ** schema hash tables and therefore do not have to make any changes
422 ** to any of those tables.
424 for(i=0; i<db->nDb; i++){
425 struct Db *pDb = &db->aDb[i];
427 if( pDb->pAux && pDb->xFreeAux ) pDb->xFreeAux(pDb->pAux);
431 for(i=j=2; i<db->nDb; i++){
432 struct Db *pDb = &db->aDb[i];
434 sqlite3_free(pDb->zName);
439 db->aDb[j] = db->aDb[i];
443 memset(&db->aDb[j], 0, (db->nDb-j)*sizeof(db->aDb[j]));
445 if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
446 memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
447 sqlite3_free(db->aDb);
448 db->aDb = db->aDbStatic;
453 ** This routine is called when a commit occurs.
455 void sqlite3CommitInternalChanges(sqlite3 *db){
456 db->flags &= ~SQLITE_InternChanges;
460 ** Clear the column names from a table or view.
462 static void sqliteResetColumnNames(Table *pTable){
466 if( (pCol = pTable->aCol)!=0 ){
467 for(i=0; i<pTable->nCol; i++, pCol++){
468 sqlite3_free(pCol->zName);
469 sqlite3ExprDelete(pCol->pDflt);
470 sqlite3_free(pCol->zType);
471 sqlite3_free(pCol->zColl);
473 sqlite3_free(pTable->aCol);
480 ** Remove the memory data structures associated with the given
481 ** Table. No changes are made to disk by this routine.
483 ** This routine just deletes the data structure. It does not unlink
484 ** the table data structure from the hash table. Nor does it remove
485 ** foreign keys from the sqlite.aFKey hash table. But it does destroy
486 ** memory structures of the indices and foreign keys associated with
489 void sqlite3DeleteTable(Table *pTable){
490 Index *pIndex, *pNext;
491 FKey *pFKey, *pNextFKey;
493 if( pTable==0 ) return;
495 /* Do not delete the table until the reference count reaches zero. */
497 if( pTable->nRef>0 ){
500 assert( pTable->nRef==0 );
502 /* Delete all indices associated with this table
504 for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
505 pNext = pIndex->pNext;
506 assert( pIndex->pSchema==pTable->pSchema );
507 sqliteDeleteIndex(pIndex);
510 #ifndef SQLITE_OMIT_FOREIGN_KEY
511 /* Delete all foreign keys associated with this table. The keys
512 ** should have already been unlinked from the pSchema->aFKey hash table
514 for(pFKey=pTable->pFKey; pFKey; pFKey=pNextFKey){
515 pNextFKey = pFKey->pNextFrom;
516 assert( sqlite3HashFind(&pTable->pSchema->aFKey,
517 pFKey->zTo, strlen(pFKey->zTo)+1)!=pFKey );
522 /* Delete the Table structure itself.
524 sqliteResetColumnNames(pTable);
525 sqlite3_free(pTable->zName);
526 sqlite3_free(pTable->zColAff);
527 sqlite3SelectDelete(pTable->pSelect);
528 #ifndef SQLITE_OMIT_CHECK
529 sqlite3ExprDelete(pTable->pCheck);
531 sqlite3VtabClear(pTable);
532 sqlite3_free(pTable);
536 ** Unlink the given table from the hash tables and the delete the
537 ** table structure with all its indices and foreign keys.
539 void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
545 assert( iDb>=0 && iDb<db->nDb );
546 assert( zTabName && zTabName[0] );
548 p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName, strlen(zTabName)+1,0);
550 #ifndef SQLITE_OMIT_FOREIGN_KEY
551 for(pF1=p->pFKey; pF1; pF1=pF1->pNextFrom){
552 int nTo = strlen(pF1->zTo) + 1;
553 pF2 = sqlite3HashFind(&pDb->pSchema->aFKey, pF1->zTo, nTo);
555 sqlite3HashInsert(&pDb->pSchema->aFKey, pF1->zTo, nTo, pF1->pNextTo);
557 while( pF2 && pF2->pNextTo!=pF1 ){ pF2=pF2->pNextTo; }
559 pF2->pNextTo = pF1->pNextTo;
564 sqlite3DeleteTable(p);
566 db->flags |= SQLITE_InternChanges;
570 ** Given a token, return a string that consists of the text of that
571 ** token with any quotations removed. Space to hold the returned string
572 ** is obtained from sqliteMalloc() and must be freed by the calling
575 ** Tokens are often just pointers into the original SQL text and so
576 ** are not \000 terminated and are not persistent. The returned string
577 ** is \000 terminated and is persistent.
579 char *sqlite3NameFromToken(sqlite3 *db, Token *pName){
582 zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n);
583 sqlite3Dequote(zName);
591 ** Open the sqlite_master table stored in database number iDb for
592 ** writing. The table is opened using cursor 0.
594 void sqlite3OpenMasterTable(Parse *p, int iDb){
595 Vdbe *v = sqlite3GetVdbe(p);
596 sqlite3TableLock(p, iDb, MASTER_ROOT, 1, SCHEMA_TABLE(iDb));
597 sqlite3VdbeAddOp(v, OP_Integer, iDb, 0);
598 sqlite3VdbeAddOp(v, OP_OpenWrite, 0, MASTER_ROOT);
599 sqlite3VdbeAddOp(v, OP_SetNumColumns, 0, 5); /* sqlite_master has 5 columns */
603 ** The token *pName contains the name of a database (either "main" or
604 ** "temp" or the name of an attached db). This routine returns the
605 ** index of the named database in db->aDb[], or -1 if the named db
608 int sqlite3FindDb(sqlite3 *db, Token *pName){
609 int i = -1; /* Database number */
610 int n; /* Number of characters in the name */
611 Db *pDb; /* A database whose name space is being searched */
612 char *zName; /* Name we are searching for */
614 zName = sqlite3NameFromToken(db, pName);
617 for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
618 if( (!OMIT_TEMPDB || i!=1 ) && n==strlen(pDb->zName) &&
619 0==sqlite3StrICmp(pDb->zName, zName) ){
628 /* The table or view or trigger name is passed to this routine via tokens
629 ** pName1 and pName2. If the table name was fully qualified, for example:
631 ** CREATE TABLE xxx.yyy (...);
633 ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
634 ** the table name is not fully qualified, i.e.:
636 ** CREATE TABLE yyy(...);
638 ** Then pName1 is set to "yyy" and pName2 is "".
640 ** This routine sets the *ppUnqual pointer to point at the token (pName1 or
641 ** pName2) that stores the unqualified table name. The index of the
642 ** database "xxx" is returned.
644 int sqlite3TwoPartName(
645 Parse *pParse, /* Parsing and code generating context */
646 Token *pName1, /* The "xxx" in the name "xxx.yyy" or "xxx" */
647 Token *pName2, /* The "yyy" in the name "xxx.yyy" */
648 Token **pUnqual /* Write the unqualified object name here */
650 int iDb; /* Database holding the object */
651 sqlite3 *db = pParse->db;
653 if( pName2 && pName2->n>0 ){
654 assert( !db->init.busy );
656 iDb = sqlite3FindDb(db, pName1);
658 sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
663 assert( db->init.iDb==0 || db->init.busy );
671 ** This routine is used to check if the UTF-8 string zName is a legal
672 ** unqualified name for a new schema object (table, index, view or
673 ** trigger). All names are legal except those that begin with the string
674 ** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
675 ** is reserved for internal use.
677 int sqlite3CheckObjectName(Parse *pParse, const char *zName){
678 if( !pParse->db->init.busy && pParse->nested==0
679 && (pParse->db->flags & SQLITE_WriteSchema)==0
680 && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
681 sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName);
688 ** Begin constructing a new table representation in memory. This is
689 ** the first of several action routines that get called in response
690 ** to a CREATE TABLE statement. In particular, this routine is called
691 ** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
692 ** flag is true if the table should be stored in the auxiliary database
693 ** file instead of in the main database file. This is normally the case
694 ** when the "TEMP" or "TEMPORARY" keyword occurs in between
697 ** The new table record is initialized and put in pParse->pNewTable.
698 ** As more of the CREATE TABLE statement is parsed, additional action
699 ** routines will be called to add more information to this record.
700 ** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
701 ** is called to complete the construction of the new table record.
703 void sqlite3StartTable(
704 Parse *pParse, /* Parser context */
705 Token *pName1, /* First part of the name of the table or view */
706 Token *pName2, /* Second part of the name of the table or view */
707 int isTemp, /* True if this is a TEMP table */
708 int isView, /* True if this is a VIEW */
709 int isVirtual, /* True if this is a VIRTUAL table */
710 int noErr /* Do nothing if table already exists */
713 char *zName = 0; /* The name of the new table */
714 sqlite3 *db = pParse->db;
716 int iDb; /* Database number to create the table in */
717 Token *pName; /* Unqualified name of the table to create */
719 /* The table or view name to create is passed to this routine via tokens
720 ** pName1 and pName2. If the table name was fully qualified, for example:
722 ** CREATE TABLE xxx.yyy (...);
724 ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
725 ** the table name is not fully qualified, i.e.:
727 ** CREATE TABLE yyy(...);
729 ** Then pName1 is set to "yyy" and pName2 is "".
731 ** The call below sets the pName pointer to point at the token (pName1 or
732 ** pName2) that stores the unqualified table name. The variable iDb is
733 ** set to the index of the database that the table or view is to be
736 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
738 if( !OMIT_TEMPDB && isTemp && iDb>1 ){
739 /* If creating a temp table, the name may not be qualified */
740 sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
743 if( !OMIT_TEMPDB && isTemp ) iDb = 1;
745 pParse->sNameToken = *pName;
746 zName = sqlite3NameFromToken(db, pName);
747 if( zName==0 ) return;
748 if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
749 goto begin_table_error;
751 if( db->init.iDb==1 ) isTemp = 1;
752 #ifndef SQLITE_OMIT_AUTHORIZATION
753 assert( (isTemp & 1)==isTemp );
756 char *zDb = db->aDb[iDb].zName;
757 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
758 goto begin_table_error;
761 if( !OMIT_TEMPDB && isTemp ){
762 code = SQLITE_CREATE_TEMP_VIEW;
764 code = SQLITE_CREATE_VIEW;
767 if( !OMIT_TEMPDB && isTemp ){
768 code = SQLITE_CREATE_TEMP_TABLE;
770 code = SQLITE_CREATE_TABLE;
773 if( !isVirtual && sqlite3AuthCheck(pParse, code, zName, 0, zDb) ){
774 goto begin_table_error;
779 /* Make sure the new table name does not collide with an existing
780 ** index or table name in the same database. Issue an error message if
781 ** it does. The exception is if the statement being parsed was passed
782 ** to an sqlite3_declare_vtab() call. In that case only the column names
783 ** and types will be used, so there is no need to test for namespace
786 if( !IN_DECLARE_VTAB ){
787 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
788 goto begin_table_error;
790 pTable = sqlite3FindTable(db, zName, db->aDb[iDb].zName);
793 sqlite3ErrorMsg(pParse, "table %T already exists", pName);
795 goto begin_table_error;
797 if( sqlite3FindIndex(db, zName, 0)!=0 && (iDb==0 || !db->init.busy) ){
798 sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
799 goto begin_table_error;
803 pTable = sqlite3DbMallocZero(db, sizeof(Table));
805 db->mallocFailed = 1;
806 pParse->rc = SQLITE_NOMEM;
808 goto begin_table_error;
810 pTable->zName = zName;
812 pTable->pSchema = db->aDb[iDb].pSchema;
814 if( pParse->pNewTable ) sqlite3DeleteTable(pParse->pNewTable);
815 pParse->pNewTable = pTable;
817 /* If this is the magic sqlite_sequence table used by autoincrement,
818 ** then record a pointer to this table in the main database structure
819 ** so that INSERT can find the table easily.
821 #ifndef SQLITE_OMIT_AUTOINCREMENT
822 if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){
823 pTable->pSchema->pSeqTab = pTable;
827 /* Begin generating the code that will insert the table record into
828 ** the SQLITE_MASTER table. Note in particular that we must go ahead
829 ** and allocate the record number for the table entry now. Before any
830 ** PRIMARY KEY or UNIQUE keywords are parsed. Those keywords will cause
831 ** indices to be created and the table record must come before the
832 ** indices. Hence, the record number for the table must be allocated
835 if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
838 sqlite3BeginWriteOperation(pParse, 0, iDb);
840 #ifndef SQLITE_OMIT_VIRTUALTABLE
842 sqlite3VdbeAddOp(v, OP_VBegin, 0, 0);
846 /* If the file format and encoding in the database have not been set,
849 sqlite3VdbeAddOp(v, OP_ReadCookie, iDb, 1); /* file_format */
850 sqlite3VdbeUsesBtree(v, iDb);
851 lbl = sqlite3VdbeMakeLabel(v);
852 sqlite3VdbeAddOp(v, OP_If, 0, lbl);
853 fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
854 1 : SQLITE_MAX_FILE_FORMAT;
855 sqlite3VdbeAddOp(v, OP_Integer, fileFormat, 0);
856 sqlite3VdbeAddOp(v, OP_SetCookie, iDb, 1);
857 sqlite3VdbeAddOp(v, OP_Integer, ENC(db), 0);
858 sqlite3VdbeAddOp(v, OP_SetCookie, iDb, 4);
859 sqlite3VdbeResolveLabel(v, lbl);
861 /* This just creates a place-holder record in the sqlite_master table.
862 ** The record created does not contain anything yet. It will be replaced
863 ** by the real entry in code generated at sqlite3EndTable().
865 ** The rowid for the new entry is left on the top of the stack.
866 ** The rowid value is needed by the code that sqlite3EndTable will
869 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
870 if( isView || isVirtual ){
871 sqlite3VdbeAddOp(v, OP_Integer, 0, 0);
875 sqlite3VdbeAddOp(v, OP_CreateTable, iDb, 0);
877 sqlite3OpenMasterTable(pParse, iDb);
878 sqlite3VdbeAddOp(v, OP_NewRowid, 0, 0);
879 sqlite3VdbeAddOp(v, OP_Dup, 0, 0);
880 sqlite3VdbeAddOp(v, OP_Null, 0, 0);
881 sqlite3VdbeAddOp(v, OP_Insert, 0, OPFLAG_APPEND);
882 sqlite3VdbeAddOp(v, OP_Close, 0, 0);
883 sqlite3VdbeAddOp(v, OP_Pull, 1, 0);
886 /* Normal (non-error) return. */
889 /* If an error occurs, we jump here */
896 ** This macro is used to compare two strings in a case-insensitive manner.
897 ** It is slightly faster than calling sqlite3StrICmp() directly, but
898 ** produces larger code.
900 ** WARNING: This macro is not compatible with the strcmp() family. It
901 ** returns true if the two strings are equal, otherwise false.
903 #define STRICMP(x, y) (\
904 sqlite3UpperToLower[*(unsigned char *)(x)]== \
905 sqlite3UpperToLower[*(unsigned char *)(y)] \
906 && sqlite3StrICmp((x)+1,(y)+1)==0 )
909 ** Add a new column to the table currently being constructed.
911 ** The parser calls this routine once for each column declaration
912 ** in a CREATE TABLE statement. sqlite3StartTable() gets called
913 ** first to get things going. Then this routine is called for each
916 void sqlite3AddColumn(Parse *pParse, Token *pName){
921 if( (p = pParse->pNewTable)==0 ) return;
922 if( p->nCol+1>SQLITE_MAX_COLUMN ){
923 sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
926 z = sqlite3NameFromToken(pParse->db, pName);
928 for(i=0; i<p->nCol; i++){
929 if( STRICMP(z, p->aCol[i].zName) ){
930 sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
935 if( (p->nCol & 0x7)==0 ){
937 aNew = sqlite3DbRealloc(pParse->db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0]));
944 pCol = &p->aCol[p->nCol];
945 memset(pCol, 0, sizeof(p->aCol[0]));
948 /* If there is no type specified, columns have the default affinity
949 ** 'NONE'. If there is a type specified, then sqlite3AddColumnType() will
950 ** be called next to set pCol->affinity correctly.
952 pCol->affinity = SQLITE_AFF_NONE;
957 ** This routine is called by the parser while in the middle of
958 ** parsing a CREATE TABLE statement. A "NOT NULL" constraint has
959 ** been seen on a column. This routine sets the notNull flag on
960 ** the column currently under construction.
962 void sqlite3AddNotNull(Parse *pParse, int onError){
965 if( (p = pParse->pNewTable)==0 ) return;
967 if( i>=0 ) p->aCol[i].notNull = onError;
971 ** Scan the column type name zType (length nType) and return the
972 ** associated affinity type.
974 ** This routine does a case-independent search of zType for the
975 ** substrings in the following table. If one of the substrings is
976 ** found, the corresponding affinity is returned. If zType contains
977 ** more than one of the substrings, entries toward the top of
978 ** the table take priority. For example, if zType is 'BLOBINT',
979 ** SQLITE_AFF_INTEGER is returned.
981 ** Substring | Affinity
982 ** --------------------------------
983 ** 'INT' | SQLITE_AFF_INTEGER
984 ** 'CHAR' | SQLITE_AFF_TEXT
985 ** 'CLOB' | SQLITE_AFF_TEXT
986 ** 'TEXT' | SQLITE_AFF_TEXT
987 ** 'BLOB' | SQLITE_AFF_NONE
988 ** 'REAL' | SQLITE_AFF_REAL
989 ** 'FLOA' | SQLITE_AFF_REAL
990 ** 'DOUB' | SQLITE_AFF_REAL
992 ** If none of the substrings in the above table are found,
993 ** SQLITE_AFF_NUMERIC is returned.
995 char sqlite3AffinityType(const Token *pType){
997 char aff = SQLITE_AFF_NUMERIC;
998 const unsigned char *zIn = pType->z;
999 const unsigned char *zEnd = &pType->z[pType->n];
1002 h = (h<<8) + sqlite3UpperToLower[*zIn];
1004 if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){ /* CHAR */
1005 aff = SQLITE_AFF_TEXT;
1006 }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){ /* CLOB */
1007 aff = SQLITE_AFF_TEXT;
1008 }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){ /* TEXT */
1009 aff = SQLITE_AFF_TEXT;
1010 }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b') /* BLOB */
1011 && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
1012 aff = SQLITE_AFF_NONE;
1013 #ifndef SQLITE_OMIT_FLOATING_POINT
1014 }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l') /* REAL */
1015 && aff==SQLITE_AFF_NUMERIC ){
1016 aff = SQLITE_AFF_REAL;
1017 }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a') /* FLOA */
1018 && aff==SQLITE_AFF_NUMERIC ){
1019 aff = SQLITE_AFF_REAL;
1020 }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b') /* DOUB */
1021 && aff==SQLITE_AFF_NUMERIC ){
1022 aff = SQLITE_AFF_REAL;
1024 }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){ /* INT */
1025 aff = SQLITE_AFF_INTEGER;
1034 ** This routine is called by the parser while in the middle of
1035 ** parsing a CREATE TABLE statement. The pFirst token is the first
1036 ** token in the sequence of tokens that describe the type of the
1037 ** column currently under construction. pLast is the last token
1038 ** in the sequence. Use this information to construct a string
1039 ** that contains the typename of the column and store that string
1042 void sqlite3AddColumnType(Parse *pParse, Token *pType){
1047 if( (p = pParse->pNewTable)==0 ) return;
1051 sqlite3_free(pCol->zType);
1052 pCol->zType = sqlite3NameFromToken(pParse->db, pType);
1053 pCol->affinity = sqlite3AffinityType(pType);
1057 ** The expression is the default value for the most recently added column
1058 ** of the table currently under construction.
1060 ** Default value expressions must be constant. Raise an exception if this
1063 ** This routine is called by the parser while in the middle of
1064 ** parsing a CREATE TABLE statement.
1066 void sqlite3AddDefaultValue(Parse *pParse, Expr *pExpr){
1069 if( (p = pParse->pNewTable)!=0 ){
1070 pCol = &(p->aCol[p->nCol-1]);
1071 if( !sqlite3ExprIsConstantOrFunction(pExpr) ){
1072 sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
1076 sqlite3 *db = pParse->db;
1077 sqlite3ExprDelete(pCol->pDflt);
1078 pCol->pDflt = pCopy = sqlite3ExprDup(db, pExpr);
1080 sqlite3TokenCopy(db, &pCopy->span, &pExpr->span);
1084 sqlite3ExprDelete(pExpr);
1088 ** Designate the PRIMARY KEY for the table. pList is a list of names
1089 ** of columns that form the primary key. If pList is NULL, then the
1090 ** most recently added column of the table is the primary key.
1092 ** A table can have at most one primary key. If the table already has
1093 ** a primary key (and this is the second primary key) then create an
1096 ** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
1097 ** then we will try to use that column as the rowid. Set the Table.iPKey
1098 ** field of the table under construction to be the index of the
1099 ** INTEGER PRIMARY KEY column. Table.iPKey is set to -1 if there is
1100 ** no INTEGER PRIMARY KEY.
1102 ** If the key is not an INTEGER PRIMARY KEY, then create a unique
1103 ** index for the key. No index is created for INTEGER PRIMARY KEYs.
1105 void sqlite3AddPrimaryKey(
1106 Parse *pParse, /* Parsing context */
1107 ExprList *pList, /* List of field names to be indexed */
1108 int onError, /* What to do with a uniqueness conflict */
1109 int autoInc, /* True if the AUTOINCREMENT keyword is present */
1110 int sortOrder /* SQLITE_SO_ASC or SQLITE_SO_DESC */
1112 Table *pTab = pParse->pNewTable;
1115 if( pTab==0 || IN_DECLARE_VTAB ) goto primary_key_exit;
1116 if( pTab->hasPrimKey ){
1117 sqlite3ErrorMsg(pParse,
1118 "table \"%s\" has more than one primary key", pTab->zName);
1119 goto primary_key_exit;
1121 pTab->hasPrimKey = 1;
1123 iCol = pTab->nCol - 1;
1124 pTab->aCol[iCol].isPrimKey = 1;
1126 for(i=0; i<pList->nExpr; i++){
1127 for(iCol=0; iCol<pTab->nCol; iCol++){
1128 if( sqlite3StrICmp(pList->a[i].zName, pTab->aCol[iCol].zName)==0 ){
1132 if( iCol<pTab->nCol ){
1133 pTab->aCol[iCol].isPrimKey = 1;
1136 if( pList->nExpr>1 ) iCol = -1;
1138 if( iCol>=0 && iCol<pTab->nCol ){
1139 zType = pTab->aCol[iCol].zType;
1141 if( zType && sqlite3StrICmp(zType, "INTEGER")==0
1142 && sortOrder==SQLITE_SO_ASC ){
1144 pTab->keyConf = onError;
1145 pTab->autoInc = autoInc;
1146 }else if( autoInc ){
1147 #ifndef SQLITE_OMIT_AUTOINCREMENT
1148 sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
1149 "INTEGER PRIMARY KEY");
1152 sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0, 0, sortOrder, 0);
1157 sqlite3ExprListDelete(pList);
1162 ** Add a new CHECK constraint to the table currently under construction.
1164 void sqlite3AddCheckConstraint(
1165 Parse *pParse, /* Parsing context */
1166 Expr *pCheckExpr /* The check expression */
1168 #ifndef SQLITE_OMIT_CHECK
1169 Table *pTab = pParse->pNewTable;
1170 sqlite3 *db = pParse->db;
1171 if( pTab && !IN_DECLARE_VTAB ){
1172 /* The CHECK expression must be duplicated so that tokens refer
1173 ** to malloced space and not the (ephemeral) text of the CREATE TABLE
1175 pTab->pCheck = sqlite3ExprAnd(db, pTab->pCheck,
1176 sqlite3ExprDup(db, pCheckExpr));
1179 sqlite3ExprDelete(pCheckExpr);
1183 ** Set the collation function of the most recently parsed table column
1184 ** to the CollSeq given.
1186 void sqlite3AddCollateType(Parse *pParse, const char *zType, int nType){
1190 if( (p = pParse->pNewTable)==0 ) return;
1193 if( sqlite3LocateCollSeq(pParse, zType, nType) ){
1195 p->aCol[i].zColl = sqlite3DbStrNDup(pParse->db, zType, nType);
1197 /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
1198 ** then an index may have been created on this column before the
1199 ** collation type was added. Correct this if it is the case.
1201 for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
1202 assert( pIdx->nColumn==1 );
1203 if( pIdx->aiColumn[0]==i ){
1204 pIdx->azColl[0] = p->aCol[i].zColl;
1211 ** This function returns the collation sequence for database native text
1212 ** encoding identified by the string zName, length nName.
1214 ** If the requested collation sequence is not available, or not available
1215 ** in the database native encoding, the collation factory is invoked to
1216 ** request it. If the collation factory does not supply such a sequence,
1217 ** and the sequence is available in another text encoding, then that is
1218 ** returned instead.
1220 ** If no versions of the requested collations sequence are available, or
1221 ** another error occurs, NULL is returned and an error message written into
1224 ** This routine is a wrapper around sqlite3FindCollSeq(). This routine
1225 ** invokes the collation factory if the named collation cannot be found
1226 ** and generates an error message.
1228 CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName, int nName){
1229 sqlite3 *db = pParse->db;
1231 u8 initbusy = db->init.busy;
1234 pColl = sqlite3FindCollSeq(db, enc, zName, nName, initbusy);
1235 if( !initbusy && (!pColl || !pColl->xCmp) ){
1236 pColl = sqlite3GetCollSeq(db, pColl, zName, nName);
1239 nName = strlen(zName);
1241 sqlite3ErrorMsg(pParse, "no such collation sequence: %.*s", nName, zName);
1251 ** Generate code that will increment the schema cookie.
1253 ** The schema cookie is used to determine when the schema for the
1254 ** database changes. After each schema change, the cookie value
1255 ** changes. When a process first reads the schema it records the
1256 ** cookie. Thereafter, whenever it goes to access the database,
1257 ** it checks the cookie to make sure the schema has not changed
1258 ** since it was last read.
1260 ** This plan is not completely bullet-proof. It is possible for
1261 ** the schema to change multiple times and for the cookie to be
1262 ** set back to prior value. But schema changes are infrequent
1263 ** and the probability of hitting the same cookie value is only
1264 ** 1 chance in 2^32. So we're safe enough.
1266 void sqlite3ChangeCookie(sqlite3 *db, Vdbe *v, int iDb){
1267 sqlite3VdbeAddOp(v, OP_Integer, db->aDb[iDb].pSchema->schema_cookie+1, 0);
1268 sqlite3VdbeAddOp(v, OP_SetCookie, iDb, 0);
1272 ** Measure the number of characters needed to output the given
1273 ** identifier. The number returned includes any quotes used
1274 ** but does not include the null terminator.
1276 ** The estimate is conservative. It might be larger that what is
1279 static int identLength(const char *z){
1281 for(n=0; *z; n++, z++){
1282 if( *z=='"' ){ n++; }
1288 ** Write an identifier onto the end of the given string. Add
1289 ** quote characters as needed.
1291 static void identPut(char *z, int *pIdx, char *zSignedIdent){
1292 unsigned char *zIdent = (unsigned char*)zSignedIdent;
1293 int i, j, needQuote;
1295 for(j=0; zIdent[j]; j++){
1296 if( !isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
1298 needQuote = zIdent[j]!=0 || isdigit(zIdent[0])
1299 || sqlite3KeywordCode(zIdent, j)!=TK_ID;
1300 if( needQuote ) z[i++] = '"';
1301 for(j=0; zIdent[j]; j++){
1303 if( zIdent[j]=='"' ) z[i++] = '"';
1305 if( needQuote ) z[i++] = '"';
1311 ** Generate a CREATE TABLE statement appropriate for the given
1312 ** table. Memory to hold the text of the statement is obtained
1313 ** from sqliteMalloc() and must be freed by the calling function.
1315 static char *createTableStmt(Table *p, int isTemp){
1318 char *zSep, *zSep2, *zEnd, *z;
1321 for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
1322 n += identLength(pCol->zName);
1325 n += (strlen(z) + 1);
1328 n += identLength(p->zName);
1338 n += 35 + 6*p->nCol;
1339 zStmt = sqlite3_malloc( n );
1340 if( zStmt==0 ) return 0;
1341 sqlite3_snprintf(n, zStmt,
1342 !OMIT_TEMPDB&&isTemp ? "CREATE TEMP TABLE ":"CREATE TABLE ");
1344 identPut(zStmt, &k, p->zName);
1346 for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
1347 sqlite3_snprintf(n-k, &zStmt[k], zSep);
1348 k += strlen(&zStmt[k]);
1350 identPut(zStmt, &k, pCol->zName);
1351 if( (z = pCol->zType)!=0 ){
1353 assert( strlen(z)+k+1<=n );
1354 sqlite3_snprintf(n-k, &zStmt[k], "%s", z);
1358 sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
1363 ** This routine is called to report the final ")" that terminates
1364 ** a CREATE TABLE statement.
1366 ** The table structure that other action routines have been building
1367 ** is added to the internal hash tables, assuming no errors have
1370 ** An entry for the table is made in the master table on disk, unless
1371 ** this is a temporary table or db->init.busy==1. When db->init.busy==1
1372 ** it means we are reading the sqlite_master table because we just
1373 ** connected to the database or because the sqlite_master table has
1374 ** recently changed, so the entry for this table already exists in
1375 ** the sqlite_master table. We do not want to create it again.
1377 ** If the pSelect argument is not NULL, it means that this routine
1378 ** was called to create a table generated from a
1379 ** "CREATE TABLE ... AS SELECT ..." statement. The column names of
1380 ** the new table will match the result set of the SELECT.
1382 void sqlite3EndTable(
1383 Parse *pParse, /* Parse context */
1384 Token *pCons, /* The ',' token after the last column defn. */
1385 Token *pEnd, /* The final ')' token in the CREATE TABLE */
1386 Select *pSelect /* Select from a "CREATE ... AS SELECT" */
1389 sqlite3 *db = pParse->db;
1392 if( (pEnd==0 && pSelect==0) || pParse->nErr || db->mallocFailed ) {
1395 p = pParse->pNewTable;
1398 assert( !db->init.busy || !pSelect );
1400 iDb = sqlite3SchemaToIndex(db, p->pSchema);
1402 #ifndef SQLITE_OMIT_CHECK
1403 /* Resolve names in all CHECK constraint expressions.
1406 SrcList sSrc; /* Fake SrcList for pParse->pNewTable */
1407 NameContext sNC; /* Name context for pParse->pNewTable */
1409 memset(&sNC, 0, sizeof(sNC));
1410 memset(&sSrc, 0, sizeof(sSrc));
1412 sSrc.a[0].zName = p->zName;
1414 sSrc.a[0].iCursor = -1;
1415 sNC.pParse = pParse;
1416 sNC.pSrcList = &sSrc;
1418 if( sqlite3ExprResolveNames(&sNC, p->pCheck) ){
1422 #endif /* !defined(SQLITE_OMIT_CHECK) */
1424 /* If the db->init.busy is 1 it means we are reading the SQL off the
1425 ** "sqlite_master" or "sqlite_temp_master" table on the disk.
1426 ** So do not write to the disk again. Extract the root page number
1427 ** for the table from the db->init.newTnum field. (The page number
1428 ** should have been put there by the sqliteOpenCb routine.)
1430 if( db->init.busy ){
1431 p->tnum = db->init.newTnum;
1434 /* If not initializing, then create a record for the new table
1435 ** in the SQLITE_MASTER table of the database. The record number
1436 ** for the new table entry should already be on the stack.
1438 ** If this is a TEMPORARY table, write the entry into the auxiliary
1439 ** file instead of into the main database file.
1441 if( !db->init.busy ){
1444 char *zType; /* "view" or "table" */
1445 char *zType2; /* "VIEW" or "TABLE" */
1446 char *zStmt; /* Text of the CREATE TABLE or CREATE VIEW statement */
1448 v = sqlite3GetVdbe(pParse);
1451 sqlite3VdbeAddOp(v, OP_Close, 0, 0);
1453 /* Create the rootpage for the new table and push it onto the stack.
1454 ** A view has no rootpage, so just push a zero onto the stack for
1455 ** views. Initialize zType at the same time.
1457 if( p->pSelect==0 ){
1458 /* A regular table */
1461 #ifndef SQLITE_OMIT_VIEW
1469 /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
1470 ** statement to populate the new table. The root-page number for the
1471 ** new table is on the top of the vdbe stack.
1473 ** Once the SELECT has been coded by sqlite3Select(), it is in a
1474 ** suitable state to query for the column names and types to be used
1475 ** by the new table.
1477 ** A shared-cache write-lock is not required to write to the new table,
1478 ** as a schema-lock must have already been obtained to create it. Since
1479 ** a schema-lock excludes all other database users, the write-lock would
1484 sqlite3VdbeAddOp(v, OP_Dup, 0, 0);
1485 sqlite3VdbeAddOp(v, OP_Integer, iDb, 0);
1486 sqlite3VdbeAddOp(v, OP_OpenWrite, 1, 0);
1488 sqlite3Select(pParse, pSelect, SRT_Table, 1, 0, 0, 0, 0);
1489 sqlite3VdbeAddOp(v, OP_Close, 1, 0);
1490 if( pParse->nErr==0 ){
1491 pSelTab = sqlite3ResultSetOfSelect(pParse, 0, pSelect);
1492 if( pSelTab==0 ) return;
1493 assert( p->aCol==0 );
1494 p->nCol = pSelTab->nCol;
1495 p->aCol = pSelTab->aCol;
1498 sqlite3DeleteTable(pSelTab);
1502 /* Compute the complete text of the CREATE statement */
1504 zStmt = createTableStmt(p, p->pSchema==db->aDb[1].pSchema);
1506 n = pEnd->z - pParse->sNameToken.z + 1;
1507 zStmt = sqlite3MPrintf(db,
1508 "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
1512 /* A slot for the record has already been allocated in the
1513 ** SQLITE_MASTER table. We just need to update that slot with all
1514 ** the information we've collected. The rowid for the preallocated
1515 ** slot is the 2nd item on the stack. The top of the stack is the
1516 ** root page for the new table (or a 0 if this is a view).
1518 sqlite3NestedParse(pParse,
1520 "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#0, sql=%Q "
1522 db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
1528 sqlite3_free(zStmt);
1529 sqlite3ChangeCookie(db, v, iDb);
1531 #ifndef SQLITE_OMIT_AUTOINCREMENT
1532 /* Check to see if we need to create an sqlite_sequence table for
1533 ** keeping track of autoincrement keys.
1536 Db *pDb = &db->aDb[iDb];
1537 if( pDb->pSchema->pSeqTab==0 ){
1538 sqlite3NestedParse(pParse,
1539 "CREATE TABLE %Q.sqlite_sequence(name,seq)",
1546 /* Reparse everything to update our internal data structures */
1547 sqlite3VdbeOp3(v, OP_ParseSchema, iDb, 0,
1548 sqlite3MPrintf(db, "tbl_name='%q'",p->zName), P3_DYNAMIC);
1552 /* Add the table to the in-memory representation of the database.
1554 if( db->init.busy && pParse->nErr==0 ){
1557 Schema *pSchema = p->pSchema;
1558 pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName, strlen(p->zName)+1,p);
1560 assert( p==pOld ); /* Malloc must have failed inside HashInsert() */
1561 db->mallocFailed = 1;
1564 #ifndef SQLITE_OMIT_FOREIGN_KEY
1565 for(pFKey=p->pFKey; pFKey; pFKey=pFKey->pNextFrom){
1567 int nTo = strlen(pFKey->zTo) + 1;
1568 pFKey->pNextTo = sqlite3HashFind(&pSchema->aFKey, pFKey->zTo, nTo);
1569 data = sqlite3HashInsert(&pSchema->aFKey, pFKey->zTo, nTo, pFKey);
1570 if( data==(void *)pFKey ){
1571 db->mallocFailed = 1;
1575 pParse->pNewTable = 0;
1577 db->flags |= SQLITE_InternChanges;
1579 #ifndef SQLITE_OMIT_ALTERTABLE
1581 const char *zName = (const char *)pParse->sNameToken.z;
1583 assert( !pSelect && pCons && pEnd );
1587 nName = (const char *)pCons->z - zName;
1588 p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName);
1594 #ifndef SQLITE_OMIT_VIEW
1596 ** The parser calls this routine in order to create a new VIEW
1598 void sqlite3CreateView(
1599 Parse *pParse, /* The parsing context */
1600 Token *pBegin, /* The CREATE token that begins the statement */
1601 Token *pName1, /* The token that holds the name of the view */
1602 Token *pName2, /* The token that holds the name of the view */
1603 Select *pSelect, /* A SELECT statement that will become the new view */
1604 int isTemp, /* TRUE for a TEMPORARY view */
1605 int noErr /* Suppress error messages if VIEW already exists */
1609 const unsigned char *z;
1614 sqlite3 *db = pParse->db;
1616 if( pParse->nVar>0 ){
1617 sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
1618 sqlite3SelectDelete(pSelect);
1621 sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
1622 p = pParse->pNewTable;
1623 if( p==0 || pParse->nErr ){
1624 sqlite3SelectDelete(pSelect);
1627 sqlite3TwoPartName(pParse, pName1, pName2, &pName);
1628 iDb = sqlite3SchemaToIndex(db, p->pSchema);
1629 if( sqlite3FixInit(&sFix, pParse, iDb, "view", pName)
1630 && sqlite3FixSelect(&sFix, pSelect)
1632 sqlite3SelectDelete(pSelect);
1636 /* Make a copy of the entire SELECT statement that defines the view.
1637 ** This will force all the Expr.token.z values to be dynamically
1638 ** allocated rather than point to the input string - which means that
1639 ** they will persist after the current sqlite3_exec() call returns.
1641 p->pSelect = sqlite3SelectDup(db, pSelect);
1642 sqlite3SelectDelete(pSelect);
1643 if( db->mallocFailed ){
1646 if( !db->init.busy ){
1647 sqlite3ViewGetColumnNames(pParse, p);
1650 /* Locate the end of the CREATE VIEW statement. Make sEnd point to
1653 sEnd = pParse->sLastToken;
1654 if( sEnd.z[0]!=0 && sEnd.z[0]!=';' ){
1658 n = sEnd.z - pBegin->z;
1659 z = (const unsigned char*)pBegin->z;
1660 while( n>0 && (z[n-1]==';' || isspace(z[n-1])) ){ n--; }
1664 /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
1665 sqlite3EndTable(pParse, 0, &sEnd, 0);
1668 #endif /* SQLITE_OMIT_VIEW */
1670 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
1672 ** The Table structure pTable is really a VIEW. Fill in the names of
1673 ** the columns of the view in the pTable structure. Return the number
1674 ** of errors. If an error is seen leave an error message in pParse->zErrMsg.
1676 int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
1677 Table *pSelTab; /* A fake table from which we get the result set */
1678 Select *pSel; /* Copy of the SELECT that implements the view */
1679 int nErr = 0; /* Number of errors encountered */
1680 int n; /* Temporarily holds the number of cursors assigned */
1681 sqlite3 *db = pParse->db; /* Database connection for malloc errors */
1685 #ifndef SQLITE_OMIT_VIRTUALTABLE
1686 if( sqlite3VtabCallConnect(pParse, pTable) ){
1687 return SQLITE_ERROR;
1689 if( IsVirtual(pTable) ) return 0;
1692 #ifndef SQLITE_OMIT_VIEW
1693 /* A positive nCol means the columns names for this view are
1696 if( pTable->nCol>0 ) return 0;
1698 /* A negative nCol is a special marker meaning that we are currently
1699 ** trying to compute the column names. If we enter this routine with
1700 ** a negative nCol, it means two or more views form a loop, like this:
1702 ** CREATE VIEW one AS SELECT * FROM two;
1703 ** CREATE VIEW two AS SELECT * FROM one;
1705 ** Actually, this error is caught previously and so the following test
1706 ** should always fail. But we will leave it in place just to be safe.
1708 if( pTable->nCol<0 ){
1709 sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
1712 assert( pTable->nCol>=0 );
1714 /* If we get this far, it means we need to compute the table names.
1715 ** Note that the call to sqlite3ResultSetOfSelect() will expand any
1716 ** "*" elements in the results set of the view and will assign cursors
1717 ** to the elements of the FROM clause. But we do not want these changes
1718 ** to be permanent. So the computation is done on a copy of the SELECT
1719 ** statement that defines the view.
1721 assert( pTable->pSelect );
1722 pSel = sqlite3SelectDup(db, pTable->pSelect);
1725 sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
1727 pSelTab = sqlite3ResultSetOfSelect(pParse, 0, pSel);
1730 assert( pTable->aCol==0 );
1731 pTable->nCol = pSelTab->nCol;
1732 pTable->aCol = pSelTab->aCol;
1735 sqlite3DeleteTable(pSelTab);
1736 pTable->pSchema->flags |= DB_UnresetViews;
1741 sqlite3SelectDelete(pSel);
1745 #endif /* SQLITE_OMIT_VIEW */
1748 #endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
1750 #ifndef SQLITE_OMIT_VIEW
1752 ** Clear the column names from every VIEW in database idx.
1754 static void sqliteViewResetAll(sqlite3 *db, int idx){
1756 if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
1757 for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
1758 Table *pTab = sqliteHashData(i);
1759 if( pTab->pSelect ){
1760 sqliteResetColumnNames(pTab);
1763 DbClearProperty(db, idx, DB_UnresetViews);
1766 # define sqliteViewResetAll(A,B)
1767 #endif /* SQLITE_OMIT_VIEW */
1770 ** This function is called by the VDBE to adjust the internal schema
1771 ** used by SQLite when the btree layer moves a table root page. The
1772 ** root-page of a table or index in database iDb has changed from iFrom
1775 ** Ticket #1728: The symbol table might still contain information
1776 ** on tables and/or indices that are the process of being deleted.
1777 ** If you are unlucky, one of those deleted indices or tables might
1778 ** have the same rootpage number as the real table or index that is
1779 ** being moved. So we cannot stop searching after the first match
1780 ** because the first match might be for one of the deleted indices
1781 ** or tables and not the table/index that is actually being moved.
1782 ** We must continue looping until all tables and indices with
1783 ** rootpage==iFrom have been converted to have a rootpage of iTo
1784 ** in order to be certain that we got the right one.
1786 #ifndef SQLITE_OMIT_AUTOVACUUM
1787 void sqlite3RootPageMoved(Db *pDb, int iFrom, int iTo){
1791 pHash = &pDb->pSchema->tblHash;
1792 for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
1793 Table *pTab = sqliteHashData(pElem);
1794 if( pTab->tnum==iFrom ){
1798 pHash = &pDb->pSchema->idxHash;
1799 for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
1800 Index *pIdx = sqliteHashData(pElem);
1801 if( pIdx->tnum==iFrom ){
1809 ** Write code to erase the table with root-page iTable from database iDb.
1810 ** Also write code to modify the sqlite_master table and internal schema
1811 ** if a root-page of another table is moved by the btree-layer whilst
1812 ** erasing iTable (this can happen with an auto-vacuum database).
1814 static void destroyRootPage(Parse *pParse, int iTable, int iDb){
1815 Vdbe *v = sqlite3GetVdbe(pParse);
1816 sqlite3VdbeAddOp(v, OP_Destroy, iTable, iDb);
1817 #ifndef SQLITE_OMIT_AUTOVACUUM
1818 /* OP_Destroy pushes an integer onto the stack. If this integer
1819 ** is non-zero, then it is the root page number of a table moved to
1820 ** location iTable. The following code modifies the sqlite_master table to
1823 ** The "#0" in the SQL is a special constant that means whatever value
1824 ** is on the top of the stack. See sqlite3RegisterExpr().
1826 sqlite3NestedParse(pParse,
1827 "UPDATE %Q.%s SET rootpage=%d WHERE #0 AND rootpage=#0",
1828 pParse->db->aDb[iDb].zName, SCHEMA_TABLE(iDb), iTable);
1833 ** Write VDBE code to erase table pTab and all associated indices on disk.
1834 ** Code to update the sqlite_master tables and internal schema definitions
1835 ** in case a root-page belonging to another table is moved by the btree layer
1836 ** is also added (this can happen with an auto-vacuum database).
1838 static void destroyTable(Parse *pParse, Table *pTab){
1839 #ifdef SQLITE_OMIT_AUTOVACUUM
1841 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
1842 destroyRootPage(pParse, pTab->tnum, iDb);
1843 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
1844 destroyRootPage(pParse, pIdx->tnum, iDb);
1847 /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
1848 ** is not defined), then it is important to call OP_Destroy on the
1849 ** table and index root-pages in order, starting with the numerically
1850 ** largest root-page number. This guarantees that none of the root-pages
1851 ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
1852 ** following were coded:
1858 ** and root page 5 happened to be the largest root-page number in the
1859 ** database, then root page 5 would be moved to page 4 by the
1860 ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
1861 ** a free-list page.
1863 int iTab = pTab->tnum;
1870 if( iDestroyed==0 || iTab<iDestroyed ){
1873 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
1874 int iIdx = pIdx->tnum;
1875 assert( pIdx->pSchema==pTab->pSchema );
1876 if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
1883 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
1884 destroyRootPage(pParse, iLargest, iDb);
1885 iDestroyed = iLargest;
1892 ** This routine is called to do the work of a DROP TABLE statement.
1893 ** pName is the name of the table to be dropped.
1895 void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
1898 sqlite3 *db = pParse->db;
1901 if( pParse->nErr || db->mallocFailed ){
1902 goto exit_drop_table;
1904 assert( pName->nSrc==1 );
1905 pTab = sqlite3LocateTable(pParse, pName->a[0].zName, pName->a[0].zDatabase);
1909 sqlite3ErrorClear(pParse);
1911 goto exit_drop_table;
1913 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
1914 assert( iDb>=0 && iDb<db->nDb );
1915 #ifndef SQLITE_OMIT_AUTHORIZATION
1918 const char *zTab = SCHEMA_TABLE(iDb);
1919 const char *zDb = db->aDb[iDb].zName;
1920 const char *zArg2 = 0;
1921 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
1922 goto exit_drop_table;
1925 if( !OMIT_TEMPDB && iDb==1 ){
1926 code = SQLITE_DROP_TEMP_VIEW;
1928 code = SQLITE_DROP_VIEW;
1930 #ifndef SQLITE_OMIT_VIRTUALTABLE
1931 }else if( IsVirtual(pTab) ){
1932 if( sqlite3ViewGetColumnNames(pParse, pTab) ){
1933 goto exit_drop_table;
1935 code = SQLITE_DROP_VTABLE;
1936 zArg2 = pTab->pMod->zName;
1939 if( !OMIT_TEMPDB && iDb==1 ){
1940 code = SQLITE_DROP_TEMP_TABLE;
1942 code = SQLITE_DROP_TABLE;
1945 if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
1946 goto exit_drop_table;
1948 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
1949 goto exit_drop_table;
1953 if( pTab->readOnly || pTab==db->aDb[iDb].pSchema->pSeqTab ){
1954 sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
1955 goto exit_drop_table;
1958 #ifndef SQLITE_OMIT_VIEW
1959 /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
1962 if( isView && pTab->pSelect==0 ){
1963 sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
1964 goto exit_drop_table;
1966 if( !isView && pTab->pSelect ){
1967 sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
1968 goto exit_drop_table;
1972 /* Generate code to remove the table from the master table
1975 v = sqlite3GetVdbe(pParse);
1978 Db *pDb = &db->aDb[iDb];
1979 sqlite3BeginWriteOperation(pParse, 0, iDb);
1981 #ifndef SQLITE_OMIT_VIRTUALTABLE
1982 if( IsVirtual(pTab) ){
1983 Vdbe *v = sqlite3GetVdbe(pParse);
1985 sqlite3VdbeAddOp(v, OP_VBegin, 0, 0);
1990 /* Drop all triggers associated with the table being dropped. Code
1991 ** is generated to remove entries from sqlite_master and/or
1992 ** sqlite_temp_master if required.
1994 pTrigger = pTab->pTrigger;
1996 assert( pTrigger->pSchema==pTab->pSchema ||
1997 pTrigger->pSchema==db->aDb[1].pSchema );
1998 sqlite3DropTriggerPtr(pParse, pTrigger);
1999 pTrigger = pTrigger->pNext;
2002 #ifndef SQLITE_OMIT_AUTOINCREMENT
2003 /* Remove any entries of the sqlite_sequence table associated with
2004 ** the table being dropped. This is done before the table is dropped
2005 ** at the btree level, in case the sqlite_sequence table needs to
2006 ** move as a result of the drop (can happen in auto-vacuum mode).
2008 if( pTab->autoInc ){
2009 sqlite3NestedParse(pParse,
2010 "DELETE FROM %s.sqlite_sequence WHERE name=%Q",
2011 pDb->zName, pTab->zName
2016 /* Drop all SQLITE_MASTER table and index entries that refer to the
2017 ** table. The program name loops through the master table and deletes
2018 ** every row that refers to a table of the same name as the one being
2019 ** dropped. Triggers are handled seperately because a trigger can be
2020 ** created in the temp database that refers to a table in another
2023 sqlite3NestedParse(pParse,
2024 "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
2025 pDb->zName, SCHEMA_TABLE(iDb), pTab->zName);
2026 if( !isView && !IsVirtual(pTab) ){
2027 destroyTable(pParse, pTab);
2030 /* Remove the table entry from SQLite's internal schema and modify
2031 ** the schema cookie.
2033 if( IsVirtual(pTab) ){
2034 sqlite3VdbeOp3(v, OP_VDestroy, iDb, 0, pTab->zName, 0);
2036 sqlite3VdbeOp3(v, OP_DropTable, iDb, 0, pTab->zName, 0);
2037 sqlite3ChangeCookie(db, v, iDb);
2039 sqliteViewResetAll(db, iDb);
2042 sqlite3SrcListDelete(pName);
2046 ** This routine is called to create a new foreign key on the table
2047 ** currently under construction. pFromCol determines which columns
2048 ** in the current table point to the foreign key. If pFromCol==0 then
2049 ** connect the key to the last column inserted. pTo is the name of
2050 ** the table referred to. pToCol is a list of tables in the other
2051 ** pTo table that the foreign key points to. flags contains all
2052 ** information about the conflict resolution algorithms specified
2053 ** in the ON DELETE, ON UPDATE and ON INSERT clauses.
2055 ** An FKey structure is created and added to the table currently
2056 ** under construction in the pParse->pNewTable field. The new FKey
2057 ** is not linked into db->aFKey at this point - that does not happen
2058 ** until sqlite3EndTable().
2060 ** The foreign key is set for IMMEDIATE processing. A subsequent call
2061 ** to sqlite3DeferForeignKey() might change this to DEFERRED.
2063 void sqlite3CreateForeignKey(
2064 Parse *pParse, /* Parsing context */
2065 ExprList *pFromCol, /* Columns in this table that point to other table */
2066 Token *pTo, /* Name of the other table */
2067 ExprList *pToCol, /* Columns in the other table */
2068 int flags /* Conflict resolution algorithms. */
2070 #ifndef SQLITE_OMIT_FOREIGN_KEY
2072 Table *p = pParse->pNewTable;
2079 if( p==0 || pParse->nErr || IN_DECLARE_VTAB ) goto fk_end;
2081 int iCol = p->nCol-1;
2082 if( iCol<0 ) goto fk_end;
2083 if( pToCol && pToCol->nExpr!=1 ){
2084 sqlite3ErrorMsg(pParse, "foreign key on %s"
2085 " should reference only one column of table %T",
2086 p->aCol[iCol].zName, pTo);
2090 }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
2091 sqlite3ErrorMsg(pParse,
2092 "number of columns in foreign key does not match the number of "
2093 "columns in the referenced table");
2096 nCol = pFromCol->nExpr;
2098 nByte = sizeof(*pFKey) + nCol*sizeof(pFKey->aCol[0]) + pTo->n + 1;
2100 for(i=0; i<pToCol->nExpr; i++){
2101 nByte += strlen(pToCol->a[i].zName) + 1;
2104 pFKey = sqlite3DbMallocZero(pParse->db, nByte );
2109 pFKey->pNextFrom = p->pFKey;
2110 z = (char*)&pFKey[1];
2111 pFKey->aCol = (struct sColMap*)z;
2112 z += sizeof(struct sColMap)*nCol;
2114 memcpy(z, pTo->z, pTo->n);
2120 pFKey->aCol[0].iFrom = p->nCol-1;
2122 for(i=0; i<nCol; i++){
2124 for(j=0; j<p->nCol; j++){
2125 if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
2126 pFKey->aCol[i].iFrom = j;
2131 sqlite3ErrorMsg(pParse,
2132 "unknown column \"%s\" in foreign key definition",
2133 pFromCol->a[i].zName);
2139 for(i=0; i<nCol; i++){
2140 int n = strlen(pToCol->a[i].zName);
2141 pFKey->aCol[i].zCol = z;
2142 memcpy(z, pToCol->a[i].zName, n);
2147 pFKey->isDeferred = 0;
2148 pFKey->deleteConf = flags & 0xff;
2149 pFKey->updateConf = (flags >> 8 ) & 0xff;
2150 pFKey->insertConf = (flags >> 16 ) & 0xff;
2152 /* Link the foreign key to the table as the last step.
2158 sqlite3_free(pFKey);
2159 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
2160 sqlite3ExprListDelete(pFromCol);
2161 sqlite3ExprListDelete(pToCol);
2165 ** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
2166 ** clause is seen as part of a foreign key definition. The isDeferred
2167 ** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
2168 ** The behavior of the most recently created foreign key is adjusted
2171 void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
2172 #ifndef SQLITE_OMIT_FOREIGN_KEY
2175 if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
2176 pFKey->isDeferred = isDeferred;
2181 ** Generate code that will erase and refill index *pIdx. This is
2182 ** used to initialize a newly created index or to recompute the
2183 ** content of an index in response to a REINDEX command.
2185 ** if memRootPage is not negative, it means that the index is newly
2186 ** created. The memory cell specified by memRootPage contains the
2187 ** root page number of the index. If memRootPage is negative, then
2188 ** the index already exists and must be cleared before being refilled and
2189 ** the root page number of the index is taken from pIndex->tnum.
2191 static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
2192 Table *pTab = pIndex->pTable; /* The table that is indexed */
2193 int iTab = pParse->nTab; /* Btree cursor used for pTab */
2194 int iIdx = pParse->nTab+1; /* Btree cursor used for pIndex */
2195 int addr1; /* Address of top of loop */
2196 int tnum; /* Root page of index */
2197 Vdbe *v; /* Generate code into this virtual machine */
2198 KeyInfo *pKey; /* KeyInfo for index */
2199 sqlite3 *db = pParse->db; /* The database connection */
2200 int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
2202 #ifndef SQLITE_OMIT_AUTHORIZATION
2203 if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
2204 db->aDb[iDb].zName ) ){
2209 /* Require a write-lock on the table to perform this operation */
2210 sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
2212 v = sqlite3GetVdbe(pParse);
2214 if( memRootPage>=0 ){
2215 sqlite3VdbeAddOp(v, OP_MemLoad, memRootPage, 0);
2218 tnum = pIndex->tnum;
2219 sqlite3VdbeAddOp(v, OP_Clear, tnum, iDb);
2221 sqlite3VdbeAddOp(v, OP_Integer, iDb, 0);
2222 pKey = sqlite3IndexKeyinfo(pParse, pIndex);
2223 sqlite3VdbeOp3(v, OP_OpenWrite, iIdx, tnum, (char *)pKey, P3_KEYINFO_HANDOFF);
2224 sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
2225 addr1 = sqlite3VdbeAddOp(v, OP_Rewind, iTab, 0);
2226 sqlite3GenerateIndexKey(v, pIndex, iTab);
2227 if( pIndex->onError!=OE_None ){
2228 int curaddr = sqlite3VdbeCurrentAddr(v);
2229 int addr2 = curaddr+4;
2230 sqlite3VdbeChangeP2(v, curaddr-1, addr2);
2231 sqlite3VdbeAddOp(v, OP_Rowid, iTab, 0);
2232 sqlite3VdbeAddOp(v, OP_AddImm, 1, 0);
2233 sqlite3VdbeAddOp(v, OP_IsUnique, iIdx, addr2);
2234 sqlite3VdbeOp3(v, OP_Halt, SQLITE_CONSTRAINT, OE_Abort,
2235 "indexed columns are not unique", P3_STATIC);
2236 assert( db->mallocFailed || addr2==sqlite3VdbeCurrentAddr(v) );
2238 sqlite3VdbeAddOp(v, OP_IdxInsert, iIdx, 0);
2239 sqlite3VdbeAddOp(v, OP_Next, iTab, addr1+1);
2240 sqlite3VdbeJumpHere(v, addr1);
2241 sqlite3VdbeAddOp(v, OP_Close, iTab, 0);
2242 sqlite3VdbeAddOp(v, OP_Close, iIdx, 0);
2246 ** Create a new index for an SQL table. pName1.pName2 is the name of the index
2247 ** and pTblList is the name of the table that is to be indexed. Both will
2248 ** be NULL for a primary key or an index that is created to satisfy a
2249 ** UNIQUE constraint. If pTable and pIndex are NULL, use pParse->pNewTable
2250 ** as the table to be indexed. pParse->pNewTable is a table that is
2251 ** currently being constructed by a CREATE TABLE statement.
2253 ** pList is a list of columns to be indexed. pList will be NULL if this
2254 ** is a primary key or unique-constraint on the most recent column added
2255 ** to the table currently under construction.
2257 void sqlite3CreateIndex(
2258 Parse *pParse, /* All information about this parse */
2259 Token *pName1, /* First part of index name. May be NULL */
2260 Token *pName2, /* Second part of index name. May be NULL */
2261 SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
2262 ExprList *pList, /* A list of columns to be indexed */
2263 int onError, /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
2264 Token *pStart, /* The CREATE token that begins this statement */
2265 Token *pEnd, /* The ")" that closes the CREATE INDEX statement */
2266 int sortOrder, /* Sort order of primary key when pList==NULL */
2267 int ifNotExist /* Omit error if index already exists */
2269 Table *pTab = 0; /* Table to be indexed */
2270 Index *pIndex = 0; /* The index to be created */
2271 char *zName = 0; /* Name of the index */
2272 int nName; /* Number of characters in zName */
2274 Token nullId; /* Fake token for an empty ID list */
2275 DbFixer sFix; /* For assigning database names to pTable */
2276 int sortOrderMask; /* 1 to honor DESC in index. 0 to ignore. */
2277 sqlite3 *db = pParse->db;
2278 Db *pDb; /* The specific table containing the indexed database */
2279 int iDb; /* Index of the database that is being written */
2280 Token *pName = 0; /* Unqualified name of the index to create */
2281 struct ExprList_item *pListItem; /* For looping over pList */
2286 if( pParse->nErr || db->mallocFailed || IN_DECLARE_VTAB ){
2287 goto exit_create_index;
2291 ** Find the table that is to be indexed. Return early if not found.
2295 /* Use the two-part index name to determine the database
2296 ** to search for the table. 'Fix' the table name to this db
2297 ** before looking up the table.
2299 assert( pName1 && pName2 );
2300 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
2301 if( iDb<0 ) goto exit_create_index;
2303 #ifndef SQLITE_OMIT_TEMPDB
2304 /* If the index name was unqualified, check if the the table
2305 ** is a temp table. If so, set the database to 1.
2307 pTab = sqlite3SrcListLookup(pParse, pTblName);
2308 if( pName2 && pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
2313 if( sqlite3FixInit(&sFix, pParse, iDb, "index", pName) &&
2314 sqlite3FixSrcList(&sFix, pTblName)
2316 /* Because the parser constructs pTblName from a single identifier,
2317 ** sqlite3FixSrcList can never fail. */
2320 pTab = sqlite3LocateTable(pParse, pTblName->a[0].zName,
2321 pTblName->a[0].zDatabase);
2322 if( !pTab ) goto exit_create_index;
2323 assert( db->aDb[iDb].pSchema==pTab->pSchema );
2326 pTab = pParse->pNewTable;
2327 if( !pTab ) goto exit_create_index;
2328 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
2330 pDb = &db->aDb[iDb];
2332 if( pTab==0 || pParse->nErr ) goto exit_create_index;
2333 if( pTab->readOnly ){
2334 sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
2335 goto exit_create_index;
2337 #ifndef SQLITE_OMIT_VIEW
2338 if( pTab->pSelect ){
2339 sqlite3ErrorMsg(pParse, "views may not be indexed");
2340 goto exit_create_index;
2343 #ifndef SQLITE_OMIT_VIRTUALTABLE
2344 if( IsVirtual(pTab) ){
2345 sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
2346 goto exit_create_index;
2351 ** Find the name of the index. Make sure there is not already another
2352 ** index or table with the same name.
2354 ** Exception: If we are reading the names of permanent indices from the
2355 ** sqlite_master table (because some other process changed the schema) and
2356 ** one of the index names collides with the name of a temporary table or
2357 ** index, then we will continue to process this index.
2359 ** If pName==0 it means that we are
2360 ** dealing with a primary key or UNIQUE constraint. We have to invent our
2364 zName = sqlite3NameFromToken(db, pName);
2365 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ) goto exit_create_index;
2366 if( zName==0 ) goto exit_create_index;
2367 if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
2368 goto exit_create_index;
2370 if( !db->init.busy ){
2371 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ) goto exit_create_index;
2372 if( sqlite3FindTable(db, zName, 0)!=0 ){
2373 sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
2374 goto exit_create_index;
2377 if( sqlite3FindIndex(db, zName, pDb->zName)!=0 ){
2379 sqlite3ErrorMsg(pParse, "index %s already exists", zName);
2381 goto exit_create_index;
2387 for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
2388 sqlite3_snprintf(sizeof(zBuf),zBuf,"_%d",n);
2390 sqlite3SetString(&zName, "sqlite_autoindex_", pTab->zName, zBuf, (char*)0);
2392 db->mallocFailed = 1;
2393 goto exit_create_index;
2397 /* Check for authorization to create an index.
2399 #ifndef SQLITE_OMIT_AUTHORIZATION
2401 const char *zDb = pDb->zName;
2402 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
2403 goto exit_create_index;
2405 i = SQLITE_CREATE_INDEX;
2406 if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
2407 if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
2408 goto exit_create_index;
2413 /* If pList==0, it means this routine was called to make a primary
2414 ** key out of the last column added to the table under construction.
2415 ** So create a fake list to simulate this.
2418 nullId.z = (u8*)pTab->aCol[pTab->nCol-1].zName;
2419 nullId.n = strlen((char*)nullId.z);
2420 pList = sqlite3ExprListAppend(pParse, 0, 0, &nullId);
2421 if( pList==0 ) goto exit_create_index;
2422 pList->a[0].sortOrder = sortOrder;
2425 /* Figure out how many bytes of space are required to store explicitly
2426 ** specified collation sequence names.
2428 for(i=0; i<pList->nExpr; i++){
2429 Expr *pExpr = pList->a[i].pExpr;
2431 nExtra += (1 + strlen(pExpr->pColl->zName));
2436 ** Allocate the index structure.
2438 nName = strlen(zName);
2439 nCol = pList->nExpr;
2440 pIndex = sqlite3DbMallocZero(db,
2441 sizeof(Index) + /* Index structure */
2442 sizeof(int)*nCol + /* Index.aiColumn */
2443 sizeof(int)*(nCol+1) + /* Index.aiRowEst */
2444 sizeof(char *)*nCol + /* Index.azColl */
2445 sizeof(u8)*nCol + /* Index.aSortOrder */
2446 nName + 1 + /* Index.zName */
2447 nExtra /* Collation sequence names */
2449 if( db->mallocFailed ){
2450 goto exit_create_index;
2452 pIndex->azColl = (char**)(&pIndex[1]);
2453 pIndex->aiColumn = (int *)(&pIndex->azColl[nCol]);
2454 pIndex->aiRowEst = (unsigned *)(&pIndex->aiColumn[nCol]);
2455 pIndex->aSortOrder = (u8 *)(&pIndex->aiRowEst[nCol+1]);
2456 pIndex->zName = (char *)(&pIndex->aSortOrder[nCol]);
2457 zExtra = (char *)(&pIndex->zName[nName+1]);
2458 memcpy(pIndex->zName, zName, nName+1);
2459 pIndex->pTable = pTab;
2460 pIndex->nColumn = pList->nExpr;
2461 pIndex->onError = onError;
2462 pIndex->autoIndex = pName==0;
2463 pIndex->pSchema = db->aDb[iDb].pSchema;
2465 /* Check to see if we should honor DESC requests on index columns
2467 if( pDb->pSchema->file_format>=4 ){
2468 sortOrderMask = -1; /* Honor DESC */
2470 sortOrderMask = 0; /* Ignore DESC */
2473 /* Scan the names of the columns of the table to be indexed and
2474 ** load the column indices into the Index structure. Report an error
2475 ** if any column is not found.
2477 for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){
2478 const char *zColName = pListItem->zName;
2480 int requestedSortOrder;
2481 char *zColl; /* Collation sequence name */
2483 for(j=0, pTabCol=pTab->aCol; j<pTab->nCol; j++, pTabCol++){
2484 if( sqlite3StrICmp(zColName, pTabCol->zName)==0 ) break;
2486 if( j>=pTab->nCol ){
2487 sqlite3ErrorMsg(pParse, "table %s has no column named %s",
2488 pTab->zName, zColName);
2489 goto exit_create_index;
2491 /* TODO: Add a test to make sure that the same column is not named
2492 ** more than once within the same index. Only the first instance of
2493 ** the column will ever be used by the optimizer. Note that using the
2494 ** same column more than once cannot be an error because that would
2495 ** break backwards compatibility - it needs to be a warning.
2497 pIndex->aiColumn[i] = j;
2498 if( pListItem->pExpr ){
2499 assert( pListItem->pExpr->pColl );
2501 sqlite3_snprintf(nExtra, zExtra, "%s", pListItem->pExpr->pColl->zName);
2502 zExtra += (strlen(zColl) + 1);
2504 zColl = pTab->aCol[j].zColl;
2506 zColl = db->pDfltColl->zName;
2509 if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl, -1) ){
2510 goto exit_create_index;
2512 pIndex->azColl[i] = zColl;
2513 requestedSortOrder = pListItem->sortOrder & sortOrderMask;
2514 pIndex->aSortOrder[i] = requestedSortOrder;
2516 sqlite3DefaultRowEst(pIndex);
2518 if( pTab==pParse->pNewTable ){
2519 /* This routine has been called to create an automatic index as a
2520 ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
2521 ** a PRIMARY KEY or UNIQUE clause following the column definitions.
2524 ** CREATE TABLE t(x PRIMARY KEY, y);
2525 ** CREATE TABLE t(x, y, UNIQUE(x, y));
2527 ** Either way, check to see if the table already has such an index. If
2528 ** so, don't bother creating this one. This only applies to
2529 ** automatically created indices. Users can do as they wish with
2530 ** explicit indices.
2533 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
2535 assert( pIdx->onError!=OE_None );
2536 assert( pIdx->autoIndex );
2537 assert( pIndex->onError!=OE_None );
2539 if( pIdx->nColumn!=pIndex->nColumn ) continue;
2540 for(k=0; k<pIdx->nColumn; k++){
2541 const char *z1 = pIdx->azColl[k];
2542 const char *z2 = pIndex->azColl[k];
2543 if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
2544 if( pIdx->aSortOrder[k]!=pIndex->aSortOrder[k] ) break;
2545 if( z1!=z2 && sqlite3StrICmp(z1, z2) ) break;
2547 if( k==pIdx->nColumn ){
2548 if( pIdx->onError!=pIndex->onError ){
2549 /* This constraint creates the same index as a previous
2550 ** constraint specified somewhere in the CREATE TABLE statement.
2551 ** However the ON CONFLICT clauses are different. If both this
2552 ** constraint and the previous equivalent constraint have explicit
2553 ** ON CONFLICT clauses this is an error. Otherwise, use the
2554 ** explicitly specified behaviour for the index.
2556 if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
2557 sqlite3ErrorMsg(pParse,
2558 "conflicting ON CONFLICT clauses specified", 0);
2560 if( pIdx->onError==OE_Default ){
2561 pIdx->onError = pIndex->onError;
2564 goto exit_create_index;
2569 /* Link the new Index structure to its table and to the other
2570 ** in-memory database structures.
2572 if( db->init.busy ){
2574 p = sqlite3HashInsert(&pIndex->pSchema->idxHash,
2575 pIndex->zName, strlen(pIndex->zName)+1, pIndex);
2577 assert( p==pIndex ); /* Malloc must have failed */
2578 db->mallocFailed = 1;
2579 goto exit_create_index;
2581 db->flags |= SQLITE_InternChanges;
2583 pIndex->tnum = db->init.newTnum;
2587 /* If the db->init.busy is 0 then create the index on disk. This
2588 ** involves writing the index into the master table and filling in the
2589 ** index with the current table contents.
2591 ** The db->init.busy is 0 when the user first enters a CREATE INDEX
2592 ** command. db->init.busy is 1 when a database is opened and
2593 ** CREATE INDEX statements are read out of the master table. In
2594 ** the latter case the index already exists on disk, which is why
2595 ** we don't want to recreate it.
2597 ** If pTblName==0 it means this index is generated as a primary key
2598 ** or UNIQUE constraint of a CREATE TABLE statement. Since the table
2599 ** has just been created, it contains no data and the index initialization
2600 ** step can be skipped.
2602 else if( db->init.busy==0 ){
2605 int iMem = pParse->nMem++;
2607 v = sqlite3GetVdbe(pParse);
2608 if( v==0 ) goto exit_create_index;
2611 /* Create the rootpage for the index
2613 sqlite3BeginWriteOperation(pParse, 1, iDb);
2614 sqlite3VdbeAddOp(v, OP_CreateIndex, iDb, 0);
2615 sqlite3VdbeAddOp(v, OP_MemStore, iMem, 0);
2617 /* Gather the complete text of the CREATE INDEX statement into
2618 ** the zStmt variable
2620 if( pStart && pEnd ){
2621 /* A named index with an explicit CREATE INDEX statement */
2622 zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
2623 onError==OE_None ? "" : " UNIQUE",
2624 pEnd->z - pName->z + 1,
2627 /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
2628 /* zStmt = sqlite3MPrintf(""); */
2632 /* Add an entry in sqlite_master for this index
2634 sqlite3NestedParse(pParse,
2635 "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#0,%Q);",
2636 db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
2641 sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
2642 sqlite3_free(zStmt);
2644 /* Fill the index with data and reparse the schema. Code an OP_Expire
2645 ** to invalidate all pre-compiled statements.
2648 sqlite3RefillIndex(pParse, pIndex, iMem);
2649 sqlite3ChangeCookie(db, v, iDb);
2650 sqlite3VdbeOp3(v, OP_ParseSchema, iDb, 0,
2651 sqlite3MPrintf(db, "name='%q'", pIndex->zName), P3_DYNAMIC);
2652 sqlite3VdbeAddOp(v, OP_Expire, 0, 0);
2656 /* When adding an index to the list of indices for a table, make
2657 ** sure all indices labeled OE_Replace come after all those labeled
2658 ** OE_Ignore. This is necessary for the correct operation of UPDATE
2661 if( db->init.busy || pTblName==0 ){
2662 if( onError!=OE_Replace || pTab->pIndex==0
2663 || pTab->pIndex->onError==OE_Replace){
2664 pIndex->pNext = pTab->pIndex;
2665 pTab->pIndex = pIndex;
2667 Index *pOther = pTab->pIndex;
2668 while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
2669 pOther = pOther->pNext;
2671 pIndex->pNext = pOther->pNext;
2672 pOther->pNext = pIndex;
2677 /* Clean up before exiting */
2682 sqlite3ExprListDelete(pList);
2683 sqlite3SrcListDelete(pTblName);
2684 sqlite3_free(zName);
2689 ** Generate code to make sure the file format number is at least minFormat.
2690 ** The generated code will increase the file format number if necessary.
2692 void sqlite3MinimumFileFormat(Parse *pParse, int iDb, int minFormat){
2694 v = sqlite3GetVdbe(pParse);
2696 sqlite3VdbeAddOp(v, OP_ReadCookie, iDb, 1);
2697 sqlite3VdbeUsesBtree(v, iDb);
2698 sqlite3VdbeAddOp(v, OP_Integer, minFormat, 0);
2699 sqlite3VdbeAddOp(v, OP_Ge, 0, sqlite3VdbeCurrentAddr(v)+3);
2700 sqlite3VdbeAddOp(v, OP_Integer, minFormat, 0);
2701 sqlite3VdbeAddOp(v, OP_SetCookie, iDb, 1);
2706 ** Fill the Index.aiRowEst[] array with default information - information
2707 ** to be used when we have not run the ANALYZE command.
2709 ** aiRowEst[0] is suppose to contain the number of elements in the index.
2710 ** Since we do not know, guess 1 million. aiRowEst[1] is an estimate of the
2711 ** number of rows in the table that match any particular value of the
2712 ** first column of the index. aiRowEst[2] is an estimate of the number
2713 ** of rows that match any particular combiniation of the first 2 columns
2714 ** of the index. And so forth. It must always be the case that
2716 ** aiRowEst[N]<=aiRowEst[N-1]
2719 ** Apart from that, we have little to go on besides intuition as to
2720 ** how aiRowEst[] should be initialized. The numbers generated here
2721 ** are based on typical values found in actual indices.
2723 void sqlite3DefaultRowEst(Index *pIdx){
2724 unsigned *a = pIdx->aiRowEst;
2728 for(i=pIdx->nColumn; i>=5; i--){
2735 if( pIdx->onError!=OE_None ){
2736 a[pIdx->nColumn] = 1;
2741 ** This routine will drop an existing named index. This routine
2742 ** implements the DROP INDEX statement.
2744 void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
2747 sqlite3 *db = pParse->db;
2750 if( pParse->nErr || db->mallocFailed ){
2751 goto exit_drop_index;
2753 assert( pName->nSrc==1 );
2754 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
2755 goto exit_drop_index;
2757 pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
2760 sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
2762 pParse->checkSchema = 1;
2763 goto exit_drop_index;
2765 if( pIndex->autoIndex ){
2766 sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
2767 "or PRIMARY KEY constraint cannot be dropped", 0);
2768 goto exit_drop_index;
2770 iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
2771 #ifndef SQLITE_OMIT_AUTHORIZATION
2773 int code = SQLITE_DROP_INDEX;
2774 Table *pTab = pIndex->pTable;
2775 const char *zDb = db->aDb[iDb].zName;
2776 const char *zTab = SCHEMA_TABLE(iDb);
2777 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
2778 goto exit_drop_index;
2780 if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
2781 if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
2782 goto exit_drop_index;
2787 /* Generate code to remove the index and from the master table */
2788 v = sqlite3GetVdbe(pParse);
2790 sqlite3NestedParse(pParse,
2791 "DELETE FROM %Q.%s WHERE name=%Q",
2792 db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
2795 sqlite3ChangeCookie(db, v, iDb);
2796 destroyRootPage(pParse, pIndex->tnum, iDb);
2797 sqlite3VdbeOp3(v, OP_DropIndex, iDb, 0, pIndex->zName, 0);
2801 sqlite3SrcListDelete(pName);
2805 ** pArray is a pointer to an array of objects. Each object in the
2806 ** array is szEntry bytes in size. This routine allocates a new
2807 ** object on the end of the array.
2809 ** *pnEntry is the number of entries already in use. *pnAlloc is
2810 ** the previously allocated size of the array. initSize is the
2811 ** suggested initial array size allocation.
2813 ** The index of the new entry is returned in *pIdx.
2815 ** This routine returns a pointer to the array of objects. This
2816 ** might be the same as the pArray parameter or it might be a different
2817 ** pointer if the array was resized.
2819 void *sqlite3ArrayAllocate(
2820 sqlite3 *db, /* Connection to notify of malloc failures */
2821 void *pArray, /* Array of objects. Might be reallocated */
2822 int szEntry, /* Size of each object in the array */
2823 int initSize, /* Suggested initial allocation, in elements */
2824 int *pnEntry, /* Number of objects currently in use */
2825 int *pnAlloc, /* Current size of the allocation, in elements */
2826 int *pIdx /* Write the index of a new slot here */
2829 if( *pnEntry >= *pnAlloc ){
2832 newSize = (*pnAlloc)*2 + initSize;
2833 pNew = sqlite3DbRealloc(db, pArray, newSize*szEntry);
2842 memset(&z[*pnEntry * szEntry], 0, szEntry);
2849 ** Append a new element to the given IdList. Create a new IdList if
2852 ** A new IdList is returned, or NULL if malloc() fails.
2854 IdList *sqlite3IdListAppend(sqlite3 *db, IdList *pList, Token *pToken){
2857 pList = sqlite3DbMallocZero(db, sizeof(IdList) );
2858 if( pList==0 ) return 0;
2861 pList->a = sqlite3ArrayAllocate(
2864 sizeof(pList->a[0]),
2871 sqlite3IdListDelete(pList);
2874 pList->a[i].zName = sqlite3NameFromToken(db, pToken);
2879 ** Delete an IdList.
2881 void sqlite3IdListDelete(IdList *pList){
2883 if( pList==0 ) return;
2884 for(i=0; i<pList->nId; i++){
2885 sqlite3_free(pList->a[i].zName);
2887 sqlite3_free(pList->a);
2888 sqlite3_free(pList);
2892 ** Return the index in pList of the identifier named zId. Return -1
2895 int sqlite3IdListIndex(IdList *pList, const char *zName){
2897 if( pList==0 ) return -1;
2898 for(i=0; i<pList->nId; i++){
2899 if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
2905 ** Append a new table name to the given SrcList. Create a new SrcList if
2906 ** need be. A new entry is created in the SrcList even if pToken is NULL.
2908 ** A new SrcList is returned, or NULL if malloc() fails.
2910 ** If pDatabase is not null, it means that the table has an optional
2911 ** database name prefix. Like this: "database.table". The pDatabase
2912 ** points to the table name and the pTable points to the database name.
2913 ** The SrcList.a[].zName field is filled with the table name which might
2914 ** come from pTable (if pDatabase is NULL) or from pDatabase.
2915 ** SrcList.a[].zDatabase is filled with the database name from pTable,
2916 ** or with NULL if no database is specified.
2918 ** In other words, if call like this:
2920 ** sqlite3SrcListAppend(D,A,B,0);
2922 ** Then B is a table name and the database name is unspecified. If called
2925 ** sqlite3SrcListAppend(D,A,B,C);
2927 ** Then C is the table name and B is the database name.
2929 SrcList *sqlite3SrcListAppend(
2930 sqlite3 *db, /* Connection to notify of malloc failures */
2931 SrcList *pList, /* Append to this SrcList. NULL creates a new SrcList */
2932 Token *pTable, /* Table to append */
2933 Token *pDatabase /* Database of the table */
2935 struct SrcList_item *pItem;
2937 pList = sqlite3DbMallocZero(db, sizeof(SrcList) );
2938 if( pList==0 ) return 0;
2941 if( pList->nSrc>=pList->nAlloc ){
2944 pNew = sqlite3DbRealloc(db, pList,
2945 sizeof(*pList) + (pList->nAlloc-1)*sizeof(pList->a[0]) );
2947 sqlite3SrcListDelete(pList);
2952 pItem = &pList->a[pList->nSrc];
2953 memset(pItem, 0, sizeof(pList->a[0]));
2954 if( pDatabase && pDatabase->z==0 ){
2957 if( pDatabase && pTable ){
2958 Token *pTemp = pDatabase;
2962 pItem->zName = sqlite3NameFromToken(db, pTable);
2963 pItem->zDatabase = sqlite3NameFromToken(db, pDatabase);
2964 pItem->iCursor = -1;
2965 pItem->isPopulated = 0;
2971 ** Assign cursors to all tables in a SrcList
2973 void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
2975 struct SrcList_item *pItem;
2976 assert(pList || pParse->db->mallocFailed );
2978 for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
2979 if( pItem->iCursor>=0 ) break;
2980 pItem->iCursor = pParse->nTab++;
2981 if( pItem->pSelect ){
2982 sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
2989 ** Delete an entire SrcList including all its substructure.
2991 void sqlite3SrcListDelete(SrcList *pList){
2993 struct SrcList_item *pItem;
2994 if( pList==0 ) return;
2995 for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
2996 sqlite3_free(pItem->zDatabase);
2997 sqlite3_free(pItem->zName);
2998 sqlite3_free(pItem->zAlias);
2999 sqlite3DeleteTable(pItem->pTab);
3000 sqlite3SelectDelete(pItem->pSelect);
3001 sqlite3ExprDelete(pItem->pOn);
3002 sqlite3IdListDelete(pItem->pUsing);
3004 sqlite3_free(pList);
3008 ** This routine is called by the parser to add a new term to the
3009 ** end of a growing FROM clause. The "p" parameter is the part of
3010 ** the FROM clause that has already been constructed. "p" is NULL
3011 ** if this is the first term of the FROM clause. pTable and pDatabase
3012 ** are the name of the table and database named in the FROM clause term.
3013 ** pDatabase is NULL if the database name qualifier is missing - the
3014 ** usual case. If the term has a alias, then pAlias points to the
3015 ** alias token. If the term is a subquery, then pSubquery is the
3016 ** SELECT statement that the subquery encodes. The pTable and
3017 ** pDatabase parameters are NULL for subqueries. The pOn and pUsing
3018 ** parameters are the content of the ON and USING clauses.
3020 ** Return a new SrcList which encodes is the FROM with the new
3023 SrcList *sqlite3SrcListAppendFromTerm(
3024 Parse *pParse, /* Parsing context */
3025 SrcList *p, /* The left part of the FROM clause already seen */
3026 Token *pTable, /* Name of the table to add to the FROM clause */
3027 Token *pDatabase, /* Name of the database containing pTable */
3028 Token *pAlias, /* The right-hand side of the AS subexpression */
3029 Select *pSubquery, /* A subquery used in place of a table name */
3030 Expr *pOn, /* The ON clause of a join */
3031 IdList *pUsing /* The USING clause of a join */
3033 struct SrcList_item *pItem;
3034 sqlite3 *db = pParse->db;
3035 p = sqlite3SrcListAppend(db, p, pTable, pDatabase);
3036 if( p==0 || p->nSrc==0 ){
3037 sqlite3ExprDelete(pOn);
3038 sqlite3IdListDelete(pUsing);
3039 sqlite3SelectDelete(pSubquery);
3042 pItem = &p->a[p->nSrc-1];
3043 if( pAlias && pAlias->n ){
3044 pItem->zAlias = sqlite3NameFromToken(db, pAlias);
3046 pItem->pSelect = pSubquery;
3048 pItem->pUsing = pUsing;
3053 ** When building up a FROM clause in the parser, the join operator
3054 ** is initially attached to the left operand. But the code generator
3055 ** expects the join operator to be on the right operand. This routine
3056 ** Shifts all join operators from left to right for an entire FROM
3059 ** Example: Suppose the join is like this:
3061 ** A natural cross join B
3063 ** The operator is "natural cross join". The A and B operands are stored
3064 ** in p->a[0] and p->a[1], respectively. The parser initially stores the
3065 ** operator with A. This routine shifts that operator over to B.
3067 void sqlite3SrcListShiftJoinType(SrcList *p){
3070 for(i=p->nSrc-1; i>0; i--){
3071 p->a[i].jointype = p->a[i-1].jointype;
3073 p->a[0].jointype = 0;
3078 ** Begin a transaction
3080 void sqlite3BeginTransaction(Parse *pParse, int type){
3085 if( pParse==0 || (db=pParse->db)==0 || db->aDb[0].pBt==0 ) return;
3086 if( pParse->nErr || db->mallocFailed ) return;
3087 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ) return;
3089 v = sqlite3GetVdbe(pParse);
3091 if( type!=TK_DEFERRED ){
3092 for(i=0; i<db->nDb; i++){
3093 sqlite3VdbeAddOp(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
3094 sqlite3VdbeUsesBtree(v, i);
3097 sqlite3VdbeAddOp(v, OP_AutoCommit, 0, 0);
3101 ** Commit a transaction
3103 void sqlite3CommitTransaction(Parse *pParse){
3107 if( pParse==0 || (db=pParse->db)==0 || db->aDb[0].pBt==0 ) return;
3108 if( pParse->nErr || db->mallocFailed ) return;
3109 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ) return;
3111 v = sqlite3GetVdbe(pParse);
3113 sqlite3VdbeAddOp(v, OP_AutoCommit, 1, 0);
3118 ** Rollback a transaction
3120 void sqlite3RollbackTransaction(Parse *pParse){
3124 if( pParse==0 || (db=pParse->db)==0 || db->aDb[0].pBt==0 ) return;
3125 if( pParse->nErr || db->mallocFailed ) return;
3126 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ) return;
3128 v = sqlite3GetVdbe(pParse);
3130 sqlite3VdbeAddOp(v, OP_AutoCommit, 1, 1);
3135 ** Make sure the TEMP database is open and available for use. Return
3136 ** the number of errors. Leave any error messages in the pParse structure.
3138 int sqlite3OpenTempDatabase(Parse *pParse){
3139 sqlite3 *db = pParse->db;
3140 if( db->aDb[1].pBt==0 && !pParse->explain ){
3142 static const int flags =
3143 SQLITE_OPEN_READWRITE |
3144 SQLITE_OPEN_CREATE |
3145 SQLITE_OPEN_EXCLUSIVE |
3146 SQLITE_OPEN_DELETEONCLOSE |
3147 SQLITE_OPEN_TEMP_DB;
3149 rc = sqlite3BtreeFactory(db, 0, 0, SQLITE_DEFAULT_CACHE_SIZE, flags,
3151 if( rc!=SQLITE_OK ){
3152 sqlite3ErrorMsg(pParse, "unable to open a temporary database "
3153 "file for storing temporary tables");
3157 if( db->flags & !db->autoCommit ){
3158 rc = sqlite3BtreeBeginTrans(db->aDb[1].pBt, 1);
3159 if( rc!=SQLITE_OK ){
3160 sqlite3ErrorMsg(pParse, "unable to get a write lock on "
3161 "the temporary database file");
3166 assert( db->aDb[1].pSchema );
3172 ** Generate VDBE code that will verify the schema cookie and start
3173 ** a read-transaction for all named database files.
3175 ** It is important that all schema cookies be verified and all
3176 ** read transactions be started before anything else happens in
3177 ** the VDBE program. But this routine can be called after much other
3178 ** code has been generated. So here is what we do:
3180 ** The first time this routine is called, we code an OP_Goto that
3181 ** will jump to a subroutine at the end of the program. Then we
3182 ** record every database that needs its schema verified in the
3183 ** pParse->cookieMask field. Later, after all other code has been
3184 ** generated, the subroutine that does the cookie verifications and
3185 ** starts the transactions will be coded and the OP_Goto P2 value
3186 ** will be made to point to that subroutine. The generation of the
3187 ** cookie verification subroutine code happens in sqlite3FinishCoding().
3189 ** If iDb<0 then code the OP_Goto only - don't set flag to verify the
3190 ** schema on any databases. This can be used to position the OP_Goto
3191 ** early in the code, before we know if any database tables will be used.
3193 void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
3198 v = sqlite3GetVdbe(pParse);
3199 if( v==0 ) return; /* This only happens if there was a prior error */
3201 if( pParse->cookieGoto==0 ){
3202 pParse->cookieGoto = sqlite3VdbeAddOp(v, OP_Goto, 0, 0)+1;
3205 assert( iDb<db->nDb );
3206 assert( db->aDb[iDb].pBt!=0 || iDb==1 );
3207 assert( iDb<SQLITE_MAX_ATTACHED+2 );
3209 if( (pParse->cookieMask & mask)==0 ){
3210 pParse->cookieMask |= mask;
3211 pParse->cookieValue[iDb] = db->aDb[iDb].pSchema->schema_cookie;
3212 if( !OMIT_TEMPDB && iDb==1 ){
3213 sqlite3OpenTempDatabase(pParse);
3220 ** Generate VDBE code that prepares for doing an operation that
3221 ** might change the database.
3223 ** This routine starts a new transaction if we are not already within
3224 ** a transaction. If we are already within a transaction, then a checkpoint
3225 ** is set if the setStatement parameter is true. A checkpoint should
3226 ** be set for operations that might fail (due to a constraint) part of
3227 ** the way through and which will need to undo some writes without having to
3228 ** rollback the whole transaction. For operations where all constraints
3229 ** can be checked before any changes are made to the database, it is never
3230 ** necessary to undo a write and the checkpoint should not be set.
3232 ** Only database iDb and the temp database are made writable by this call.
3233 ** If iDb==0, then the main and temp databases are made writable. If
3234 ** iDb==1 then only the temp database is made writable. If iDb>1 then the
3235 ** specified auxiliary database and the temp database are made writable.
3237 void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
3238 Vdbe *v = sqlite3GetVdbe(pParse);
3240 sqlite3CodeVerifySchema(pParse, iDb);
3241 pParse->writeMask |= 1<<iDb;
3242 if( setStatement && pParse->nested==0 ){
3243 sqlite3VdbeAddOp(v, OP_Statement, iDb, 0);
3245 if( (OMIT_TEMPDB || iDb!=1) && pParse->db->aDb[1].pBt!=0 ){
3246 sqlite3BeginWriteOperation(pParse, setStatement, 1);
3251 ** Check to see if pIndex uses the collating sequence pColl. Return
3252 ** true if it does and false if it does not.
3254 #ifndef SQLITE_OMIT_REINDEX
3255 static int collationMatch(const char *zColl, Index *pIndex){
3257 for(i=0; i<pIndex->nColumn; i++){
3258 const char *z = pIndex->azColl[i];
3259 if( z==zColl || (z && zColl && 0==sqlite3StrICmp(z, zColl)) ){
3268 ** Recompute all indices of pTab that use the collating sequence pColl.
3269 ** If pColl==0 then recompute all indices of pTab.
3271 #ifndef SQLITE_OMIT_REINDEX
3272 static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
3273 Index *pIndex; /* An index associated with pTab */
3275 for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
3276 if( zColl==0 || collationMatch(zColl, pIndex) ){
3277 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
3278 sqlite3BeginWriteOperation(pParse, 0, iDb);
3279 sqlite3RefillIndex(pParse, pIndex, -1);
3286 ** Recompute all indices of all tables in all databases where the
3287 ** indices use the collating sequence pColl. If pColl==0 then recompute
3288 ** all indices everywhere.
3290 #ifndef SQLITE_OMIT_REINDEX
3291 static void reindexDatabases(Parse *pParse, char const *zColl){
3292 Db *pDb; /* A single database */
3293 int iDb; /* The database index number */
3294 sqlite3 *db = pParse->db; /* The database connection */
3295 HashElem *k; /* For looping over tables in pDb */
3296 Table *pTab; /* A table in the database */
3298 for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
3300 for(k=sqliteHashFirst(&pDb->pSchema->tblHash); k; k=sqliteHashNext(k)){
3301 pTab = (Table*)sqliteHashData(k);
3302 reindexTable(pParse, pTab, zColl);
3309 ** Generate code for the REINDEX command.
3312 ** REINDEX <collation> -- 2
3313 ** REINDEX ?<database>.?<tablename> -- 3
3314 ** REINDEX ?<database>.?<indexname> -- 4
3316 ** Form 1 causes all indices in all attached databases to be rebuilt.
3317 ** Form 2 rebuilds all indices in all databases that use the named
3318 ** collating function. Forms 3 and 4 rebuild the named index or all
3319 ** indices associated with the named table.
3321 #ifndef SQLITE_OMIT_REINDEX
3322 void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
3323 CollSeq *pColl; /* Collating sequence to be reindexed, or NULL */
3324 char *z; /* Name of a table or index */
3325 const char *zDb; /* Name of the database */
3326 Table *pTab; /* A table in the database */
3327 Index *pIndex; /* An index associated with pTab */
3328 int iDb; /* The database index number */
3329 sqlite3 *db = pParse->db; /* The database connection */
3330 Token *pObjName; /* Name of the table or index to be reindexed */
3332 /* Read the database schema. If an error occurs, leave an error message
3333 ** and code in pParse and return NULL. */
3334 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
3338 if( pName1==0 || pName1->z==0 ){
3339 reindexDatabases(pParse, 0);
3341 }else if( pName2==0 || pName2->z==0 ){
3342 assert( pName1->z );
3343 pColl = sqlite3FindCollSeq(db, ENC(db), (char*)pName1->z, pName1->n, 0);
3345 char *zColl = sqlite3DbStrNDup(db, (const char *)pName1->z, pName1->n);
3347 reindexDatabases(pParse, zColl);
3348 sqlite3_free(zColl);
3353 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
3355 z = sqlite3NameFromToken(db, pObjName);
3357 zDb = db->aDb[iDb].zName;
3358 pTab = sqlite3FindTable(db, z, zDb);
3360 reindexTable(pParse, pTab, 0);
3364 pIndex = sqlite3FindIndex(db, z, zDb);
3367 sqlite3BeginWriteOperation(pParse, 0, iDb);
3368 sqlite3RefillIndex(pParse, pIndex, -1);
3371 sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
3376 ** Return a dynamicly allocated KeyInfo structure that can be used
3377 ** with OP_OpenRead or OP_OpenWrite to access database index pIdx.
3379 ** If successful, a pointer to the new structure is returned. In this case
3380 ** the caller is responsible for calling sqlite3_free() on the returned
3381 ** pointer. If an error occurs (out of memory or missing collation
3382 ** sequence), NULL is returned and the state of pParse updated to reflect
3385 KeyInfo *sqlite3IndexKeyinfo(Parse *pParse, Index *pIdx){
3387 int nCol = pIdx->nColumn;
3388 int nBytes = sizeof(KeyInfo) + (nCol-1)*sizeof(CollSeq*) + nCol;
3389 KeyInfo *pKey = (KeyInfo *)sqlite3DbMallocZero(pParse->db, nBytes);
3392 pKey->db = pParse->db;
3393 pKey->aSortOrder = (u8 *)&(pKey->aColl[nCol]);
3394 assert( &pKey->aSortOrder[nCol]==&(((u8 *)pKey)[nBytes]) );
3395 for(i=0; i<nCol; i++){
3396 char *zColl = pIdx->azColl[i];
3398 pKey->aColl[i] = sqlite3LocateCollSeq(pParse, zColl, -1);
3399 pKey->aSortOrder[i] = pIdx->aSortOrder[i];
3401 pKey->nField = nCol;