xref: /sqlite-3.40.0/src/build.c (revision 5723c659)
175897234Sdrh /*
2b19a2bc6Sdrh ** 2001 September 15
375897234Sdrh **
4b19a2bc6Sdrh ** The author disclaims copyright to this source code.  In place of
5b19a2bc6Sdrh ** a legal notice, here is a blessing:
675897234Sdrh **
7b19a2bc6Sdrh **    May you do good and not evil.
8b19a2bc6Sdrh **    May you find forgiveness for yourself and forgive others.
9b19a2bc6Sdrh **    May you share freely, never taking more than you give.
1075897234Sdrh **
1175897234Sdrh *************************************************************************
12b19a2bc6Sdrh ** This file contains C code routines that are called by the SQLite parser
13b19a2bc6Sdrh ** when syntax rules are reduced.  The routines in this file handle the
14b19a2bc6Sdrh ** following kinds of SQL syntax:
1575897234Sdrh **
16bed8690fSdrh **     CREATE TABLE
17bed8690fSdrh **     DROP TABLE
18bed8690fSdrh **     CREATE INDEX
19bed8690fSdrh **     DROP INDEX
20832508b7Sdrh **     creating ID lists
21b19a2bc6Sdrh **     BEGIN TRANSACTION
22b19a2bc6Sdrh **     COMMIT
23b19a2bc6Sdrh **     ROLLBACK
2475897234Sdrh */
2575897234Sdrh #include "sqliteInt.h"
2675897234Sdrh 
27c00da105Sdanielk1977 #ifndef SQLITE_OMIT_SHARED_CACHE
28c00da105Sdanielk1977 /*
29c00da105Sdanielk1977 ** The TableLock structure is only used by the sqlite3TableLock() and
30c00da105Sdanielk1977 ** codeTableLocks() functions.
31c00da105Sdanielk1977 */
32c00da105Sdanielk1977 struct TableLock {
33d698bc15Sdrh   int iDb;               /* The database containing the table to be locked */
34abc38158Sdrh   Pgno iTab;             /* The root page of the table to be locked */
35d698bc15Sdrh   u8 isWriteLock;        /* True for write lock.  False for a read lock */
36e0a04a36Sdrh   const char *zLockName; /* Name of the table */
37c00da105Sdanielk1977 };
38c00da105Sdanielk1977 
39c00da105Sdanielk1977 /*
40d698bc15Sdrh ** Record the fact that we want to lock a table at run-time.
41c00da105Sdanielk1977 **
42d698bc15Sdrh ** The table to be locked has root page iTab and is found in database iDb.
43d698bc15Sdrh ** A read or a write lock can be taken depending on isWritelock.
44d698bc15Sdrh **
45d698bc15Sdrh ** This routine just records the fact that the lock is desired.  The
46d698bc15Sdrh ** code to make the lock occur is generated by a later call to
47d698bc15Sdrh ** codeTableLocks() which occurs during sqlite3FinishCoding().
48c00da105Sdanielk1977 */
lockTable(Parse * pParse,int iDb,Pgno iTab,u8 isWriteLock,const char * zName)499430506dSdrh static SQLITE_NOINLINE void lockTable(
50d698bc15Sdrh   Parse *pParse,     /* Parsing context */
51d698bc15Sdrh   int iDb,           /* Index of the database containing the table to lock */
52abc38158Sdrh   Pgno iTab,         /* Root page number of the table to be locked */
53d698bc15Sdrh   u8 isWriteLock,    /* True for a write lock */
54d698bc15Sdrh   const char *zName  /* Name of the table to be locked */
55c00da105Sdanielk1977 ){
561d8f892aSdrh   Parse *pToplevel;
57c00da105Sdanielk1977   int i;
58c00da105Sdanielk1977   int nBytes;
59c00da105Sdanielk1977   TableLock *p;
608af73d41Sdrh   assert( iDb>=0 );
61165921a7Sdan 
621d8f892aSdrh   pToplevel = sqlite3ParseToplevel(pParse);
6365a7cd16Sdan   for(i=0; i<pToplevel->nTableLock; i++){
6465a7cd16Sdan     p = &pToplevel->aTableLock[i];
65c00da105Sdanielk1977     if( p->iDb==iDb && p->iTab==iTab ){
66c00da105Sdanielk1977       p->isWriteLock = (p->isWriteLock || isWriteLock);
67c00da105Sdanielk1977       return;
68c00da105Sdanielk1977     }
69c00da105Sdanielk1977   }
70c00da105Sdanielk1977 
7165a7cd16Sdan   nBytes = sizeof(TableLock) * (pToplevel->nTableLock+1);
7265a7cd16Sdan   pToplevel->aTableLock =
7365a7cd16Sdan       sqlite3DbReallocOrFree(pToplevel->db, pToplevel->aTableLock, nBytes);
7465a7cd16Sdan   if( pToplevel->aTableLock ){
7565a7cd16Sdan     p = &pToplevel->aTableLock[pToplevel->nTableLock++];
76c00da105Sdanielk1977     p->iDb = iDb;
77c00da105Sdanielk1977     p->iTab = iTab;
78c00da105Sdanielk1977     p->isWriteLock = isWriteLock;
79e0a04a36Sdrh     p->zLockName = zName;
80f3a65f7eSdrh   }else{
8165a7cd16Sdan     pToplevel->nTableLock = 0;
824a642b60Sdrh     sqlite3OomFault(pToplevel->db);
83c00da105Sdanielk1977   }
84c00da105Sdanielk1977 }
sqlite3TableLock(Parse * pParse,int iDb,Pgno iTab,u8 isWriteLock,const char * zName)859430506dSdrh void sqlite3TableLock(
869430506dSdrh   Parse *pParse,     /* Parsing context */
879430506dSdrh   int iDb,           /* Index of the database containing the table to lock */
889430506dSdrh   Pgno iTab,         /* Root page number of the table to be locked */
899430506dSdrh   u8 isWriteLock,    /* True for a write lock */
909430506dSdrh   const char *zName  /* Name of the table to be locked */
919430506dSdrh ){
929430506dSdrh   if( iDb==1 ) return;
939430506dSdrh   if( !sqlite3BtreeSharable(pParse->db->aDb[iDb].pBt) ) return;
949430506dSdrh   lockTable(pParse, iDb, iTab, isWriteLock, zName);
959430506dSdrh }
96c00da105Sdanielk1977 
97c00da105Sdanielk1977 /*
98c00da105Sdanielk1977 ** Code an OP_TableLock instruction for each table locked by the
99c00da105Sdanielk1977 ** statement (configured by calls to sqlite3TableLock()).
100c00da105Sdanielk1977 */
codeTableLocks(Parse * pParse)101c00da105Sdanielk1977 static void codeTableLocks(Parse *pParse){
102c00da105Sdanielk1977   int i;
103f0b41745Sdrh   Vdbe *pVdbe = pParse->pVdbe;
104289a0c84Sdrh   assert( pVdbe!=0 );
105c00da105Sdanielk1977 
106c00da105Sdanielk1977   for(i=0; i<pParse->nTableLock; i++){
107c00da105Sdanielk1977     TableLock *p = &pParse->aTableLock[i];
108c00da105Sdanielk1977     int p1 = p->iDb;
1096a9ad3daSdrh     sqlite3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, p->isWriteLock,
110e0a04a36Sdrh                       p->zLockName, P4_STATIC);
111c00da105Sdanielk1977   }
112c00da105Sdanielk1977 }
113c00da105Sdanielk1977 #else
114c00da105Sdanielk1977   #define codeTableLocks(x)
115c00da105Sdanielk1977 #endif
116c00da105Sdanielk1977 
117e0bc4048Sdrh /*
118a7ab6d81Sdrh ** Return TRUE if the given yDbMask object is empty - if it contains no
119a7ab6d81Sdrh ** 1 bits.  This routine is used by the DbMaskAllZero() and DbMaskNotZero()
120a7ab6d81Sdrh ** macros when SQLITE_MAX_ATTACHED is greater than 30.
121a7ab6d81Sdrh */
122a7ab6d81Sdrh #if SQLITE_MAX_ATTACHED>30
sqlite3DbMaskAllZero(yDbMask m)123a7ab6d81Sdrh int sqlite3DbMaskAllZero(yDbMask m){
124a7ab6d81Sdrh   int i;
125a7ab6d81Sdrh   for(i=0; i<sizeof(yDbMask); i++) if( m[i] ) return 0;
126a7ab6d81Sdrh   return 1;
127a7ab6d81Sdrh }
128a7ab6d81Sdrh #endif
129a7ab6d81Sdrh 
130a7ab6d81Sdrh /*
13175897234Sdrh ** This routine is called after a single SQL statement has been
13280242055Sdrh ** parsed and a VDBE program to execute that statement has been
13380242055Sdrh ** prepared.  This routine puts the finishing touches on the
13480242055Sdrh ** VDBE program and resets the pParse structure for the next
13580242055Sdrh ** parse.
13675897234Sdrh **
13775897234Sdrh ** Note that if an error occurred, it might be the case that
13875897234Sdrh ** no VDBE code was generated.
13975897234Sdrh */
sqlite3FinishCoding(Parse * pParse)14080242055Sdrh void sqlite3FinishCoding(Parse *pParse){
1419bb575fdSdrh   sqlite3 *db;
14280242055Sdrh   Vdbe *v;
1437bace9e9Sdrh   int iDb, i;
144b86ccfb2Sdrh 
145f78baafeSdan   assert( pParse->pToplevel==0 );
14617435752Sdrh   db = pParse->db;
1470c7d3d39Sdrh   assert( db->pParse==pParse );
148205f48e6Sdrh   if( pParse->nested ) return;
1490c7d3d39Sdrh   if( pParse->nErr ){
150a5c9a707Sdrh     if( db->mallocFailed ) pParse->rc = SQLITE_NOMEM;
151d99d2836Sdrh     return;
152d99d2836Sdrh   }
1530c7d3d39Sdrh   assert( db->mallocFailed==0 );
15448d0d866Sdanielk1977 
15580242055Sdrh   /* Begin by generating some termination code at the end of the
15680242055Sdrh   ** vdbe program
15780242055Sdrh   */
15802c4aa39Sdrh   v = pParse->pVdbe;
15902c4aa39Sdrh   if( v==0 ){
16002c4aa39Sdrh     if( db->init.busy ){
161c8af879eSdrh       pParse->rc = SQLITE_DONE;
162c8af879eSdrh       return;
163c8af879eSdrh     }
16480242055Sdrh     v = sqlite3GetVdbe(pParse);
16502c4aa39Sdrh     if( v==0 ) pParse->rc = SQLITE_ERROR;
16602c4aa39Sdrh   }
167f3677212Sdan   assert( !pParse->isMultiWrite
168f3677212Sdan        || sqlite3VdbeAssertMayAbort(v, pParse->mayAbort));
16980242055Sdrh   if( v ){
170381bdaccSdrh     if( pParse->bReturning ){
171381bdaccSdrh       Returning *pReturning = pParse->u1.pReturning;
172381bdaccSdrh       int addrRewind;
173381bdaccSdrh       int reg;
174381bdaccSdrh 
1751a6bac0dSdrh       if( pReturning->nRetCol ){
1763b26b2b5Sdrh         sqlite3VdbeAddOp0(v, OP_FkCheck);
177381bdaccSdrh         addrRewind =
178381bdaccSdrh            sqlite3VdbeAddOp1(v, OP_Rewind, pReturning->iRetCur);
1796859d324Sdrh         VdbeCoverage(v);
180552562c4Sdrh         reg = pReturning->iRetReg;
181381bdaccSdrh         for(i=0; i<pReturning->nRetCol; i++){
182381bdaccSdrh           sqlite3VdbeAddOp3(v, OP_Column, pReturning->iRetCur, i, reg+i);
183381bdaccSdrh         }
184381bdaccSdrh         sqlite3VdbeAddOp2(v, OP_ResultRow, reg, i);
185381bdaccSdrh         sqlite3VdbeAddOp2(v, OP_Next, pReturning->iRetCur, addrRewind+1);
1866859d324Sdrh         VdbeCoverage(v);
187381bdaccSdrh         sqlite3VdbeJumpHere(v, addrRewind);
188381bdaccSdrh       }
1897132f436Sdrh     }
19066a5167bSdrh     sqlite3VdbeAddOp0(v, OP_Halt);
1910e3d7476Sdrh 
192b2445d5eSdrh #if SQLITE_USER_AUTHENTICATION
193b2445d5eSdrh     if( pParse->nTableLock>0 && db->init.busy==0 ){
1947883ecfcSdrh       sqlite3UserAuthInit(db);
195b2445d5eSdrh       if( db->auth.authLevel<UAUTH_User ){
196b2445d5eSdrh         sqlite3ErrorMsg(pParse, "user not authenticated");
1976ae3ab00Sdrh         pParse->rc = SQLITE_AUTH_USER;
198b2445d5eSdrh         return;
199b2445d5eSdrh       }
200b2445d5eSdrh     }
201b2445d5eSdrh #endif
202b2445d5eSdrh 
2030e3d7476Sdrh     /* The cookie mask contains one bit for each database file open.
2040e3d7476Sdrh     ** (Bit 0 is for main, bit 1 is for temp, and so forth.)  Bits are
2050e3d7476Sdrh     ** set for each database that is used.  Generate code to start a
2060e3d7476Sdrh     ** transaction on each used database and to verify the schema cookie
2070e3d7476Sdrh     ** on each used database.
2080e3d7476Sdrh     */
2097bace9e9Sdrh     assert( pParse->nErr>0 || sqlite3VdbeGetOp(v, 0)->opcode==OP_Init );
210aceb31b1Sdrh     sqlite3VdbeJumpHere(v, 0);
21166f58bf3Sdrh     assert( db->nDb>0 );
21266f58bf3Sdrh     iDb = 0;
21366f58bf3Sdrh     do{
2141d96cc60Sdrh       Schema *pSchema;
215a7ab6d81Sdrh       if( DbMaskTest(pParse->cookieMask, iDb)==0 ) continue;
216fb98264aSdrh       sqlite3VdbeUsesBtree(v, iDb);
2171d96cc60Sdrh       pSchema = db->aDb[iDb].pSchema;
218b22f7c83Sdrh       sqlite3VdbeAddOp4Int(v,
219b22f7c83Sdrh         OP_Transaction,                    /* Opcode */
220b22f7c83Sdrh         iDb,                               /* P1 */
221a7ab6d81Sdrh         DbMaskTest(pParse->writeMask,iDb), /* P2 */
2221d96cc60Sdrh         pSchema->schema_cookie,            /* P3 */
2231d96cc60Sdrh         pSchema->iGeneration               /* P4 */
224b22f7c83Sdrh       );
225b22f7c83Sdrh       if( db->init.busy==0 ) sqlite3VdbeChangeP5(v, 1);
226076e0f96Sdan       VdbeComment((v,
227076e0f96Sdan             "usesStmtJournal=%d", pParse->mayAbort && pParse->isMultiWrite));
22866f58bf3Sdrh     }while( ++iDb<db->nDb );
229f9e7dda7Sdanielk1977 #ifndef SQLITE_OMIT_VIRTUALTABLE
2304f3dd150Sdrh     for(i=0; i<pParse->nVtabLock; i++){
231595a523aSdanielk1977       char *vtab = (char *)sqlite3GetVTable(db, pParse->apVtabLock[i]);
23266a5167bSdrh       sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB);
233f9e7dda7Sdanielk1977     }
2344f3dd150Sdrh     pParse->nVtabLock = 0;
235f9e7dda7Sdanielk1977 #endif
236c00da105Sdanielk1977 
237c00da105Sdanielk1977     /* Once all the cookies have been verified and transactions opened,
238c00da105Sdanielk1977     ** obtain the required table-locks. This is a no-op unless the
239c00da105Sdanielk1977     ** shared-cache feature is enabled.
240c00da105Sdanielk1977     */
241c00da105Sdanielk1977     codeTableLocks(pParse);
2420b9f50d8Sdrh 
2430b9f50d8Sdrh     /* Initialize any AUTOINCREMENT data structures required.
2440b9f50d8Sdrh     */
2450b9f50d8Sdrh     sqlite3AutoincrementBegin(pParse);
2460b9f50d8Sdrh 
24789636628Sdrh     /* Code constant expressions that where factored out of inner loops.
24889636628Sdrh     **
24989636628Sdrh     ** The pConstExpr list might also contain expressions that we simply
25089636628Sdrh     ** want to keep around until the Parse object is deleted.  Such
25189636628Sdrh     ** expressions have iConstExprReg==0.  Do not generate code for
25289636628Sdrh     ** those expressions, of course.
25389636628Sdrh     */
254f30a969bSdrh     if( pParse->pConstExpr ){
255f30a969bSdrh       ExprList *pEL = pParse->pConstExpr;
256aceb31b1Sdrh       pParse->okConstFactor = 0;
257f30a969bSdrh       for(i=0; i<pEL->nExpr; i++){
25889636628Sdrh         int iReg = pEL->a[i].u.iConstExprReg;
25989636628Sdrh         sqlite3ExprCode(pParse, pEL->a[i].pExpr, iReg);
26089636628Sdrh       }
261f30a969bSdrh     }
262f30a969bSdrh 
263381bdaccSdrh     if( pParse->bReturning ){
264381bdaccSdrh       Returning *pRet = pParse->u1.pReturning;
2651a6bac0dSdrh       if( pRet->nRetCol ){
266381bdaccSdrh         sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pRet->iRetCur, pRet->nRetCol);
267381bdaccSdrh       }
2687132f436Sdrh     }
269381bdaccSdrh 
2700b9f50d8Sdrh     /* Finally, jump back to the beginning of the executable code. */
271076e85f5Sdrh     sqlite3VdbeGoto(v, 1);
27280242055Sdrh   }
27371c697efSdrh 
27480242055Sdrh   /* Get the VDBE program ready for execution
27580242055Sdrh   */
2761da88b5cSdrh   assert( v!=0 || pParse->nErr );
2771da88b5cSdrh   assert( db->mallocFailed==0 || pParse->nErr );
2781da88b5cSdrh   if( pParse->nErr==0 ){
2793492dd71Sdrh     /* A minimum of one cursor is required if autoincrement is used
2803492dd71Sdrh     *  See ticket [a696379c1f08866] */
28104ab586bSdrh     assert( pParse->pAinc==0 || pParse->nTab>0 );
282124c0b49Sdrh     sqlite3VdbeMakeReady(v, pParse);
283441daf68Sdanielk1977     pParse->rc = SQLITE_DONE;
284e294da02Sdrh   }else{
285483750baSdrh     pParse->rc = SQLITE_ERROR;
28675897234Sdrh   }
28775897234Sdrh }
28875897234Sdrh 
28975897234Sdrh /*
290205f48e6Sdrh ** Run the parser and code generator recursively in order to generate
291205f48e6Sdrh ** code for the SQL statement given onto the end of the pParse context
2923edc927eSdrh ** currently under construction.  Notes:
2933edc927eSdrh **
2943edc927eSdrh **   *  The final OP_Halt is not appended and other initialization
295205f48e6Sdrh **      and finalization steps are omitted because those are handling by the
296205f48e6Sdrh **      outermost parser.
297205f48e6Sdrh **
2983edc927eSdrh **   *  Built-in SQL functions always take precedence over application-defined
2993edc927eSdrh **      SQL functions.  In other words, it is not possible to override a
3003edc927eSdrh **      built-in function.
301205f48e6Sdrh */
sqlite3NestedParse(Parse * pParse,const char * zFormat,...)302205f48e6Sdrh void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
303205f48e6Sdrh   va_list ap;
304205f48e6Sdrh   char *zSql;
305633e6d57Sdrh   sqlite3 *db = pParse->db;
3063edc927eSdrh   u32 savedDbFlags = db->mDbFlags;
307cd9af608Sdrh   char saveBuf[PARSE_TAIL_SZ];
308f1974846Sdrh 
309205f48e6Sdrh   if( pParse->nErr ) return;
310205f48e6Sdrh   assert( pParse->nested<10 );  /* Nesting should only be of limited depth */
311205f48e6Sdrh   va_start(ap, zFormat);
312633e6d57Sdrh   zSql = sqlite3VMPrintf(db, zFormat, ap);
313205f48e6Sdrh   va_end(ap);
31473c42a13Sdrh   if( zSql==0 ){
315480c572fSdrh     /* This can result either from an OOM or because the formatted string
316480c572fSdrh     ** exceeds SQLITE_LIMIT_LENGTH.  In the latter case, we need to set
317480c572fSdrh     ** an error */
318480c572fSdrh     if( !db->mallocFailed ) pParse->rc = SQLITE_TOOBIG;
319a2b6806bSdrh     pParse->nErr++;
320480c572fSdrh     return;
32173c42a13Sdrh   }
322205f48e6Sdrh   pParse->nested++;
323cd9af608Sdrh   memcpy(saveBuf, PARSE_TAIL(pParse), PARSE_TAIL_SZ);
324cd9af608Sdrh   memset(PARSE_TAIL(pParse), 0, PARSE_TAIL_SZ);
3253edc927eSdrh   db->mDbFlags |= DBFLAG_PreferBuiltin;
32654bc6381Sdrh   sqlite3RunParser(pParse, zSql);
3273edc927eSdrh   db->mDbFlags = savedDbFlags;
328633e6d57Sdrh   sqlite3DbFree(db, zSql);
329cd9af608Sdrh   memcpy(PARSE_TAIL(pParse), saveBuf, PARSE_TAIL_SZ);
330205f48e6Sdrh   pParse->nested--;
331205f48e6Sdrh }
332205f48e6Sdrh 
333d4530979Sdrh #if SQLITE_USER_AUTHENTICATION
334d4530979Sdrh /*
335d4530979Sdrh ** Return TRUE if zTable is the name of the system table that stores the
336d4530979Sdrh ** list of users and their access credentials.
337d4530979Sdrh */
sqlite3UserAuthTable(const char * zTable)338d4530979Sdrh int sqlite3UserAuthTable(const char *zTable){
339d4530979Sdrh   return sqlite3_stricmp(zTable, "sqlite_user")==0;
340d4530979Sdrh }
341d4530979Sdrh #endif
342d4530979Sdrh 
343205f48e6Sdrh /*
3448a41449eSdanielk1977 ** Locate the in-memory structure that describes a particular database
3458a41449eSdanielk1977 ** table given the name of that table and (optionally) the name of the
3468a41449eSdanielk1977 ** database containing the table.  Return NULL if not found.
347a69d9168Sdrh **
3488a41449eSdanielk1977 ** If zDatabase is 0, all databases are searched for the table and the
3498a41449eSdanielk1977 ** first matching table is returned.  (No checking for duplicate table
3508a41449eSdanielk1977 ** names is done.)  The search order is TEMP first, then MAIN, then any
3518a41449eSdanielk1977 ** auxiliary databases added using the ATTACH command.
352f26e09c8Sdrh **
3534adee20fSdanielk1977 ** See also sqlite3LocateTable().
35475897234Sdrh */
sqlite3FindTable(sqlite3 * db,const char * zName,const char * zDatabase)3559bb575fdSdrh Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
356d24cc427Sdrh   Table *p = 0;
357d24cc427Sdrh   int i;
3589ca95730Sdrh 
3592120608eSdrh   /* All mutexes are required for schema access.  Make sure we hold them. */
3602120608eSdrh   assert( zDatabase!=0 || sqlite3BtreeHoldsAllMutexes(db) );
361d4530979Sdrh #if SQLITE_USER_AUTHENTICATION
362d4530979Sdrh   /* Only the admin user is allowed to know that the sqlite_user table
363d4530979Sdrh   ** exists */
364e933b83fSdrh   if( db->auth.authLevel<UAUTH_Admin && sqlite3UserAuthTable(zName)!=0 ){
365e933b83fSdrh     return 0;
366e933b83fSdrh   }
367d4530979Sdrh #endif
368b2eb7e46Sdrh   if( zDatabase ){
369b2eb7e46Sdrh     for(i=0; i<db->nDb; i++){
370b2eb7e46Sdrh       if( sqlite3StrICmp(zDatabase, db->aDb[i].zDbSName)==0 ) break;
371d24cc427Sdrh     }
372b2eb7e46Sdrh     if( i>=db->nDb ){
373b2eb7e46Sdrh       /* No match against the official names.  But always match "main"
374b2eb7e46Sdrh       ** to schema 0 as a legacy fallback. */
375b2eb7e46Sdrh       if( sqlite3StrICmp(zDatabase,"main")==0 ){
376b2eb7e46Sdrh         i = 0;
377b2eb7e46Sdrh       }else{
378e0a04a36Sdrh         return 0;
37975897234Sdrh       }
380b2eb7e46Sdrh     }
381b2eb7e46Sdrh     p = sqlite3HashFind(&db->aDb[i].pSchema->tblHash, zName);
382346a70caSdrh     if( p==0 && sqlite3StrNICmp(zName, "sqlite_", 7)==0 ){
383346a70caSdrh       if( i==1 ){
384a4a871c2Sdrh         if( sqlite3StrICmp(zName+7, &PREFERRED_TEMP_SCHEMA_TABLE[7])==0
385a4a871c2Sdrh          || sqlite3StrICmp(zName+7, &PREFERRED_SCHEMA_TABLE[7])==0
386a4a871c2Sdrh          || sqlite3StrICmp(zName+7, &LEGACY_SCHEMA_TABLE[7])==0
387346a70caSdrh         ){
388346a70caSdrh           p = sqlite3HashFind(&db->aDb[1].pSchema->tblHash,
389a4a871c2Sdrh                               LEGACY_TEMP_SCHEMA_TABLE);
390346a70caSdrh         }
391346a70caSdrh       }else{
392a4a871c2Sdrh         if( sqlite3StrICmp(zName+7, &PREFERRED_SCHEMA_TABLE[7])==0 ){
393346a70caSdrh           p = sqlite3HashFind(&db->aDb[i].pSchema->tblHash,
394a4a871c2Sdrh                               LEGACY_SCHEMA_TABLE);
395346a70caSdrh         }
396346a70caSdrh       }
397b2eb7e46Sdrh     }
398b2eb7e46Sdrh   }else{
399b2eb7e46Sdrh     /* Match against TEMP first */
400b2eb7e46Sdrh     p = sqlite3HashFind(&db->aDb[1].pSchema->tblHash, zName);
401b2eb7e46Sdrh     if( p ) return p;
402b2eb7e46Sdrh     /* The main database is second */
403b2eb7e46Sdrh     p = sqlite3HashFind(&db->aDb[0].pSchema->tblHash, zName);
404b2eb7e46Sdrh     if( p ) return p;
405b2eb7e46Sdrh     /* Attached databases are in order of attachment */
406b2eb7e46Sdrh     for(i=2; i<db->nDb; i++){
407b2eb7e46Sdrh       assert( sqlite3SchemaMutexHeld(db, i, 0) );
408b2eb7e46Sdrh       p = sqlite3HashFind(&db->aDb[i].pSchema->tblHash, zName);
409b2eb7e46Sdrh       if( p ) break;
410b2eb7e46Sdrh     }
411346a70caSdrh     if( p==0 && sqlite3StrNICmp(zName, "sqlite_", 7)==0 ){
412a4a871c2Sdrh       if( sqlite3StrICmp(zName+7, &PREFERRED_SCHEMA_TABLE[7])==0 ){
413a4a871c2Sdrh         p = sqlite3HashFind(&db->aDb[0].pSchema->tblHash, LEGACY_SCHEMA_TABLE);
414a4a871c2Sdrh       }else if( sqlite3StrICmp(zName+7, &PREFERRED_TEMP_SCHEMA_TABLE[7])==0 ){
415346a70caSdrh         p = sqlite3HashFind(&db->aDb[1].pSchema->tblHash,
416a4a871c2Sdrh                             LEGACY_TEMP_SCHEMA_TABLE);
417346a70caSdrh       }
418346a70caSdrh     }
419b2eb7e46Sdrh   }
420b2eb7e46Sdrh   return p;
421b2eb7e46Sdrh }
42275897234Sdrh 
42375897234Sdrh /*
4248a41449eSdanielk1977 ** Locate the in-memory structure that describes a particular database
4258a41449eSdanielk1977 ** table given the name of that table and (optionally) the name of the
4268a41449eSdanielk1977 ** database containing the table.  Return NULL if not found.  Also leave an
4278a41449eSdanielk1977 ** error message in pParse->zErrMsg.
428a69d9168Sdrh **
4298a41449eSdanielk1977 ** The difference between this routine and sqlite3FindTable() is that this
4308a41449eSdanielk1977 ** routine leaves an error message in pParse->zErrMsg where
4318a41449eSdanielk1977 ** sqlite3FindTable() does not.
432a69d9168Sdrh */
sqlite3LocateTable(Parse * pParse,u32 flags,const char * zName,const char * zDbase)433ca424114Sdrh Table *sqlite3LocateTable(
434ca424114Sdrh   Parse *pParse,         /* context in which to report errors */
4354d249e61Sdrh   u32 flags,             /* LOCATE_VIEW or LOCATE_NOERR */
436ca424114Sdrh   const char *zName,     /* Name of the table we are looking for */
437ca424114Sdrh   const char *zDbase     /* Name of the database.  Might be NULL */
438ca424114Sdrh ){
439a69d9168Sdrh   Table *p;
440b2c8559fSdrh   sqlite3 *db = pParse->db;
441f26e09c8Sdrh 
4428a41449eSdanielk1977   /* Read the database schema. If an error occurs, leave an error message
4438a41449eSdanielk1977   ** and code in pParse and return NULL. */
444b2c8559fSdrh   if( (db->mDbFlags & DBFLAG_SchemaKnownOk)==0
445b2c8559fSdrh    && SQLITE_OK!=sqlite3ReadSchema(pParse)
446b2c8559fSdrh   ){
4478a41449eSdanielk1977     return 0;
4488a41449eSdanielk1977   }
4498a41449eSdanielk1977 
450b2c8559fSdrh   p = sqlite3FindTable(db, zName, zDbase);
451a69d9168Sdrh   if( p==0 ){
452d2975928Sdrh #ifndef SQLITE_OMIT_VIRTUALTABLE
45351be3873Sdrh     /* If zName is the not the name of a table in the schema created using
45451be3873Sdrh     ** CREATE, then check to see if it is the name of an virtual table that
45551be3873Sdrh     ** can be an eponymous virtual table. */
4567424aeffSdrh     if( (pParse->prepFlags & SQLITE_PREPARE_NO_VTAB)==0 && db->init.busy==0 ){
457b2c8559fSdrh       Module *pMod = (Module*)sqlite3HashFind(&db->aModule, zName);
4582fcc1590Sdrh       if( pMod==0 && sqlite3_strnicmp(zName, "pragma_", 7)==0 ){
459b2c8559fSdrh         pMod = sqlite3PragmaVtabRegister(db, zName);
4602fcc1590Sdrh       }
46151be3873Sdrh       if( pMod && sqlite3VtabEponymousTableInit(pParse, pMod) ){
462bd24e8faSdan         testcase( pMod->pEpoTab==0 );
46351be3873Sdrh         return pMod->pEpoTab;
46451be3873Sdrh       }
4651ea0443cSdan     }
46651be3873Sdrh #endif
4671ea0443cSdan     if( flags & LOCATE_NOERR ) return 0;
4681ea0443cSdan     pParse->checkSchema = 1;
4697424aeffSdrh   }else if( IsVirtual(p) && (pParse->prepFlags & SQLITE_PREPARE_NO_VTAB)!=0 ){
4701ea0443cSdan     p = 0;
4711ea0443cSdan   }
4721ea0443cSdan 
4731ea0443cSdan   if( p==0 ){
4741ea0443cSdan     const char *zMsg = flags & LOCATE_VIEW ? "no such view" : "no such table";
4758a41449eSdanielk1977     if( zDbase ){
476ca424114Sdrh       sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName);
477a69d9168Sdrh     }else{
478ca424114Sdrh       sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName);
479a69d9168Sdrh     }
4801bb89e9cSdrh   }else{
4811bb89e9cSdrh     assert( HasRowid(p) || p->iPKey<0 );
4824d249e61Sdrh   }
483fab1d401Sdan 
484a69d9168Sdrh   return p;
485a69d9168Sdrh }
486a69d9168Sdrh 
487a69d9168Sdrh /*
48841fb5cd1Sdan ** Locate the table identified by *p.
48941fb5cd1Sdan **
49041fb5cd1Sdan ** This is a wrapper around sqlite3LocateTable(). The difference between
49141fb5cd1Sdan ** sqlite3LocateTable() and this function is that this function restricts
49241fb5cd1Sdan ** the search to schema (p->pSchema) if it is not NULL. p->pSchema may be
49341fb5cd1Sdan ** non-NULL if it is part of a view or trigger program definition. See
49441fb5cd1Sdan ** sqlite3FixSrcList() for details.
49541fb5cd1Sdan */
sqlite3LocateTableItem(Parse * pParse,u32 flags,SrcItem * p)49641fb5cd1Sdan Table *sqlite3LocateTableItem(
49741fb5cd1Sdan   Parse *pParse,
4984d249e61Sdrh   u32 flags,
4997601294aSdrh   SrcItem *p
50041fb5cd1Sdan ){
50141fb5cd1Sdan   const char *zDb;
502cd1499f4Sdrh   assert( p->pSchema==0 || p->zDatabase==0 );
50341fb5cd1Sdan   if( p->pSchema ){
50441fb5cd1Sdan     int iDb = sqlite3SchemaToIndex(pParse->db, p->pSchema);
50569c33826Sdrh     zDb = pParse->db->aDb[iDb].zDbSName;
50641fb5cd1Sdan   }else{
50741fb5cd1Sdan     zDb = p->zDatabase;
50841fb5cd1Sdan   }
5094d249e61Sdrh   return sqlite3LocateTable(pParse, flags, p->zName, zDb);
51041fb5cd1Sdan }
51141fb5cd1Sdan 
51241fb5cd1Sdan /*
513a4a871c2Sdrh ** Return the preferred table name for system tables.  Translate legacy
514a4a871c2Sdrh ** names into the new preferred names, as appropriate.
515a4a871c2Sdrh */
sqlite3PreferredTableName(const char * zName)516a4a871c2Sdrh const char *sqlite3PreferredTableName(const char *zName){
517a4a871c2Sdrh   if( sqlite3StrNICmp(zName, "sqlite_", 7)==0 ){
518a4a871c2Sdrh     if( sqlite3StrICmp(zName+7, &LEGACY_SCHEMA_TABLE[7])==0 ){
519a4a871c2Sdrh       return PREFERRED_SCHEMA_TABLE;
520a4a871c2Sdrh     }
521a4a871c2Sdrh     if( sqlite3StrICmp(zName+7, &LEGACY_TEMP_SCHEMA_TABLE[7])==0 ){
522a4a871c2Sdrh       return PREFERRED_TEMP_SCHEMA_TABLE;
523a4a871c2Sdrh     }
524a4a871c2Sdrh   }
525a4a871c2Sdrh   return zName;
526a4a871c2Sdrh }
527a4a871c2Sdrh 
528a4a871c2Sdrh /*
529a69d9168Sdrh ** Locate the in-memory structure that describes
530a69d9168Sdrh ** a particular index given the name of that index
531a69d9168Sdrh ** and the name of the database that contains the index.
532f57b3399Sdrh ** Return NULL if not found.
533f26e09c8Sdrh **
534f26e09c8Sdrh ** If zDatabase is 0, all databases are searched for the
535f26e09c8Sdrh ** table and the first matching index is returned.  (No checking
536f26e09c8Sdrh ** for duplicate index names is done.)  The search order is
537f26e09c8Sdrh ** TEMP first, then MAIN, then any auxiliary databases added
538f26e09c8Sdrh ** using the ATTACH command.
53975897234Sdrh */
sqlite3FindIndex(sqlite3 * db,const char * zName,const char * zDb)5409bb575fdSdrh Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
541d24cc427Sdrh   Index *p = 0;
542d24cc427Sdrh   int i;
5432120608eSdrh   /* All mutexes are required for schema access.  Make sure we hold them. */
5442120608eSdrh   assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
54553c0f748Sdanielk1977   for(i=OMIT_TEMPDB; i<db->nDb; i++){
546812d7a21Sdrh     int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
547e501b89aSdanielk1977     Schema *pSchema = db->aDb[j].pSchema;
5480449171eSdrh     assert( pSchema );
549465c2b89Sdan     if( zDb && sqlite3DbIsNamed(db, j, zDb)==0 ) continue;
5502120608eSdrh     assert( sqlite3SchemaMutexHeld(db, j, 0) );
551acbcb7e0Sdrh     p = sqlite3HashFind(&pSchema->idxHash, zName);
552d24cc427Sdrh     if( p ) break;
553d24cc427Sdrh   }
55474e24cd0Sdrh   return p;
55575897234Sdrh }
55675897234Sdrh 
55775897234Sdrh /*
558956bc92cSdrh ** Reclaim the memory used by an index
559956bc92cSdrh */
sqlite3FreeIndex(sqlite3 * db,Index * p)560cf8f2895Sdan void sqlite3FreeIndex(sqlite3 *db, Index *p){
56192aa5eacSdrh #ifndef SQLITE_OMIT_ANALYZE
562d46def77Sdan   sqlite3DeleteIndexSamples(db, p);
56392aa5eacSdrh #endif
5641fe0537eSdrh   sqlite3ExprDelete(db, p->pPartIdxWhere);
5651f9ca2c8Sdrh   sqlite3ExprListDelete(db, p->aColExpr);
566633e6d57Sdrh   sqlite3DbFree(db, p->zColAff);
5675905f86bSmistachkin   if( p->isResized ) sqlite3DbFree(db, (void *)p->azColl);
568175b8f06Sdrh #ifdef SQLITE_ENABLE_STAT4
56975b170b1Sdrh   sqlite3_free(p->aiRowEst);
57075b170b1Sdrh #endif
571633e6d57Sdrh   sqlite3DbFree(db, p);
572956bc92cSdrh }
573956bc92cSdrh 
574956bc92cSdrh /*
575c96d8530Sdrh ** For the index called zIdxName which is found in the database iDb,
576c96d8530Sdrh ** unlike that index from its Table then remove the index from
577c96d8530Sdrh ** the index hash table and free all memory structures associated
578c96d8530Sdrh ** with the index.
5795e00f6c7Sdrh */
sqlite3UnlinkAndDeleteIndex(sqlite3 * db,int iDb,const char * zIdxName)5809bb575fdSdrh void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
581956bc92cSdrh   Index *pIndex;
5822120608eSdrh   Hash *pHash;
583956bc92cSdrh 
5842120608eSdrh   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
5852120608eSdrh   pHash = &db->aDb[iDb].pSchema->idxHash;
586acbcb7e0Sdrh   pIndex = sqlite3HashInsert(pHash, zIdxName, 0);
58722645842Sdrh   if( ALWAYS(pIndex) ){
5885e00f6c7Sdrh     if( pIndex->pTable->pIndex==pIndex ){
5895e00f6c7Sdrh       pIndex->pTable->pIndex = pIndex->pNext;
5905e00f6c7Sdrh     }else{
5915e00f6c7Sdrh       Index *p;
5920449171eSdrh       /* Justification of ALWAYS();  The index must be on the list of
5930449171eSdrh       ** indices. */
5940449171eSdrh       p = pIndex->pTable->pIndex;
5950449171eSdrh       while( ALWAYS(p) && p->pNext!=pIndex ){ p = p->pNext; }
5960449171eSdrh       if( ALWAYS(p && p->pNext==pIndex) ){
5975e00f6c7Sdrh         p->pNext = pIndex->pNext;
5985e00f6c7Sdrh       }
5995e00f6c7Sdrh     }
600cf8f2895Sdan     sqlite3FreeIndex(db, pIndex);
601956bc92cSdrh   }
6028257aa8dSdrh   db->mDbFlags |= DBFLAG_SchemaChange;
6035e00f6c7Sdrh }
6045e00f6c7Sdrh 
6055e00f6c7Sdrh /*
60681028a45Sdrh ** Look through the list of open database files in db->aDb[] and if
60781028a45Sdrh ** any have been closed, remove them from the list.  Reallocate the
60881028a45Sdrh ** db->aDb[] structure to a smaller size, if possible.
6091c2d8414Sdrh **
61081028a45Sdrh ** Entry 0 (the "main" database) and entry 1 (the "temp" database)
61181028a45Sdrh ** are never candidates for being collapsed.
61274e24cd0Sdrh */
sqlite3CollapseDatabaseArray(sqlite3 * db)61381028a45Sdrh void sqlite3CollapseDatabaseArray(sqlite3 *db){
6141c2d8414Sdrh   int i, j;
6151c2d8414Sdrh   for(i=j=2; i<db->nDb; i++){
6164d189ca4Sdrh     struct Db *pDb = &db->aDb[i];
6174d189ca4Sdrh     if( pDb->pBt==0 ){
61869c33826Sdrh       sqlite3DbFree(db, pDb->zDbSName);
61969c33826Sdrh       pDb->zDbSName = 0;
6201c2d8414Sdrh       continue;
6211c2d8414Sdrh     }
6221c2d8414Sdrh     if( j<i ){
6238bf8dc92Sdrh       db->aDb[j] = db->aDb[i];
6241c2d8414Sdrh     }
6258bf8dc92Sdrh     j++;
6261c2d8414Sdrh   }
6271c2d8414Sdrh   db->nDb = j;
6281c2d8414Sdrh   if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
6291c2d8414Sdrh     memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
630633e6d57Sdrh     sqlite3DbFree(db, db->aDb);
6311c2d8414Sdrh     db->aDb = db->aDbStatic;
6321c2d8414Sdrh   }
633e0bc4048Sdrh }
634e0bc4048Sdrh 
635e0bc4048Sdrh /*
63681028a45Sdrh ** Reset the schema for the database at index iDb.  Also reset the
637dc6b41edSdrh ** TEMP schema.  The reset is deferred if db->nSchemaLock is not zero.
638dc6b41edSdrh ** Deferred resets may be run by calling with iDb<0.
63981028a45Sdrh */
sqlite3ResetOneSchema(sqlite3 * db,int iDb)64081028a45Sdrh void sqlite3ResetOneSchema(sqlite3 *db, int iDb){
641dc6b41edSdrh   int i;
64281028a45Sdrh   assert( iDb<db->nDb );
64381028a45Sdrh 
644dc6b41edSdrh   if( iDb>=0 ){
64581028a45Sdrh     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
646dc6b41edSdrh     DbSetProperty(db, iDb, DB_ResetWanted);
647dc6b41edSdrh     DbSetProperty(db, 1, DB_ResetWanted);
648b2c8559fSdrh     db->mDbFlags &= ~DBFLAG_SchemaKnownOk;
64981028a45Sdrh   }
650dc6b41edSdrh 
651dc6b41edSdrh   if( db->nSchemaLock==0 ){
652dc6b41edSdrh     for(i=0; i<db->nDb; i++){
653dc6b41edSdrh       if( DbHasProperty(db, i, DB_ResetWanted) ){
654dc6b41edSdrh         sqlite3SchemaClear(db->aDb[i].pSchema);
655dc6b41edSdrh       }
656dc6b41edSdrh     }
657dc6b41edSdrh   }
65881028a45Sdrh }
65981028a45Sdrh 
66081028a45Sdrh /*
66181028a45Sdrh ** Erase all schema information from all attached databases (including
66281028a45Sdrh ** "main" and "temp") for a single database connection.
66381028a45Sdrh */
sqlite3ResetAllSchemasOfConnection(sqlite3 * db)66481028a45Sdrh void sqlite3ResetAllSchemasOfConnection(sqlite3 *db){
66581028a45Sdrh   int i;
66681028a45Sdrh   sqlite3BtreeEnterAll(db);
66781028a45Sdrh   for(i=0; i<db->nDb; i++){
66881028a45Sdrh     Db *pDb = &db->aDb[i];
66981028a45Sdrh     if( pDb->pSchema ){
67063e50b9eSdan       if( db->nSchemaLock==0 ){
67181028a45Sdrh         sqlite3SchemaClear(pDb->pSchema);
67263e50b9eSdan       }else{
67363e50b9eSdan         DbSetProperty(db, i, DB_ResetWanted);
67463e50b9eSdan       }
67581028a45Sdrh     }
67681028a45Sdrh   }
677b2c8559fSdrh   db->mDbFlags &= ~(DBFLAG_SchemaChange|DBFLAG_SchemaKnownOk);
67881028a45Sdrh   sqlite3VtabUnlockList(db);
67981028a45Sdrh   sqlite3BtreeLeaveAll(db);
68063e50b9eSdan   if( db->nSchemaLock==0 ){
68181028a45Sdrh     sqlite3CollapseDatabaseArray(db);
68281028a45Sdrh   }
68363e50b9eSdan }
68481028a45Sdrh 
68581028a45Sdrh /*
686e0bc4048Sdrh ** This routine is called when a commit occurs.
687e0bc4048Sdrh */
sqlite3CommitInternalChanges(sqlite3 * db)6889bb575fdSdrh void sqlite3CommitInternalChanges(sqlite3 *db){
6898257aa8dSdrh   db->mDbFlags &= ~DBFLAG_SchemaChange;
69074e24cd0Sdrh }
69174e24cd0Sdrh 
69274e24cd0Sdrh /*
69379cf2b71Sdrh ** Set the expression associated with a column.  This is usually
69479cf2b71Sdrh ** the DEFAULT value, but might also be the expression that computes
69579cf2b71Sdrh ** the value for a generated column.
69679cf2b71Sdrh */
sqlite3ColumnSetExpr(Parse * pParse,Table * pTab,Column * pCol,Expr * pExpr)69779cf2b71Sdrh void sqlite3ColumnSetExpr(
69879cf2b71Sdrh   Parse *pParse,    /* Parsing context */
69979cf2b71Sdrh   Table *pTab,      /* The table containing the column */
70079cf2b71Sdrh   Column *pCol,     /* The column to receive the new DEFAULT expression */
70179cf2b71Sdrh   Expr *pExpr       /* The new default expression */
70279cf2b71Sdrh ){
703f38524d2Sdrh   ExprList *pList;
70478b2fa86Sdrh   assert( IsOrdinaryTable(pTab) );
705f38524d2Sdrh   pList = pTab->u.tab.pDfltList;
70679cf2b71Sdrh   if( pCol->iDflt==0
707324f91a5Sdrh    || NEVER(pList==0)
708324f91a5Sdrh    || NEVER(pList->nExpr<pCol->iDflt)
70979cf2b71Sdrh   ){
71079cf2b71Sdrh     pCol->iDflt = pList==0 ? 1 : pList->nExpr+1;
711f38524d2Sdrh     pTab->u.tab.pDfltList = sqlite3ExprListAppend(pParse, pList, pExpr);
71279cf2b71Sdrh   }else{
71379cf2b71Sdrh     sqlite3ExprDelete(pParse->db, pList->a[pCol->iDflt-1].pExpr);
71479cf2b71Sdrh     pList->a[pCol->iDflt-1].pExpr = pExpr;
71579cf2b71Sdrh   }
71679cf2b71Sdrh }
71779cf2b71Sdrh 
71879cf2b71Sdrh /*
71979cf2b71Sdrh ** Return the expression associated with a column.  The expression might be
72079cf2b71Sdrh ** the DEFAULT clause or the AS clause of a generated column.
72179cf2b71Sdrh ** Return NULL if the column has no associated expression.
72279cf2b71Sdrh */
sqlite3ColumnExpr(Table * pTab,Column * pCol)72379cf2b71Sdrh Expr *sqlite3ColumnExpr(Table *pTab, Column *pCol){
72479cf2b71Sdrh   if( pCol->iDflt==0 ) return 0;
72578b2fa86Sdrh   if( NEVER(!IsOrdinaryTable(pTab)) ) return 0;
726324f91a5Sdrh   if( NEVER(pTab->u.tab.pDfltList==0) ) return 0;
727324f91a5Sdrh   if( NEVER(pTab->u.tab.pDfltList->nExpr<pCol->iDflt) ) return 0;
728f38524d2Sdrh   return pTab->u.tab.pDfltList->a[pCol->iDflt-1].pExpr;
72979cf2b71Sdrh }
73079cf2b71Sdrh 
73179cf2b71Sdrh /*
73265b40093Sdrh ** Set the collating sequence name for a column.
73365b40093Sdrh */
sqlite3ColumnSetColl(sqlite3 * db,Column * pCol,const char * zColl)73465b40093Sdrh void sqlite3ColumnSetColl(
73565b40093Sdrh   sqlite3 *db,
73665b40093Sdrh   Column *pCol,
73765b40093Sdrh   const char *zColl
73865b40093Sdrh ){
739913306a5Sdrh   i64 nColl;
740913306a5Sdrh   i64 n;
74165b40093Sdrh   char *zNew;
74265b40093Sdrh   assert( zColl!=0 );
74365b40093Sdrh   n = sqlite3Strlen30(pCol->zCnName) + 1;
74465b40093Sdrh   if( pCol->colFlags & COLFLAG_HASTYPE ){
74565b40093Sdrh     n += sqlite3Strlen30(pCol->zCnName+n) + 1;
74665b40093Sdrh   }
74765b40093Sdrh   nColl = sqlite3Strlen30(zColl) + 1;
74865b40093Sdrh   zNew = sqlite3DbRealloc(db, pCol->zCnName, nColl+n);
74965b40093Sdrh   if( zNew ){
75065b40093Sdrh     pCol->zCnName = zNew;
75165b40093Sdrh     memcpy(pCol->zCnName + n, zColl, nColl);
75265b40093Sdrh     pCol->colFlags |= COLFLAG_HASCOLL;
75365b40093Sdrh   }
75465b40093Sdrh }
75565b40093Sdrh 
75665b40093Sdrh /*
75765b40093Sdrh ** Return the collating squence name for a column
75865b40093Sdrh */
sqlite3ColumnColl(Column * pCol)75965b40093Sdrh const char *sqlite3ColumnColl(Column *pCol){
76065b40093Sdrh   const char *z;
76165b40093Sdrh   if( (pCol->colFlags & COLFLAG_HASCOLL)==0 ) return 0;
76265b40093Sdrh   z = pCol->zCnName;
76365b40093Sdrh   while( *z ){ z++; }
76465b40093Sdrh   if( pCol->colFlags & COLFLAG_HASTYPE ){
76565b40093Sdrh     do{ z++; }while( *z );
76665b40093Sdrh   }
76765b40093Sdrh   return z+1;
76865b40093Sdrh }
76965b40093Sdrh 
77065b40093Sdrh /*
771d46def77Sdan ** Delete memory allocated for the column names of a table or view (the
772d46def77Sdan ** Table.aCol[] array).
773956bc92cSdrh */
sqlite3DeleteColumnNames(sqlite3 * db,Table * pTable)77451be3873Sdrh void sqlite3DeleteColumnNames(sqlite3 *db, Table *pTable){
775956bc92cSdrh   int i;
776956bc92cSdrh   Column *pCol;
777956bc92cSdrh   assert( pTable!=0 );
77841ce47c4Sdrh   assert( db!=0 );
779dd5b2fa5Sdrh   if( (pCol = pTable->aCol)!=0 ){
780dd5b2fa5Sdrh     for(i=0; i<pTable->nCol; i++, pCol++){
781cf9d36d1Sdrh       assert( pCol->zCnName==0 || pCol->hName==sqlite3StrIHash(pCol->zCnName) );
782cf9d36d1Sdrh       sqlite3DbFree(db, pCol->zCnName);
783956bc92cSdrh     }
78441ce47c4Sdrh     sqlite3DbNNFreeNN(db, pTable->aCol);
78578b2fa86Sdrh     if( IsOrdinaryTable(pTable) ){
786f38524d2Sdrh       sqlite3ExprListDelete(db, pTable->u.tab.pDfltList);
787f38524d2Sdrh     }
78841ce47c4Sdrh     if( db->pnBytesFreed==0 ){
78979cf2b71Sdrh       pTable->aCol = 0;
79079cf2b71Sdrh       pTable->nCol = 0;
79178b2fa86Sdrh       if( IsOrdinaryTable(pTable) ){
792f38524d2Sdrh         pTable->u.tab.pDfltList = 0;
793f38524d2Sdrh       }
79479cf2b71Sdrh     }
795dd5b2fa5Sdrh   }
796956bc92cSdrh }
797956bc92cSdrh 
798956bc92cSdrh /*
79975897234Sdrh ** Remove the memory data structures associated with the given
800967e8b73Sdrh ** Table.  No changes are made to disk by this routine.
80175897234Sdrh **
80275897234Sdrh ** This routine just deletes the data structure.  It does not unlink
803e61922a6Sdrh ** the table data structure from the hash table.  But it does destroy
804c2eef3b3Sdrh ** memory structures of the indices and foreign keys associated with
805c2eef3b3Sdrh ** the table.
80629ddd3acSdrh **
80729ddd3acSdrh ** The db parameter is optional.  It is needed if the Table object
80829ddd3acSdrh ** contains lookaside memory.  (Table objects in the schema do not use
80929ddd3acSdrh ** lookaside memory, but some ephemeral Table objects do.)  Or the
81029ddd3acSdrh ** db parameter can be used with db->pnBytesFreed to measure the memory
81129ddd3acSdrh ** used by the Table object.
81275897234Sdrh */
deleteTable(sqlite3 * db,Table * pTable)813e8da01c1Sdrh static void SQLITE_NOINLINE deleteTable(sqlite3 *db, Table *pTable){
81475897234Sdrh   Index *pIndex, *pNext;
815c2eef3b3Sdrh 
81652fb8e19Sdrh #ifdef SQLITE_DEBUG
81729ddd3acSdrh   /* Record the number of outstanding lookaside allocations in schema Tables
81829ddd3acSdrh   ** prior to doing any free() operations. Since schema Tables do not use
819bedf84c1Sdan   ** lookaside, this number should not change.
820bedf84c1Sdan   **
821bedf84c1Sdan   ** If malloc has already failed, it may be that it failed while allocating
822bedf84c1Sdan   ** a Table object that was going to be marked ephemeral. So do not check
823bedf84c1Sdan   ** that no lookaside memory is used in this case either. */
82452fb8e19Sdrh   int nLookaside = 0;
82541ce47c4Sdrh   assert( db!=0 );
82641ce47c4Sdrh   if( !db->mallocFailed && (pTable->tabFlags & TF_Ephemeral)==0 ){
82752fb8e19Sdrh     nLookaside = sqlite3LookasideUsed(db, 0);
82852fb8e19Sdrh   }
82952fb8e19Sdrh #endif
83029ddd3acSdrh 
831d46def77Sdan   /* Delete all indices associated with this table. */
832c2eef3b3Sdrh   for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
833c2eef3b3Sdrh     pNext = pIndex->pNext;
83462340f84Sdrh     assert( pIndex->pSchema==pTable->pSchema
83562340f84Sdrh          || (IsVirtual(pTable) && pIndex->idxType!=SQLITE_IDXTYPE_APPDEF) );
83641ce47c4Sdrh     if( db->pnBytesFreed==0 && !IsVirtual(pTable) ){
837d46def77Sdan       char *zName = pIndex->zName;
838d46def77Sdan       TESTONLY ( Index *pOld = ) sqlite3HashInsert(
839acbcb7e0Sdrh          &pIndex->pSchema->idxHash, zName, 0
840d46def77Sdan       );
8412120608eSdrh       assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
842d46def77Sdan       assert( pOld==pIndex || pOld==0 );
843d46def77Sdan     }
844cf8f2895Sdan     sqlite3FreeIndex(db, pIndex);
845c2eef3b3Sdrh   }
846c2eef3b3Sdrh 
847f38524d2Sdrh   if( IsOrdinaryTable(pTable) ){
8481feeaed2Sdan     sqlite3FkDelete(db, pTable);
849f38524d2Sdrh   }
850f38524d2Sdrh #ifndef SQLITE_OMIT_VIRTUAL_TABLE
851f38524d2Sdrh   else if( IsVirtual(pTable) ){
852f38524d2Sdrh     sqlite3VtabClear(db, pTable);
853f38524d2Sdrh   }
854f38524d2Sdrh #endif
855f38524d2Sdrh   else{
856f38524d2Sdrh     assert( IsView(pTable) );
857f38524d2Sdrh     sqlite3SelectDelete(db, pTable->u.view.pSelect);
858f38524d2Sdrh   }
859c2eef3b3Sdrh 
860c2eef3b3Sdrh   /* Delete the Table structure itself.
861c2eef3b3Sdrh   */
86251be3873Sdrh   sqlite3DeleteColumnNames(db, pTable);
863633e6d57Sdrh   sqlite3DbFree(db, pTable->zName);
864633e6d57Sdrh   sqlite3DbFree(db, pTable->zColAff);
8652938f924Sdrh   sqlite3ExprListDelete(db, pTable->pCheck);
866633e6d57Sdrh   sqlite3DbFree(db, pTable);
86729ddd3acSdrh 
86829ddd3acSdrh   /* Verify that no lookaside memory was used by schema tables */
86952fb8e19Sdrh   assert( nLookaside==0 || nLookaside==sqlite3LookasideUsed(db,0) );
87075897234Sdrh }
sqlite3DeleteTable(sqlite3 * db,Table * pTable)871e8da01c1Sdrh void sqlite3DeleteTable(sqlite3 *db, Table *pTable){
872e8da01c1Sdrh   /* Do not delete the table until the reference count reaches zero. */
87341ce47c4Sdrh   assert( db!=0 );
874e8da01c1Sdrh   if( !pTable ) return;
87541ce47c4Sdrh   if( db->pnBytesFreed==0 && (--pTable->nTabRef)>0 ) return;
876e8da01c1Sdrh   deleteTable(db, pTable);
877e8da01c1Sdrh }
878e8da01c1Sdrh 
87975897234Sdrh 
88075897234Sdrh /*
8815edc3124Sdrh ** Unlink the given table from the hash tables and the delete the
882c2eef3b3Sdrh ** table structure with all its indices and foreign keys.
8835edc3124Sdrh */
sqlite3UnlinkAndDeleteTable(sqlite3 * db,int iDb,const char * zTabName)8849bb575fdSdrh void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
885956bc92cSdrh   Table *p;
886956bc92cSdrh   Db *pDb;
887956bc92cSdrh 
888d229ca94Sdrh   assert( db!=0 );
889956bc92cSdrh   assert( iDb>=0 && iDb<db->nDb );
890972a2311Sdrh   assert( zTabName );
8912120608eSdrh   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
892972a2311Sdrh   testcase( zTabName[0]==0 );  /* Zero-length table names are allowed */
893956bc92cSdrh   pDb = &db->aDb[iDb];
894acbcb7e0Sdrh   p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName, 0);
8951feeaed2Sdan   sqlite3DeleteTable(db, p);
8968257aa8dSdrh   db->mDbFlags |= DBFLAG_SchemaChange;
897956bc92cSdrh }
89874e24cd0Sdrh 
89974e24cd0Sdrh /*
900a99db3b6Sdrh ** Given a token, return a string that consists of the text of that
90124fb627aSdrh ** token.  Space to hold the returned string
902a99db3b6Sdrh ** is obtained from sqliteMalloc() and must be freed by the calling
903a99db3b6Sdrh ** function.
90475897234Sdrh **
90524fb627aSdrh ** Any quotation marks (ex:  "name", 'name', [name], or `name`) that
90624fb627aSdrh ** surround the body of the token are removed.
90724fb627aSdrh **
908c96d8530Sdrh ** Tokens are often just pointers into the original SQL text and so
909a99db3b6Sdrh ** are not \000 terminated and are not persistent.  The returned string
910a99db3b6Sdrh ** is \000 terminated and is persistent.
91175897234Sdrh */
sqlite3NameFromToken(sqlite3 * db,const Token * pName)912b6dad520Sdrh char *sqlite3NameFromToken(sqlite3 *db, const Token *pName){
913a99db3b6Sdrh   char *zName;
914a99db3b6Sdrh   if( pName ){
915b6dad520Sdrh     zName = sqlite3DbStrNDup(db, (const char*)pName->z, pName->n);
916b7916a78Sdrh     sqlite3Dequote(zName);
917a99db3b6Sdrh   }else{
918a99db3b6Sdrh     zName = 0;
919a99db3b6Sdrh   }
92075897234Sdrh   return zName;
92175897234Sdrh }
92275897234Sdrh 
92375897234Sdrh /*
9241e32bed3Sdrh ** Open the sqlite_schema table stored in database number iDb for
925cbb18d22Sdanielk1977 ** writing. The table is opened using cursor 0.
926e0bc4048Sdrh */
sqlite3OpenSchemaTable(Parse * p,int iDb)927346a70caSdrh void sqlite3OpenSchemaTable(Parse *p, int iDb){
928c00da105Sdanielk1977   Vdbe *v = sqlite3GetVdbe(p);
929a4a871c2Sdrh   sqlite3TableLock(p, iDb, SCHEMA_ROOT, 1, LEGACY_SCHEMA_TABLE);
930346a70caSdrh   sqlite3VdbeAddOp4Int(v, OP_OpenWrite, 0, SCHEMA_ROOT, iDb, 5);
9316ab3a2ecSdanielk1977   if( p->nTab==0 ){
9326ab3a2ecSdanielk1977     p->nTab = 1;
9336ab3a2ecSdanielk1977   }
934e0bc4048Sdrh }
935e0bc4048Sdrh 
936e0bc4048Sdrh /*
9370410302eSdanielk1977 ** Parameter zName points to a nul-terminated buffer containing the name
9380410302eSdanielk1977 ** of a database ("main", "temp" or the name of an attached db). This
9390410302eSdanielk1977 ** function returns the index of the named database in db->aDb[], or
9400410302eSdanielk1977 ** -1 if the named db cannot be found.
941cbb18d22Sdanielk1977 */
sqlite3FindDbName(sqlite3 * db,const char * zName)9420410302eSdanielk1977 int sqlite3FindDbName(sqlite3 *db, const char *zName){
943576ec6b3Sdanielk1977   int i = -1;         /* Database number */
94473c42a13Sdrh   if( zName ){
9450410302eSdanielk1977     Db *pDb;
946576ec6b3Sdanielk1977     for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
9472951809eSdrh       if( 0==sqlite3_stricmp(pDb->zDbSName, zName) ) break;
9482951809eSdrh       /* "main" is always an acceptable alias for the primary database
9492951809eSdrh       ** even if it has been renamed using SQLITE_DBCONFIG_MAINDBNAME. */
9502951809eSdrh       if( i==0 && 0==sqlite3_stricmp("main", zName) ) break;
951576ec6b3Sdanielk1977     }
952576ec6b3Sdanielk1977   }
953cbb18d22Sdanielk1977   return i;
954cbb18d22Sdanielk1977 }
955cbb18d22Sdanielk1977 
9560410302eSdanielk1977 /*
9570410302eSdanielk1977 ** The token *pName contains the name of a database (either "main" or
9580410302eSdanielk1977 ** "temp" or the name of an attached db). This routine returns the
9590410302eSdanielk1977 ** index of the named database in db->aDb[], or -1 if the named db
9600410302eSdanielk1977 ** does not exist.
9610410302eSdanielk1977 */
sqlite3FindDb(sqlite3 * db,Token * pName)9620410302eSdanielk1977 int sqlite3FindDb(sqlite3 *db, Token *pName){
9630410302eSdanielk1977   int i;                               /* Database number */
9640410302eSdanielk1977   char *zName;                         /* Name we are searching for */
9650410302eSdanielk1977   zName = sqlite3NameFromToken(db, pName);
9660410302eSdanielk1977   i = sqlite3FindDbName(db, zName);
9670410302eSdanielk1977   sqlite3DbFree(db, zName);
9680410302eSdanielk1977   return i;
9690410302eSdanielk1977 }
9700410302eSdanielk1977 
9710e3d7476Sdrh /* The table or view or trigger name is passed to this routine via tokens
9720e3d7476Sdrh ** pName1 and pName2. If the table name was fully qualified, for example:
9730e3d7476Sdrh **
9740e3d7476Sdrh ** CREATE TABLE xxx.yyy (...);
9750e3d7476Sdrh **
9760e3d7476Sdrh ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
9770e3d7476Sdrh ** the table name is not fully qualified, i.e.:
9780e3d7476Sdrh **
9790e3d7476Sdrh ** CREATE TABLE yyy(...);
9800e3d7476Sdrh **
9810e3d7476Sdrh ** Then pName1 is set to "yyy" and pName2 is "".
9820e3d7476Sdrh **
9830e3d7476Sdrh ** This routine sets the *ppUnqual pointer to point at the token (pName1 or
9840e3d7476Sdrh ** pName2) that stores the unqualified table name.  The index of the
9850e3d7476Sdrh ** database "xxx" is returned.
9860e3d7476Sdrh */
sqlite3TwoPartName(Parse * pParse,Token * pName1,Token * pName2,Token ** pUnqual)987ef2cb63eSdanielk1977 int sqlite3TwoPartName(
9880e3d7476Sdrh   Parse *pParse,      /* Parsing and code generating context */
98990f5ecb3Sdrh   Token *pName1,      /* The "xxx" in the name "xxx.yyy" or "xxx" */
9900e3d7476Sdrh   Token *pName2,      /* The "yyy" in the name "xxx.yyy" */
9910e3d7476Sdrh   Token **pUnqual     /* Write the unqualified object name here */
992cbb18d22Sdanielk1977 ){
9930e3d7476Sdrh   int iDb;                    /* Database holding the object */
994cbb18d22Sdanielk1977   sqlite3 *db = pParse->db;
995cbb18d22Sdanielk1977 
996055f298aSdrh   assert( pName2!=0 );
997055f298aSdrh   if( pName2->n>0 ){
998dcc50b74Sshane     if( db->init.busy ) {
999dcc50b74Sshane       sqlite3ErrorMsg(pParse, "corrupt database");
1000dcc50b74Sshane       return -1;
1001dcc50b74Sshane     }
1002cbb18d22Sdanielk1977     *pUnqual = pName2;
1003ff2d5ea4Sdrh     iDb = sqlite3FindDb(db, pName1);
1004cbb18d22Sdanielk1977     if( iDb<0 ){
1005cbb18d22Sdanielk1977       sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
1006cbb18d22Sdanielk1977       return -1;
1007cbb18d22Sdanielk1977     }
1008cbb18d22Sdanielk1977   }else{
1009d36bcec9Sdrh     assert( db->init.iDb==0 || db->init.busy || IN_SPECIAL_PARSE
10108257aa8dSdrh              || (db->mDbFlags & DBFLAG_Vacuum)!=0);
1011cbb18d22Sdanielk1977     iDb = db->init.iDb;
1012cbb18d22Sdanielk1977     *pUnqual = pName1;
1013cbb18d22Sdanielk1977   }
1014cbb18d22Sdanielk1977   return iDb;
1015cbb18d22Sdanielk1977 }
1016cbb18d22Sdanielk1977 
1017cbb18d22Sdanielk1977 /*
10180f1c2eb5Sdrh ** True if PRAGMA writable_schema is ON
10190f1c2eb5Sdrh */
sqlite3WritableSchema(sqlite3 * db)10200f1c2eb5Sdrh int sqlite3WritableSchema(sqlite3 *db){
10210f1c2eb5Sdrh   testcase( (db->flags&(SQLITE_WriteSchema|SQLITE_Defensive))==0 );
10220f1c2eb5Sdrh   testcase( (db->flags&(SQLITE_WriteSchema|SQLITE_Defensive))==
10230f1c2eb5Sdrh                SQLITE_WriteSchema );
10240f1c2eb5Sdrh   testcase( (db->flags&(SQLITE_WriteSchema|SQLITE_Defensive))==
10250f1c2eb5Sdrh                SQLITE_Defensive );
10260f1c2eb5Sdrh   testcase( (db->flags&(SQLITE_WriteSchema|SQLITE_Defensive))==
10270f1c2eb5Sdrh                (SQLITE_WriteSchema|SQLITE_Defensive) );
10280f1c2eb5Sdrh   return (db->flags&(SQLITE_WriteSchema|SQLITE_Defensive))==SQLITE_WriteSchema;
10290f1c2eb5Sdrh }
10300f1c2eb5Sdrh 
10310f1c2eb5Sdrh /*
1032d8123366Sdanielk1977 ** This routine is used to check if the UTF-8 string zName is a legal
1033d8123366Sdanielk1977 ** unqualified name for a new schema object (table, index, view or
1034d8123366Sdanielk1977 ** trigger). All names are legal except those that begin with the string
1035d8123366Sdanielk1977 ** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
1036d8123366Sdanielk1977 ** is reserved for internal use.
1037c5a93d4cSdrh **
10381e32bed3Sdrh ** When parsing the sqlite_schema table, this routine also checks to
1039c5a93d4cSdrh ** make sure the "type", "name", and "tbl_name" columns are consistent
1040c5a93d4cSdrh ** with the SQL.
1041d8123366Sdanielk1977 */
sqlite3CheckObjectName(Parse * pParse,const char * zName,const char * zType,const char * zTblName)1042c5a93d4cSdrh int sqlite3CheckObjectName(
1043c5a93d4cSdrh   Parse *pParse,            /* Parsing context */
1044c5a93d4cSdrh   const char *zName,        /* Name of the object to check */
1045c5a93d4cSdrh   const char *zType,        /* Type of this object */
1046c5a93d4cSdrh   const char *zTblName      /* Parent table name for triggers and indexes */
1047c5a93d4cSdrh ){
1048c5a93d4cSdrh   sqlite3 *db = pParse->db;
1049ca439a49Sdrh   if( sqlite3WritableSchema(db)
1050ca439a49Sdrh    || db->init.imposterTable
1051ca439a49Sdrh    || !sqlite3Config.bExtraSchemaChecks
1052ca439a49Sdrh   ){
1053c5a93d4cSdrh     /* Skip these error checks for writable_schema=ON */
1054c5a93d4cSdrh     return SQLITE_OK;
1055c5a93d4cSdrh   }
1056c5a93d4cSdrh   if( db->init.busy ){
1057c5a93d4cSdrh     if( sqlite3_stricmp(zType, db->init.azInit[0])
1058c5a93d4cSdrh      || sqlite3_stricmp(zName, db->init.azInit[1])
1059c5a93d4cSdrh      || sqlite3_stricmp(zTblName, db->init.azInit[2])
1060c5a93d4cSdrh     ){
1061c5a93d4cSdrh       sqlite3ErrorMsg(pParse, ""); /* corruptSchema() will supply the error */
1062d8123366Sdanielk1977       return SQLITE_ERROR;
1063d8123366Sdanielk1977     }
1064c5a93d4cSdrh   }else{
1065527cbd4aSdrh     if( (pParse->nested==0 && 0==sqlite3StrNICmp(zName, "sqlite_", 7))
1066527cbd4aSdrh      || (sqlite3ReadOnlyShadowTables(db) && sqlite3ShadowTableName(db, zName))
1067c5a93d4cSdrh     ){
1068c5a93d4cSdrh       sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s",
1069c5a93d4cSdrh                       zName);
1070c5a93d4cSdrh       return SQLITE_ERROR;
1071c5a93d4cSdrh     }
1072527cbd4aSdrh 
1073c5a93d4cSdrh   }
1074d8123366Sdanielk1977   return SQLITE_OK;
1075d8123366Sdanielk1977 }
1076d8123366Sdanielk1977 
1077d8123366Sdanielk1977 /*
10784415628aSdrh ** Return the PRIMARY KEY index of a table
10794415628aSdrh */
sqlite3PrimaryKeyIndex(Table * pTab)10804415628aSdrh Index *sqlite3PrimaryKeyIndex(Table *pTab){
10814415628aSdrh   Index *p;
108248dd1d8eSdrh   for(p=pTab->pIndex; p && !IsPrimaryKeyIndex(p); p=p->pNext){}
10834415628aSdrh   return p;
10844415628aSdrh }
10854415628aSdrh 
10864415628aSdrh /*
1087b9bcf7caSdrh ** Convert an table column number into a index column number.  That is,
1088b9bcf7caSdrh ** for the column iCol in the table (as defined by the CREATE TABLE statement)
1089b9bcf7caSdrh ** find the (first) offset of that column in index pIdx.  Or return -1
1090b9bcf7caSdrh ** if column iCol is not used in index pIdx.
10914415628aSdrh */
sqlite3TableColumnToIndex(Index * pIdx,i16 iCol)1092b9bcf7caSdrh i16 sqlite3TableColumnToIndex(Index *pIdx, i16 iCol){
10934415628aSdrh   int i;
10944415628aSdrh   for(i=0; i<pIdx->nColumn; i++){
10954415628aSdrh     if( iCol==pIdx->aiColumn[i] ) return i;
10964415628aSdrh   }
10974415628aSdrh   return -1;
10984415628aSdrh }
10994415628aSdrh 
110081f7b372Sdrh #ifndef SQLITE_OMIT_GENERATED_COLUMNS
1101b9bcf7caSdrh /* Convert a storage column number into a table column number.
110281f7b372Sdrh **
11038e10d74bSdrh ** The storage column number (0,1,2,....) is the index of the value
11048e10d74bSdrh ** as it appears in the record on disk.  The true column number
11058e10d74bSdrh ** is the index (0,1,2,...) of the column in the CREATE TABLE statement.
11068e10d74bSdrh **
1107b9bcf7caSdrh ** The storage column number is less than the table column number if
1108b9bcf7caSdrh ** and only there are VIRTUAL columns to the left.
11098e10d74bSdrh **
11108e10d74bSdrh ** If SQLITE_OMIT_GENERATED_COLUMNS, this routine is a no-op macro.
11118e10d74bSdrh */
sqlite3StorageColumnToTable(Table * pTab,i16 iCol)1112b9bcf7caSdrh i16 sqlite3StorageColumnToTable(Table *pTab, i16 iCol){
11138e10d74bSdrh   if( pTab->tabFlags & TF_HasVirtual ){
11148e10d74bSdrh     int i;
11158e10d74bSdrh     for(i=0; i<=iCol; i++){
11168e10d74bSdrh       if( pTab->aCol[i].colFlags & COLFLAG_VIRTUAL ) iCol++;
11178e10d74bSdrh     }
11188e10d74bSdrh   }
11198e10d74bSdrh   return iCol;
11208e10d74bSdrh }
11218e10d74bSdrh #endif
11228e10d74bSdrh 
11238e10d74bSdrh #ifndef SQLITE_OMIT_GENERATED_COLUMNS
1124b9bcf7caSdrh /* Convert a table column number into a storage column number.
11258e10d74bSdrh **
11268e10d74bSdrh ** The storage column number (0,1,2,....) is the index of the value
1127dd6cc9b5Sdrh ** as it appears in the record on disk.  Or, if the input column is
1128dd6cc9b5Sdrh ** the N-th virtual column (zero-based) then the storage number is
1129dd6cc9b5Sdrh ** the number of non-virtual columns in the table plus N.
11308e10d74bSdrh **
1131dd6cc9b5Sdrh ** The true column number is the index (0,1,2,...) of the column in
1132dd6cc9b5Sdrh ** the CREATE TABLE statement.
11338e10d74bSdrh **
1134dd6cc9b5Sdrh ** If the input column is a VIRTUAL column, then it should not appear
1135dd6cc9b5Sdrh ** in storage.  But the value sometimes is cached in registers that
1136dd6cc9b5Sdrh ** follow the range of registers used to construct storage.  This
1137dd6cc9b5Sdrh ** avoids computing the same VIRTUAL column multiple times, and provides
1138dd6cc9b5Sdrh ** values for use by OP_Param opcodes in triggers.  Hence, if the
1139dd6cc9b5Sdrh ** input column is a VIRTUAL table, put it after all the other columns.
1140dd6cc9b5Sdrh **
1141dd6cc9b5Sdrh ** In the following, N means "normal column", S means STORED, and
1142dd6cc9b5Sdrh ** V means VIRTUAL.  Suppose the CREATE TABLE has columns like this:
1143dd6cc9b5Sdrh **
1144dd6cc9b5Sdrh **        CREATE TABLE ex(N,S,V,N,S,V,N,S,V);
1145dd6cc9b5Sdrh **                     -- 0 1 2 3 4 5 6 7 8
1146dd6cc9b5Sdrh **
1147dd6cc9b5Sdrh ** Then the mapping from this function is as follows:
1148dd6cc9b5Sdrh **
1149dd6cc9b5Sdrh **    INPUTS:     0 1 2 3 4 5 6 7 8
1150dd6cc9b5Sdrh **    OUTPUTS:    0 1 6 2 3 7 4 5 8
1151dd6cc9b5Sdrh **
1152dd6cc9b5Sdrh ** So, in other words, this routine shifts all the virtual columns to
1153dd6cc9b5Sdrh ** the end.
1154dd6cc9b5Sdrh **
1155dd6cc9b5Sdrh ** If SQLITE_OMIT_GENERATED_COLUMNS then there are no virtual columns and
11567fe2fc0dSdrh ** this routine is a no-op macro.  If the pTab does not have any virtual
11577fe2fc0dSdrh ** columns, then this routine is no-op that always return iCol.  If iCol
11587fe2fc0dSdrh ** is negative (indicating the ROWID column) then this routine return iCol.
115981f7b372Sdrh */
sqlite3TableColumnToStorage(Table * pTab,i16 iCol)1160b9bcf7caSdrh i16 sqlite3TableColumnToStorage(Table *pTab, i16 iCol){
116181f7b372Sdrh   int i;
116281f7b372Sdrh   i16 n;
116381f7b372Sdrh   assert( iCol<pTab->nCol );
11647fe2fc0dSdrh   if( (pTab->tabFlags & TF_HasVirtual)==0 || iCol<0 ) return iCol;
116581f7b372Sdrh   for(i=0, n=0; i<iCol; i++){
116681f7b372Sdrh     if( (pTab->aCol[i].colFlags & COLFLAG_VIRTUAL)==0 ) n++;
116781f7b372Sdrh   }
1168dd6cc9b5Sdrh   if( pTab->aCol[i].colFlags & COLFLAG_VIRTUAL ){
1169dd6cc9b5Sdrh     /* iCol is a virtual column itself */
1170dd6cc9b5Sdrh     return pTab->nNVCol + i - n;
1171dd6cc9b5Sdrh   }else{
1172dd6cc9b5Sdrh     /* iCol is a normal or stored column */
117381f7b372Sdrh     return n;
117481f7b372Sdrh   }
1175dd6cc9b5Sdrh }
117681f7b372Sdrh #endif
117781f7b372Sdrh 
11784415628aSdrh /*
117931da7be9Sdrh ** Insert a single OP_JournalMode query opcode in order to force the
118031da7be9Sdrh ** prepared statement to return false for sqlite3_stmt_readonly().  This
118131da7be9Sdrh ** is used by CREATE TABLE IF NOT EXISTS and similar if the table already
118231da7be9Sdrh ** exists, so that the prepared statement for CREATE TABLE IF NOT EXISTS
118331da7be9Sdrh ** will return false for sqlite3_stmt_readonly() even if that statement
118431da7be9Sdrh ** is a read-only no-op.
118531da7be9Sdrh */
sqlite3ForceNotReadOnly(Parse * pParse)118631da7be9Sdrh static void sqlite3ForceNotReadOnly(Parse *pParse){
118731da7be9Sdrh   int iReg = ++pParse->nMem;
118831da7be9Sdrh   Vdbe *v = sqlite3GetVdbe(pParse);
118931da7be9Sdrh   if( v ){
119031da7be9Sdrh     sqlite3VdbeAddOp3(v, OP_JournalMode, 0, iReg, PAGER_JOURNALMODE_QUERY);
1191a8f249f1Sdan     sqlite3VdbeUsesBtree(v, 0);
119231da7be9Sdrh   }
119331da7be9Sdrh }
119431da7be9Sdrh 
119531da7be9Sdrh /*
119675897234Sdrh ** Begin constructing a new table representation in memory.  This is
119775897234Sdrh ** the first of several action routines that get called in response
1198d9b0257aSdrh ** to a CREATE TABLE statement.  In particular, this routine is called
119974161705Sdrh ** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
1200e0bc4048Sdrh ** flag is true if the table should be stored in the auxiliary database
1201e0bc4048Sdrh ** file instead of in the main database file.  This is normally the case
1202e0bc4048Sdrh ** when the "TEMP" or "TEMPORARY" keyword occurs in between
1203f57b3399Sdrh ** CREATE and TABLE.
1204d9b0257aSdrh **
1205f57b3399Sdrh ** The new table record is initialized and put in pParse->pNewTable.
1206f57b3399Sdrh ** As more of the CREATE TABLE statement is parsed, additional action
1207f57b3399Sdrh ** routines will be called to add more information to this record.
12084adee20fSdanielk1977 ** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
1209f57b3399Sdrh ** is called to complete the construction of the new table record.
121075897234Sdrh */
sqlite3StartTable(Parse * pParse,Token * pName1,Token * pName2,int isTemp,int isView,int isVirtual,int noErr)12114adee20fSdanielk1977 void sqlite3StartTable(
1212e5f9c644Sdrh   Parse *pParse,   /* Parser context */
1213cbb18d22Sdanielk1977   Token *pName1,   /* First part of the name of the table or view */
1214cbb18d22Sdanielk1977   Token *pName2,   /* Second part of the name of the table or view */
1215e5f9c644Sdrh   int isTemp,      /* True if this is a TEMP table */
1216faa59554Sdrh   int isView,      /* True if this is a VIEW */
1217f1a381e7Sdanielk1977   int isVirtual,   /* True if this is a VIRTUAL table */
1218faa59554Sdrh   int noErr        /* Do nothing if table already exists */
1219e5f9c644Sdrh ){
122075897234Sdrh   Table *pTable;
122123bf66d6Sdrh   char *zName = 0; /* The name of the new table */
12229bb575fdSdrh   sqlite3 *db = pParse->db;
1223adbca9cfSdrh   Vdbe *v;
1224cbb18d22Sdanielk1977   int iDb;         /* Database number to create the table in */
1225cbb18d22Sdanielk1977   Token *pName;    /* Unqualified name of the table to create */
122675897234Sdrh 
1227055f298aSdrh   if( db->init.busy && db->init.newTnum==1 ){
12281e32bed3Sdrh     /* Special case:  Parsing the sqlite_schema or sqlite_temp_schema schema */
1229055f298aSdrh     iDb = db->init.iDb;
1230055f298aSdrh     zName = sqlite3DbStrDup(db, SCHEMA_TABLE(iDb));
1231055f298aSdrh     pName = pName1;
1232055f298aSdrh   }else{
1233055f298aSdrh     /* The common case */
1234ef2cb63eSdanielk1977     iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
1235cbb18d22Sdanielk1977     if( iDb<0 ) return;
123672c5ea32Sdan     if( !OMIT_TEMPDB && isTemp && pName2->n>0 && iDb!=1 ){
123772c5ea32Sdan       /* If creating a temp table, the name may not be qualified. Unless
123872c5ea32Sdan       ** the database name is "temp" anyway.  */
1239cbb18d22Sdanielk1977       sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
1240cbb18d22Sdanielk1977       return;
1241cbb18d22Sdanielk1977     }
124253c0f748Sdanielk1977     if( !OMIT_TEMPDB && isTemp ) iDb = 1;
124317435752Sdrh     zName = sqlite3NameFromToken(db, pName);
1244c9461eccSdan     if( IN_RENAME_OBJECT ){
1245c9461eccSdan       sqlite3RenameTokenMap(pParse, (void*)zName, pName);
1246c9461eccSdan     }
1247055f298aSdrh   }
1248055f298aSdrh   pParse->sNameToken = *pName;
1249e0048400Sdanielk1977   if( zName==0 ) return;
1250c5a93d4cSdrh   if( sqlite3CheckObjectName(pParse, zName, isView?"view":"table", zName) ){
125123bf66d6Sdrh     goto begin_table_error;
1252d8123366Sdanielk1977   }
12531d85d931Sdrh   if( db->init.iDb==1 ) isTemp = 1;
1254e5f9c644Sdrh #ifndef SQLITE_OMIT_AUTHORIZATION
1255055f298aSdrh   assert( isTemp==0 || isTemp==1 );
1256055f298aSdrh   assert( isView==0 || isView==1 );
1257e22a334bSdrh   {
1258055f298aSdrh     static const u8 aCode[] = {
1259055f298aSdrh        SQLITE_CREATE_TABLE,
1260055f298aSdrh        SQLITE_CREATE_TEMP_TABLE,
1261055f298aSdrh        SQLITE_CREATE_VIEW,
1262055f298aSdrh        SQLITE_CREATE_TEMP_VIEW
1263055f298aSdrh     };
126469c33826Sdrh     char *zDb = db->aDb[iDb].zDbSName;
12654adee20fSdanielk1977     if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
126623bf66d6Sdrh       goto begin_table_error;
1267ed6c8671Sdrh     }
1268055f298aSdrh     if( !isVirtual && sqlite3AuthCheck(pParse, (int)aCode[isTemp+2*isView],
1269055f298aSdrh                                        zName, 0, zDb) ){
127023bf66d6Sdrh       goto begin_table_error;
1271e5f9c644Sdrh     }
1272e5f9c644Sdrh   }
1273e5f9c644Sdrh #endif
1274e5f9c644Sdrh 
1275f57b3399Sdrh   /* Make sure the new table name does not collide with an existing
12763df6b257Sdanielk1977   ** index or table name in the same database.  Issue an error message if
12777e6ebfb2Sdanielk1977   ** it does. The exception is if the statement being parsed was passed
12787e6ebfb2Sdanielk1977   ** to an sqlite3_declare_vtab() call. In that case only the column names
12797e6ebfb2Sdanielk1977   ** and types will be used, so there is no need to test for namespace
12807e6ebfb2Sdanielk1977   ** collisions.
1281f57b3399Sdrh   */
1282cf8f2895Sdan   if( !IN_SPECIAL_PARSE ){
128369c33826Sdrh     char *zDb = db->aDb[iDb].zDbSName;
12845558a8a6Sdanielk1977     if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
12855558a8a6Sdanielk1977       goto begin_table_error;
12865558a8a6Sdanielk1977     }
1287a16d1060Sdan     pTable = sqlite3FindTable(db, zName, zDb);
12883df6b257Sdanielk1977     if( pTable ){
1289faa59554Sdrh       if( !noErr ){
12906e85b27cSlarrybr         sqlite3ErrorMsg(pParse, "%s %T already exists",
12916e85b27cSlarrybr                         (IsView(pTable)? "view" : "table"), pName);
12927687c83dSdan       }else{
129333c59ecaSdrh         assert( !db->init.busy || CORRUPT_DB );
12947687c83dSdan         sqlite3CodeVerifySchema(pParse, iDb);
129531da7be9Sdrh         sqlite3ForceNotReadOnly(pParse);
1296faa59554Sdrh       }
129723bf66d6Sdrh       goto begin_table_error;
129875897234Sdrh     }
12998a8a0d1dSdrh     if( sqlite3FindIndex(db, zName, zDb)!=0 ){
13004adee20fSdanielk1977       sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
130123bf66d6Sdrh       goto begin_table_error;
130275897234Sdrh     }
13037e6ebfb2Sdanielk1977   }
13047e6ebfb2Sdanielk1977 
130526783a58Sdanielk1977   pTable = sqlite3DbMallocZero(db, sizeof(Table));
13066d4abfbeSdrh   if( pTable==0 ){
13074df86af3Sdrh     assert( db->mallocFailed );
1308fad3039cSmistachkin     pParse->rc = SQLITE_NOMEM_BKPT;
1309e0048400Sdanielk1977     pParse->nErr++;
131023bf66d6Sdrh     goto begin_table_error;
13116d4abfbeSdrh   }
131275897234Sdrh   pTable->zName = zName;
13134a32431cSdrh   pTable->iPKey = -1;
1314da184236Sdanielk1977   pTable->pSchema = db->aDb[iDb].pSchema;
131579df7782Sdrh   pTable->nTabRef = 1;
1316d1417ee1Sdrh #ifdef SQLITE_DEFAULT_ROWEST
1317d1417ee1Sdrh   pTable->nRowLogEst = sqlite3LogEst(SQLITE_DEFAULT_ROWEST);
1318d1417ee1Sdrh #else
1319cfc9df76Sdan   pTable->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
1320d1417ee1Sdrh #endif
1321c4a64facSdrh   assert( pParse->pNewTable==0 );
132275897234Sdrh   pParse->pNewTable = pTable;
132317f71934Sdrh 
132417f71934Sdrh   /* Begin generating the code that will insert the table record into
1325346a70caSdrh   ** the schema table.  Note in particular that we must go ahead
132617f71934Sdrh   ** and allocate the record number for the table entry now.  Before any
132717f71934Sdrh   ** PRIMARY KEY or UNIQUE keywords are parsed.  Those keywords will cause
132817f71934Sdrh   ** indices to be created and the table record must come before the
132917f71934Sdrh   ** indices.  Hence, the record number for the table must be allocated
133017f71934Sdrh   ** now.
133117f71934Sdrh   */
13324adee20fSdanielk1977   if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
1333728e0f91Sdrh     int addr1;
1334e321c29aSdrh     int fileFormat;
1335b7654111Sdrh     int reg1, reg2, reg3;
13363c03afd3Sdrh     /* nullRow[] is an OP_Record encoding of a row containing 5 NULLs */
13373c03afd3Sdrh     static const char nullRow[] = { 6, 0, 0, 0, 0, 0 };
13380dd5cdaeSdrh     sqlite3BeginWriteOperation(pParse, 1, iDb);
1339b17131a0Sdrh 
134020b1eaffSdanielk1977 #ifndef SQLITE_OMIT_VIRTUALTABLE
134120b1eaffSdanielk1977     if( isVirtual ){
134266a5167bSdrh       sqlite3VdbeAddOp0(v, OP_VBegin);
134320b1eaffSdanielk1977     }
134420b1eaffSdanielk1977 #endif
134520b1eaffSdanielk1977 
134636963fdcSdanielk1977     /* If the file format and encoding in the database have not been set,
134736963fdcSdanielk1977     ** set them now.
1348cbb18d22Sdanielk1977     */
1349b7654111Sdrh     reg1 = pParse->regRowid = ++pParse->nMem;
1350b7654111Sdrh     reg2 = pParse->regRoot = ++pParse->nMem;
1351b7654111Sdrh     reg3 = ++pParse->nMem;
13520d19f7acSdanielk1977     sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT);
1353fb98264aSdrh     sqlite3VdbeUsesBtree(v, iDb);
1354728e0f91Sdrh     addr1 = sqlite3VdbeAddOp1(v, OP_If, reg3); VdbeCoverage(v);
1355e321c29aSdrh     fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
135676fe8032Sdrh                   1 : SQLITE_MAX_FILE_FORMAT;
13571861afcdSdrh     sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, fileFormat);
13581861afcdSdrh     sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, ENC(db));
1359728e0f91Sdrh     sqlite3VdbeJumpHere(v, addr1);
1360d008cfe3Sdanielk1977 
13611e32bed3Sdrh     /* This just creates a place-holder record in the sqlite_schema table.
13624794f735Sdrh     ** The record created does not contain anything yet.  It will be replaced
13634794f735Sdrh     ** by the real entry in code generated at sqlite3EndTable().
1364b17131a0Sdrh     **
13650fa991b9Sdrh     ** The rowid for the new entry is left in register pParse->regRowid.
13660fa991b9Sdrh     ** The root page number of the new table is left in reg pParse->regRoot.
13670fa991b9Sdrh     ** The rowid and root page number values are needed by the code that
13680fa991b9Sdrh     ** sqlite3EndTable will generate.
13694794f735Sdrh     */
1370f1a381e7Sdanielk1977 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
1371f1a381e7Sdanielk1977     if( isView || isVirtual ){
1372b7654111Sdrh       sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2);
1373a21c6b6fSdanielk1977     }else
1374a21c6b6fSdanielk1977 #endif
1375a21c6b6fSdanielk1977     {
1376381bdaccSdrh       assert( !pParse->bReturning );
1377381bdaccSdrh       pParse->u1.addrCrTab =
13780f3f7664Sdrh          sqlite3VdbeAddOp3(v, OP_CreateBtree, iDb, reg2, BTREE_INTKEY);
1379a21c6b6fSdanielk1977     }
1380346a70caSdrh     sqlite3OpenSchemaTable(pParse, iDb);
1381b7654111Sdrh     sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1);
13823c03afd3Sdrh     sqlite3VdbeAddOp4(v, OP_Blob, 6, reg3, 0, nullRow, P4_STATIC);
1383b7654111Sdrh     sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1);
1384b7654111Sdrh     sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
138566a5167bSdrh     sqlite3VdbeAddOp0(v, OP_Close);
13865e00f6c7Sdrh   }
138723bf66d6Sdrh 
138823bf66d6Sdrh   /* Normal (non-error) return. */
138923bf66d6Sdrh   return;
139023bf66d6Sdrh 
139123bf66d6Sdrh   /* If an error occurs, we jump here */
139223bf66d6Sdrh begin_table_error:
1393c0495e8cSdrh   pParse->checkSchema = 1;
1394633e6d57Sdrh   sqlite3DbFree(db, zName);
139523bf66d6Sdrh   return;
139675897234Sdrh }
139775897234Sdrh 
139803d69a68Sdrh /* Set properties of a table column based on the (magical)
139903d69a68Sdrh ** name of the column.
140003d69a68Sdrh */
140103d69a68Sdrh #if SQLITE_ENABLE_HIDDEN_COLUMNS
sqlite3ColumnPropertiesFromName(Table * pTab,Column * pCol)1402e6110505Sdrh void sqlite3ColumnPropertiesFromName(Table *pTab, Column *pCol){
1403cf9d36d1Sdrh   if( sqlite3_strnicmp(pCol->zCnName, "__hidden__", 10)==0 ){
140403d69a68Sdrh     pCol->colFlags |= COLFLAG_HIDDEN;
14056f6e60ddSdrh     if( pTab ) pTab->tabFlags |= TF_HasHidden;
1406ba68f8f3Sdan   }else if( pTab && pCol!=pTab->aCol && (pCol[-1].colFlags & COLFLAG_HIDDEN) ){
1407ba68f8f3Sdan     pTab->tabFlags |= TF_OOOHidden;
140803d69a68Sdrh   }
140903d69a68Sdrh }
1410e6110505Sdrh #endif
141103d69a68Sdrh 
14122053f313Sdrh /*
141328828c55Sdrh ** Name of the special TEMP trigger used to implement RETURNING.  The
141428828c55Sdrh ** name begins with "sqlite_" so that it is guaranteed not to collide
141528828c55Sdrh ** with any application-generated triggers.
1416b8352479Sdrh */
141728828c55Sdrh #define RETURNING_TRIGGER_NAME  "sqlite_returning"
1418b8352479Sdrh 
1419b8352479Sdrh /*
142028828c55Sdrh ** Clean up the data structures associated with the RETURNING clause.
1421b8352479Sdrh */
sqlite3DeleteReturning(sqlite3 * db,Returning * pRet)1422b8352479Sdrh static void sqlite3DeleteReturning(sqlite3 *db, Returning *pRet){
1423b8352479Sdrh   Hash *pHash;
1424b8352479Sdrh   pHash = &(db->aDb[1].pSchema->trigHash);
142528828c55Sdrh   sqlite3HashInsert(pHash, RETURNING_TRIGGER_NAME, 0);
1426b8352479Sdrh   sqlite3ExprListDelete(db, pRet->pReturnEL);
1427b8352479Sdrh   sqlite3DbFree(db, pRet);
1428b8352479Sdrh }
1429b8352479Sdrh 
1430b8352479Sdrh /*
143128828c55Sdrh ** Add the RETURNING clause to the parse currently underway.
143228828c55Sdrh **
143328828c55Sdrh ** This routine creates a special TEMP trigger that will fire for each row
143428828c55Sdrh ** of the DML statement.  That TEMP trigger contains a single SELECT
143528828c55Sdrh ** statement with a result set that is the argument of the RETURNING clause.
143628828c55Sdrh ** The trigger has the Trigger.bReturning flag and an opcode of
143728828c55Sdrh ** TK_RETURNING instead of TK_SELECT, so that the trigger code generator
143828828c55Sdrh ** knows to handle it specially.  The TEMP trigger is automatically
143928828c55Sdrh ** removed at the end of the parse.
144028828c55Sdrh **
144128828c55Sdrh ** When this routine is called, we do not yet know if the RETURNING clause
144228828c55Sdrh ** is attached to a DELETE, INSERT, or UPDATE, so construct it as a
144328828c55Sdrh ** RETURNING trigger instead.  It will then be converted into the appropriate
144428828c55Sdrh ** type on the first call to sqlite3TriggersExist().
14452053f313Sdrh */
sqlite3AddReturning(Parse * pParse,ExprList * pList)14462053f313Sdrh void sqlite3AddReturning(Parse *pParse, ExprList *pList){
1447b8352479Sdrh   Returning *pRet;
1448b8352479Sdrh   Hash *pHash;
1449b8352479Sdrh   sqlite3 *db = pParse->db;
1450e1c9a4ebSdrh   if( pParse->pNewTrigger ){
1451e1c9a4ebSdrh     sqlite3ErrorMsg(pParse, "cannot use RETURNING in a trigger");
1452e1c9a4ebSdrh   }else{
1453e1c9a4ebSdrh     assert( pParse->bReturning==0 );
1454e1c9a4ebSdrh   }
1455d086aa0aSdrh   pParse->bReturning = 1;
1456b8352479Sdrh   pRet = sqlite3DbMallocZero(db, sizeof(*pRet));
1457b8352479Sdrh   if( pRet==0 ){
1458b8352479Sdrh     sqlite3ExprListDelete(db, pList);
1459b8352479Sdrh     return;
1460b8352479Sdrh   }
1461381bdaccSdrh   pParse->u1.pReturning = pRet;
1462b8352479Sdrh   pRet->pParse = pParse;
1463b8352479Sdrh   pRet->pReturnEL = pList;
14642053f313Sdrh   sqlite3ParserAddCleanup(pParse,
1465b8352479Sdrh      (void(*)(sqlite3*,void*))sqlite3DeleteReturning, pRet);
14666d0053cfSdrh   testcase( pParse->earlyCleanup );
1467cf4108bbSdrh   if( db->mallocFailed ) return;
146828828c55Sdrh   pRet->retTrig.zName = RETURNING_TRIGGER_NAME;
1469b8352479Sdrh   pRet->retTrig.op = TK_RETURNING;
1470b8352479Sdrh   pRet->retTrig.tr_tm = TRIGGER_AFTER;
1471b8352479Sdrh   pRet->retTrig.bReturning = 1;
1472b8352479Sdrh   pRet->retTrig.pSchema = db->aDb[1].pSchema;
1473a4767683Sdrh   pRet->retTrig.pTabSchema = db->aDb[1].pSchema;
1474b8352479Sdrh   pRet->retTrig.step_list = &pRet->retTStep;
1475dac9a5f7Sdrh   pRet->retTStep.op = TK_RETURNING;
1476b8352479Sdrh   pRet->retTStep.pTrig = &pRet->retTrig;
1477381bdaccSdrh   pRet->retTStep.pExprList = pList;
1478b8352479Sdrh   pHash = &(db->aDb[1].pSchema->trigHash);
1479e1c9a4ebSdrh   assert( sqlite3HashFind(pHash, RETURNING_TRIGGER_NAME)==0 || pParse->nErr );
148028828c55Sdrh   if( sqlite3HashInsert(pHash, RETURNING_TRIGGER_NAME, &pRet->retTrig)
14810166df0bSdrh           ==&pRet->retTrig ){
14820166df0bSdrh     sqlite3OomFault(db);
14830166df0bSdrh   }
14842053f313Sdrh }
148503d69a68Sdrh 
148675897234Sdrh /*
148775897234Sdrh ** Add a new column to the table currently being constructed.
1488d9b0257aSdrh **
1489d9b0257aSdrh ** The parser calls this routine once for each column declaration
14904adee20fSdanielk1977 ** in a CREATE TABLE statement.  sqlite3StartTable() gets called
1491d9b0257aSdrh ** first to get things going.  Then this routine is called for each
1492d9b0257aSdrh ** column.
149375897234Sdrh */
sqlite3AddColumn(Parse * pParse,Token sName,Token sType)149477441fafSdrh void sqlite3AddColumn(Parse *pParse, Token sName, Token sType){
149575897234Sdrh   Table *p;
149697fc3d06Sdrh   int i;
1497a99db3b6Sdrh   char *z;
149894eaafa9Sdrh   char *zType;
1499c9b84a1fSdrh   Column *pCol;
1500bb4957f8Sdrh   sqlite3 *db = pParse->db;
15013e992d1aSdrh   u8 hName;
15027b3c514bSdrh   Column *aNew;
1503c2df4d6aSdrh   u8 eType = COLTYPE_CUSTOM;
1504c2df4d6aSdrh   u8 szEst = 1;
1505c2df4d6aSdrh   char affinity = SQLITE_AFF_BLOB;
15063e992d1aSdrh 
150775897234Sdrh   if( (p = pParse->pNewTable)==0 ) return;
1508bb4957f8Sdrh   if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){
1509e5c941b8Sdrh     sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
1510e5c941b8Sdrh     return;
1511e5c941b8Sdrh   }
151277441fafSdrh   if( !IN_RENAME_OBJECT ) sqlite3DequoteToken(&sName);
1513e48f261eSdrh 
1514e48f261eSdrh   /* Because keywords GENERATE ALWAYS can be converted into indentifiers
1515e48f261eSdrh   ** by the parser, we can sometimes end up with a typename that ends
1516e48f261eSdrh   ** with "generated always".  Check for this case and omit the surplus
1517e48f261eSdrh   ** text. */
1518e48f261eSdrh   if( sType.n>=16
1519e48f261eSdrh    && sqlite3_strnicmp(sType.z+(sType.n-6),"always",6)==0
1520e48f261eSdrh   ){
1521e48f261eSdrh     sType.n -= 6;
1522e48f261eSdrh     while( ALWAYS(sType.n>0) && sqlite3Isspace(sType.z[sType.n-1]) ) sType.n--;
1523e48f261eSdrh     if( sType.n>=9
1524e48f261eSdrh      && sqlite3_strnicmp(sType.z+(sType.n-9),"generated",9)==0
1525e48f261eSdrh     ){
1526e48f261eSdrh       sType.n -= 9;
1527e48f261eSdrh       while( sType.n>0 && sqlite3Isspace(sType.z[sType.n-1]) ) sType.n--;
1528e48f261eSdrh     }
1529e48f261eSdrh   }
1530e48f261eSdrh 
1531c2df4d6aSdrh   /* Check for standard typenames.  For standard typenames we will
1532c2df4d6aSdrh   ** set the Column.eType field rather than storing the typename after
1533c2df4d6aSdrh   ** the column name, in order to save space. */
1534c2df4d6aSdrh   if( sType.n>=3 ){
1535c2df4d6aSdrh     sqlite3DequoteToken(&sType);
1536c2df4d6aSdrh     for(i=0; i<SQLITE_N_STDTYPE; i++){
1537c2df4d6aSdrh        if( sType.n==sqlite3StdTypeLen[i]
1538c2df4d6aSdrh         && sqlite3_strnicmp(sType.z, sqlite3StdType[i], sType.n)==0
1539c2df4d6aSdrh        ){
1540c2df4d6aSdrh          sType.n = 0;
1541c2df4d6aSdrh          eType = i+1;
1542c2df4d6aSdrh          affinity = sqlite3StdTypeAffinity[i];
1543c2df4d6aSdrh          if( affinity<=SQLITE_AFF_TEXT ) szEst = 5;
1544c2df4d6aSdrh          break;
1545c2df4d6aSdrh        }
1546c2df4d6aSdrh     }
1547c2df4d6aSdrh   }
1548c2df4d6aSdrh 
1549913306a5Sdrh   z = sqlite3DbMallocRaw(db, (i64)sName.n + 1 + (i64)sType.n + (sType.n>0) );
155097fc3d06Sdrh   if( z==0 ) return;
155177441fafSdrh   if( IN_RENAME_OBJECT ) sqlite3RenameTokenMap(pParse, (void*)z, &sName);
155277441fafSdrh   memcpy(z, sName.z, sName.n);
155377441fafSdrh   z[sName.n] = 0;
155494eaafa9Sdrh   sqlite3Dequote(z);
15553e992d1aSdrh   hName = sqlite3StrIHash(z);
155697fc3d06Sdrh   for(i=0; i<p->nCol; i++){
1557cf9d36d1Sdrh     if( p->aCol[i].hName==hName && sqlite3StrICmp(z, p->aCol[i].zCnName)==0 ){
15584adee20fSdanielk1977       sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
1559633e6d57Sdrh       sqlite3DbFree(db, z);
156097fc3d06Sdrh       return;
156197fc3d06Sdrh     }
156297fc3d06Sdrh   }
1563913306a5Sdrh   aNew = sqlite3DbRealloc(db,p->aCol,((i64)p->nCol+1)*sizeof(p->aCol[0]));
1564d5d56523Sdanielk1977   if( aNew==0 ){
1565633e6d57Sdrh     sqlite3DbFree(db, z);
1566d5d56523Sdanielk1977     return;
1567d5d56523Sdanielk1977   }
15686d4abfbeSdrh   p->aCol = aNew;
1569c9b84a1fSdrh   pCol = &p->aCol[p->nCol];
1570c9b84a1fSdrh   memset(pCol, 0, sizeof(p->aCol[0]));
1571cf9d36d1Sdrh   pCol->zCnName = z;
15723e992d1aSdrh   pCol->hName = hName;
1573ba68f8f3Sdan   sqlite3ColumnPropertiesFromName(p, pCol);
1574a37cdde0Sdanielk1977 
157577441fafSdrh   if( sType.n==0 ){
1576a37cdde0Sdanielk1977     /* If there is no type specified, columns have the default affinity
1577bbade8d1Sdrh     ** 'BLOB' with a default size of 4 bytes. */
1578c2df4d6aSdrh     pCol->affinity = affinity;
1579b70f2eabSdrh     pCol->eCType = eType;
1580c2df4d6aSdrh     pCol->szEst = szEst;
1581bbade8d1Sdrh #ifdef SQLITE_ENABLE_SORTER_REFERENCES
1582c2df4d6aSdrh     if( affinity==SQLITE_AFF_BLOB ){
15832e3a5a81Sdan       if( 4>=sqlite3GlobalConfig.szSorterRef ){
15842e3a5a81Sdan         pCol->colFlags |= COLFLAG_SORTERREF;
15852e3a5a81Sdan       }
1586c2df4d6aSdrh     }
1587bbade8d1Sdrh #endif
15882881ab62Sdrh   }else{
1589ddb2b4a3Sdrh     zType = z + sqlite3Strlen30(z) + 1;
159077441fafSdrh     memcpy(zType, sType.z, sType.n);
159177441fafSdrh     zType[sType.n] = 0;
1592a6dddd9bSdrh     sqlite3Dequote(zType);
15932e3a5a81Sdan     pCol->affinity = sqlite3AffinityType(zType, pCol);
1594d7564865Sdrh     pCol->colFlags |= COLFLAG_HASTYPE;
15952881ab62Sdrh   }
1596c9b84a1fSdrh   p->nCol++;
1597f95909c7Sdrh   p->nNVCol++;
1598986dde70Sdrh   pParse->constraintName.n = 0;
159975897234Sdrh }
160075897234Sdrh 
160175897234Sdrh /*
1602382c0247Sdrh ** This routine is called by the parser while in the middle of
1603382c0247Sdrh ** parsing a CREATE TABLE statement.  A "NOT NULL" constraint has
1604382c0247Sdrh ** been seen on a column.  This routine sets the notNull flag on
1605382c0247Sdrh ** the column currently under construction.
1606382c0247Sdrh */
sqlite3AddNotNull(Parse * pParse,int onError)16074adee20fSdanielk1977 void sqlite3AddNotNull(Parse *pParse, int onError){
1608382c0247Sdrh   Table *p;
160926e731ccSdan   Column *pCol;
1610c4a64facSdrh   p = pParse->pNewTable;
1611c4a64facSdrh   if( p==0 || NEVER(p->nCol<1) ) return;
161226e731ccSdan   pCol = &p->aCol[p->nCol-1];
161326e731ccSdan   pCol->notNull = (u8)onError;
16148b174f29Sdrh   p->tabFlags |= TF_HasNotNull;
161526e731ccSdan 
161626e731ccSdan   /* Set the uniqNotNull flag on any UNIQUE or PK indexes already created
161726e731ccSdan   ** on this column.  */
161826e731ccSdan   if( pCol->colFlags & COLFLAG_UNIQUE ){
161926e731ccSdan     Index *pIdx;
162026e731ccSdan     for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
162126e731ccSdan       assert( pIdx->nKeyCol==1 && pIdx->onError!=OE_None );
162226e731ccSdan       if( pIdx->aiColumn[0]==p->nCol-1 ){
162326e731ccSdan         pIdx->uniqNotNull = 1;
162426e731ccSdan       }
162526e731ccSdan     }
162626e731ccSdan   }
1627382c0247Sdrh }
1628382c0247Sdrh 
1629382c0247Sdrh /*
163052a83fbbSdanielk1977 ** Scan the column type name zType (length nType) and return the
163152a83fbbSdanielk1977 ** associated affinity type.
1632b3dff964Sdanielk1977 **
1633b3dff964Sdanielk1977 ** This routine does a case-independent search of zType for the
1634b3dff964Sdanielk1977 ** substrings in the following table. If one of the substrings is
1635b3dff964Sdanielk1977 ** found, the corresponding affinity is returned. If zType contains
1636b3dff964Sdanielk1977 ** more than one of the substrings, entries toward the top of
1637b3dff964Sdanielk1977 ** the table take priority. For example, if zType is 'BLOBINT',
16388a51256cSdrh ** SQLITE_AFF_INTEGER is returned.
1639b3dff964Sdanielk1977 **
1640b3dff964Sdanielk1977 ** Substring     | Affinity
1641b3dff964Sdanielk1977 ** --------------------------------
1642b3dff964Sdanielk1977 ** 'INT'         | SQLITE_AFF_INTEGER
1643b3dff964Sdanielk1977 ** 'CHAR'        | SQLITE_AFF_TEXT
1644b3dff964Sdanielk1977 ** 'CLOB'        | SQLITE_AFF_TEXT
1645b3dff964Sdanielk1977 ** 'TEXT'        | SQLITE_AFF_TEXT
164605883a34Sdrh ** 'BLOB'        | SQLITE_AFF_BLOB
16478a51256cSdrh ** 'REAL'        | SQLITE_AFF_REAL
16488a51256cSdrh ** 'FLOA'        | SQLITE_AFF_REAL
16498a51256cSdrh ** 'DOUB'        | SQLITE_AFF_REAL
1650b3dff964Sdanielk1977 **
1651b3dff964Sdanielk1977 ** If none of the substrings in the above table are found,
1652b3dff964Sdanielk1977 ** SQLITE_AFF_NUMERIC is returned.
165352a83fbbSdanielk1977 */
sqlite3AffinityType(const char * zIn,Column * pCol)16542e3a5a81Sdan char sqlite3AffinityType(const char *zIn, Column *pCol){
1655b3dff964Sdanielk1977   u32 h = 0;
1656b3dff964Sdanielk1977   char aff = SQLITE_AFF_NUMERIC;
1657d3037a41Sdrh   const char *zChar = 0;
165852a83fbbSdanielk1977 
16592f1e02e8Sdrh   assert( zIn!=0 );
1660fdaac671Sdrh   while( zIn[0] ){
1661b7916a78Sdrh     h = (h<<8) + sqlite3UpperToLower[(*zIn)&0xff];
1662b3dff964Sdanielk1977     zIn++;
1663201f7168Sdanielk1977     if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){             /* CHAR */
1664201f7168Sdanielk1977       aff = SQLITE_AFF_TEXT;
1665fdaac671Sdrh       zChar = zIn;
1666201f7168Sdanielk1977     }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){       /* CLOB */
1667201f7168Sdanielk1977       aff = SQLITE_AFF_TEXT;
1668201f7168Sdanielk1977     }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){       /* TEXT */
1669201f7168Sdanielk1977       aff = SQLITE_AFF_TEXT;
1670201f7168Sdanielk1977     }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b')          /* BLOB */
16718a51256cSdrh         && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
167205883a34Sdrh       aff = SQLITE_AFF_BLOB;
1673d3037a41Sdrh       if( zIn[0]=='(' ) zChar = zIn;
16748a51256cSdrh #ifndef SQLITE_OMIT_FLOATING_POINT
16758a51256cSdrh     }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l')          /* REAL */
16768a51256cSdrh         && aff==SQLITE_AFF_NUMERIC ){
16778a51256cSdrh       aff = SQLITE_AFF_REAL;
16788a51256cSdrh     }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a')          /* FLOA */
16798a51256cSdrh         && aff==SQLITE_AFF_NUMERIC ){
16808a51256cSdrh       aff = SQLITE_AFF_REAL;
16818a51256cSdrh     }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b')          /* DOUB */
16828a51256cSdrh         && aff==SQLITE_AFF_NUMERIC ){
16838a51256cSdrh       aff = SQLITE_AFF_REAL;
16848a51256cSdrh #endif
1685201f7168Sdanielk1977     }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){    /* INT */
16868a51256cSdrh       aff = SQLITE_AFF_INTEGER;
1687b3dff964Sdanielk1977       break;
168852a83fbbSdanielk1977     }
168952a83fbbSdanielk1977   }
1690d3037a41Sdrh 
16912e3a5a81Sdan   /* If pCol is not NULL, store an estimate of the field size.  The
1692d3037a41Sdrh   ** estimate is scaled so that the size of an integer is 1.  */
16932e3a5a81Sdan   if( pCol ){
16942e3a5a81Sdan     int v = 0;   /* default size is approx 4 bytes */
16957ea31ccbSdrh     if( aff<SQLITE_AFF_NUMERIC ){
1696d3037a41Sdrh       if( zChar ){
1697fdaac671Sdrh         while( zChar[0] ){
1698d3037a41Sdrh           if( sqlite3Isdigit(zChar[0]) ){
16992e3a5a81Sdan             /* BLOB(k), VARCHAR(k), CHAR(k) -> r=(k/4+1) */
1700d3037a41Sdrh             sqlite3GetInt32(zChar, &v);
1701fdaac671Sdrh             break;
1702fdaac671Sdrh           }
1703fdaac671Sdrh           zChar++;
1704fdaac671Sdrh         }
1705fdaac671Sdrh       }else{
17062e3a5a81Sdan         v = 16;   /* BLOB, TEXT, CLOB -> r=5  (approx 20 bytes)*/
1707d3037a41Sdrh       }
1708fdaac671Sdrh     }
1709bbade8d1Sdrh #ifdef SQLITE_ENABLE_SORTER_REFERENCES
17102e3a5a81Sdan     if( v>=sqlite3GlobalConfig.szSorterRef ){
17112e3a5a81Sdan       pCol->colFlags |= COLFLAG_SORTERREF;
17122e3a5a81Sdan     }
1713bbade8d1Sdrh #endif
17142e3a5a81Sdan     v = v/4 + 1;
17152e3a5a81Sdan     if( v>255 ) v = 255;
17162e3a5a81Sdan     pCol->szEst = v;
1717fdaac671Sdrh   }
1718b3dff964Sdanielk1977   return aff;
171952a83fbbSdanielk1977 }
172052a83fbbSdanielk1977 
172152a83fbbSdanielk1977 /*
17227977a17fSdanielk1977 ** The expression is the default value for the most recently added column
17237977a17fSdanielk1977 ** of the table currently under construction.
17247977a17fSdanielk1977 **
17257977a17fSdanielk1977 ** Default value expressions must be constant.  Raise an exception if this
17267977a17fSdanielk1977 ** is not the case.
1727d9b0257aSdrh **
1728d9b0257aSdrh ** This routine is called by the parser while in the middle of
1729d9b0257aSdrh ** parsing a CREATE TABLE statement.
17307020f651Sdrh */
sqlite3AddDefaultValue(Parse * pParse,Expr * pExpr,const char * zStart,const char * zEnd)17311be266baSdrh void sqlite3AddDefaultValue(
17321be266baSdrh   Parse *pParse,           /* Parsing context */
17331be266baSdrh   Expr *pExpr,             /* The parsed expression of the default value */
17341be266baSdrh   const char *zStart,      /* Start of the default value text */
17351be266baSdrh   const char *zEnd         /* First character past end of defaut value text */
17361be266baSdrh ){
17377020f651Sdrh   Table *p;
17387977a17fSdanielk1977   Column *pCol;
1739633e6d57Sdrh   sqlite3 *db = pParse->db;
1740c4a64facSdrh   p = pParse->pNewTable;
1741c4a64facSdrh   if( p!=0 ){
1742014fff20Sdrh     int isInit = db->init.busy && db->init.iDb!=1;
17437977a17fSdanielk1977     pCol = &(p->aCol[p->nCol-1]);
1744014fff20Sdrh     if( !sqlite3ExprIsConstantOrFunction(pExpr, isInit) ){
17457977a17fSdanielk1977       sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
1746cf9d36d1Sdrh           pCol->zCnName);
17477e7fd73bSdrh #ifndef SQLITE_OMIT_GENERATED_COLUMNS
17487e7fd73bSdrh     }else if( pCol->colFlags & COLFLAG_GENERATED ){
1749ab0992f0Sdrh       testcase( pCol->colFlags & COLFLAG_VIRTUAL );
1750ab0992f0Sdrh       testcase( pCol->colFlags & COLFLAG_STORED );
17517e7fd73bSdrh       sqlite3ErrorMsg(pParse, "cannot use DEFAULT on a generated column");
17527e7fd73bSdrh #endif
17537977a17fSdanielk1977     }else{
17546ab3a2ecSdanielk1977       /* A copy of pExpr is used instead of the original, as pExpr contains
17551be266baSdrh       ** tokens that point to volatile memory.
17566ab3a2ecSdanielk1977       */
175779cf2b71Sdrh       Expr x, *pDfltExpr;
175894fa9c41Sdrh       memset(&x, 0, sizeof(x));
175994fa9c41Sdrh       x.op = TK_SPAN;
17609b2e0435Sdrh       x.u.zToken = sqlite3DbSpanDup(db, zStart, zEnd);
17611be266baSdrh       x.pLeft = pExpr;
176294fa9c41Sdrh       x.flags = EP_Skip;
176379cf2b71Sdrh       pDfltExpr = sqlite3ExprDup(db, &x, EXPRDUP_REDUCE);
176494fa9c41Sdrh       sqlite3DbFree(db, x.u.zToken);
176579cf2b71Sdrh       sqlite3ColumnSetExpr(pParse, p, pCol, pDfltExpr);
17667977a17fSdanielk1977     }
176742b9d7c5Sdrh   }
17688900a48bSdan   if( IN_RENAME_OBJECT ){
17698900a48bSdan     sqlite3RenameExprUnmap(pParse, pExpr);
17708900a48bSdan   }
17711be266baSdrh   sqlite3ExprDelete(db, pExpr);
17727020f651Sdrh }
17737020f651Sdrh 
17747020f651Sdrh /*
1775153110a7Sdrh ** Backwards Compatibility Hack:
1776153110a7Sdrh **
1777153110a7Sdrh ** Historical versions of SQLite accepted strings as column names in
1778153110a7Sdrh ** indexes and PRIMARY KEY constraints and in UNIQUE constraints.  Example:
1779153110a7Sdrh **
1780153110a7Sdrh **     CREATE TABLE xyz(a,b,c,d,e,PRIMARY KEY('a'),UNIQUE('b','c' COLLATE trim)
1781153110a7Sdrh **     CREATE INDEX abc ON xyz('c','d' DESC,'e' COLLATE nocase DESC);
1782153110a7Sdrh **
1783153110a7Sdrh ** This is goofy.  But to preserve backwards compatibility we continue to
1784153110a7Sdrh ** accept it.  This routine does the necessary conversion.  It converts
1785153110a7Sdrh ** the expression given in its argument from a TK_STRING into a TK_ID
1786153110a7Sdrh ** if the expression is just a TK_STRING with an optional COLLATE clause.
17876c591364Sdrh ** If the expression is anything other than TK_STRING, the expression is
1788153110a7Sdrh ** unchanged.
1789153110a7Sdrh */
sqlite3StringToId(Expr * p)1790153110a7Sdrh static void sqlite3StringToId(Expr *p){
1791153110a7Sdrh   if( p->op==TK_STRING ){
1792153110a7Sdrh     p->op = TK_ID;
1793153110a7Sdrh   }else if( p->op==TK_COLLATE && p->pLeft->op==TK_STRING ){
1794153110a7Sdrh     p->pLeft->op = TK_ID;
1795153110a7Sdrh   }
1796153110a7Sdrh }
1797153110a7Sdrh 
1798153110a7Sdrh /*
1799f4b1d8dcSdrh ** Tag the given column as being part of the PRIMARY KEY
1800f4b1d8dcSdrh */
makeColumnPartOfPrimaryKey(Parse * pParse,Column * pCol)1801f4b1d8dcSdrh static void makeColumnPartOfPrimaryKey(Parse *pParse, Column *pCol){
1802f4b1d8dcSdrh   pCol->colFlags |= COLFLAG_PRIMKEY;
1803f4b1d8dcSdrh #ifndef SQLITE_OMIT_GENERATED_COLUMNS
1804f4b1d8dcSdrh   if( pCol->colFlags & COLFLAG_GENERATED ){
1805f4b1d8dcSdrh     testcase( pCol->colFlags & COLFLAG_VIRTUAL );
1806f4b1d8dcSdrh     testcase( pCol->colFlags & COLFLAG_STORED );
1807f4b1d8dcSdrh     sqlite3ErrorMsg(pParse,
1808f4b1d8dcSdrh       "generated columns cannot be part of the PRIMARY KEY");
1809f4b1d8dcSdrh   }
1810f4b1d8dcSdrh #endif
1811f4b1d8dcSdrh }
1812f4b1d8dcSdrh 
1813f4b1d8dcSdrh /*
18144a32431cSdrh ** Designate the PRIMARY KEY for the table.  pList is a list of names
18154a32431cSdrh ** of columns that form the primary key.  If pList is NULL, then the
18164a32431cSdrh ** most recently added column of the table is the primary key.
18174a32431cSdrh **
18184a32431cSdrh ** A table can have at most one primary key.  If the table already has
18194a32431cSdrh ** a primary key (and this is the second primary key) then create an
18204a32431cSdrh ** error.
18214a32431cSdrh **
18224a32431cSdrh ** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
182323bf66d6Sdrh ** then we will try to use that column as the rowid.  Set the Table.iPKey
18244a32431cSdrh ** field of the table under construction to be the index of the
18254a32431cSdrh ** INTEGER PRIMARY KEY column.  Table.iPKey is set to -1 if there is
18264a32431cSdrh ** no INTEGER PRIMARY KEY.
18274a32431cSdrh **
18284a32431cSdrh ** If the key is not an INTEGER PRIMARY KEY, then create a unique
18294a32431cSdrh ** index for the key.  No index is created for INTEGER PRIMARY KEYs.
18304a32431cSdrh */
sqlite3AddPrimaryKey(Parse * pParse,ExprList * pList,int onError,int autoInc,int sortOrder)1831205f48e6Sdrh void sqlite3AddPrimaryKey(
1832205f48e6Sdrh   Parse *pParse,    /* Parsing context */
1833205f48e6Sdrh   ExprList *pList,  /* List of field names to be indexed */
1834205f48e6Sdrh   int onError,      /* What to do with a uniqueness conflict */
1835fdd6e85aSdrh   int autoInc,      /* True if the AUTOINCREMENT keyword is present */
1836fdd6e85aSdrh   int sortOrder     /* SQLITE_SO_ASC or SQLITE_SO_DESC */
1837205f48e6Sdrh ){
18384a32431cSdrh   Table *pTab = pParse->pNewTable;
1839d7564865Sdrh   Column *pCol = 0;
184078100cc9Sdrh   int iCol = -1, i;
18418ea30bfcSdrh   int nTerm;
184262340f84Sdrh   if( pTab==0 ) goto primary_key_exit;
18437d10d5a6Sdrh   if( pTab->tabFlags & TF_HasPrimaryKey ){
18444adee20fSdanielk1977     sqlite3ErrorMsg(pParse,
1845f7a9e1acSdrh       "table \"%s\" has more than one primary key", pTab->zName);
1846e0194f2bSdrh     goto primary_key_exit;
18474a32431cSdrh   }
18487d10d5a6Sdrh   pTab->tabFlags |= TF_HasPrimaryKey;
18494a32431cSdrh   if( pList==0 ){
18504a32431cSdrh     iCol = pTab->nCol - 1;
1851d7564865Sdrh     pCol = &pTab->aCol[iCol];
1852f4b1d8dcSdrh     makeColumnPartOfPrimaryKey(pParse, pCol);
18538ea30bfcSdrh     nTerm = 1;
185478100cc9Sdrh   }else{
18558ea30bfcSdrh     nTerm = pList->nExpr;
18568ea30bfcSdrh     for(i=0; i<nTerm; i++){
1857108aa00aSdrh       Expr *pCExpr = sqlite3ExprSkipCollate(pList->a[i].pExpr);
18587d3d9daeSdrh       assert( pCExpr!=0 );
1859153110a7Sdrh       sqlite3StringToId(pCExpr);
18607d3d9daeSdrh       if( pCExpr->op==TK_ID ){
1861f9751074Sdrh         const char *zCName;
1862f9751074Sdrh         assert( !ExprHasProperty(pCExpr, EP_IntValue) );
1863f9751074Sdrh         zCName = pCExpr->u.zToken;
18644a32431cSdrh         for(iCol=0; iCol<pTab->nCol; iCol++){
1865cf9d36d1Sdrh           if( sqlite3StrICmp(zCName, pTab->aCol[iCol].zCnName)==0 ){
1866d7564865Sdrh             pCol = &pTab->aCol[iCol];
1867f4b1d8dcSdrh             makeColumnPartOfPrimaryKey(pParse, pCol);
1868d3d39e93Sdrh             break;
1869d3d39e93Sdrh           }
18704a32431cSdrh         }
18716e4fc2caSdrh       }
187278100cc9Sdrh     }
1873108aa00aSdrh   }
18748ea30bfcSdrh   if( nTerm==1
1875d7564865Sdrh    && pCol
1876b70f2eabSdrh    && pCol->eCType==COLTYPE_INTEGER
1877bc622bc0Sdrh    && sortOrder!=SQLITE_SO_DESC
18788ea30bfcSdrh   ){
1879c9461eccSdan     if( IN_RENAME_OBJECT && pList ){
18802381f6d7Sdan       Expr *pCExpr = sqlite3ExprSkipCollate(pList->a[0].pExpr);
18812381f6d7Sdan       sqlite3RenameTokenRemap(pParse, &pTab->iPKey, pCExpr);
1882987db767Sdan     }
18834a32431cSdrh     pTab->iPKey = iCol;
18841bd10f8aSdrh     pTab->keyConf = (u8)onError;
18857d10d5a6Sdrh     assert( autoInc==0 || autoInc==1 );
18867d10d5a6Sdrh     pTab->tabFlags |= autoInc*TF_Autoincrement;
1887d88fd539Sdrh     if( pList ) pParse->iPkSortOrder = pList->a[0].fg.sortFlags;
188834ab941eSdrh     (void)sqlite3HasExplicitNulls(pParse, pList);
1889205f48e6Sdrh   }else if( autoInc ){
18904794f735Sdrh #ifndef SQLITE_OMIT_AUTOINCREMENT
1891205f48e6Sdrh     sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
1892205f48e6Sdrh        "INTEGER PRIMARY KEY");
18934794f735Sdrh #endif
18944a32431cSdrh   }else{
189562340f84Sdrh     sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0,
189662340f84Sdrh                            0, sortOrder, 0, SQLITE_IDXTYPE_PRIMARYKEY);
1897e0194f2bSdrh     pList = 0;
18984a32431cSdrh   }
1899e0194f2bSdrh 
1900e0194f2bSdrh primary_key_exit:
1901633e6d57Sdrh   sqlite3ExprListDelete(pParse->db, pList);
1902e0194f2bSdrh   return;
19034a32431cSdrh }
19044a32431cSdrh 
19054a32431cSdrh /*
1906ffe07b2dSdrh ** Add a new CHECK constraint to the table currently under construction.
1907ffe07b2dSdrh */
sqlite3AddCheckConstraint(Parse * pParse,Expr * pCheckExpr,const char * zStart,const char * zEnd)1908ffe07b2dSdrh void sqlite3AddCheckConstraint(
1909ffe07b2dSdrh   Parse *pParse,      /* Parsing context */
191092e21ef0Sdrh   Expr *pCheckExpr,   /* The check expression */
191192e21ef0Sdrh   const char *zStart, /* Opening "(" */
191292e21ef0Sdrh   const char *zEnd    /* Closing ")" */
1913ffe07b2dSdrh ){
1914ffe07b2dSdrh #ifndef SQLITE_OMIT_CHECK
1915ffe07b2dSdrh   Table *pTab = pParse->pNewTable;
1916c9bbb011Sdrh   sqlite3 *db = pParse->db;
1917c9bbb011Sdrh   if( pTab && !IN_DECLARE_VTAB
1918c9bbb011Sdrh    && !sqlite3BtreeIsReadonly(db->aDb[db->init.iDb].pBt)
1919c9bbb011Sdrh   ){
19202938f924Sdrh     pTab->pCheck = sqlite3ExprListAppend(pParse, pTab->pCheck, pCheckExpr);
19212938f924Sdrh     if( pParse->constraintName.n ){
19222938f924Sdrh       sqlite3ExprListSetName(pParse, pTab->pCheck, &pParse->constraintName, 1);
192392e21ef0Sdrh     }else{
192492e21ef0Sdrh       Token t;
192592e21ef0Sdrh       for(zStart++; sqlite3Isspace(zStart[0]); zStart++){}
192692e21ef0Sdrh       while( sqlite3Isspace(zEnd[-1]) ){ zEnd--; }
192792e21ef0Sdrh       t.z = zStart;
192892e21ef0Sdrh       t.n = (int)(zEnd - t.z);
192992e21ef0Sdrh       sqlite3ExprListSetName(pParse, pTab->pCheck, &t, 1);
19302938f924Sdrh     }
193133e619fcSdrh   }else
1932ffe07b2dSdrh #endif
193333e619fcSdrh   {
19342938f924Sdrh     sqlite3ExprDelete(pParse->db, pCheckExpr);
1935ffe07b2dSdrh   }
193633e619fcSdrh }
1937ffe07b2dSdrh 
1938ffe07b2dSdrh /*
1939d3d39e93Sdrh ** Set the collation function of the most recently parsed table column
1940d3d39e93Sdrh ** to the CollSeq given.
19418e2ca029Sdrh */
sqlite3AddCollateType(Parse * pParse,Token * pToken)194239002505Sdanielk1977 void sqlite3AddCollateType(Parse *pParse, Token *pToken){
19438e2ca029Sdrh   Table *p;
19440202b29eSdanielk1977   int i;
194539002505Sdanielk1977   char *zColl;              /* Dequoted name of collation sequence */
1946633e6d57Sdrh   sqlite3 *db;
1947a37cdde0Sdanielk1977 
1948936a3059Sdan   if( (p = pParse->pNewTable)==0 || IN_RENAME_OBJECT ) return;
19490202b29eSdanielk1977   i = p->nCol-1;
1950633e6d57Sdrh   db = pParse->db;
1951633e6d57Sdrh   zColl = sqlite3NameFromToken(db, pToken);
195239002505Sdanielk1977   if( !zColl ) return;
195339002505Sdanielk1977 
1954c4a64facSdrh   if( sqlite3LocateCollSeq(pParse, zColl) ){
1955b3bf556eSdanielk1977     Index *pIdx;
195665b40093Sdrh     sqlite3ColumnSetColl(db, &p->aCol[i], zColl);
19570202b29eSdanielk1977 
19580202b29eSdanielk1977     /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
19590202b29eSdanielk1977     ** then an index may have been created on this column before the
19600202b29eSdanielk1977     ** collation type was added. Correct this if it is the case.
19610202b29eSdanielk1977     */
19620202b29eSdanielk1977     for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
1963bbbdc83bSdrh       assert( pIdx->nKeyCol==1 );
1964b3bf556eSdanielk1977       if( pIdx->aiColumn[0]==i ){
196565b40093Sdrh         pIdx->azColl[0] = sqlite3ColumnColl(&p->aCol[i]);
19667cedc8d4Sdanielk1977       }
19677cedc8d4Sdanielk1977     }
196865b40093Sdrh   }
1969633e6d57Sdrh   sqlite3DbFree(db, zColl);
19707cedc8d4Sdanielk1977 }
19717cedc8d4Sdanielk1977 
197281f7b372Sdrh /* Change the most recently parsed column to be a GENERATED ALWAYS AS
197381f7b372Sdrh ** column.
197481f7b372Sdrh */
sqlite3AddGenerated(Parse * pParse,Expr * pExpr,Token * pType)197581f7b372Sdrh void sqlite3AddGenerated(Parse *pParse, Expr *pExpr, Token *pType){
197681f7b372Sdrh #ifndef SQLITE_OMIT_GENERATED_COLUMNS
197781f7b372Sdrh   u8 eType = COLFLAG_VIRTUAL;
197881f7b372Sdrh   Table *pTab = pParse->pNewTable;
197981f7b372Sdrh   Column *pCol;
1980f68bf5fbSdrh   if( pTab==0 ){
1981f68bf5fbSdrh     /* generated column in an CREATE TABLE IF NOT EXISTS that already exists */
1982f68bf5fbSdrh     goto generated_done;
1983f68bf5fbSdrh   }
198481f7b372Sdrh   pCol = &(pTab->aCol[pTab->nCol-1]);
1985b9bcf7caSdrh   if( IN_DECLARE_VTAB ){
1986b9bcf7caSdrh     sqlite3ErrorMsg(pParse, "virtual tables cannot use computed columns");
1987b9bcf7caSdrh     goto generated_done;
1988b9bcf7caSdrh   }
198979cf2b71Sdrh   if( pCol->iDflt>0 ) goto generated_error;
199081f7b372Sdrh   if( pType ){
199181f7b372Sdrh     if( pType->n==7 && sqlite3StrNICmp("virtual",pType->z,7)==0 ){
199281f7b372Sdrh       /* no-op */
199381f7b372Sdrh     }else if( pType->n==6 && sqlite3StrNICmp("stored",pType->z,6)==0 ){
199481f7b372Sdrh       eType = COLFLAG_STORED;
199581f7b372Sdrh     }else{
199681f7b372Sdrh       goto generated_error;
199781f7b372Sdrh     }
199881f7b372Sdrh   }
1999f95909c7Sdrh   if( eType==COLFLAG_VIRTUAL ) pTab->nNVCol--;
200081f7b372Sdrh   pCol->colFlags |= eType;
2001c1431144Sdrh   assert( TF_HasVirtual==COLFLAG_VIRTUAL );
2002c1431144Sdrh   assert( TF_HasStored==COLFLAG_STORED );
2003c1431144Sdrh   pTab->tabFlags |= eType;
2004a0e16a22Sdrh   if( pCol->colFlags & COLFLAG_PRIMKEY ){
2005a0e16a22Sdrh     makeColumnPartOfPrimaryKey(pParse, pCol); /* For the error message */
2006a0e16a22Sdrh   }
200779cf2b71Sdrh   sqlite3ColumnSetExpr(pParse, pTab, pCol, pExpr);
2008b9bcf7caSdrh   pExpr = 0;
200981f7b372Sdrh   goto generated_done;
201081f7b372Sdrh 
201181f7b372Sdrh generated_error:
20127e7fd73bSdrh   sqlite3ErrorMsg(pParse, "error in generated column \"%s\"",
2013cf9d36d1Sdrh                   pCol->zCnName);
201481f7b372Sdrh generated_done:
201581f7b372Sdrh   sqlite3ExprDelete(pParse->db, pExpr);
201681f7b372Sdrh #else
201781f7b372Sdrh   /* Throw and error for the GENERATED ALWAYS AS clause if the
201881f7b372Sdrh   ** SQLITE_OMIT_GENERATED_COLUMNS compile-time option is used. */
20197e7fd73bSdrh   sqlite3ErrorMsg(pParse, "generated columns not supported");
202081f7b372Sdrh   sqlite3ExprDelete(pParse->db, pExpr);
202181f7b372Sdrh #endif
202281f7b372Sdrh }
202381f7b372Sdrh 
2024466be56bSdanielk1977 /*
20253f7d4e49Sdrh ** Generate code that will increment the schema cookie.
202650e5dadfSdrh **
202750e5dadfSdrh ** The schema cookie is used to determine when the schema for the
202850e5dadfSdrh ** database changes.  After each schema change, the cookie value
202950e5dadfSdrh ** changes.  When a process first reads the schema it records the
203050e5dadfSdrh ** cookie.  Thereafter, whenever it goes to access the database,
203150e5dadfSdrh ** it checks the cookie to make sure the schema has not changed
203250e5dadfSdrh ** since it was last read.
203350e5dadfSdrh **
203450e5dadfSdrh ** This plan is not completely bullet-proof.  It is possible for
203550e5dadfSdrh ** the schema to change multiple times and for the cookie to be
203650e5dadfSdrh ** set back to prior value.  But schema changes are infrequent
203750e5dadfSdrh ** and the probability of hitting the same cookie value is only
203850e5dadfSdrh ** 1 chance in 2^32.  So we're safe enough.
203996fdcb40Sdrh **
204096fdcb40Sdrh ** IMPLEMENTATION-OF: R-34230-56049 SQLite automatically increments
204196fdcb40Sdrh ** the schema-version whenever the schema changes.
204250e5dadfSdrh */
sqlite3ChangeCookie(Parse * pParse,int iDb)20439cbf3425Sdrh void sqlite3ChangeCookie(Parse *pParse, int iDb){
20449cbf3425Sdrh   sqlite3 *db = pParse->db;
20459cbf3425Sdrh   Vdbe *v = pParse->pVdbe;
20462120608eSdrh   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
20471861afcdSdrh   sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION,
20483517b312Sdrh                    (int)(1+(unsigned)db->aDb[iDb].pSchema->schema_cookie));
204950e5dadfSdrh }
205050e5dadfSdrh 
205150e5dadfSdrh /*
2052969fa7c1Sdrh ** Measure the number of characters needed to output the given
2053969fa7c1Sdrh ** identifier.  The number returned includes any quotes used
2054969fa7c1Sdrh ** but does not include the null terminator.
2055234c39dfSdrh **
2056234c39dfSdrh ** The estimate is conservative.  It might be larger that what is
2057234c39dfSdrh ** really needed.
2058969fa7c1Sdrh */
identLength(const char * z)2059969fa7c1Sdrh static int identLength(const char *z){
2060969fa7c1Sdrh   int n;
206117f71934Sdrh   for(n=0; *z; n++, z++){
2062234c39dfSdrh     if( *z=='"' ){ n++; }
2063969fa7c1Sdrh   }
2064234c39dfSdrh   return n + 2;
2065969fa7c1Sdrh }
2066969fa7c1Sdrh 
2067969fa7c1Sdrh /*
20681b870de6Sdanielk1977 ** The first parameter is a pointer to an output buffer. The second
20691b870de6Sdanielk1977 ** parameter is a pointer to an integer that contains the offset at
20701b870de6Sdanielk1977 ** which to write into the output buffer. This function copies the
20711b870de6Sdanielk1977 ** nul-terminated string pointed to by the third parameter, zSignedIdent,
20721b870de6Sdanielk1977 ** to the specified offset in the buffer and updates *pIdx to refer
20731b870de6Sdanielk1977 ** to the first byte after the last byte written before returning.
20741b870de6Sdanielk1977 **
20751b870de6Sdanielk1977 ** If the string zSignedIdent consists entirely of alpha-numeric
20761b870de6Sdanielk1977 ** characters, does not begin with a digit and is not an SQL keyword,
20771b870de6Sdanielk1977 ** then it is copied to the output buffer exactly as it is. Otherwise,
20781b870de6Sdanielk1977 ** it is quoted using double-quotes.
20791b870de6Sdanielk1977 */
identPut(char * z,int * pIdx,char * zSignedIdent)2080c4a64facSdrh static void identPut(char *z, int *pIdx, char *zSignedIdent){
20814c755c0fSdrh   unsigned char *zIdent = (unsigned char*)zSignedIdent;
208217f71934Sdrh   int i, j, needQuote;
2083969fa7c1Sdrh   i = *pIdx;
20841b870de6Sdanielk1977 
208517f71934Sdrh   for(j=0; zIdent[j]; j++){
208678ca0e7eSdanielk1977     if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
208717f71934Sdrh   }
2088c7407524Sdrh   needQuote = sqlite3Isdigit(zIdent[0])
2089c7407524Sdrh             || sqlite3KeywordCode(zIdent, j)!=TK_ID
2090c7407524Sdrh             || zIdent[j]!=0
2091c7407524Sdrh             || j==0;
20921b870de6Sdanielk1977 
2093234c39dfSdrh   if( needQuote ) z[i++] = '"';
2094969fa7c1Sdrh   for(j=0; zIdent[j]; j++){
2095969fa7c1Sdrh     z[i++] = zIdent[j];
2096234c39dfSdrh     if( zIdent[j]=='"' ) z[i++] = '"';
2097969fa7c1Sdrh   }
2098234c39dfSdrh   if( needQuote ) z[i++] = '"';
2099969fa7c1Sdrh   z[i] = 0;
2100969fa7c1Sdrh   *pIdx = i;
2101969fa7c1Sdrh }
2102969fa7c1Sdrh 
2103969fa7c1Sdrh /*
2104969fa7c1Sdrh ** Generate a CREATE TABLE statement appropriate for the given
2105969fa7c1Sdrh ** table.  Memory to hold the text of the statement is obtained
2106969fa7c1Sdrh ** from sqliteMalloc() and must be freed by the calling function.
2107969fa7c1Sdrh */
createTableStmt(sqlite3 * db,Table * p)21081d34fdecSdrh static char *createTableStmt(sqlite3 *db, Table *p){
2109969fa7c1Sdrh   int i, k, n;
2110969fa7c1Sdrh   char *zStmt;
2111c4a64facSdrh   char *zSep, *zSep2, *zEnd;
2112234c39dfSdrh   Column *pCol;
2113969fa7c1Sdrh   n = 0;
2114234c39dfSdrh   for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
2115cf9d36d1Sdrh     n += identLength(pCol->zCnName) + 5;
2116969fa7c1Sdrh   }
2117969fa7c1Sdrh   n += identLength(p->zName);
2118234c39dfSdrh   if( n<50 ){
2119969fa7c1Sdrh     zSep = "";
2120969fa7c1Sdrh     zSep2 = ",";
2121969fa7c1Sdrh     zEnd = ")";
2122969fa7c1Sdrh   }else{
2123969fa7c1Sdrh     zSep = "\n  ";
2124969fa7c1Sdrh     zSep2 = ",\n  ";
2125969fa7c1Sdrh     zEnd = "\n)";
2126969fa7c1Sdrh   }
2127e0bc4048Sdrh   n += 35 + 6*p->nCol;
2128b975598eSdrh   zStmt = sqlite3DbMallocRaw(0, n);
2129820a9069Sdrh   if( zStmt==0 ){
21304a642b60Sdrh     sqlite3OomFault(db);
2131820a9069Sdrh     return 0;
2132820a9069Sdrh   }
2133bdb339ffSdrh   sqlite3_snprintf(n, zStmt, "CREATE TABLE ");
2134ea678832Sdrh   k = sqlite3Strlen30(zStmt);
2135c4a64facSdrh   identPut(zStmt, &k, p->zName);
2136969fa7c1Sdrh   zStmt[k++] = '(';
2137234c39dfSdrh   for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
2138c4a64facSdrh     static const char * const azType[] = {
213905883a34Sdrh         /* SQLITE_AFF_BLOB    */ "",
21407ea31ccbSdrh         /* SQLITE_AFF_TEXT    */ " TEXT",
2141c4a64facSdrh         /* SQLITE_AFF_NUMERIC */ " NUM",
2142c4a64facSdrh         /* SQLITE_AFF_INTEGER */ " INT",
2143c4a64facSdrh         /* SQLITE_AFF_REAL    */ " REAL"
2144c4a64facSdrh     };
2145c4a64facSdrh     int len;
2146c4a64facSdrh     const char *zType;
2147c4a64facSdrh 
21485bb3eb9bSdrh     sqlite3_snprintf(n-k, &zStmt[k], zSep);
2149ea678832Sdrh     k += sqlite3Strlen30(&zStmt[k]);
2150969fa7c1Sdrh     zSep = zSep2;
2151cf9d36d1Sdrh     identPut(zStmt, &k, pCol->zCnName);
215205883a34Sdrh     assert( pCol->affinity-SQLITE_AFF_BLOB >= 0 );
215305883a34Sdrh     assert( pCol->affinity-SQLITE_AFF_BLOB < ArraySize(azType) );
215405883a34Sdrh     testcase( pCol->affinity==SQLITE_AFF_BLOB );
21557ea31ccbSdrh     testcase( pCol->affinity==SQLITE_AFF_TEXT );
2156c4a64facSdrh     testcase( pCol->affinity==SQLITE_AFF_NUMERIC );
2157c4a64facSdrh     testcase( pCol->affinity==SQLITE_AFF_INTEGER );
2158c4a64facSdrh     testcase( pCol->affinity==SQLITE_AFF_REAL );
2159c4a64facSdrh 
216005883a34Sdrh     zType = azType[pCol->affinity - SQLITE_AFF_BLOB];
2161c4a64facSdrh     len = sqlite3Strlen30(zType);
216205883a34Sdrh     assert( pCol->affinity==SQLITE_AFF_BLOB
2163fdaac671Sdrh             || pCol->affinity==sqlite3AffinityType(zType, 0) );
2164c4a64facSdrh     memcpy(&zStmt[k], zType, len);
2165c4a64facSdrh     k += len;
2166c4a64facSdrh     assert( k<=n );
2167969fa7c1Sdrh   }
21685bb3eb9bSdrh   sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
2169969fa7c1Sdrh   return zStmt;
2170969fa7c1Sdrh }
2171969fa7c1Sdrh 
2172969fa7c1Sdrh /*
21737f9c5dbfSdrh ** Resize an Index object to hold N columns total.  Return SQLITE_OK
21747f9c5dbfSdrh ** on success and SQLITE_NOMEM on an OOM error.
21757f9c5dbfSdrh */
resizeIndexObject(sqlite3 * db,Index * pIdx,int N)21767f9c5dbfSdrh static int resizeIndexObject(sqlite3 *db, Index *pIdx, int N){
21777f9c5dbfSdrh   char *zExtra;
21787f9c5dbfSdrh   int nByte;
21797f9c5dbfSdrh   if( pIdx->nColumn>=N ) return SQLITE_OK;
21807f9c5dbfSdrh   assert( pIdx->isResized==0 );
2181b5a69238Sdan   nByte = (sizeof(char*) + sizeof(LogEst) + sizeof(i16) + 1)*N;
21827f9c5dbfSdrh   zExtra = sqlite3DbMallocZero(db, nByte);
2183fad3039cSmistachkin   if( zExtra==0 ) return SQLITE_NOMEM_BKPT;
21847f9c5dbfSdrh   memcpy(zExtra, pIdx->azColl, sizeof(char*)*pIdx->nColumn);
2185f19aa5faSdrh   pIdx->azColl = (const char**)zExtra;
21867f9c5dbfSdrh   zExtra += sizeof(char*)*N;
2187b5a69238Sdan   memcpy(zExtra, pIdx->aiRowLogEst, sizeof(LogEst)*(pIdx->nKeyCol+1));
2188b5a69238Sdan   pIdx->aiRowLogEst = (LogEst*)zExtra;
2189b5a69238Sdan   zExtra += sizeof(LogEst)*N;
21907f9c5dbfSdrh   memcpy(zExtra, pIdx->aiColumn, sizeof(i16)*pIdx->nColumn);
21917f9c5dbfSdrh   pIdx->aiColumn = (i16*)zExtra;
21927f9c5dbfSdrh   zExtra += sizeof(i16)*N;
21937f9c5dbfSdrh   memcpy(zExtra, pIdx->aSortOrder, pIdx->nColumn);
21947f9c5dbfSdrh   pIdx->aSortOrder = (u8*)zExtra;
21957f9c5dbfSdrh   pIdx->nColumn = N;
21967f9c5dbfSdrh   pIdx->isResized = 1;
21977f9c5dbfSdrh   return SQLITE_OK;
21987f9c5dbfSdrh }
21997f9c5dbfSdrh 
22007f9c5dbfSdrh /*
2201fdaac671Sdrh ** Estimate the total row width for a table.
2202fdaac671Sdrh */
estimateTableWidth(Table * pTab)2203e13e9f54Sdrh static void estimateTableWidth(Table *pTab){
2204fdaac671Sdrh   unsigned wTable = 0;
2205fdaac671Sdrh   const Column *pTabCol;
2206fdaac671Sdrh   int i;
2207fdaac671Sdrh   for(i=pTab->nCol, pTabCol=pTab->aCol; i>0; i--, pTabCol++){
2208fdaac671Sdrh     wTable += pTabCol->szEst;
2209fdaac671Sdrh   }
2210fdaac671Sdrh   if( pTab->iPKey<0 ) wTable++;
2211e13e9f54Sdrh   pTab->szTabRow = sqlite3LogEst(wTable*4);
2212fdaac671Sdrh }
2213fdaac671Sdrh 
2214fdaac671Sdrh /*
2215e13e9f54Sdrh ** Estimate the average size of a row for an index.
2216fdaac671Sdrh */
estimateIndexWidth(Index * pIdx)2217e13e9f54Sdrh static void estimateIndexWidth(Index *pIdx){
2218bbbdc83bSdrh   unsigned wIndex = 0;
2219fdaac671Sdrh   int i;
2220fdaac671Sdrh   const Column *aCol = pIdx->pTable->aCol;
2221fdaac671Sdrh   for(i=0; i<pIdx->nColumn; i++){
2222bbbdc83bSdrh     i16 x = pIdx->aiColumn[i];
2223bbbdc83bSdrh     assert( x<pIdx->pTable->nCol );
2224bbbdc83bSdrh     wIndex += x<0 ? 1 : aCol[pIdx->aiColumn[i]].szEst;
2225fdaac671Sdrh   }
2226e13e9f54Sdrh   pIdx->szIdxRow = sqlite3LogEst(wIndex*4);
2227fdaac671Sdrh }
2228fdaac671Sdrh 
2229f78d0f42Sdrh /* Return true if column number x is any of the first nCol entries of aiCol[].
2230f78d0f42Sdrh ** This is used to determine if the column number x appears in any of the
2231f78d0f42Sdrh ** first nCol entries of an index.
22327f9c5dbfSdrh */
hasColumn(const i16 * aiCol,int nCol,int x)22337f9c5dbfSdrh static int hasColumn(const i16 *aiCol, int nCol, int x){
2234f78d0f42Sdrh   while( nCol-- > 0 ){
2235f78d0f42Sdrh     if( x==*(aiCol++) ){
2236f78d0f42Sdrh       return 1;
2237f78d0f42Sdrh     }
2238f78d0f42Sdrh   }
2239f78d0f42Sdrh   return 0;
2240f78d0f42Sdrh }
2241f78d0f42Sdrh 
2242f78d0f42Sdrh /*
2243c19b63c9Sdrh ** Return true if any of the first nKey entries of index pIdx exactly
2244c19b63c9Sdrh ** match the iCol-th entry of pPk.  pPk is always a WITHOUT ROWID
2245c19b63c9Sdrh ** PRIMARY KEY index.  pIdx is an index on the same table.  pIdx may
2246c19b63c9Sdrh ** or may not be the same index as pPk.
2247f78d0f42Sdrh **
2248c19b63c9Sdrh ** The first nKey entries of pIdx are guaranteed to be ordinary columns,
2249f78d0f42Sdrh ** not a rowid or expression.
2250f78d0f42Sdrh **
2251f78d0f42Sdrh ** This routine differs from hasColumn() in that both the column and the
2252f78d0f42Sdrh ** collating sequence must match for this routine, but for hasColumn() only
2253f78d0f42Sdrh ** the column name must match.
2254f78d0f42Sdrh */
isDupColumn(Index * pIdx,int nKey,Index * pPk,int iCol)2255c19b63c9Sdrh static int isDupColumn(Index *pIdx, int nKey, Index *pPk, int iCol){
2256f78d0f42Sdrh   int i, j;
2257c19b63c9Sdrh   assert( nKey<=pIdx->nColumn );
2258c19b63c9Sdrh   assert( iCol<MAX(pPk->nColumn,pPk->nKeyCol) );
2259c19b63c9Sdrh   assert( pPk->idxType==SQLITE_IDXTYPE_PRIMARYKEY );
2260c19b63c9Sdrh   assert( pPk->pTable->tabFlags & TF_WithoutRowid );
2261c19b63c9Sdrh   assert( pPk->pTable==pIdx->pTable );
2262c19b63c9Sdrh   testcase( pPk==pIdx );
2263c19b63c9Sdrh   j = pPk->aiColumn[iCol];
2264c19b63c9Sdrh   assert( j!=XN_ROWID && j!=XN_EXPR );
2265f78d0f42Sdrh   for(i=0; i<nKey; i++){
2266c19b63c9Sdrh     assert( pIdx->aiColumn[i]>=0 || j>=0 );
2267c19b63c9Sdrh     if( pIdx->aiColumn[i]==j
2268c19b63c9Sdrh      && sqlite3StrICmp(pIdx->azColl[i], pPk->azColl[iCol])==0
2269f78d0f42Sdrh     ){
2270f78d0f42Sdrh       return 1;
2271f78d0f42Sdrh     }
2272f78d0f42Sdrh   }
22737f9c5dbfSdrh   return 0;
22747f9c5dbfSdrh }
22757f9c5dbfSdrh 
22761fe3ac73Sdrh /* Recompute the colNotIdxed field of the Index.
22771fe3ac73Sdrh **
22781fe3ac73Sdrh ** colNotIdxed is a bitmask that has a 0 bit representing each indexed
2279*5723c659Sdrh ** columns that are within the first 63 columns of the table and a 1 for
2280*5723c659Sdrh ** all other bits (all columns that are not in the index).  The
22811fe3ac73Sdrh ** high-order bit of colNotIdxed is always 1.  All unindexed columns
22821fe3ac73Sdrh ** of the table have a 1.
22831fe3ac73Sdrh **
2284c7476735Sdrh ** 2019-10-24:  For the purpose of this computation, virtual columns are
2285c7476735Sdrh ** not considered to be covered by the index, even if they are in the
2286c7476735Sdrh ** index, because we do not trust the logic in whereIndexExprTrans() to be
2287c7476735Sdrh ** able to find all instances of a reference to the indexed table column
2288c7476735Sdrh ** and convert them into references to the index.  Hence we always want
2289c7476735Sdrh ** the actual table at hand in order to recompute the virtual column, if
2290c7476735Sdrh ** necessary.
2291c7476735Sdrh **
22921fe3ac73Sdrh ** The colNotIdxed mask is AND-ed with the SrcList.a[].colUsed mask
22931fe3ac73Sdrh ** to determine if the index is covering index.
22941fe3ac73Sdrh */
recomputeColumnsNotIndexed(Index * pIdx)22951fe3ac73Sdrh static void recomputeColumnsNotIndexed(Index *pIdx){
22961fe3ac73Sdrh   Bitmask m = 0;
22971fe3ac73Sdrh   int j;
2298c7476735Sdrh   Table *pTab = pIdx->pTable;
22991fe3ac73Sdrh   for(j=pIdx->nColumn-1; j>=0; j--){
23001fe3ac73Sdrh     int x = pIdx->aiColumn[j];
2301c7476735Sdrh     if( x>=0 && (pTab->aCol[x].colFlags & COLFLAG_VIRTUAL)==0 ){
23021fe3ac73Sdrh       testcase( x==BMS-1 );
23031fe3ac73Sdrh       testcase( x==BMS-2 );
23041fe3ac73Sdrh       if( x<BMS-1 ) m |= MASKBIT(x);
23051fe3ac73Sdrh     }
23061fe3ac73Sdrh   }
23071fe3ac73Sdrh   pIdx->colNotIdxed = ~m;
2308*5723c659Sdrh   assert( (pIdx->colNotIdxed>>63)==1 );  /* See note-20221022-a */
23091fe3ac73Sdrh }
23101fe3ac73Sdrh 
23117f9c5dbfSdrh /*
2312c6bd4e4aSdrh ** This routine runs at the end of parsing a CREATE TABLE statement that
2313c6bd4e4aSdrh ** has a WITHOUT ROWID clause.  The job of this routine is to convert both
2314c6bd4e4aSdrh ** internal schema data structures and the generated VDBE code so that they
2315c6bd4e4aSdrh ** are appropriate for a WITHOUT ROWID table instead of a rowid table.
2316c6bd4e4aSdrh ** Changes include:
23177f9c5dbfSdrh **
231862340f84Sdrh **     (1)  Set all columns of the PRIMARY KEY schema object to be NOT NULL.
23190f3f7664Sdrh **     (2)  Convert P3 parameter of the OP_CreateBtree from BTREE_INTKEY
23200f3f7664Sdrh **          into BTREE_BLOBKEY.
23211e32bed3Sdrh **     (3)  Bypass the creation of the sqlite_schema table entry
232260ec914cSpeter.d.reid **          for the PRIMARY KEY as the primary key index is now
23231e32bed3Sdrh **          identified by the sqlite_schema table entry of the table itself.
232462340f84Sdrh **     (4)  Set the Index.tnum of the PRIMARY KEY Index object in the
2325c6bd4e4aSdrh **          schema to the rootpage from the main table.
2326c6bd4e4aSdrh **     (5)  Add all table columns to the PRIMARY KEY Index object
2327c6bd4e4aSdrh **          so that the PRIMARY KEY is a covering index.  The surplus
2328a485ad19Sdrh **          columns are part of KeyInfo.nAllField and are not used for
2329c6bd4e4aSdrh **          sorting or lookup or uniqueness checks.
2330c6bd4e4aSdrh **     (6)  Replace the rowid tail on all automatically generated UNIQUE
2331c6bd4e4aSdrh **          indices with the PRIMARY KEY columns.
233262340f84Sdrh **
233362340f84Sdrh ** For virtual tables, only (1) is performed.
23347f9c5dbfSdrh */
convertToWithoutRowidTable(Parse * pParse,Table * pTab)23357f9c5dbfSdrh static void convertToWithoutRowidTable(Parse *pParse, Table *pTab){
23367f9c5dbfSdrh   Index *pIdx;
23377f9c5dbfSdrh   Index *pPk;
23387f9c5dbfSdrh   int nPk;
23391ff94071Sdan   int nExtra;
23407f9c5dbfSdrh   int i, j;
23417f9c5dbfSdrh   sqlite3 *db = pParse->db;
2342c6bd4e4aSdrh   Vdbe *v = pParse->pVdbe;
23437f9c5dbfSdrh 
234462340f84Sdrh   /* Mark every PRIMARY KEY column as NOT NULL (except for imposter tables)
234562340f84Sdrh   */
234662340f84Sdrh   if( !db->init.imposterTable ){
234762340f84Sdrh     for(i=0; i<pTab->nCol; i++){
2348fd46ec64Sdrh       if( (pTab->aCol[i].colFlags & COLFLAG_PRIMKEY)!=0
2349fd46ec64Sdrh        && (pTab->aCol[i].notNull==OE_None)
2350fd46ec64Sdrh       ){
235162340f84Sdrh         pTab->aCol[i].notNull = OE_Abort;
235262340f84Sdrh       }
235362340f84Sdrh     }
2354cbda9c7aSdrh     pTab->tabFlags |= TF_HasNotNull;
235562340f84Sdrh   }
235662340f84Sdrh 
23570f3f7664Sdrh   /* Convert the P3 operand of the OP_CreateBtree opcode from BTREE_INTKEY
23580f3f7664Sdrh   ** into BTREE_BLOBKEY.
23597f9c5dbfSdrh   */
2360381bdaccSdrh   assert( !pParse->bReturning );
2361381bdaccSdrh   if( pParse->u1.addrCrTab ){
2362c6bd4e4aSdrh     assert( v );
2363381bdaccSdrh     sqlite3VdbeChangeP3(v, pParse->u1.addrCrTab, BTREE_BLOBKEY);
2364c6bd4e4aSdrh   }
2365c6bd4e4aSdrh 
23667f9c5dbfSdrh   /* Locate the PRIMARY KEY index.  Or, if this table was originally
23677f9c5dbfSdrh   ** an INTEGER PRIMARY KEY table, create a new PRIMARY KEY index.
23687f9c5dbfSdrh   */
23697f9c5dbfSdrh   if( pTab->iPKey>=0 ){
23707f9c5dbfSdrh     ExprList *pList;
2371108aa00aSdrh     Token ipkToken;
2372cf9d36d1Sdrh     sqlite3TokenInit(&ipkToken, pTab->aCol[pTab->iPKey].zCnName);
2373108aa00aSdrh     pList = sqlite3ExprListAppend(pParse, 0,
2374108aa00aSdrh                   sqlite3ExprAlloc(db, TK_ID, &ipkToken, 0));
23751bb89e9cSdrh     if( pList==0 ){
23761bb89e9cSdrh       pTab->tabFlags &= ~TF_WithoutRowid;
23771bb89e9cSdrh       return;
23781bb89e9cSdrh     }
2379f9b0c451Sdan     if( IN_RENAME_OBJECT ){
2380f9b0c451Sdan       sqlite3RenameTokenRemap(pParse, pList->a[0].pExpr, &pTab->iPKey);
2381f9b0c451Sdan     }
2382d88fd539Sdrh     pList->a[0].fg.sortFlags = pParse->iPkSortOrder;
23837f9c5dbfSdrh     assert( pParse->pNewTable==pTab );
2384f9b0c451Sdan     pTab->iPKey = -1;
238562340f84Sdrh     sqlite3CreateIndex(pParse, 0, 0, 0, pList, pTab->keyConf, 0, 0, 0, 0,
238662340f84Sdrh                        SQLITE_IDXTYPE_PRIMARYKEY);
23870c7d3d39Sdrh     if( pParse->nErr ){
23883bb9d75aSdrh       pTab->tabFlags &= ~TF_WithoutRowid;
23893bb9d75aSdrh       return;
23903bb9d75aSdrh     }
23910c7d3d39Sdrh     assert( db->mallocFailed==0 );
239262340f84Sdrh     pPk = sqlite3PrimaryKeyIndex(pTab);
23931ff94071Sdan     assert( pPk->nKeyCol==1 );
23944415628aSdrh   }else{
23954415628aSdrh     pPk = sqlite3PrimaryKeyIndex(pTab);
2396f0c48b1cSdrh     assert( pPk!=0 );
2397c5b73585Sdan 
2398e385d887Sdrh     /*
2399e385d887Sdrh     ** Remove all redundant columns from the PRIMARY KEY.  For example, change
2400e385d887Sdrh     ** "PRIMARY KEY(a,b,a,b,c,b,c,d)" into just "PRIMARY KEY(a,b,c,d)".  Later
2401e385d887Sdrh     ** code assumes the PRIMARY KEY contains no repeated columns.
2402e385d887Sdrh     */
2403e385d887Sdrh     for(i=j=1; i<pPk->nKeyCol; i++){
2404f78d0f42Sdrh       if( isDupColumn(pPk, j, pPk, i) ){
2405e385d887Sdrh         pPk->nColumn--;
2406e385d887Sdrh       }else{
2407f78d0f42Sdrh         testcase( hasColumn(pPk->aiColumn, j, pPk->aiColumn[i]) );
24081ff94071Sdan         pPk->azColl[j] = pPk->azColl[i];
24091ff94071Sdan         pPk->aSortOrder[j] = pPk->aSortOrder[i];
2410e385d887Sdrh         pPk->aiColumn[j++] = pPk->aiColumn[i];
2411e385d887Sdrh       }
2412e385d887Sdrh     }
2413e385d887Sdrh     pPk->nKeyCol = j;
24147f9c5dbfSdrh   }
24157f9c5dbfSdrh   assert( pPk!=0 );
241662340f84Sdrh   pPk->isCovering = 1;
241762340f84Sdrh   if( !db->init.imposterTable ) pPk->uniqNotNull = 1;
24181ff94071Sdan   nPk = pPk->nColumn = pPk->nKeyCol;
24197f9c5dbfSdrh 
24201e32bed3Sdrh   /* Bypass the creation of the PRIMARY KEY btree and the sqlite_schema
2421df94966cSdrh   ** table entry. This is only required if currently generating VDBE
2422df94966cSdrh   ** code for a CREATE TABLE (not when parsing one as part of reading
2423df94966cSdrh   ** a database schema).  */
2424df94966cSdrh   if( v && pPk->tnum>0 ){
2425df94966cSdrh     assert( db->init.busy==0 );
2426abc38158Sdrh     sqlite3VdbeChangeOpcode(v, (int)pPk->tnum, OP_Goto);
2427df94966cSdrh   }
2428df94966cSdrh 
2429c6bd4e4aSdrh   /* The root page of the PRIMARY KEY is the table root page */
2430c6bd4e4aSdrh   pPk->tnum = pTab->tnum;
2431c6bd4e4aSdrh 
24327f9c5dbfSdrh   /* Update the in-memory representation of all UNIQUE indices by converting
24337f9c5dbfSdrh   ** the final rowid column into one or more columns of the PRIMARY KEY.
24347f9c5dbfSdrh   */
24357f9c5dbfSdrh   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
24367f9c5dbfSdrh     int n;
243748dd1d8eSdrh     if( IsPrimaryKeyIndex(pIdx) ) continue;
24387f9c5dbfSdrh     for(i=n=0; i<nPk; i++){
2439f78d0f42Sdrh       if( !isDupColumn(pIdx, pIdx->nKeyCol, pPk, i) ){
2440f78d0f42Sdrh         testcase( hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) );
2441f78d0f42Sdrh         n++;
2442f78d0f42Sdrh       }
24437f9c5dbfSdrh     }
24445a9a37b7Sdrh     if( n==0 ){
24455a9a37b7Sdrh       /* This index is a superset of the primary key */
24465a9a37b7Sdrh       pIdx->nColumn = pIdx->nKeyCol;
24475a9a37b7Sdrh       continue;
24485a9a37b7Sdrh     }
24497f9c5dbfSdrh     if( resizeIndexObject(db, pIdx, pIdx->nKeyCol+n) ) return;
24507f9c5dbfSdrh     for(i=0, j=pIdx->nKeyCol; i<nPk; i++){
2451f78d0f42Sdrh       if( !isDupColumn(pIdx, pIdx->nKeyCol, pPk, i) ){
2452f78d0f42Sdrh         testcase( hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) );
24537f9c5dbfSdrh         pIdx->aiColumn[j] = pPk->aiColumn[i];
24547f9c5dbfSdrh         pIdx->azColl[j] = pPk->azColl[i];
2455bf9ff256Sdrh         if( pPk->aSortOrder[i] ){
2456bf9ff256Sdrh           /* See ticket https://www.sqlite.org/src/info/bba7b69f9849b5bf */
2457bf9ff256Sdrh           pIdx->bAscKeyBug = 1;
2458bf9ff256Sdrh         }
24597f9c5dbfSdrh         j++;
24607f9c5dbfSdrh       }
24617f9c5dbfSdrh     }
246200012df4Sdrh     assert( pIdx->nColumn>=pIdx->nKeyCol+n );
246300012df4Sdrh     assert( pIdx->nColumn>=j );
24647f9c5dbfSdrh   }
24657f9c5dbfSdrh 
24667f9c5dbfSdrh   /* Add all table columns to the PRIMARY KEY index
24677f9c5dbfSdrh   */
24681ff94071Sdan   nExtra = 0;
24691ff94071Sdan   for(i=0; i<pTab->nCol; i++){
24708e10d74bSdrh     if( !hasColumn(pPk->aiColumn, nPk, i)
24718e10d74bSdrh      && (pTab->aCol[i].colFlags & COLFLAG_VIRTUAL)==0 ) nExtra++;
24721ff94071Sdan   }
24731ff94071Sdan   if( resizeIndexObject(db, pPk, nPk+nExtra) ) return;
24747f9c5dbfSdrh   for(i=0, j=nPk; i<pTab->nCol; i++){
24758e10d74bSdrh     if( !hasColumn(pPk->aiColumn, j, i)
24768e10d74bSdrh      && (pTab->aCol[i].colFlags & COLFLAG_VIRTUAL)==0
24778e10d74bSdrh     ){
24787f9c5dbfSdrh       assert( j<pPk->nColumn );
24797f9c5dbfSdrh       pPk->aiColumn[j] = i;
2480f19aa5faSdrh       pPk->azColl[j] = sqlite3StrBINARY;
24817f9c5dbfSdrh       j++;
24827f9c5dbfSdrh     }
24837f9c5dbfSdrh   }
24847f9c5dbfSdrh   assert( pPk->nColumn==j );
24858e10d74bSdrh   assert( pTab->nNVCol<=j );
24861fe3ac73Sdrh   recomputeColumnsNotIndexed(pPk);
24877f9c5dbfSdrh }
24887f9c5dbfSdrh 
24893d863b5eSdrh 
24903d863b5eSdrh #ifndef SQLITE_OMIT_VIRTUALTABLE
24913d863b5eSdrh /*
24923d863b5eSdrh ** Return true if pTab is a virtual table and zName is a shadow table name
24933d863b5eSdrh ** for that virtual table.
24943d863b5eSdrh */
sqlite3IsShadowTableOf(sqlite3 * db,Table * pTab,const char * zName)24953d863b5eSdrh int sqlite3IsShadowTableOf(sqlite3 *db, Table *pTab, const char *zName){
24963d863b5eSdrh   int nName;                    /* Length of zName */
24973d863b5eSdrh   Module *pMod;                 /* Module for the virtual table */
24983d863b5eSdrh 
24993d863b5eSdrh   if( !IsVirtual(pTab) ) return 0;
25003d863b5eSdrh   nName = sqlite3Strlen30(pTab->zName);
25013d863b5eSdrh   if( sqlite3_strnicmp(zName, pTab->zName, nName)!=0 ) return 0;
25023d863b5eSdrh   if( zName[nName]!='_' ) return 0;
2503f38524d2Sdrh   pMod = (Module*)sqlite3HashFind(&db->aModule, pTab->u.vtab.azArg[0]);
25043d863b5eSdrh   if( pMod==0 ) return 0;
25053d863b5eSdrh   if( pMod->pModule->iVersion<3 ) return 0;
25063d863b5eSdrh   if( pMod->pModule->xShadowName==0 ) return 0;
25073d863b5eSdrh   return pMod->pModule->xShadowName(zName+nName+1);
25083d863b5eSdrh }
25093d863b5eSdrh #endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
25103d863b5eSdrh 
2511f6e015faSdan #ifndef SQLITE_OMIT_VIRTUALTABLE
2512fdaac671Sdrh /*
2513ddfec00dSdrh ** Table pTab is a virtual table.  If it the virtual table implementation
2514ddfec00dSdrh ** exists and has an xShadowName method, then loop over all other ordinary
2515ddfec00dSdrh ** tables within the same schema looking for shadow tables of pTab, and mark
2516ddfec00dSdrh ** any shadow tables seen using the TF_Shadow flag.
2517ddfec00dSdrh */
sqlite3MarkAllShadowTablesOf(sqlite3 * db,Table * pTab)2518ddfec00dSdrh void sqlite3MarkAllShadowTablesOf(sqlite3 *db, Table *pTab){
2519ddfec00dSdrh   int nName;                    /* Length of pTab->zName */
2520ddfec00dSdrh   Module *pMod;                 /* Module for the virtual table */
2521ddfec00dSdrh   HashElem *k;                  /* For looping through the symbol table */
2522ddfec00dSdrh 
2523ddfec00dSdrh   assert( IsVirtual(pTab) );
2524ddfec00dSdrh   pMod = (Module*)sqlite3HashFind(&db->aModule, pTab->u.vtab.azArg[0]);
2525ddfec00dSdrh   if( pMod==0 ) return;
2526ddfec00dSdrh   if( NEVER(pMod->pModule==0) ) return;
252762561b82Sdrh   if( pMod->pModule->iVersion<3 ) return;
2528ddfec00dSdrh   if( pMod->pModule->xShadowName==0 ) return;
2529ddfec00dSdrh   assert( pTab->zName!=0 );
2530ddfec00dSdrh   nName = sqlite3Strlen30(pTab->zName);
2531ddfec00dSdrh   for(k=sqliteHashFirst(&pTab->pSchema->tblHash); k; k=sqliteHashNext(k)){
2532ddfec00dSdrh     Table *pOther = sqliteHashData(k);
2533ddfec00dSdrh     assert( pOther->zName!=0 );
2534ddfec00dSdrh     if( !IsOrdinaryTable(pOther) ) continue;
2535ddfec00dSdrh     if( pOther->tabFlags & TF_Shadow ) continue;
2536ddfec00dSdrh     if( sqlite3StrNICmp(pOther->zName, pTab->zName, nName)==0
2537ddfec00dSdrh      && pOther->zName[nName]=='_'
2538ddfec00dSdrh      && pMod->pModule->xShadowName(pOther->zName+nName+1)
2539ddfec00dSdrh     ){
2540ddfec00dSdrh       pOther->tabFlags |= TF_Shadow;
2541ddfec00dSdrh     }
2542ddfec00dSdrh   }
2543ddfec00dSdrh }
2544ddfec00dSdrh #endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
2545ddfec00dSdrh 
2546ddfec00dSdrh #ifndef SQLITE_OMIT_VIRTUALTABLE
2547ddfec00dSdrh /*
254884c501baSdrh ** Return true if zName is a shadow table name in the current database
254984c501baSdrh ** connection.
255084c501baSdrh **
255184c501baSdrh ** zName is temporarily modified while this routine is running, but is
255284c501baSdrh ** restored to its original value prior to this routine returning.
255384c501baSdrh */
sqlite3ShadowTableName(sqlite3 * db,const char * zName)2554527cbd4aSdrh int sqlite3ShadowTableName(sqlite3 *db, const char *zName){
255584c501baSdrh   char *zTail;                  /* Pointer to the last "_" in zName */
255684c501baSdrh   Table *pTab;                  /* Table that zName is a shadow of */
255784c501baSdrh   zTail = strrchr(zName, '_');
255884c501baSdrh   if( zTail==0 ) return 0;
255984c501baSdrh   *zTail = 0;
256084c501baSdrh   pTab = sqlite3FindTable(db, zName, 0);
256184c501baSdrh   *zTail = '_';
256284c501baSdrh   if( pTab==0 ) return 0;
256384c501baSdrh   if( !IsVirtual(pTab) ) return 0;
25643d863b5eSdrh   return sqlite3IsShadowTableOf(db, pTab, zName);
256584c501baSdrh }
2566f6e015faSdan #endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
256784c501baSdrh 
25683d863b5eSdrh 
2569e7375bfaSdrh #ifdef SQLITE_DEBUG
2570e7375bfaSdrh /*
2571e7375bfaSdrh ** Mark all nodes of an expression as EP_Immutable, indicating that
2572e7375bfaSdrh ** they should not be changed.  Expressions attached to a table or
2573e7375bfaSdrh ** index definition are tagged this way to help ensure that we do
2574e7375bfaSdrh ** not pass them into code generator routines by mistake.
2575e7375bfaSdrh */
markImmutableExprStep(Walker * pWalker,Expr * pExpr)2576e7375bfaSdrh static int markImmutableExprStep(Walker *pWalker, Expr *pExpr){
2577e7375bfaSdrh   ExprSetVVAProperty(pExpr, EP_Immutable);
2578e7375bfaSdrh   return WRC_Continue;
2579e7375bfaSdrh }
markExprListImmutable(ExprList * pList)2580e7375bfaSdrh static void markExprListImmutable(ExprList *pList){
2581e7375bfaSdrh   if( pList ){
2582e7375bfaSdrh     Walker w;
2583e7375bfaSdrh     memset(&w, 0, sizeof(w));
2584e7375bfaSdrh     w.xExprCallback = markImmutableExprStep;
2585e7375bfaSdrh     w.xSelectCallback = sqlite3SelectWalkNoop;
2586e7375bfaSdrh     w.xSelectCallback2 = 0;
2587e7375bfaSdrh     sqlite3WalkExprList(&w, pList);
2588e7375bfaSdrh   }
2589e7375bfaSdrh }
2590e7375bfaSdrh #else
2591e7375bfaSdrh #define markExprListImmutable(X)  /* no-op */
2592e7375bfaSdrh #endif /* SQLITE_DEBUG */
2593e7375bfaSdrh 
2594e7375bfaSdrh 
259584c501baSdrh /*
259675897234Sdrh ** This routine is called to report the final ")" that terminates
259775897234Sdrh ** a CREATE TABLE statement.
259875897234Sdrh **
2599f57b3399Sdrh ** The table structure that other action routines have been building
2600f57b3399Sdrh ** is added to the internal hash tables, assuming no errors have
2601f57b3399Sdrh ** occurred.
260275897234Sdrh **
2603067b92baSdrh ** An entry for the table is made in the schema table on disk, unless
26041d85d931Sdrh ** this is a temporary table or db->init.busy==1.  When db->init.busy==1
26051e32bed3Sdrh ** it means we are reading the sqlite_schema table because we just
26061e32bed3Sdrh ** connected to the database or because the sqlite_schema table has
2607ddba9e54Sdrh ** recently changed, so the entry for this table already exists in
26081e32bed3Sdrh ** the sqlite_schema table.  We do not want to create it again.
2609969fa7c1Sdrh **
2610969fa7c1Sdrh ** If the pSelect argument is not NULL, it means that this routine
2611969fa7c1Sdrh ** was called to create a table generated from a
2612969fa7c1Sdrh ** "CREATE TABLE ... AS SELECT ..." statement.  The column names of
2613969fa7c1Sdrh ** the new table will match the result set of the SELECT.
261475897234Sdrh */
sqlite3EndTable(Parse * pParse,Token * pCons,Token * pEnd,u32 tabOpts,Select * pSelect)261519a8e7e8Sdanielk1977 void sqlite3EndTable(
261619a8e7e8Sdanielk1977   Parse *pParse,          /* Parse context */
261719a8e7e8Sdanielk1977   Token *pCons,           /* The ',' token after the last column defn. */
26185969da4aSdrh   Token *pEnd,            /* The ')' before options in the CREATE TABLE */
261944183f83Sdrh   u32 tabOpts,            /* Extra table options. Usually 0. */
262019a8e7e8Sdanielk1977   Select *pSelect         /* Select from a "CREATE ... AS SELECT" */
262119a8e7e8Sdanielk1977 ){
2622fdaac671Sdrh   Table *p;                 /* The new table */
2623fdaac671Sdrh   sqlite3 *db = pParse->db; /* The database connection */
2624fdaac671Sdrh   int iDb;                  /* Database in which the table lives */
2625fdaac671Sdrh   Index *pIdx;              /* An implied index of the table */
262675897234Sdrh 
2627027616d4Sdrh   if( pEnd==0 && pSelect==0 ){
26285969da4aSdrh     return;
2629261919ccSdanielk1977   }
26302803757aSdrh   p = pParse->pNewTable;
26315969da4aSdrh   if( p==0 ) return;
263275897234Sdrh 
2633527cbd4aSdrh   if( pSelect==0 && sqlite3ShadowTableName(db, p->zName) ){
263484c501baSdrh     p->tabFlags |= TF_Shadow;
263584c501baSdrh   }
263684c501baSdrh 
2637c6bd4e4aSdrh   /* If the db->init.busy is 1 it means we are reading the SQL off the
26381e32bed3Sdrh   ** "sqlite_schema" or "sqlite_temp_schema" table on the disk.
2639c6bd4e4aSdrh   ** So do not write to the disk again.  Extract the root page number
2640c6bd4e4aSdrh   ** for the table from the db->init.newTnum field.  (The page number
2641c6bd4e4aSdrh   ** should have been put there by the sqliteOpenCb routine.)
2642055f298aSdrh   **
26431e32bed3Sdrh   ** If the root page number is 1, that means this is the sqlite_schema
2644055f298aSdrh   ** table itself.  So mark it read-only.
2645c6bd4e4aSdrh   */
2646c6bd4e4aSdrh   if( db->init.busy ){
264754e3f94eSdrh     if( pSelect || (!IsOrdinaryTable(p) && db->init.newTnum) ){
26481e9c47beSdrh       sqlite3ErrorMsg(pParse, "");
26491e9c47beSdrh       return;
26501e9c47beSdrh     }
2651c6bd4e4aSdrh     p->tnum = db->init.newTnum;
2652055f298aSdrh     if( p->tnum==1 ) p->tabFlags |= TF_Readonly;
2653c6bd4e4aSdrh   }
2654c6bd4e4aSdrh 
265571c770fbSdrh   /* Special processing for tables that include the STRICT keyword:
265671c770fbSdrh   **
265771c770fbSdrh   **   *  Do not allow custom column datatypes.  Every column must have
265871c770fbSdrh   **      a datatype that is one of INT, INTEGER, REAL, TEXT, or BLOB.
265971c770fbSdrh   **
266071c770fbSdrh   **   *  If a PRIMARY KEY is defined, other than the INTEGER PRIMARY KEY,
266171c770fbSdrh   **      then all columns of the PRIMARY KEY must have a NOT NULL
266271c770fbSdrh   **      constraint.
266371c770fbSdrh   */
266444183f83Sdrh   if( tabOpts & TF_Strict ){
266544183f83Sdrh     int ii;
266644183f83Sdrh     p->tabFlags |= TF_Strict;
266744183f83Sdrh     for(ii=0; ii<p->nCol; ii++){
2668ab16578bSdrh       Column *pCol = &p->aCol[ii];
2669b9fd0101Sdrh       if( pCol->eCType==COLTYPE_CUSTOM ){
2670b9fd0101Sdrh         if( pCol->colFlags & COLFLAG_HASTYPE ){
267144183f83Sdrh           sqlite3ErrorMsg(pParse,
267244183f83Sdrh             "unknown datatype for %s.%s: \"%s\"",
2673ab16578bSdrh             p->zName, pCol->zCnName, sqlite3ColumnType(pCol, "")
267444183f83Sdrh           );
2675b9fd0101Sdrh         }else{
2676b9fd0101Sdrh           sqlite3ErrorMsg(pParse, "missing datatype for %s.%s",
2677b9fd0101Sdrh                           p->zName, pCol->zCnName);
2678b9fd0101Sdrh         }
267944183f83Sdrh         return;
2680b9fd0101Sdrh       }else if( pCol->eCType==COLTYPE_ANY ){
2681b9fd0101Sdrh         pCol->affinity = SQLITE_AFF_BLOB;
268244183f83Sdrh       }
2683ab16578bSdrh       if( (pCol->colFlags & COLFLAG_PRIMKEY)!=0
2684ab16578bSdrh        && p->iPKey!=ii
2685ab16578bSdrh        && pCol->notNull == OE_None
2686ab16578bSdrh       ){
2687ab16578bSdrh         pCol->notNull = OE_Abort;
2688ab16578bSdrh         p->tabFlags |= TF_HasNotNull;
2689ab16578bSdrh       }
269044183f83Sdrh     }
269144183f83Sdrh   }
269244183f83Sdrh 
26933cbd2b72Sdrh   assert( (p->tabFlags & TF_HasPrimaryKey)==0
26943cbd2b72Sdrh        || p->iPKey>=0 || sqlite3PrimaryKeyIndex(p)!=0 );
26953cbd2b72Sdrh   assert( (p->tabFlags & TF_HasPrimaryKey)!=0
26963cbd2b72Sdrh        || (p->iPKey<0 && sqlite3PrimaryKeyIndex(p)==0) );
26973cbd2b72Sdrh 
2698c6bd4e4aSdrh   /* Special processing for WITHOUT ROWID Tables */
26995969da4aSdrh   if( tabOpts & TF_WithoutRowid ){
2700d2fe3358Sdrh     if( (p->tabFlags & TF_Autoincrement) ){
2701d2fe3358Sdrh       sqlite3ErrorMsg(pParse,
2702d2fe3358Sdrh           "AUTOINCREMENT not allowed on WITHOUT ROWID tables");
2703d2fe3358Sdrh       return;
2704d2fe3358Sdrh     }
270581eba73eSdrh     if( (p->tabFlags & TF_HasPrimaryKey)==0 ){
2706d2fe3358Sdrh       sqlite3ErrorMsg(pParse, "PRIMARY KEY missing on table %s", p->zName);
27078e10d74bSdrh       return;
27088e10d74bSdrh     }
2709fccda8a1Sdrh     p->tabFlags |= TF_WithoutRowid | TF_NoVisibleRowid;
27107f9c5dbfSdrh     convertToWithoutRowidTable(pParse, p);
27117f9c5dbfSdrh   }
2712b9bb7c18Sdrh   iDb = sqlite3SchemaToIndex(db, p->pSchema);
2713da184236Sdanielk1977 
2714ffe07b2dSdrh #ifndef SQLITE_OMIT_CHECK
2715ffe07b2dSdrh   /* Resolve names in all CHECK constraint expressions.
2716ffe07b2dSdrh   */
2717ffe07b2dSdrh   if( p->pCheck ){
27183780be11Sdrh     sqlite3ResolveSelfReference(pParse, p, NC_IsCheck, 0, p->pCheck);
27199524a7eaSdrh     if( pParse->nErr ){
27209524a7eaSdrh       /* If errors are seen, delete the CHECK constraints now, else they might
27219524a7eaSdrh       ** actually be used if PRAGMA writable_schema=ON is set. */
27229524a7eaSdrh       sqlite3ExprListDelete(db, p->pCheck);
27239524a7eaSdrh       p->pCheck = 0;
2724e7375bfaSdrh     }else{
2725e7375bfaSdrh       markExprListImmutable(p->pCheck);
27269524a7eaSdrh     }
27272938f924Sdrh   }
2728ffe07b2dSdrh #endif /* !defined(SQLITE_OMIT_CHECK) */
272981f7b372Sdrh #ifndef SQLITE_OMIT_GENERATED_COLUMNS
2730427b96aeSdrh   if( p->tabFlags & TF_HasGenerated ){
2731f4658b68Sdrh     int ii, nNG = 0;
2732427b96aeSdrh     testcase( p->tabFlags & TF_HasVirtual );
2733427b96aeSdrh     testcase( p->tabFlags & TF_HasStored );
273481f7b372Sdrh     for(ii=0; ii<p->nCol; ii++){
27350b0b3a95Sdrh       u32 colFlags = p->aCol[ii].colFlags;
2736427b96aeSdrh       if( (colFlags & COLFLAG_GENERATED)!=0 ){
273779cf2b71Sdrh         Expr *pX = sqlite3ColumnExpr(p, &p->aCol[ii]);
2738427b96aeSdrh         testcase( colFlags & COLFLAG_VIRTUAL );
2739427b96aeSdrh         testcase( colFlags & COLFLAG_STORED );
27407e3f135cSdrh         if( sqlite3ResolveSelfReference(pParse, p, NC_GenCol, pX, 0) ){
27417e3f135cSdrh           /* If there are errors in resolving the expression, change the
27427e3f135cSdrh           ** expression to a NULL.  This prevents code generators that operate
27437e3f135cSdrh           ** on the expression from inserting extra parts into the expression
27447e3f135cSdrh           ** tree that have been allocated from lookaside memory, which is
27452d58b7f4Sdrh           ** illegal in a schema and will lead to errors or heap corruption
27462d58b7f4Sdrh           ** when the database connection closes. */
274779cf2b71Sdrh           sqlite3ColumnSetExpr(pParse, p, &p->aCol[ii],
274879cf2b71Sdrh                sqlite3ExprAlloc(db, TK_NULL, 0, 0));
27497e3f135cSdrh         }
2750f4658b68Sdrh       }else{
2751f4658b68Sdrh         nNG++;
275281f7b372Sdrh       }
27532c40a3ebSdrh     }
2754f4658b68Sdrh     if( nNG==0 ){
2755f4658b68Sdrh       sqlite3ErrorMsg(pParse, "must have at least one non-generated column");
27562c40a3ebSdrh       return;
275781f7b372Sdrh     }
275881f7b372Sdrh   }
275981f7b372Sdrh #endif
2760ffe07b2dSdrh 
2761e13e9f54Sdrh   /* Estimate the average row size for the table and for all implied indices */
2762e13e9f54Sdrh   estimateTableWidth(p);
2763fdaac671Sdrh   for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
2764e13e9f54Sdrh     estimateIndexWidth(pIdx);
2765fdaac671Sdrh   }
2766fdaac671Sdrh 
2767e3c41372Sdrh   /* If not initializing, then create a record for the new table
2768346a70caSdrh   ** in the schema table of the database.
2769f57b3399Sdrh   **
2770e0bc4048Sdrh   ** If this is a TEMPORARY table, write the entry into the auxiliary
2771e0bc4048Sdrh   ** file instead of into the main database file.
277275897234Sdrh   */
27731d85d931Sdrh   if( !db->init.busy ){
27744ff6dfa7Sdrh     int n;
2775d8bc7086Sdrh     Vdbe *v;
27764794f735Sdrh     char *zType;    /* "view" or "table" */
27774794f735Sdrh     char *zType2;   /* "VIEW" or "TABLE" */
27784794f735Sdrh     char *zStmt;    /* Text of the CREATE TABLE or CREATE VIEW statement */
277975897234Sdrh 
27804adee20fSdanielk1977     v = sqlite3GetVdbe(pParse);
27815969da4aSdrh     if( NEVER(v==0) ) return;
2782517eb646Sdanielk1977 
278366a5167bSdrh     sqlite3VdbeAddOp1(v, OP_Close, 0);
2784e6efa74bSdanielk1977 
27850fa991b9Sdrh     /*
27860fa991b9Sdrh     ** Initialize zType for the new view or table.
27874794f735Sdrh     */
2788f38524d2Sdrh     if( IsOrdinaryTable(p) ){
27894ff6dfa7Sdrh       /* A regular table */
27904794f735Sdrh       zType = "table";
27914794f735Sdrh       zType2 = "TABLE";
2792576ec6b3Sdanielk1977 #ifndef SQLITE_OMIT_VIEW
27934ff6dfa7Sdrh     }else{
27944ff6dfa7Sdrh       /* A view */
27954794f735Sdrh       zType = "view";
27964794f735Sdrh       zType2 = "VIEW";
2797576ec6b3Sdanielk1977 #endif
27984ff6dfa7Sdrh     }
2799517eb646Sdanielk1977 
2800517eb646Sdanielk1977     /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
2801517eb646Sdanielk1977     ** statement to populate the new table. The root-page number for the
28020fa991b9Sdrh     ** new table is in register pParse->regRoot.
2803517eb646Sdanielk1977     **
2804517eb646Sdanielk1977     ** Once the SELECT has been coded by sqlite3Select(), it is in a
2805517eb646Sdanielk1977     ** suitable state to query for the column names and types to be used
2806517eb646Sdanielk1977     ** by the new table.
2807c00da105Sdanielk1977     **
2808c00da105Sdanielk1977     ** A shared-cache write-lock is not required to write to the new table,
2809c00da105Sdanielk1977     ** as a schema-lock must have already been obtained to create it. Since
2810c00da105Sdanielk1977     ** a schema-lock excludes all other database users, the write-lock would
2811c00da105Sdanielk1977     ** be redundant.
2812517eb646Sdanielk1977     */
2813517eb646Sdanielk1977     if( pSelect ){
281492632204Sdrh       SelectDest dest;    /* Where the SELECT should store results */
28159df25c47Sdrh       int regYield;       /* Register holding co-routine entry-point */
28169df25c47Sdrh       int addrTop;        /* Top of the co-routine */
281792632204Sdrh       int regRec;         /* A record to be insert into the new table */
281892632204Sdrh       int regRowid;       /* Rowid of the next row to insert */
281992632204Sdrh       int addrInsLoop;    /* Top of the loop for inserting rows */
282092632204Sdrh       Table *pSelTab;     /* A table that describes the SELECT results */
28211013c932Sdrh 
2822fde30432Sdrh       if( IN_SPECIAL_PARSE ){
2823fde30432Sdrh         pParse->rc = SQLITE_ERROR;
2824fde30432Sdrh         pParse->nErr++;
2825fde30432Sdrh         return;
2826fde30432Sdrh       }
28279df25c47Sdrh       regYield = ++pParse->nMem;
282892632204Sdrh       regRec = ++pParse->nMem;
282992632204Sdrh       regRowid = ++pParse->nMem;
28306ab3a2ecSdanielk1977       assert(pParse->nTab==1);
28310dd5cdaeSdrh       sqlite3MayAbort(pParse);
2832b7654111Sdrh       sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb);
2833428c218cSdan       sqlite3VdbeChangeP5(v, OPFLAG_P2ISREG);
2834517eb646Sdanielk1977       pParse->nTab = 2;
28359df25c47Sdrh       addrTop = sqlite3VdbeCurrentAddr(v) + 1;
28369df25c47Sdrh       sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, addrTop);
2837512795dfSdrh       if( pParse->nErr ) return;
283881506b88Sdrh       pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect, SQLITE_AFF_BLOB);
28395969da4aSdrh       if( pSelTab==0 ) return;
2840517eb646Sdanielk1977       assert( p->aCol==0 );
2841f5f1915dSdrh       p->nCol = p->nNVCol = pSelTab->nCol;
2842517eb646Sdanielk1977       p->aCol = pSelTab->aCol;
2843517eb646Sdanielk1977       pSelTab->nCol = 0;
2844517eb646Sdanielk1977       pSelTab->aCol = 0;
28451feeaed2Sdan       sqlite3DeleteTable(db, pSelTab);
2846755b0fd3Sdrh       sqlite3SelectDestInit(&dest, SRT_Coroutine, regYield);
2847755b0fd3Sdrh       sqlite3Select(pParse, pSelect, &dest);
28485060a67cSdrh       if( pParse->nErr ) return;
2849755b0fd3Sdrh       sqlite3VdbeEndCoroutine(v, regYield);
2850755b0fd3Sdrh       sqlite3VdbeJumpHere(v, addrTop - 1);
28519df25c47Sdrh       addrInsLoop = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
28529df25c47Sdrh       VdbeCoverage(v);
28539df25c47Sdrh       sqlite3VdbeAddOp3(v, OP_MakeRecord, dest.iSdst, dest.nSdst, regRec);
28549df25c47Sdrh       sqlite3TableAffinity(v, p, 0);
28559df25c47Sdrh       sqlite3VdbeAddOp2(v, OP_NewRowid, 1, regRowid);
28569df25c47Sdrh       sqlite3VdbeAddOp3(v, OP_Insert, 1, regRec, regRowid);
2857076e85f5Sdrh       sqlite3VdbeGoto(v, addrInsLoop);
28589df25c47Sdrh       sqlite3VdbeJumpHere(v, addrInsLoop);
28599df25c47Sdrh       sqlite3VdbeAddOp1(v, OP_Close, 1);
2860517eb646Sdanielk1977     }
2861517eb646Sdanielk1977 
28624794f735Sdrh     /* Compute the complete text of the CREATE statement */
28634794f735Sdrh     if( pSelect ){
28641d34fdecSdrh       zStmt = createTableStmt(db, p);
28654794f735Sdrh     }else{
28668ea30bfcSdrh       Token *pEnd2 = tabOpts ? &pParse->sLastToken : pEnd;
28678ea30bfcSdrh       n = (int)(pEnd2->z - pParse->sNameToken.z);
28688ea30bfcSdrh       if( pEnd2->z[0]!=';' ) n += pEnd2->n;
28691e536953Sdanielk1977       zStmt = sqlite3MPrintf(db,
28701e536953Sdanielk1977           "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
28711e536953Sdanielk1977       );
28724794f735Sdrh     }
28734794f735Sdrh 
28744794f735Sdrh     /* A slot for the record has already been allocated in the
2875346a70caSdrh     ** schema table.  We just need to update that slot with all
28760fa991b9Sdrh     ** the information we've collected.
28774794f735Sdrh     */
28784794f735Sdrh     sqlite3NestedParse(pParse,
2879a4a871c2Sdrh       "UPDATE %Q." LEGACY_SCHEMA_TABLE
2880b7654111Sdrh       " SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q"
2881b7654111Sdrh       " WHERE rowid=#%d",
2882346a70caSdrh       db->aDb[iDb].zDbSName,
28834794f735Sdrh       zType,
28844794f735Sdrh       p->zName,
28854794f735Sdrh       p->zName,
2886b7654111Sdrh       pParse->regRoot,
2887b7654111Sdrh       zStmt,
2888b7654111Sdrh       pParse->regRowid
28894794f735Sdrh     );
2890633e6d57Sdrh     sqlite3DbFree(db, zStmt);
28919cbf3425Sdrh     sqlite3ChangeCookie(pParse, iDb);
28922958a4e6Sdrh 
28932958a4e6Sdrh #ifndef SQLITE_OMIT_AUTOINCREMENT
28942958a4e6Sdrh     /* Check to see if we need to create an sqlite_sequence table for
28952958a4e6Sdrh     ** keeping track of autoincrement keys.
28962958a4e6Sdrh     */
2897755ed41fSdan     if( (p->tabFlags & TF_Autoincrement)!=0 && !IN_SPECIAL_PARSE ){
2898da184236Sdanielk1977       Db *pDb = &db->aDb[iDb];
28992120608eSdrh       assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
2900da184236Sdanielk1977       if( pDb->pSchema->pSeqTab==0 ){
29012958a4e6Sdrh         sqlite3NestedParse(pParse,
2902f3388144Sdrh           "CREATE TABLE %Q.sqlite_sequence(name,seq)",
290369c33826Sdrh           pDb->zDbSName
29042958a4e6Sdrh         );
29052958a4e6Sdrh       }
29062958a4e6Sdrh     }
29072958a4e6Sdrh #endif
29084794f735Sdrh 
29094794f735Sdrh     /* Reparse everything to update our internal data structures */
29105d9c9da6Sdrh     sqlite3VdbeAddParseSchemaOp(v, iDb,
29116a5a13dfSdan            sqlite3MPrintf(db, "tbl_name='%q' AND type!='trigger'", p->zName),0);
291275897234Sdrh   }
291317e9e29dSdrh 
291417e9e29dSdrh   /* Add the table to the in-memory representation of the database.
291517e9e29dSdrh   */
29168af73d41Sdrh   if( db->init.busy ){
291717e9e29dSdrh     Table *pOld;
2918e501b89aSdanielk1977     Schema *pSchema = p->pSchema;
29192120608eSdrh     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
29201bb89e9cSdrh     assert( HasRowid(p) || p->iPKey<0 );
2921acbcb7e0Sdrh     pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName, p);
292217e9e29dSdrh     if( pOld ){
292317e9e29dSdrh       assert( p==pOld );  /* Malloc must have failed inside HashInsert() */
29244a642b60Sdrh       sqlite3OomFault(db);
29255969da4aSdrh       return;
292617e9e29dSdrh     }
292717e9e29dSdrh     pParse->pNewTable = 0;
29288257aa8dSdrh     db->mDbFlags |= DBFLAG_SchemaChange;
2929d4b64699Sdan 
2930d4b64699Sdan     /* If this is the magic sqlite_sequence table used by autoincrement,
2931d4b64699Sdan     ** then record a pointer to this table in the main database structure
2932d4b64699Sdan     ** so that INSERT can find the table easily.  */
2933d4b64699Sdan     assert( !pParse->nested );
2934d4b64699Sdan #ifndef SQLITE_OMIT_AUTOINCREMENT
2935d4b64699Sdan     if( strcmp(p->zName, "sqlite_sequence")==0 ){
2936d4b64699Sdan       assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
2937d4b64699Sdan       p->pSchema->pSeqTab = p;
2938d4b64699Sdan     }
2939d4b64699Sdan #endif
2940578277c2Sdan   }
294119a8e7e8Sdanielk1977 
294219a8e7e8Sdanielk1977 #ifndef SQLITE_OMIT_ALTERTABLE
2943f38524d2Sdrh   if( !pSelect && IsOrdinaryTable(p) ){
2944578277c2Sdan     assert( pCons && pEnd );
2945bab45c64Sdanielk1977     if( pCons->z==0 ){
29465969da4aSdrh       pCons = pEnd;
2947bab45c64Sdanielk1977     }
2948f38524d2Sdrh     p->u.tab.addColOffset = 13 + (int)(pCons->z - pParse->sNameToken.z);
294919a8e7e8Sdanielk1977   }
295019a8e7e8Sdanielk1977 #endif
295117e9e29dSdrh }
295275897234Sdrh 
2953b7f9164eSdrh #ifndef SQLITE_OMIT_VIEW
295475897234Sdrh /*
2955a76b5dfcSdrh ** The parser calls this routine in order to create a new VIEW
2956a76b5dfcSdrh */
sqlite3CreateView(Parse * pParse,Token * pBegin,Token * pName1,Token * pName2,ExprList * pCNames,Select * pSelect,int isTemp,int noErr)29574adee20fSdanielk1977 void sqlite3CreateView(
2958a76b5dfcSdrh   Parse *pParse,     /* The parsing context */
2959a76b5dfcSdrh   Token *pBegin,     /* The CREATE token that begins the statement */
296048dec7e2Sdanielk1977   Token *pName1,     /* The token that holds the name of the view */
296148dec7e2Sdanielk1977   Token *pName2,     /* The token that holds the name of the view */
29628981b904Sdrh   ExprList *pCNames, /* Optional list of view column names */
29636276c1cbSdrh   Select *pSelect,   /* A SELECT statement that will become the new view */
2964fdd48a76Sdrh   int isTemp,        /* TRUE for a TEMPORARY view */
2965fdd48a76Sdrh   int noErr          /* Suppress error messages if VIEW already exists */
2966a76b5dfcSdrh ){
2967a76b5dfcSdrh   Table *p;
29684b59ab5eSdrh   int n;
2969b7916a78Sdrh   const char *z;
29704b59ab5eSdrh   Token sEnd;
2971f26e09c8Sdrh   DbFixer sFix;
297288caeac7Sdrh   Token *pName = 0;
2973da184236Sdanielk1977   int iDb;
297417435752Sdrh   sqlite3 *db = pParse->db;
2975a76b5dfcSdrh 
29767c3d64f1Sdrh   if( pParse->nVar>0 ){
29777c3d64f1Sdrh     sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
297832498f13Sdrh     goto create_view_fail;
29797c3d64f1Sdrh   }
2980fdd48a76Sdrh   sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
2981a76b5dfcSdrh   p = pParse->pNewTable;
29828981b904Sdrh   if( p==0 || pParse->nErr ) goto create_view_fail;
29836e5020e8Sdrh 
29846e5020e8Sdrh   /* Legacy versions of SQLite allowed the use of the magic "rowid" column
29856e5020e8Sdrh   ** on a view, even though views do not have rowids.  The following flag
29866e5020e8Sdrh   ** setting fixes this problem.  But the fix can be disabled by compiling
29876e5020e8Sdrh   ** with -DSQLITE_ALLOW_ROWID_IN_VIEW in case there are legacy apps that
29886e5020e8Sdrh   ** depend upon the old buggy behavior. */
29896e5020e8Sdrh #ifndef SQLITE_ALLOW_ROWID_IN_VIEW
2990a6c54defSdrh   p->tabFlags |= TF_NoVisibleRowid;
29916e5020e8Sdrh #endif
29926e5020e8Sdrh 
2993ef2cb63eSdanielk1977   sqlite3TwoPartName(pParse, pName1, pName2, &pName);
299417435752Sdrh   iDb = sqlite3SchemaToIndex(db, p->pSchema);
2995d100f691Sdrh   sqlite3FixInit(&sFix, pParse, iDb, "view", pName);
29968981b904Sdrh   if( sqlite3FixSelect(&sFix, pSelect) ) goto create_view_fail;
2997174b6195Sdrh 
29984b59ab5eSdrh   /* Make a copy of the entire SELECT statement that defines the view.
29994b59ab5eSdrh   ** This will force all the Expr.token.z values to be dynamically
30004b59ab5eSdrh   ** allocated rather than point to the input string - which means that
300124b03fd0Sdanielk1977   ** they will persist after the current sqlite3_exec() call returns.
30024b59ab5eSdrh   */
300338096961Sdan   pSelect->selFlags |= SF_View;
3004c9461eccSdan   if( IN_RENAME_OBJECT ){
3005f38524d2Sdrh     p->u.view.pSelect = pSelect;
3006987db767Sdan     pSelect = 0;
3007987db767Sdan   }else{
3008f38524d2Sdrh     p->u.view.pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
3009987db767Sdan   }
30108981b904Sdrh   p->pCheck = sqlite3ExprListDup(db, pCNames, EXPRDUP_REDUCE);
3011f38524d2Sdrh   p->eTabType = TABTYP_VIEW;
30128981b904Sdrh   if( db->mallocFailed ) goto create_view_fail;
30134b59ab5eSdrh 
30144b59ab5eSdrh   /* Locate the end of the CREATE VIEW statement.  Make sEnd point to
30154b59ab5eSdrh   ** the end.
30164b59ab5eSdrh   */
3017a76b5dfcSdrh   sEnd = pParse->sLastToken;
30186116ee4eSdrh   assert( sEnd.z[0]!=0 || sEnd.n==0 );
30198981b904Sdrh   if( sEnd.z[0]!=';' ){
3020a76b5dfcSdrh     sEnd.z += sEnd.n;
3021a76b5dfcSdrh   }
3022a76b5dfcSdrh   sEnd.n = 0;
30231bd10f8aSdrh   n = (int)(sEnd.z - pBegin->z);
30248981b904Sdrh   assert( n>0 );
3025b7916a78Sdrh   z = pBegin->z;
30268981b904Sdrh   while( sqlite3Isspace(z[n-1]) ){ n--; }
30274ff6dfa7Sdrh   sEnd.z = &z[n-1];
30284ff6dfa7Sdrh   sEnd.n = 1;
30294b59ab5eSdrh 
3030346a70caSdrh   /* Use sqlite3EndTable() to add the view to the schema table */
30315969da4aSdrh   sqlite3EndTable(pParse, 0, &sEnd, 0, 0);
30328981b904Sdrh 
30338981b904Sdrh create_view_fail:
30348981b904Sdrh   sqlite3SelectDelete(db, pSelect);
3035e8ab40d2Sdan   if( IN_RENAME_OBJECT ){
3036e8ab40d2Sdan     sqlite3RenameExprlistUnmap(pParse, pCNames);
3037e8ab40d2Sdan   }
30388981b904Sdrh   sqlite3ExprListDelete(db, pCNames);
3039a76b5dfcSdrh   return;
3040417be79cSdrh }
3041b7f9164eSdrh #endif /* SQLITE_OMIT_VIEW */
3042a76b5dfcSdrh 
3043fe3fcbe2Sdanielk1977 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
3044417be79cSdrh /*
3045417be79cSdrh ** The Table structure pTable is really a VIEW.  Fill in the names of
3046417be79cSdrh ** the columns of the view in the pTable structure.  Return the number
3047cfa5684dSjplyon ** of errors.  If an error is seen leave an error message in pParse->zErrMsg.
3048417be79cSdrh */
viewGetColumnNames(Parse * pParse,Table * pTable)3049ef69d2b2Sdrh static SQLITE_NOINLINE int viewGetColumnNames(Parse *pParse, Table *pTable){
30509b3187e1Sdrh   Table *pSelTab;   /* A fake table from which we get the result set */
30519b3187e1Sdrh   Select *pSel;     /* Copy of the SELECT that implements the view */
30529b3187e1Sdrh   int nErr = 0;     /* Number of errors encountered */
305317435752Sdrh   sqlite3 *db = pParse->db;  /* Database connection for malloc errors */
3054dc6b41edSdrh #ifndef SQLITE_OMIT_VIRTUALTABLE
3055dc6b41edSdrh   int rc;
3056dc6b41edSdrh #endif
3057a0daa751Sdrh #ifndef SQLITE_OMIT_AUTHORIZATION
305832c6a48bSdrh   sqlite3_xauth xAuth;       /* Saved xAuth pointer */
3059a0daa751Sdrh #endif
3060417be79cSdrh 
3061417be79cSdrh   assert( pTable );
3062417be79cSdrh 
3063fe3fcbe2Sdanielk1977 #ifndef SQLITE_OMIT_VIRTUALTABLE
3064ddfec00dSdrh   if( IsVirtual(pTable) ){
3065dc6b41edSdrh     db->nSchemaLock++;
3066dc6b41edSdrh     rc = sqlite3VtabCallConnect(pParse, pTable);
3067dc6b41edSdrh     db->nSchemaLock--;
3068ddfec00dSdrh     return rc;
3069fe3fcbe2Sdanielk1977   }
3070fe3fcbe2Sdanielk1977 #endif
3071fe3fcbe2Sdanielk1977 
3072fe3fcbe2Sdanielk1977 #ifndef SQLITE_OMIT_VIEW
3073417be79cSdrh   /* A positive nCol means the columns names for this view are
3074509a6303Sdrh   ** already known.  This routine is not called unless either the
3075509a6303Sdrh   ** table is virtual or nCol is zero.
3076417be79cSdrh   */
3077509a6303Sdrh   assert( pTable->nCol<=0 );
3078417be79cSdrh 
3079417be79cSdrh   /* A negative nCol is a special marker meaning that we are currently
3080417be79cSdrh   ** trying to compute the column names.  If we enter this routine with
3081417be79cSdrh   ** a negative nCol, it means two or more views form a loop, like this:
3082417be79cSdrh   **
3083417be79cSdrh   **     CREATE VIEW one AS SELECT * FROM two;
3084417be79cSdrh   **     CREATE VIEW two AS SELECT * FROM one;
30853b167c75Sdrh   **
3086768578eeSdrh   ** Actually, the error above is now caught prior to reaching this point.
3087768578eeSdrh   ** But the following test is still important as it does come up
3088768578eeSdrh   ** in the following:
3089768578eeSdrh   **
3090768578eeSdrh   **     CREATE TABLE main.ex1(a);
3091768578eeSdrh   **     CREATE TEMP VIEW ex1 AS SELECT a FROM ex1;
3092768578eeSdrh   **     SELECT * FROM temp.ex1;
3093417be79cSdrh   */
3094417be79cSdrh   if( pTable->nCol<0 ){
30954adee20fSdanielk1977     sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
3096417be79cSdrh     return 1;
3097417be79cSdrh   }
309885c23c61Sdrh   assert( pTable->nCol>=0 );
3099417be79cSdrh 
3100417be79cSdrh   /* If we get this far, it means we need to compute the table names.
31019b3187e1Sdrh   ** Note that the call to sqlite3ResultSetOfSelect() will expand any
31029b3187e1Sdrh   ** "*" elements in the results set of the view and will assign cursors
31039b3187e1Sdrh   ** to the elements of the FROM clause.  But we do not want these changes
31049b3187e1Sdrh   ** to be permanent.  So the computation is done on a copy of the SELECT
31059b3187e1Sdrh   ** statement that defines the view.
3106417be79cSdrh   */
3107f38524d2Sdrh   assert( IsView(pTable) );
3108f38524d2Sdrh   pSel = sqlite3SelectDup(db, pTable->u.view.pSelect, 0);
3109261919ccSdanielk1977   if( pSel ){
31100208337cSdan     u8 eParseMode = pParse->eParseMode;
31117f417569Sdrh     int nTab = pParse->nTab;
31127f417569Sdrh     int nSelect = pParse->nSelect;
31130208337cSdan     pParse->eParseMode = PARSE_MODE_NORMAL;
31149b3187e1Sdrh     sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
3115417be79cSdrh     pTable->nCol = -1;
311631f69626Sdrh     DisableLookaside;
3117db2d286bSdanielk1977 #ifndef SQLITE_OMIT_AUTHORIZATION
3118a6d0ffc3Sdrh     xAuth = db->xAuth;
3119a6d0ffc3Sdrh     db->xAuth = 0;
312096fb16eeSdrh     pSelTab = sqlite3ResultSetOfSelect(pParse, pSel, SQLITE_AFF_NONE);
3121a6d0ffc3Sdrh     db->xAuth = xAuth;
3122db2d286bSdanielk1977 #else
312396fb16eeSdrh     pSelTab = sqlite3ResultSetOfSelect(pParse, pSel, SQLITE_AFF_NONE);
3124db2d286bSdanielk1977 #endif
31257f417569Sdrh     pParse->nTab = nTab;
31267f417569Sdrh     pParse->nSelect = nSelect;
31275d59102aSdan     if( pSelTab==0 ){
31285d59102aSdan       pTable->nCol = 0;
31295d59102aSdan       nErr++;
31305d59102aSdan     }else if( pTable->pCheck ){
3131ed06a131Sdrh       /* CREATE VIEW name(arglist) AS ...
3132ed06a131Sdrh       ** The names of the columns in the table are taken from
3133ed06a131Sdrh       ** arglist which is stored in pTable->pCheck.  The pCheck field
3134ed06a131Sdrh       ** normally holds CHECK constraints on an ordinary table, but for
3135ed06a131Sdrh       ** a VIEW it holds the list of column names.
3136ed06a131Sdrh       */
3137ed06a131Sdrh       sqlite3ColumnsFromExprList(pParse, pTable->pCheck,
3138ed06a131Sdrh                                  &pTable->nCol, &pTable->aCol);
31390c7d3d39Sdrh       if( pParse->nErr==0
3140ed06a131Sdrh        && pTable->nCol==pSel->pEList->nExpr
3141ed06a131Sdrh       ){
31420c7d3d39Sdrh         assert( db->mallocFailed==0 );
314396fb16eeSdrh         sqlite3SelectAddColumnTypeAndCollation(pParse, pTable, pSel,
314496fb16eeSdrh                                                SQLITE_AFF_NONE);
3145ed06a131Sdrh       }
31465d59102aSdan     }else{
3147ed06a131Sdrh       /* CREATE VIEW name AS...  without an argument list.  Construct
3148ed06a131Sdrh       ** the column names from the SELECT statement that defines the view.
3149ed06a131Sdrh       */
3150417be79cSdrh       assert( pTable->aCol==0 );
315103836614Sdrh       pTable->nCol = pSelTab->nCol;
3152417be79cSdrh       pTable->aCol = pSelTab->aCol;
31533dc864b5Sdan       pTable->tabFlags |= (pSelTab->tabFlags & COLFLAG_NOINSERT);
3154417be79cSdrh       pSelTab->nCol = 0;
3155417be79cSdrh       pSelTab->aCol = 0;
31562120608eSdrh       assert( sqlite3SchemaMutexHeld(db, 0, pTable->pSchema) );
3157417be79cSdrh     }
315803836614Sdrh     pTable->nNVCol = pTable->nCol;
3159e8da01c1Sdrh     sqlite3DeleteTable(db, pSelTab);
3160633e6d57Sdrh     sqlite3SelectDelete(db, pSel);
316131f69626Sdrh     EnableLookaside;
31620208337cSdan     pParse->eParseMode = eParseMode;
3163261919ccSdanielk1977   } else {
3164261919ccSdanielk1977     nErr++;
3165261919ccSdanielk1977   }
31668981b904Sdrh   pTable->pSchema->schemaFlags |= DB_UnresetViews;
316777f3f402Sdan   if( db->mallocFailed ){
316877f3f402Sdan     sqlite3DeleteColumnNames(db, pTable);
316977f3f402Sdan   }
3170b7f9164eSdrh #endif /* SQLITE_OMIT_VIEW */
31714b2688abSdanielk1977   return nErr;
3172fe3fcbe2Sdanielk1977 }
sqlite3ViewGetColumnNames(Parse * pParse,Table * pTable)3173ef69d2b2Sdrh int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
3174ef69d2b2Sdrh   assert( pTable!=0 );
3175ef69d2b2Sdrh   if( !IsVirtual(pTable) && pTable->nCol>0 ) return 0;
3176ef69d2b2Sdrh   return viewGetColumnNames(pParse, pTable);
3177ef69d2b2Sdrh }
3178fe3fcbe2Sdanielk1977 #endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
3179417be79cSdrh 
3180b7f9164eSdrh #ifndef SQLITE_OMIT_VIEW
3181417be79cSdrh /*
31828bf8dc92Sdrh ** Clear the column names from every VIEW in database idx.
3183417be79cSdrh */
sqliteViewResetAll(sqlite3 * db,int idx)31849bb575fdSdrh static void sqliteViewResetAll(sqlite3 *db, int idx){
3185417be79cSdrh   HashElem *i;
31862120608eSdrh   assert( sqlite3SchemaMutexHeld(db, idx, 0) );
31878bf8dc92Sdrh   if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
3188da184236Sdanielk1977   for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
3189417be79cSdrh     Table *pTab = sqliteHashData(i);
3190f38524d2Sdrh     if( IsView(pTab) ){
319151be3873Sdrh       sqlite3DeleteColumnNames(db, pTab);
3192417be79cSdrh     }
3193417be79cSdrh   }
31948bf8dc92Sdrh   DbClearProperty(db, idx, DB_UnresetViews);
3195a76b5dfcSdrh }
3196b7f9164eSdrh #else
3197b7f9164eSdrh # define sqliteViewResetAll(A,B)
3198b7f9164eSdrh #endif /* SQLITE_OMIT_VIEW */
3199a76b5dfcSdrh 
320075897234Sdrh /*
3201a0bf2652Sdanielk1977 ** This function is called by the VDBE to adjust the internal schema
3202a0bf2652Sdanielk1977 ** used by SQLite when the btree layer moves a table root page. The
3203a0bf2652Sdanielk1977 ** root-page of a table or index in database iDb has changed from iFrom
3204a0bf2652Sdanielk1977 ** to iTo.
32056205d4a4Sdrh **
32066205d4a4Sdrh ** Ticket #1728:  The symbol table might still contain information
32076205d4a4Sdrh ** on tables and/or indices that are the process of being deleted.
32086205d4a4Sdrh ** If you are unlucky, one of those deleted indices or tables might
32096205d4a4Sdrh ** have the same rootpage number as the real table or index that is
32106205d4a4Sdrh ** being moved.  So we cannot stop searching after the first match
32116205d4a4Sdrh ** because the first match might be for one of the deleted indices
32126205d4a4Sdrh ** or tables and not the table/index that is actually being moved.
32136205d4a4Sdrh ** We must continue looping until all tables and indices with
32146205d4a4Sdrh ** rootpage==iFrom have been converted to have a rootpage of iTo
32156205d4a4Sdrh ** in order to be certain that we got the right one.
3216a0bf2652Sdanielk1977 */
3217a0bf2652Sdanielk1977 #ifndef SQLITE_OMIT_AUTOVACUUM
sqlite3RootPageMoved(sqlite3 * db,int iDb,Pgno iFrom,Pgno iTo)3218abc38158Sdrh void sqlite3RootPageMoved(sqlite3 *db, int iDb, Pgno iFrom, Pgno iTo){
3219a0bf2652Sdanielk1977   HashElem *pElem;
3220da184236Sdanielk1977   Hash *pHash;
3221cdf011dcSdrh   Db *pDb;
3222a0bf2652Sdanielk1977 
3223cdf011dcSdrh   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
3224cdf011dcSdrh   pDb = &db->aDb[iDb];
3225da184236Sdanielk1977   pHash = &pDb->pSchema->tblHash;
3226da184236Sdanielk1977   for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
3227a0bf2652Sdanielk1977     Table *pTab = sqliteHashData(pElem);
3228a0bf2652Sdanielk1977     if( pTab->tnum==iFrom ){
3229a0bf2652Sdanielk1977       pTab->tnum = iTo;
3230a0bf2652Sdanielk1977     }
3231a0bf2652Sdanielk1977   }
3232da184236Sdanielk1977   pHash = &pDb->pSchema->idxHash;
3233da184236Sdanielk1977   for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
3234a0bf2652Sdanielk1977     Index *pIdx = sqliteHashData(pElem);
3235a0bf2652Sdanielk1977     if( pIdx->tnum==iFrom ){
3236a0bf2652Sdanielk1977       pIdx->tnum = iTo;
3237a0bf2652Sdanielk1977     }
3238a0bf2652Sdanielk1977   }
3239a0bf2652Sdanielk1977 }
3240a0bf2652Sdanielk1977 #endif
3241a0bf2652Sdanielk1977 
3242a0bf2652Sdanielk1977 /*
3243a0bf2652Sdanielk1977 ** Write code to erase the table with root-page iTable from database iDb.
32441e32bed3Sdrh ** Also write code to modify the sqlite_schema table and internal schema
3245a0bf2652Sdanielk1977 ** if a root-page of another table is moved by the btree-layer whilst
3246a0bf2652Sdanielk1977 ** erasing iTable (this can happen with an auto-vacuum database).
3247a0bf2652Sdanielk1977 */
destroyRootPage(Parse * pParse,int iTable,int iDb)32484e0cff60Sdrh static void destroyRootPage(Parse *pParse, int iTable, int iDb){
32494e0cff60Sdrh   Vdbe *v = sqlite3GetVdbe(pParse);
3250b7654111Sdrh   int r1 = sqlite3GetTempReg(pParse);
325119918882Sdrh   if( iTable<2 ) sqlite3ErrorMsg(pParse, "corrupt schema");
3252b7654111Sdrh   sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
3253e0af83acSdan   sqlite3MayAbort(pParse);
325440e016e4Sdrh #ifndef SQLITE_OMIT_AUTOVACUUM
3255b7654111Sdrh   /* OP_Destroy stores an in integer r1. If this integer
32564e0cff60Sdrh   ** is non-zero, then it is the root page number of a table moved to
32571e32bed3Sdrh   ** location iTable. The following code modifies the sqlite_schema table to
32584e0cff60Sdrh   ** reflect this.
32594e0cff60Sdrh   **
32600fa991b9Sdrh   ** The "#NNN" in the SQL is a special constant that means whatever value
3261b74b1017Sdrh   ** is in register NNN.  See grammar rules associated with the TK_REGISTER
3262b74b1017Sdrh   ** token for additional information.
32634e0cff60Sdrh   */
326463e3e9f8Sdanielk1977   sqlite3NestedParse(pParse,
3265a4a871c2Sdrh      "UPDATE %Q." LEGACY_SCHEMA_TABLE
3266346a70caSdrh      " SET rootpage=%d WHERE #%d AND rootpage=#%d",
3267346a70caSdrh      pParse->db->aDb[iDb].zDbSName, iTable, r1, r1);
3268a0bf2652Sdanielk1977 #endif
3269b7654111Sdrh   sqlite3ReleaseTempReg(pParse, r1);
3270a0bf2652Sdanielk1977 }
3271a0bf2652Sdanielk1977 
3272a0bf2652Sdanielk1977 /*
3273a0bf2652Sdanielk1977 ** Write VDBE code to erase table pTab and all associated indices on disk.
32741e32bed3Sdrh ** Code to update the sqlite_schema tables and internal schema definitions
3275a0bf2652Sdanielk1977 ** in case a root-page belonging to another table is moved by the btree layer
3276a0bf2652Sdanielk1977 ** is also added (this can happen with an auto-vacuum database).
3277a0bf2652Sdanielk1977 */
destroyTable(Parse * pParse,Table * pTab)32784e0cff60Sdrh static void destroyTable(Parse *pParse, Table *pTab){
3279a0bf2652Sdanielk1977   /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
3280a0bf2652Sdanielk1977   ** is not defined), then it is important to call OP_Destroy on the
3281a0bf2652Sdanielk1977   ** table and index root-pages in order, starting with the numerically
3282a0bf2652Sdanielk1977   ** largest root-page number. This guarantees that none of the root-pages
3283a0bf2652Sdanielk1977   ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
3284a0bf2652Sdanielk1977   ** following were coded:
3285a0bf2652Sdanielk1977   **
3286a0bf2652Sdanielk1977   ** OP_Destroy 4 0
3287a0bf2652Sdanielk1977   ** ...
3288a0bf2652Sdanielk1977   ** OP_Destroy 5 0
3289a0bf2652Sdanielk1977   **
3290a0bf2652Sdanielk1977   ** and root page 5 happened to be the largest root-page number in the
3291a0bf2652Sdanielk1977   ** database, then root page 5 would be moved to page 4 by the
3292a0bf2652Sdanielk1977   ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
3293a0bf2652Sdanielk1977   ** a free-list page.
3294a0bf2652Sdanielk1977   */
3295abc38158Sdrh   Pgno iTab = pTab->tnum;
32968deae5adSdrh   Pgno iDestroyed = 0;
3297a0bf2652Sdanielk1977 
3298a0bf2652Sdanielk1977   while( 1 ){
3299a0bf2652Sdanielk1977     Index *pIdx;
33008deae5adSdrh     Pgno iLargest = 0;
3301a0bf2652Sdanielk1977 
3302a0bf2652Sdanielk1977     if( iDestroyed==0 || iTab<iDestroyed ){
3303a0bf2652Sdanielk1977       iLargest = iTab;
3304a0bf2652Sdanielk1977     }
3305a0bf2652Sdanielk1977     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
3306abc38158Sdrh       Pgno iIdx = pIdx->tnum;
3307da184236Sdanielk1977       assert( pIdx->pSchema==pTab->pSchema );
3308a0bf2652Sdanielk1977       if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
3309a0bf2652Sdanielk1977         iLargest = iIdx;
3310a0bf2652Sdanielk1977       }
3311a0bf2652Sdanielk1977     }
3312da184236Sdanielk1977     if( iLargest==0 ){
3313da184236Sdanielk1977       return;
3314da184236Sdanielk1977     }else{
3315da184236Sdanielk1977       int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
33165a05be1bSdrh       assert( iDb>=0 && iDb<pParse->db->nDb );
3317da184236Sdanielk1977       destroyRootPage(pParse, iLargest, iDb);
3318a0bf2652Sdanielk1977       iDestroyed = iLargest;
3319a0bf2652Sdanielk1977     }
3320da184236Sdanielk1977   }
3321a0bf2652Sdanielk1977 }
3322a0bf2652Sdanielk1977 
3323a0bf2652Sdanielk1977 /*
332474e7c8f5Sdrh ** Remove entries from the sqlite_statN tables (for N in (1,2,3))
3325a5ae4c33Sdrh ** after a DROP INDEX or DROP TABLE command.
3326a5ae4c33Sdrh */
sqlite3ClearStatTables(Parse * pParse,int iDb,const char * zType,const char * zName)3327a5ae4c33Sdrh static void sqlite3ClearStatTables(
3328a5ae4c33Sdrh   Parse *pParse,         /* The parsing context */
3329a5ae4c33Sdrh   int iDb,               /* The database number */
3330a5ae4c33Sdrh   const char *zType,     /* "idx" or "tbl" */
3331a5ae4c33Sdrh   const char *zName      /* Name of index or table */
3332a5ae4c33Sdrh ){
3333a5ae4c33Sdrh   int i;
333469c33826Sdrh   const char *zDbName = pParse->db->aDb[iDb].zDbSName;
3335f52bb8d3Sdan   for(i=1; i<=4; i++){
333674e7c8f5Sdrh     char zTab[24];
333774e7c8f5Sdrh     sqlite3_snprintf(sizeof(zTab),zTab,"sqlite_stat%d",i);
333874e7c8f5Sdrh     if( sqlite3FindTable(pParse->db, zTab, zDbName) ){
3339a5ae4c33Sdrh       sqlite3NestedParse(pParse,
3340a5ae4c33Sdrh         "DELETE FROM %Q.%s WHERE %s=%Q",
334174e7c8f5Sdrh         zDbName, zTab, zType, zName
3342a5ae4c33Sdrh       );
3343a5ae4c33Sdrh     }
3344a5ae4c33Sdrh   }
3345a5ae4c33Sdrh }
3346a5ae4c33Sdrh 
3347a5ae4c33Sdrh /*
3348faacf17cSdrh ** Generate code to drop a table.
3349faacf17cSdrh */
sqlite3CodeDropTable(Parse * pParse,Table * pTab,int iDb,int isView)3350faacf17cSdrh void sqlite3CodeDropTable(Parse *pParse, Table *pTab, int iDb, int isView){
3351faacf17cSdrh   Vdbe *v;
3352faacf17cSdrh   sqlite3 *db = pParse->db;
3353faacf17cSdrh   Trigger *pTrigger;
3354faacf17cSdrh   Db *pDb = &db->aDb[iDb];
3355faacf17cSdrh 
3356faacf17cSdrh   v = sqlite3GetVdbe(pParse);
3357faacf17cSdrh   assert( v!=0 );
3358faacf17cSdrh   sqlite3BeginWriteOperation(pParse, 1, iDb);
3359faacf17cSdrh 
3360faacf17cSdrh #ifndef SQLITE_OMIT_VIRTUALTABLE
3361faacf17cSdrh   if( IsVirtual(pTab) ){
3362faacf17cSdrh     sqlite3VdbeAddOp0(v, OP_VBegin);
3363faacf17cSdrh   }
3364faacf17cSdrh #endif
3365faacf17cSdrh 
3366faacf17cSdrh   /* Drop all triggers associated with the table being dropped. Code
33671e32bed3Sdrh   ** is generated to remove entries from sqlite_schema and/or
33681e32bed3Sdrh   ** sqlite_temp_schema if required.
3369faacf17cSdrh   */
3370faacf17cSdrh   pTrigger = sqlite3TriggerList(pParse, pTab);
3371faacf17cSdrh   while( pTrigger ){
3372faacf17cSdrh     assert( pTrigger->pSchema==pTab->pSchema ||
3373faacf17cSdrh         pTrigger->pSchema==db->aDb[1].pSchema );
3374faacf17cSdrh     sqlite3DropTriggerPtr(pParse, pTrigger);
3375faacf17cSdrh     pTrigger = pTrigger->pNext;
3376faacf17cSdrh   }
3377faacf17cSdrh 
3378faacf17cSdrh #ifndef SQLITE_OMIT_AUTOINCREMENT
3379faacf17cSdrh   /* Remove any entries of the sqlite_sequence table associated with
3380faacf17cSdrh   ** the table being dropped. This is done before the table is dropped
3381faacf17cSdrh   ** at the btree level, in case the sqlite_sequence table needs to
3382faacf17cSdrh   ** move as a result of the drop (can happen in auto-vacuum mode).
3383faacf17cSdrh   */
3384faacf17cSdrh   if( pTab->tabFlags & TF_Autoincrement ){
3385faacf17cSdrh     sqlite3NestedParse(pParse,
3386faacf17cSdrh       "DELETE FROM %Q.sqlite_sequence WHERE name=%Q",
338769c33826Sdrh       pDb->zDbSName, pTab->zName
3388faacf17cSdrh     );
3389faacf17cSdrh   }
3390faacf17cSdrh #endif
3391faacf17cSdrh 
3392346a70caSdrh   /* Drop all entries in the schema table that refer to the
3393067b92baSdrh   ** table. The program name loops through the schema table and deletes
3394faacf17cSdrh   ** every row that refers to a table of the same name as the one being
339548864df9Smistachkin   ** dropped. Triggers are handled separately because a trigger can be
3396faacf17cSdrh   ** created in the temp database that refers to a table in another
3397faacf17cSdrh   ** database.
3398faacf17cSdrh   */
3399faacf17cSdrh   sqlite3NestedParse(pParse,
3400a4a871c2Sdrh       "DELETE FROM %Q." LEGACY_SCHEMA_TABLE
3401346a70caSdrh       " WHERE tbl_name=%Q and type!='trigger'",
3402346a70caSdrh       pDb->zDbSName, pTab->zName);
3403faacf17cSdrh   if( !isView && !IsVirtual(pTab) ){
3404faacf17cSdrh     destroyTable(pParse, pTab);
3405faacf17cSdrh   }
3406faacf17cSdrh 
3407faacf17cSdrh   /* Remove the table entry from SQLite's internal schema and modify
3408faacf17cSdrh   ** the schema cookie.
3409faacf17cSdrh   */
3410faacf17cSdrh   if( IsVirtual(pTab) ){
3411faacf17cSdrh     sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
34121d4b1640Sdan     sqlite3MayAbort(pParse);
3413faacf17cSdrh   }
3414faacf17cSdrh   sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
3415faacf17cSdrh   sqlite3ChangeCookie(pParse, iDb);
3416faacf17cSdrh   sqliteViewResetAll(db, iDb);
3417faacf17cSdrh }
3418faacf17cSdrh 
3419faacf17cSdrh /*
3420070ae3beSdrh ** Return TRUE if shadow tables should be read-only in the current
3421070ae3beSdrh ** context.
3422070ae3beSdrh */
sqlite3ReadOnlyShadowTables(sqlite3 * db)3423070ae3beSdrh int sqlite3ReadOnlyShadowTables(sqlite3 *db){
3424070ae3beSdrh #ifndef SQLITE_OMIT_VIRTUALTABLE
3425070ae3beSdrh   if( (db->flags & SQLITE_Defensive)!=0
3426070ae3beSdrh    && db->pVtabCtx==0
3427070ae3beSdrh    && db->nVdbeExec==0
342873983658Sdan    && !sqlite3VtabInSync(db)
3429070ae3beSdrh   ){
3430070ae3beSdrh     return 1;
3431070ae3beSdrh   }
3432070ae3beSdrh #endif
3433070ae3beSdrh   return 0;
3434070ae3beSdrh }
3435070ae3beSdrh 
3436070ae3beSdrh /*
3437d0c51d1aSdrh ** Return true if it is not allowed to drop the given table
3438d0c51d1aSdrh */
tableMayNotBeDropped(sqlite3 * db,Table * pTab)3439070ae3beSdrh static int tableMayNotBeDropped(sqlite3 *db, Table *pTab){
3440d0c51d1aSdrh   if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
3441d0c51d1aSdrh     if( sqlite3StrNICmp(pTab->zName+7, "stat", 4)==0 ) return 0;
3442d0c51d1aSdrh     if( sqlite3StrNICmp(pTab->zName+7, "parameters", 10)==0 ) return 0;
3443d0c51d1aSdrh     return 1;
3444d0c51d1aSdrh   }
3445070ae3beSdrh   if( (pTab->tabFlags & TF_Shadow)!=0 && sqlite3ReadOnlyShadowTables(db) ){
3446070ae3beSdrh     return 1;
3447d0c51d1aSdrh   }
344835c7312fSdan   if( pTab->tabFlags & TF_Eponymous ){
344935c7312fSdan     return 1;
345035c7312fSdan   }
3451d0c51d1aSdrh   return 0;
3452d0c51d1aSdrh }
3453d0c51d1aSdrh 
3454d0c51d1aSdrh /*
345575897234Sdrh ** This routine is called to do the work of a DROP TABLE statement.
3456d9b0257aSdrh ** pName is the name of the table to be dropped.
345775897234Sdrh */
sqlite3DropTable(Parse * pParse,SrcList * pName,int isView,int noErr)3458a073384fSdrh void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
3459a8858103Sdanielk1977   Table *pTab;
346075897234Sdrh   Vdbe *v;
34619bb575fdSdrh   sqlite3 *db = pParse->db;
3462d24cc427Sdrh   int iDb;
346375897234Sdrh 
34648af73d41Sdrh   if( db->mallocFailed ){
34656f7adc8aSdrh     goto exit_drop_table;
34666f7adc8aSdrh   }
34678af73d41Sdrh   assert( pParse->nErr==0 );
3468a8858103Sdanielk1977   assert( pName->nSrc==1 );
346975209969Sdrh   if( sqlite3ReadSchema(pParse) ) goto exit_drop_table;
3470a7564663Sdrh   if( noErr ) db->suppressErr++;
34714d249e61Sdrh   assert( isView==0 || isView==LOCATE_VIEW );
347241fb5cd1Sdan   pTab = sqlite3LocateTableItem(pParse, isView, &pName->a[0]);
3473a7564663Sdrh   if( noErr ) db->suppressErr--;
3474a8858103Sdanielk1977 
3475a073384fSdrh   if( pTab==0 ){
347631da7be9Sdrh     if( noErr ){
347731da7be9Sdrh       sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
347831da7be9Sdrh       sqlite3ForceNotReadOnly(pParse);
347931da7be9Sdrh     }
3480a073384fSdrh     goto exit_drop_table;
3481a073384fSdrh   }
3482da184236Sdanielk1977   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
3483e22a334bSdrh   assert( iDb>=0 && iDb<db->nDb );
3484b5258c3dSdanielk1977 
3485b5258c3dSdanielk1977   /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
3486b5258c3dSdanielk1977   ** it is initialized.
3487b5258c3dSdanielk1977   */
3488b5258c3dSdanielk1977   if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){
3489b5258c3dSdanielk1977     goto exit_drop_table;
3490b5258c3dSdanielk1977   }
3491e5f9c644Sdrh #ifndef SQLITE_OMIT_AUTHORIZATION
3492e5f9c644Sdrh   {
3493e5f9c644Sdrh     int code;
3494da184236Sdanielk1977     const char *zTab = SCHEMA_TABLE(iDb);
349569c33826Sdrh     const char *zDb = db->aDb[iDb].zDbSName;
3496f1a381e7Sdanielk1977     const char *zArg2 = 0;
34974adee20fSdanielk1977     if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
3498a8858103Sdanielk1977       goto exit_drop_table;
3499e22a334bSdrh     }
3500e5f9c644Sdrh     if( isView ){
350153c0f748Sdanielk1977       if( !OMIT_TEMPDB && iDb==1 ){
3502e5f9c644Sdrh         code = SQLITE_DROP_TEMP_VIEW;
3503e5f9c644Sdrh       }else{
3504e5f9c644Sdrh         code = SQLITE_DROP_VIEW;
3505e5f9c644Sdrh       }
35064b2688abSdanielk1977 #ifndef SQLITE_OMIT_VIRTUALTABLE
3507f1a381e7Sdanielk1977     }else if( IsVirtual(pTab) ){
3508f1a381e7Sdanielk1977       code = SQLITE_DROP_VTABLE;
3509595a523aSdanielk1977       zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName;
35104b2688abSdanielk1977 #endif
3511e5f9c644Sdrh     }else{
351253c0f748Sdanielk1977       if( !OMIT_TEMPDB && iDb==1 ){
3513e5f9c644Sdrh         code = SQLITE_DROP_TEMP_TABLE;
3514e5f9c644Sdrh       }else{
3515e5f9c644Sdrh         code = SQLITE_DROP_TABLE;
3516e5f9c644Sdrh       }
3517e5f9c644Sdrh     }
3518f1a381e7Sdanielk1977     if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
3519a8858103Sdanielk1977       goto exit_drop_table;
3520e5f9c644Sdrh     }
3521a8858103Sdanielk1977     if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
3522a8858103Sdanielk1977       goto exit_drop_table;
352377ad4e41Sdrh     }
3524e5f9c644Sdrh   }
3525e5f9c644Sdrh #endif
3526070ae3beSdrh   if( tableMayNotBeDropped(db, pTab) ){
3527a8858103Sdanielk1977     sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
3528a8858103Sdanielk1977     goto exit_drop_table;
352975897234Sdrh   }
3530576ec6b3Sdanielk1977 
3531576ec6b3Sdanielk1977 #ifndef SQLITE_OMIT_VIEW
3532576ec6b3Sdanielk1977   /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
3533576ec6b3Sdanielk1977   ** on a table.
3534576ec6b3Sdanielk1977   */
3535f38524d2Sdrh   if( isView && !IsView(pTab) ){
3536a8858103Sdanielk1977     sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
3537a8858103Sdanielk1977     goto exit_drop_table;
35384ff6dfa7Sdrh   }
3539f38524d2Sdrh   if( !isView && IsView(pTab) ){
3540a8858103Sdanielk1977     sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
3541a8858103Sdanielk1977     goto exit_drop_table;
35424ff6dfa7Sdrh   }
3543576ec6b3Sdanielk1977 #endif
354475897234Sdrh 
3545067b92baSdrh   /* Generate code to remove the table from the schema table
35461ccde15dSdrh   ** on disk.
35471ccde15dSdrh   */
35484adee20fSdanielk1977   v = sqlite3GetVdbe(pParse);
354975897234Sdrh   if( v ){
355077658e2fSdrh     sqlite3BeginWriteOperation(pParse, 1, iDb);
35510fc2da3fSmistachkin     if( !isView ){
3552a5ae4c33Sdrh       sqlite3ClearStatTables(pParse, iDb, "tbl", pTab->zName);
3553e0bc4048Sdrh       sqlite3FkDropTable(pParse, pName, pTab);
35540fc2da3fSmistachkin     }
3555faacf17cSdrh     sqlite3CodeDropTable(pParse, pTab, iDb, isView);
35564ff6dfa7Sdrh   }
35572958a4e6Sdrh 
3558a8858103Sdanielk1977 exit_drop_table:
3559633e6d57Sdrh   sqlite3SrcListDelete(db, pName);
356075897234Sdrh }
356175897234Sdrh 
356275897234Sdrh /*
3563c2eef3b3Sdrh ** This routine is called to create a new foreign key on the table
3564c2eef3b3Sdrh ** currently under construction.  pFromCol determines which columns
3565c2eef3b3Sdrh ** in the current table point to the foreign key.  If pFromCol==0 then
3566c2eef3b3Sdrh ** connect the key to the last column inserted.  pTo is the name of
3567bd50a926Sdrh ** the table referred to (a.k.a the "parent" table).  pToCol is a list
3568bd50a926Sdrh ** of tables in the parent pTo table.  flags contains all
3569c2eef3b3Sdrh ** information about the conflict resolution algorithms specified
3570c2eef3b3Sdrh ** in the ON DELETE, ON UPDATE and ON INSERT clauses.
3571c2eef3b3Sdrh **
3572c2eef3b3Sdrh ** An FKey structure is created and added to the table currently
3573e61922a6Sdrh ** under construction in the pParse->pNewTable field.
3574c2eef3b3Sdrh **
3575c2eef3b3Sdrh ** The foreign key is set for IMMEDIATE processing.  A subsequent call
35764adee20fSdanielk1977 ** to sqlite3DeferForeignKey() might change this to DEFERRED.
3577c2eef3b3Sdrh */
sqlite3CreateForeignKey(Parse * pParse,ExprList * pFromCol,Token * pTo,ExprList * pToCol,int flags)35784adee20fSdanielk1977 void sqlite3CreateForeignKey(
3579c2eef3b3Sdrh   Parse *pParse,       /* Parsing context */
35800202b29eSdanielk1977   ExprList *pFromCol,  /* Columns in this table that point to other table */
3581c2eef3b3Sdrh   Token *pTo,          /* Name of the other table */
35820202b29eSdanielk1977   ExprList *pToCol,    /* Columns in the other table */
3583c2eef3b3Sdrh   int flags            /* Conflict resolution algorithms. */
3584c2eef3b3Sdrh ){
35851857693dSdanielk1977   sqlite3 *db = pParse->db;
3586b7f9164eSdrh #ifndef SQLITE_OMIT_FOREIGN_KEY
358740e016e4Sdrh   FKey *pFKey = 0;
35881da40a38Sdan   FKey *pNextTo;
3589c2eef3b3Sdrh   Table *p = pParse->pNewTable;
3590913306a5Sdrh   i64 nByte;
3591c2eef3b3Sdrh   int i;
3592c2eef3b3Sdrh   int nCol;
3593c2eef3b3Sdrh   char *z;
3594c2eef3b3Sdrh 
3595c2eef3b3Sdrh   assert( pTo!=0 );
35968af73d41Sdrh   if( p==0 || IN_DECLARE_VTAB ) goto fk_end;
3597c2eef3b3Sdrh   if( pFromCol==0 ){
3598c2eef3b3Sdrh     int iCol = p->nCol-1;
3599d3001711Sdrh     if( NEVER(iCol<0) ) goto fk_end;
36000202b29eSdanielk1977     if( pToCol && pToCol->nExpr!=1 ){
36014adee20fSdanielk1977       sqlite3ErrorMsg(pParse, "foreign key on %s"
3602f7a9e1acSdrh          " should reference only one column of table %T",
3603cf9d36d1Sdrh          p->aCol[iCol].zCnName, pTo);
3604c2eef3b3Sdrh       goto fk_end;
3605c2eef3b3Sdrh     }
3606c2eef3b3Sdrh     nCol = 1;
36070202b29eSdanielk1977   }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
36084adee20fSdanielk1977     sqlite3ErrorMsg(pParse,
3609c2eef3b3Sdrh         "number of columns in foreign key does not match the number of "
3610f7a9e1acSdrh         "columns in the referenced table");
3611c2eef3b3Sdrh     goto fk_end;
3612c2eef3b3Sdrh   }else{
36130202b29eSdanielk1977     nCol = pFromCol->nExpr;
3614c2eef3b3Sdrh   }
3615e61922a6Sdrh   nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1;
3616c2eef3b3Sdrh   if( pToCol ){
36170202b29eSdanielk1977     for(i=0; i<pToCol->nExpr; i++){
361841cee668Sdrh       nByte += sqlite3Strlen30(pToCol->a[i].zEName) + 1;
3619c2eef3b3Sdrh     }
3620c2eef3b3Sdrh   }
3621633e6d57Sdrh   pFKey = sqlite3DbMallocZero(db, nByte );
362217435752Sdrh   if( pFKey==0 ){
362317435752Sdrh     goto fk_end;
362417435752Sdrh   }
3625c2eef3b3Sdrh   pFKey->pFrom = p;
362678b2fa86Sdrh   assert( IsOrdinaryTable(p) );
3627f38524d2Sdrh   pFKey->pNextFrom = p->u.tab.pFKey;
3628e61922a6Sdrh   z = (char*)&pFKey->aCol[nCol];
3629df68f6b7Sdrh   pFKey->zTo = z;
3630c9461eccSdan   if( IN_RENAME_OBJECT ){
3631c9461eccSdan     sqlite3RenameTokenMap(pParse, (void*)z, pTo);
3632c9461eccSdan   }
3633c2eef3b3Sdrh   memcpy(z, pTo->z, pTo->n);
3634c2eef3b3Sdrh   z[pTo->n] = 0;
363570d9e9ccSdanielk1977   sqlite3Dequote(z);
3636c2eef3b3Sdrh   z += pTo->n+1;
3637c2eef3b3Sdrh   pFKey->nCol = nCol;
3638c2eef3b3Sdrh   if( pFromCol==0 ){
3639c2eef3b3Sdrh     pFKey->aCol[0].iFrom = p->nCol-1;
3640c2eef3b3Sdrh   }else{
3641c2eef3b3Sdrh     for(i=0; i<nCol; i++){
3642c2eef3b3Sdrh       int j;
3643c2eef3b3Sdrh       for(j=0; j<p->nCol; j++){
3644cf9d36d1Sdrh         if( sqlite3StrICmp(p->aCol[j].zCnName, pFromCol->a[i].zEName)==0 ){
3645c2eef3b3Sdrh           pFKey->aCol[i].iFrom = j;
3646c2eef3b3Sdrh           break;
3647c2eef3b3Sdrh         }
3648c2eef3b3Sdrh       }
3649c2eef3b3Sdrh       if( j>=p->nCol ){
36504adee20fSdanielk1977         sqlite3ErrorMsg(pParse,
3651f7a9e1acSdrh           "unknown column \"%s\" in foreign key definition",
365241cee668Sdrh           pFromCol->a[i].zEName);
3653c2eef3b3Sdrh         goto fk_end;
3654c2eef3b3Sdrh       }
3655c9461eccSdan       if( IN_RENAME_OBJECT ){
365641cee668Sdrh         sqlite3RenameTokenRemap(pParse, &pFKey->aCol[i], pFromCol->a[i].zEName);
3657cf8f2895Sdan       }
3658c2eef3b3Sdrh     }
3659c2eef3b3Sdrh   }
3660c2eef3b3Sdrh   if( pToCol ){
3661c2eef3b3Sdrh     for(i=0; i<nCol; i++){
366241cee668Sdrh       int n = sqlite3Strlen30(pToCol->a[i].zEName);
3663c2eef3b3Sdrh       pFKey->aCol[i].zCol = z;
3664c9461eccSdan       if( IN_RENAME_OBJECT ){
366541cee668Sdrh         sqlite3RenameTokenRemap(pParse, z, pToCol->a[i].zEName);
36666fe7f23fSdan       }
366741cee668Sdrh       memcpy(z, pToCol->a[i].zEName, n);
3668c2eef3b3Sdrh       z[n] = 0;
3669c2eef3b3Sdrh       z += n+1;
3670c2eef3b3Sdrh     }
3671c2eef3b3Sdrh   }
3672c2eef3b3Sdrh   pFKey->isDeferred = 0;
36738099ce6fSdan   pFKey->aAction[0] = (u8)(flags & 0xff);            /* ON DELETE action */
36748099ce6fSdan   pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff);    /* ON UPDATE action */
3675c2eef3b3Sdrh 
36762120608eSdrh   assert( sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
36771da40a38Sdan   pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash,
3678acbcb7e0Sdrh       pFKey->zTo, (void *)pFKey
36791da40a38Sdan   );
3680f59c5cacSdan   if( pNextTo==pFKey ){
36814a642b60Sdrh     sqlite3OomFault(db);
3682f59c5cacSdan     goto fk_end;
3683f59c5cacSdan   }
36841da40a38Sdan   if( pNextTo ){
36851da40a38Sdan     assert( pNextTo->pPrevTo==0 );
36861da40a38Sdan     pFKey->pNextTo = pNextTo;
36871da40a38Sdan     pNextTo->pPrevTo = pFKey;
36881da40a38Sdan   }
36891da40a38Sdan 
3690c2eef3b3Sdrh   /* Link the foreign key to the table as the last step.
3691c2eef3b3Sdrh   */
369278b2fa86Sdrh   assert( IsOrdinaryTable(p) );
3693f38524d2Sdrh   p->u.tab.pFKey = pFKey;
3694c2eef3b3Sdrh   pFKey = 0;
3695c2eef3b3Sdrh 
3696c2eef3b3Sdrh fk_end:
3697633e6d57Sdrh   sqlite3DbFree(db, pFKey);
3698b7f9164eSdrh #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
3699633e6d57Sdrh   sqlite3ExprListDelete(db, pFromCol);
3700633e6d57Sdrh   sqlite3ExprListDelete(db, pToCol);
3701c2eef3b3Sdrh }
3702c2eef3b3Sdrh 
3703c2eef3b3Sdrh /*
3704c2eef3b3Sdrh ** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
3705c2eef3b3Sdrh ** clause is seen as part of a foreign key definition.  The isDeferred
3706c2eef3b3Sdrh ** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
3707c2eef3b3Sdrh ** The behavior of the most recently created foreign key is adjusted
3708c2eef3b3Sdrh ** accordingly.
3709c2eef3b3Sdrh */
sqlite3DeferForeignKey(Parse * pParse,int isDeferred)37104adee20fSdanielk1977 void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
3711b7f9164eSdrh #ifndef SQLITE_OMIT_FOREIGN_KEY
3712c2eef3b3Sdrh   Table *pTab;
3713c2eef3b3Sdrh   FKey *pFKey;
3714f38524d2Sdrh   if( (pTab = pParse->pNewTable)==0 ) return;
371578b2fa86Sdrh   if( NEVER(!IsOrdinaryTable(pTab)) ) return;
3716f38524d2Sdrh   if( (pFKey = pTab->u.tab.pFKey)==0 ) return;
37174c429839Sdrh   assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */
37181bd10f8aSdrh   pFKey->isDeferred = (u8)isDeferred;
3719b7f9164eSdrh #endif
3720c2eef3b3Sdrh }
3721c2eef3b3Sdrh 
3722c2eef3b3Sdrh /*
3723063336a5Sdrh ** Generate code that will erase and refill index *pIdx.  This is
3724063336a5Sdrh ** used to initialize a newly created index or to recompute the
3725063336a5Sdrh ** content of an index in response to a REINDEX command.
3726063336a5Sdrh **
3727063336a5Sdrh ** if memRootPage is not negative, it means that the index is newly
37281db639ceSdrh ** created.  The register specified by memRootPage contains the
3729063336a5Sdrh ** root page number of the index.  If memRootPage is negative, then
3730063336a5Sdrh ** the index already exists and must be cleared before being refilled and
3731063336a5Sdrh ** the root page number of the index is taken from pIndex->tnum.
3732063336a5Sdrh */
sqlite3RefillIndex(Parse * pParse,Index * pIndex,int memRootPage)3733063336a5Sdrh static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
3734063336a5Sdrh   Table *pTab = pIndex->pTable;  /* The table that is indexed */
37356ab3a2ecSdanielk1977   int iTab = pParse->nTab++;     /* Btree cursor used for pTab */
37366ab3a2ecSdanielk1977   int iIdx = pParse->nTab++;     /* Btree cursor used for pIndex */
3737b07028f7Sdrh   int iSorter;                   /* Cursor opened by OpenSorter (if in use) */
3738063336a5Sdrh   int addr1;                     /* Address of top of loop */
37395134d135Sdan   int addr2;                     /* Address to jump to for next iteration */
3740abc38158Sdrh   Pgno tnum;                     /* Root page of index */
3741b2b9d3d7Sdrh   int iPartIdxLabel;             /* Jump to this label to skip a row */
3742063336a5Sdrh   Vdbe *v;                       /* Generate code into this virtual machine */
3743b3bf556eSdanielk1977   KeyInfo *pKey;                 /* KeyInfo for index */
374460ec914cSpeter.d.reid   int regRecord;                 /* Register holding assembled index record */
374517435752Sdrh   sqlite3 *db = pParse->db;      /* The database connection */
374617435752Sdrh   int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
3747063336a5Sdrh 
37481d54df88Sdanielk1977 #ifndef SQLITE_OMIT_AUTHORIZATION
37491d54df88Sdanielk1977   if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
375069c33826Sdrh       db->aDb[iDb].zDbSName ) ){
37511d54df88Sdanielk1977     return;
37521d54df88Sdanielk1977   }
37531d54df88Sdanielk1977 #endif
37541d54df88Sdanielk1977 
3755c00da105Sdanielk1977   /* Require a write-lock on the table to perform this operation */
3756c00da105Sdanielk1977   sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
3757c00da105Sdanielk1977 
3758063336a5Sdrh   v = sqlite3GetVdbe(pParse);
3759063336a5Sdrh   if( v==0 ) return;
3760063336a5Sdrh   if( memRootPage>=0 ){
3761abc38158Sdrh     tnum = (Pgno)memRootPage;
3762063336a5Sdrh   }else{
3763063336a5Sdrh     tnum = pIndex->tnum;
3764063336a5Sdrh   }
37652ec2fb22Sdrh   pKey = sqlite3KeyInfoOfIndex(pParse, pIndex);
37660c7d3d39Sdrh   assert( pKey!=0 || pParse->nErr );
3767a20fde64Sdan 
3768689ab897Sdan   /* Open the sorter cursor if we are to use one. */
3769689ab897Sdan   iSorter = pParse->nTab++;
3770fad9f9a8Sdan   sqlite3VdbeAddOp4(v, OP_SorterOpen, iSorter, 0, pIndex->nKeyCol, (char*)
37712ec2fb22Sdrh                     sqlite3KeyInfoRef(pKey), P4_KEYINFO);
3772a20fde64Sdan 
3773a20fde64Sdan   /* Open the table. Loop through all rows of the table, inserting index
3774a20fde64Sdan   ** records into the sorter. */
3775c00da105Sdanielk1977   sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
3776688852abSdrh   addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0); VdbeCoverage(v);
37772d401ab8Sdrh   regRecord = sqlite3GetTempReg(pParse);
37784031bafaSdrh   sqlite3MultiWrite(pParse);
3779689ab897Sdan 
37801c2c0b77Sdrh   sqlite3GenerateIndexKey(pParse,pIndex,iTab,regRecord,0,&iPartIdxLabel,0,0);
37815134d135Sdan   sqlite3VdbeAddOp2(v, OP_SorterInsert, iSorter, regRecord);
378287744513Sdrh   sqlite3ResolvePartIdxLabel(pParse, iPartIdxLabel);
3783688852abSdrh   sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1); VdbeCoverage(v);
3784a20fde64Sdan   sqlite3VdbeJumpHere(v, addr1);
37854415628aSdrh   if( memRootPage<0 ) sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
3786abc38158Sdrh   sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, (int)tnum, iDb,
37872ec2fb22Sdrh                     (char *)pKey, P4_KEYINFO);
37884415628aSdrh   sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR|((memRootPage>=0)?OPFLAG_P2ISREG:0));
37894415628aSdrh 
3790688852abSdrh   addr1 = sqlite3VdbeAddOp2(v, OP_SorterSort, iSorter, 0); VdbeCoverage(v);
379160de73e8Sdrh   if( IsUniqueIndex(pIndex) ){
37924031bafaSdrh     int j2 = sqlite3VdbeGoto(v, 1);
37935134d135Sdan     addr2 = sqlite3VdbeCurrentAddr(v);
37944031bafaSdrh     sqlite3VdbeVerifyAbortable(v, OE_Abort);
37951153c7b2Sdrh     sqlite3VdbeAddOp4Int(v, OP_SorterCompare, iSorter, j2, regRecord,
3796ac50232dSdrh                          pIndex->nKeyCol); VdbeCoverage(v);
3797f9c8ce3cSdrh     sqlite3UniqueConstraint(pParse, OE_Abort, pIndex);
37984031bafaSdrh     sqlite3VdbeJumpHere(v, j2);
37995134d135Sdan   }else{
38007ed6c068Sdan     /* Most CREATE INDEX and REINDEX statements that are not UNIQUE can not
38017ed6c068Sdan     ** abort. The exception is if one of the indexed expressions contains a
38027ed6c068Sdan     ** user function that throws an exception when it is evaluated. But the
38037ed6c068Sdan     ** overhead of adding a statement journal to a CREATE INDEX statement is
38047ed6c068Sdan     ** very small (since most of the pages written do not contain content that
38057ed6c068Sdan     ** needs to be restored if the statement aborts), so we call
38067ed6c068Sdan     ** sqlite3MayAbort() for all CREATE INDEX statements.  */
3807ef14abbfSdan     sqlite3MayAbort(pParse);
38085134d135Sdan     addr2 = sqlite3VdbeCurrentAddr(v);
3809689ab897Sdan   }
38106cf4a7dfSdrh   sqlite3VdbeAddOp3(v, OP_SorterData, iSorter, regRecord, iIdx);
3811bf9ff256Sdrh   if( !pIndex->bAscKeyBug ){
3812bf9ff256Sdrh     /* This OP_SeekEnd opcode makes index insert for a REINDEX go much
3813bf9ff256Sdrh     ** faster by avoiding unnecessary seeks.  But the optimization does
3814bf9ff256Sdrh     ** not work for UNIQUE constraint indexes on WITHOUT ROWID tables
3815bf9ff256Sdrh     ** with DESC primary keys, since those indexes have there keys in
3816bf9ff256Sdrh     ** a different order from the main table.
3817bf9ff256Sdrh     ** See ticket: https://www.sqlite.org/src/info/bba7b69f9849b5bf
3818bf9ff256Sdrh     */
381986b40dfdSdrh     sqlite3VdbeAddOp1(v, OP_SeekEnd, iIdx);
3820bf9ff256Sdrh   }
38219b4eaebcSdrh   sqlite3VdbeAddOp2(v, OP_IdxInsert, iIdx, regRecord);
3822ca892a72Sdrh   sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
38232d401ab8Sdrh   sqlite3ReleaseTempReg(pParse, regRecord);
3824688852abSdrh   sqlite3VdbeAddOp2(v, OP_SorterNext, iSorter, addr2); VdbeCoverage(v);
3825d654be80Sdrh   sqlite3VdbeJumpHere(v, addr1);
3826a20fde64Sdan 
382766a5167bSdrh   sqlite3VdbeAddOp1(v, OP_Close, iTab);
382866a5167bSdrh   sqlite3VdbeAddOp1(v, OP_Close, iIdx);
3829689ab897Sdan   sqlite3VdbeAddOp1(v, OP_Close, iSorter);
3830063336a5Sdrh }
3831063336a5Sdrh 
3832063336a5Sdrh /*
383377e57dfbSdrh ** Allocate heap space to hold an Index object with nCol columns.
383477e57dfbSdrh **
383577e57dfbSdrh ** Increase the allocation size to provide an extra nExtra bytes
383677e57dfbSdrh ** of 8-byte aligned space after the Index object and return a
383777e57dfbSdrh ** pointer to this extra space in *ppExtra.
383877e57dfbSdrh */
sqlite3AllocateIndexObject(sqlite3 * db,i16 nCol,int nExtra,char ** ppExtra)383977e57dfbSdrh Index *sqlite3AllocateIndexObject(
384077e57dfbSdrh   sqlite3 *db,         /* Database connection */
3841bbbdc83bSdrh   i16 nCol,            /* Total number of columns in the index */
384277e57dfbSdrh   int nExtra,          /* Number of bytes of extra space to alloc */
384377e57dfbSdrh   char **ppExtra       /* Pointer to the "extra" space */
384477e57dfbSdrh ){
384577e57dfbSdrh   Index *p;            /* Allocated index object */
384677e57dfbSdrh   int nByte;           /* Bytes of space for Index object + arrays */
384777e57dfbSdrh 
384877e57dfbSdrh   nByte = ROUND8(sizeof(Index)) +              /* Index structure  */
384977e57dfbSdrh           ROUND8(sizeof(char*)*nCol) +         /* Index.azColl     */
3850cfc9df76Sdan           ROUND8(sizeof(LogEst)*(nCol+1) +     /* Index.aiRowLogEst   */
3851bbbdc83bSdrh                  sizeof(i16)*nCol +            /* Index.aiColumn   */
385277e57dfbSdrh                  sizeof(u8)*nCol);             /* Index.aSortOrder */
385377e57dfbSdrh   p = sqlite3DbMallocZero(db, nByte + nExtra);
385477e57dfbSdrh   if( p ){
385577e57dfbSdrh     char *pExtra = ((char*)p)+ROUND8(sizeof(Index));
3856f19aa5faSdrh     p->azColl = (const char**)pExtra; pExtra += ROUND8(sizeof(char*)*nCol);
3857cfc9df76Sdan     p->aiRowLogEst = (LogEst*)pExtra; pExtra += sizeof(LogEst)*(nCol+1);
3858bbbdc83bSdrh     p->aiColumn = (i16*)pExtra;       pExtra += sizeof(i16)*nCol;
385977e57dfbSdrh     p->aSortOrder = (u8*)pExtra;
386077e57dfbSdrh     p->nColumn = nCol;
3861bbbdc83bSdrh     p->nKeyCol = nCol - 1;
386277e57dfbSdrh     *ppExtra = ((char*)p) + nByte;
386377e57dfbSdrh   }
386477e57dfbSdrh   return p;
386577e57dfbSdrh }
386677e57dfbSdrh 
386777e57dfbSdrh /*
38689105fd51Sdan ** If expression list pList contains an expression that was parsed with
38699105fd51Sdan ** an explicit "NULLS FIRST" or "NULLS LAST" clause, leave an error in
38709105fd51Sdan ** pParse and return non-zero. Otherwise, return zero.
38719105fd51Sdan */
sqlite3HasExplicitNulls(Parse * pParse,ExprList * pList)38729105fd51Sdan int sqlite3HasExplicitNulls(Parse *pParse, ExprList *pList){
38739105fd51Sdan   if( pList ){
38749105fd51Sdan     int i;
38759105fd51Sdan     for(i=0; i<pList->nExpr; i++){
3876d88fd539Sdrh       if( pList->a[i].fg.bNulls ){
3877d88fd539Sdrh         u8 sf = pList->a[i].fg.sortFlags;
38789105fd51Sdan         sqlite3ErrorMsg(pParse, "unsupported use of NULLS %s",
38799105fd51Sdan             (sf==0 || sf==3) ? "FIRST" : "LAST"
38809105fd51Sdan         );
38819105fd51Sdan         return 1;
38829105fd51Sdan       }
38839105fd51Sdan     }
38849105fd51Sdan   }
38859105fd51Sdan   return 0;
38869105fd51Sdan }
38879105fd51Sdan 
38889105fd51Sdan /*
388923bf66d6Sdrh ** Create a new index for an SQL table.  pName1.pName2 is the name of the index
389023bf66d6Sdrh ** and pTblList is the name of the table that is to be indexed.  Both will
3891adbca9cfSdrh ** be NULL for a primary key or an index that is created to satisfy a
3892adbca9cfSdrh ** UNIQUE constraint.  If pTable and pIndex are NULL, use pParse->pNewTable
3893382c0247Sdrh ** as the table to be indexed.  pParse->pNewTable is a table that is
3894382c0247Sdrh ** currently being constructed by a CREATE TABLE statement.
389575897234Sdrh **
3896382c0247Sdrh ** pList is a list of columns to be indexed.  pList will be NULL if this
3897382c0247Sdrh ** is a primary key or unique-constraint on the most recent column added
3898382c0247Sdrh ** to the table currently under construction.
389975897234Sdrh */
sqlite3CreateIndex(Parse * pParse,Token * pName1,Token * pName2,SrcList * pTblName,ExprList * pList,int onError,Token * pStart,Expr * pPIWhere,int sortOrder,int ifNotExist,u8 idxType)390062340f84Sdrh void sqlite3CreateIndex(
390175897234Sdrh   Parse *pParse,     /* All information about this parse */
3902cbb18d22Sdanielk1977   Token *pName1,     /* First part of index name. May be NULL */
3903cbb18d22Sdanielk1977   Token *pName2,     /* Second part of index name. May be NULL */
39040202b29eSdanielk1977   SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
39050202b29eSdanielk1977   ExprList *pList,   /* A list of columns to be indexed */
39069cfcf5d4Sdrh   int onError,       /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
39071c55ba09Sdrh   Token *pStart,     /* The CREATE token that begins this statement */
39081fe0537eSdrh   Expr *pPIWhere,    /* WHERE clause for partial indices */
39094d91a701Sdrh   int sortOrder,     /* Sort order of primary key when pList==NULL */
391062340f84Sdrh   int ifNotExist,    /* Omit error if index already exists */
391162340f84Sdrh   u8 idxType         /* The index type */
391275897234Sdrh ){
3913cbb18d22Sdanielk1977   Table *pTab = 0;     /* Table to be indexed */
3914d8123366Sdanielk1977   Index *pIndex = 0;   /* The index to be created */
3915fdd6e85aSdrh   char *zName = 0;     /* Name of the index */
3916fdd6e85aSdrh   int nName;           /* Number of characters in zName */
3917beae3194Sdrh   int i, j;
3918f26e09c8Sdrh   DbFixer sFix;        /* For assigning database names to pTable */
3919fdd6e85aSdrh   int sortOrderMask;   /* 1 to honor DESC in index.  0 to ignore. */
39209bb575fdSdrh   sqlite3 *db = pParse->db;
3921fdd6e85aSdrh   Db *pDb;             /* The specific table containing the indexed database */
3922cbb18d22Sdanielk1977   int iDb;             /* Index of the database that is being written */
3923cbb18d22Sdanielk1977   Token *pName = 0;    /* Unqualified name of the index to create */
3924fdd6e85aSdrh   struct ExprList_item *pListItem; /* For looping over pList */
3925c28c4e50Sdrh   int nExtra = 0;                  /* Space allocated for zExtra[] */
39264415628aSdrh   int nExtraCol;                   /* Number of extra columns needed */
392747b927d2Sdrh   char *zExtra = 0;                /* Extra space after the Index object */
39284415628aSdrh   Index *pPk = 0;      /* PRIMARY KEY index for WITHOUT ROWID tables */
3929cbb18d22Sdanielk1977 
39300c7d3d39Sdrh   assert( db->pParse==pParse );
39310c7d3d39Sdrh   if( pParse->nErr ){
393262340f84Sdrh     goto exit_create_index;
393362340f84Sdrh   }
39340c7d3d39Sdrh   assert( db->mallocFailed==0 );
393562340f84Sdrh   if( IN_DECLARE_VTAB && idxType!=SQLITE_IDXTYPE_PRIMARYKEY ){
3936d3001711Sdrh     goto exit_create_index;
3937d3001711Sdrh   }
3938d3001711Sdrh   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
3939e501b89aSdanielk1977     goto exit_create_index;
3940e501b89aSdanielk1977   }
39419105fd51Sdan   if( sqlite3HasExplicitNulls(pParse, pList) ){
39429105fd51Sdan     goto exit_create_index;
39439105fd51Sdan   }
3944daffd0e5Sdrh 
394575897234Sdrh   /*
394675897234Sdrh   ** Find the table that is to be indexed.  Return early if not found.
394775897234Sdrh   */
3948cbb18d22Sdanielk1977   if( pTblName!=0 ){
3949cbb18d22Sdanielk1977 
3950cbb18d22Sdanielk1977     /* Use the two-part index name to determine the database
3951ef2cb63eSdanielk1977     ** to search for the table. 'Fix' the table name to this db
3952ef2cb63eSdanielk1977     ** before looking up the table.
3953cbb18d22Sdanielk1977     */
3954cbb18d22Sdanielk1977     assert( pName1 && pName2 );
3955ef2cb63eSdanielk1977     iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
3956cbb18d22Sdanielk1977     if( iDb<0 ) goto exit_create_index;
3957b07028f7Sdrh     assert( pName && pName->z );
3958cbb18d22Sdanielk1977 
395953c0f748Sdanielk1977 #ifndef SQLITE_OMIT_TEMPDB
3960d5578433Smistachkin     /* If the index name was unqualified, check if the table
3961fe910339Sdanielk1977     ** is a temp table. If so, set the database to 1. Do not do this
3962fe910339Sdanielk1977     ** if initialising a database schema.
3963cbb18d22Sdanielk1977     */
3964fe910339Sdanielk1977     if( !db->init.busy ){
3965ef2cb63eSdanielk1977       pTab = sqlite3SrcListLookup(pParse, pTblName);
3966d3001711Sdrh       if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
3967ef2cb63eSdanielk1977         iDb = 1;
3968ef2cb63eSdanielk1977       }
3969fe910339Sdanielk1977     }
397053c0f748Sdanielk1977 #endif
3971ef2cb63eSdanielk1977 
3972d100f691Sdrh     sqlite3FixInit(&sFix, pParse, iDb, "index", pName);
3973d100f691Sdrh     if( sqlite3FixSrcList(&sFix, pTblName) ){
397485c23c61Sdrh       /* Because the parser constructs pTblName from a single identifier,
397585c23c61Sdrh       ** sqlite3FixSrcList can never fail. */
397685c23c61Sdrh       assert(0);
3977cbb18d22Sdanielk1977     }
397841fb5cd1Sdan     pTab = sqlite3LocateTableItem(pParse, 0, &pTblName->a[0]);
3979c31c7c1cSdrh     assert( db->mallocFailed==0 || pTab==0 );
3980c31c7c1cSdrh     if( pTab==0 ) goto exit_create_index;
3981989b116aSdrh     if( iDb==1 && db->aDb[iDb].pSchema!=pTab->pSchema ){
3982989b116aSdrh       sqlite3ErrorMsg(pParse,
3983989b116aSdrh            "cannot create a TEMP index on non-TEMP table \"%s\"",
3984989b116aSdrh            pTab->zName);
3985989b116aSdrh       goto exit_create_index;
3986989b116aSdrh     }
39874415628aSdrh     if( !HasRowid(pTab) ) pPk = sqlite3PrimaryKeyIndex(pTab);
398875897234Sdrh   }else{
3989e3c41372Sdrh     assert( pName==0 );
3990b07028f7Sdrh     assert( pStart==0 );
399175897234Sdrh     pTab = pParse->pNewTable;
3992a6370df1Sdrh     if( !pTab ) goto exit_create_index;
3993da184236Sdanielk1977     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
399475897234Sdrh   }
3995fdd6e85aSdrh   pDb = &db->aDb[iDb];
3996cbb18d22Sdanielk1977 
3997d3001711Sdrh   assert( pTab!=0 );
39980388123fSdrh   if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
39993a3a03f2Sdrh        && db->init.busy==0
4000346f4e26Sdrh        && pTblName!=0
4001d4530979Sdrh #if SQLITE_USER_AUTHENTICATION
4002d4530979Sdrh        && sqlite3UserAuthTable(pTab->zName)==0
4003d4530979Sdrh #endif
40048c2e6c5fSdrh   ){
40054adee20fSdanielk1977     sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
40060be9df07Sdrh     goto exit_create_index;
40070be9df07Sdrh   }
4008576ec6b3Sdanielk1977 #ifndef SQLITE_OMIT_VIEW
4009f38524d2Sdrh   if( IsView(pTab) ){
40104adee20fSdanielk1977     sqlite3ErrorMsg(pParse, "views may not be indexed");
4011a76b5dfcSdrh     goto exit_create_index;
4012a76b5dfcSdrh   }
4013576ec6b3Sdanielk1977 #endif
40145ee9d697Sdanielk1977 #ifndef SQLITE_OMIT_VIRTUALTABLE
40155ee9d697Sdanielk1977   if( IsVirtual(pTab) ){
40165ee9d697Sdanielk1977     sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
40175ee9d697Sdanielk1977     goto exit_create_index;
40185ee9d697Sdanielk1977   }
40195ee9d697Sdanielk1977 #endif
402075897234Sdrh 
402175897234Sdrh   /*
402275897234Sdrh   ** Find the name of the index.  Make sure there is not already another
4023f57b3399Sdrh   ** index or table with the same name.
4024f57b3399Sdrh   **
4025f57b3399Sdrh   ** Exception:  If we are reading the names of permanent indices from the
40261e32bed3Sdrh   ** sqlite_schema table (because some other process changed the schema) and
4027f57b3399Sdrh   ** one of the index names collides with the name of a temporary table or
4028d24cc427Sdrh   ** index, then we will continue to process this index.
4029f57b3399Sdrh   **
4030f57b3399Sdrh   ** If pName==0 it means that we are
4031adbca9cfSdrh   ** dealing with a primary key or UNIQUE constraint.  We have to invent our
4032adbca9cfSdrh   ** own name.
403375897234Sdrh   */
4034d8123366Sdanielk1977   if( pName ){
403517435752Sdrh     zName = sqlite3NameFromToken(db, pName);
4036d8123366Sdanielk1977     if( zName==0 ) goto exit_create_index;
4037b07028f7Sdrh     assert( pName->z!=0 );
4038c5a93d4cSdrh     if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName,"index",pTab->zName) ){
4039d8123366Sdanielk1977       goto exit_create_index;
4040d8123366Sdanielk1977     }
4041c9461eccSdan     if( !IN_RENAME_OBJECT ){
4042d8123366Sdanielk1977       if( !db->init.busy ){
4043626bcc88Sdrh         if( sqlite3FindTable(db, zName, pDb->zDbSName)!=0 ){
4044d45a0315Sdanielk1977           sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
4045d45a0315Sdanielk1977           goto exit_create_index;
4046d45a0315Sdanielk1977         }
4047d45a0315Sdanielk1977       }
404869c33826Sdrh       if( sqlite3FindIndex(db, zName, pDb->zDbSName)!=0 ){
40494d91a701Sdrh         if( !ifNotExist ){
40504adee20fSdanielk1977           sqlite3ErrorMsg(pParse, "index %s already exists", zName);
40517687c83dSdan         }else{
40527687c83dSdan           assert( !db->init.busy );
40537687c83dSdan           sqlite3CodeVerifySchema(pParse, iDb);
405431da7be9Sdrh           sqlite3ForceNotReadOnly(pParse);
40554d91a701Sdrh         }
405675897234Sdrh         goto exit_create_index;
405775897234Sdrh       }
4058cf8f2895Sdan     }
4059a21c6b6fSdanielk1977   }else{
4060adbca9cfSdrh     int n;
4061adbca9cfSdrh     Index *pLoop;
4062adbca9cfSdrh     for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
4063f089aa45Sdrh     zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n);
4064a1644fd8Sdanielk1977     if( zName==0 ){
4065a1644fd8Sdanielk1977       goto exit_create_index;
4066a1644fd8Sdanielk1977     }
40670aafa9c8Sdrh 
40680aafa9c8Sdrh     /* Automatic index names generated from within sqlite3_declare_vtab()
40690aafa9c8Sdrh     ** must have names that are distinct from normal automatic index names.
40700aafa9c8Sdrh     ** The following statement converts "sqlite3_autoindex..." into
40710aafa9c8Sdrh     ** "sqlite3_butoindex..." in order to make the names distinct.
40720aafa9c8Sdrh     ** The "vtab_err.test" test demonstrates the need of this statement. */
4073cf8f2895Sdan     if( IN_SPECIAL_PARSE ) zName[7]++;
4074e3c41372Sdrh   }
407575897234Sdrh 
4076e5f9c644Sdrh   /* Check for authorization to create an index.
4077e5f9c644Sdrh   */
4078e5f9c644Sdrh #ifndef SQLITE_OMIT_AUTHORIZATION
4079c9461eccSdan   if( !IN_RENAME_OBJECT ){
408069c33826Sdrh     const char *zDb = pDb->zDbSName;
408153c0f748Sdanielk1977     if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
4082e5f9c644Sdrh       goto exit_create_index;
4083e5f9c644Sdrh     }
4084e5f9c644Sdrh     i = SQLITE_CREATE_INDEX;
408553c0f748Sdanielk1977     if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
40864adee20fSdanielk1977     if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
4087e5f9c644Sdrh       goto exit_create_index;
4088e5f9c644Sdrh     }
4089e22a334bSdrh   }
4090e5f9c644Sdrh #endif
4091e5f9c644Sdrh 
409275897234Sdrh   /* If pList==0, it means this routine was called to make a primary
40931ccde15dSdrh   ** key out of the last column added to the table under construction.
409475897234Sdrh   ** So create a fake list to simulate this.
409575897234Sdrh   */
409675897234Sdrh   if( pList==0 ){
4097108aa00aSdrh     Token prevCol;
409826e731ccSdan     Column *pCol = &pTab->aCol[pTab->nCol-1];
409926e731ccSdan     pCol->colFlags |= COLFLAG_UNIQUE;
4100cf9d36d1Sdrh     sqlite3TokenInit(&prevCol, pCol->zCnName);
4101108aa00aSdrh     pList = sqlite3ExprListAppend(pParse, 0,
4102108aa00aSdrh               sqlite3ExprAlloc(db, TK_ID, &prevCol, 0));
410375897234Sdrh     if( pList==0 ) goto exit_create_index;
4104bc622bc0Sdrh     assert( pList->nExpr==1 );
41055b32bdffSdan     sqlite3ExprListSetSortOrder(pList, sortOrder, SQLITE_SO_UNDEFINED);
4106108aa00aSdrh   }else{
4107108aa00aSdrh     sqlite3ExprListCheckLength(pParse, pList, "index");
41088fe25c64Sdrh     if( pParse->nErr ) goto exit_create_index;
410975897234Sdrh   }
411075897234Sdrh 
4111b3bf556eSdanielk1977   /* Figure out how many bytes of space are required to store explicitly
4112b3bf556eSdanielk1977   ** specified collation sequence names.
4113b3bf556eSdanielk1977   */
4114b3bf556eSdanielk1977   for(i=0; i<pList->nExpr; i++){
4115d3001711Sdrh     Expr *pExpr = pList->a[i].pExpr;
41167d3d9daeSdrh     assert( pExpr!=0 );
41177d3d9daeSdrh     if( pExpr->op==TK_COLLATE ){
4118f9751074Sdrh       assert( !ExprHasProperty(pExpr, EP_IntValue) );
4119911ce418Sdan       nExtra += (1 + sqlite3Strlen30(pExpr->u.zToken));
4120b3bf556eSdanielk1977     }
4121d3001711Sdrh   }
4122b3bf556eSdanielk1977 
412375897234Sdrh   /*
412475897234Sdrh   ** Allocate the index structure.
412575897234Sdrh   */
4126ea678832Sdrh   nName = sqlite3Strlen30(zName);
41274415628aSdrh   nExtraCol = pPk ? pPk->nKeyCol : 1;
41288fe25c64Sdrh   assert( pList->nExpr + nExtraCol <= 32767 /* Fits in i16 */ );
41294415628aSdrh   pIndex = sqlite3AllocateIndexObject(db, pList->nExpr + nExtraCol,
413077e57dfbSdrh                                       nName + nExtra + 1, &zExtra);
413117435752Sdrh   if( db->mallocFailed ){
413217435752Sdrh     goto exit_create_index;
413317435752Sdrh   }
4134cfc9df76Sdan   assert( EIGHT_BYTE_ALIGNMENT(pIndex->aiRowLogEst) );
4135e09b84c5Sdrh   assert( EIGHT_BYTE_ALIGNMENT(pIndex->azColl) );
413677e57dfbSdrh   pIndex->zName = zExtra;
413777e57dfbSdrh   zExtra += nName + 1;
41385bb3eb9bSdrh   memcpy(pIndex->zName, zName, nName+1);
413975897234Sdrh   pIndex->pTable = pTab;
41401bd10f8aSdrh   pIndex->onError = (u8)onError;
41419eade087Sdrh   pIndex->uniqNotNull = onError!=OE_None;
414262340f84Sdrh   pIndex->idxType = idxType;
4143da184236Sdanielk1977   pIndex->pSchema = db->aDb[iDb].pSchema;
414472ffd091Sdrh   pIndex->nKeyCol = pList->nExpr;
41453780be11Sdrh   if( pPIWhere ){
41463780be11Sdrh     sqlite3ResolveSelfReference(pParse, pTab, NC_PartIdx, pPIWhere, 0);
41471fe0537eSdrh     pIndex->pPartIdxWhere = pPIWhere;
41481fe0537eSdrh     pPIWhere = 0;
41493780be11Sdrh   }
41502120608eSdrh   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
415175897234Sdrh 
4152fdd6e85aSdrh   /* Check to see if we should honor DESC requests on index columns
4153fdd6e85aSdrh   */
4154da184236Sdanielk1977   if( pDb->pSchema->file_format>=4 ){
4155fdd6e85aSdrh     sortOrderMask = -1;   /* Honor DESC */
4156fdd6e85aSdrh   }else{
4157fdd6e85aSdrh     sortOrderMask = 0;    /* Ignore DESC */
4158fdd6e85aSdrh   }
4159fdd6e85aSdrh 
41601f9ca2c8Sdrh   /* Analyze the list of expressions that form the terms of the index and
41611f9ca2c8Sdrh   ** report any errors.  In the common case where the expression is exactly
41621f9ca2c8Sdrh   ** a table column, store that column in aiColumn[].  For general expressions,
41634b92f98cSdrh   ** populate pIndex->aColExpr and store XN_EXPR (-2) in aiColumn[].
4164d3001711Sdrh   **
41651f9ca2c8Sdrh   ** TODO: Issue a warning if two or more columns of the index are identical.
41661f9ca2c8Sdrh   ** TODO: Issue a warning if the table primary key is used as part of the
41671f9ca2c8Sdrh   ** index key.
416875897234Sdrh   */
4169cf8f2895Sdan   pListItem = pList->a;
4170c9461eccSdan   if( IN_RENAME_OBJECT ){
4171cf8f2895Sdan     pIndex->aColExpr = pList;
4172cf8f2895Sdan     pList = 0;
4173cf8f2895Sdan   }
4174cf8f2895Sdan   for(i=0; i<pIndex->nKeyCol; i++, pListItem++){
41751f9ca2c8Sdrh     Expr *pCExpr;                  /* The i-th index expression */
41761f9ca2c8Sdrh     int requestedSortOrder;        /* ASC or DESC on the i-th expression */
4177f19aa5faSdrh     const char *zColl;             /* Collation sequence name */
4178b3bf556eSdanielk1977 
4179edb04ed9Sdrh     sqlite3StringToId(pListItem->pExpr);
4180a514b8ebSdrh     sqlite3ResolveSelfReference(pParse, pTab, NC_IdxExpr, pListItem->pExpr, 0);
4181a514b8ebSdrh     if( pParse->nErr ) goto exit_create_index;
4182108aa00aSdrh     pCExpr = sqlite3ExprSkipCollate(pListItem->pExpr);
4183a514b8ebSdrh     if( pCExpr->op!=TK_COLUMN ){
41841f9ca2c8Sdrh       if( pTab==pParse->pNewTable ){
41851f9ca2c8Sdrh         sqlite3ErrorMsg(pParse, "expressions prohibited in PRIMARY KEY and "
41861f9ca2c8Sdrh                                 "UNIQUE constraints");
41871f9ca2c8Sdrh         goto exit_create_index;
4188108aa00aSdrh       }
41891f9ca2c8Sdrh       if( pIndex->aColExpr==0 ){
4190cf8f2895Sdan         pIndex->aColExpr = pList;
4191cf8f2895Sdan         pList = 0;
41921f9ca2c8Sdrh       }
41934b92f98cSdrh       j = XN_EXPR;
41944b92f98cSdrh       pIndex->aiColumn[i] = XN_EXPR;
41958492653cSdrh       pIndex->uniqNotNull = 0;
41964bc1cc18Sdrh       pIndex->bHasExpr = 1;
41971f9ca2c8Sdrh     }else{
4198a514b8ebSdrh       j = pCExpr->iColumn;
4199bf20a35dSdrh       assert( j<=0x7fff );
42001f9ca2c8Sdrh       if( j<0 ){
42011f9ca2c8Sdrh         j = pTab->iPKey;
4202c7476735Sdrh       }else{
4203c7476735Sdrh         if( pTab->aCol[j].notNull==0 ){
42041f9ca2c8Sdrh           pIndex->uniqNotNull = 0;
42051f9ca2c8Sdrh         }
4206c7476735Sdrh         if( pTab->aCol[j].colFlags & COLFLAG_VIRTUAL ){
4207c7476735Sdrh           pIndex->bHasVCol = 1;
420808535840Sdrh           pIndex->bHasExpr = 1;
4209c7476735Sdrh         }
4210c7476735Sdrh       }
4211bbbdc83bSdrh       pIndex->aiColumn[i] = (i16)j;
42121f9ca2c8Sdrh     }
4213a514b8ebSdrh     zColl = 0;
4214108aa00aSdrh     if( pListItem->pExpr->op==TK_COLLATE ){
4215d3001711Sdrh       int nColl;
4216f9751074Sdrh       assert( !ExprHasProperty(pListItem->pExpr, EP_IntValue) );
4217911ce418Sdan       zColl = pListItem->pExpr->u.zToken;
4218d3001711Sdrh       nColl = sqlite3Strlen30(zColl) + 1;
4219d3001711Sdrh       assert( nExtra>=nColl );
4220d3001711Sdrh       memcpy(zExtra, zColl, nColl);
4221b3bf556eSdanielk1977       zColl = zExtra;
4222d3001711Sdrh       zExtra += nColl;
4223d3001711Sdrh       nExtra -= nColl;
4224a514b8ebSdrh     }else if( j>=0 ){
422565b40093Sdrh       zColl = sqlite3ColumnColl(&pTab->aCol[j]);
4226b3bf556eSdanielk1977     }
4227f19aa5faSdrh     if( !zColl ) zColl = sqlite3StrBINARY;
4228b7f24de2Sdrh     if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){
42297cedc8d4Sdanielk1977       goto exit_create_index;
42307cedc8d4Sdanielk1977     }
4231b3bf556eSdanielk1977     pIndex->azColl[i] = zColl;
4232d88fd539Sdrh     requestedSortOrder = pListItem->fg.sortFlags & sortOrderMask;
42331bd10f8aSdrh     pIndex->aSortOrder[i] = (u8)requestedSortOrder;
42340202b29eSdanielk1977   }
42351f9ca2c8Sdrh 
42361f9ca2c8Sdrh   /* Append the table key to the end of the index.  For WITHOUT ROWID
42371f9ca2c8Sdrh   ** tables (when pPk!=0) this will be the declared PRIMARY KEY.  For
42381f9ca2c8Sdrh   ** normal tables (when pPk==0) this will be the rowid.
42391f9ca2c8Sdrh   */
42404415628aSdrh   if( pPk ){
42417913e41fSdrh     for(j=0; j<pPk->nKeyCol; j++){
42427913e41fSdrh       int x = pPk->aiColumn[j];
42431f9ca2c8Sdrh       assert( x>=0 );
4244f78d0f42Sdrh       if( isDupColumn(pIndex, pIndex->nKeyCol, pPk, j) ){
42457913e41fSdrh         pIndex->nColumn--;
42467913e41fSdrh       }else{
4247f78d0f42Sdrh         testcase( hasColumn(pIndex->aiColumn,pIndex->nKeyCol,x) );
42487913e41fSdrh         pIndex->aiColumn[i] = x;
42494415628aSdrh         pIndex->azColl[i] = pPk->azColl[j];
42504415628aSdrh         pIndex->aSortOrder[i] = pPk->aSortOrder[j];
42517913e41fSdrh         i++;
42524415628aSdrh       }
42537913e41fSdrh     }
42547913e41fSdrh     assert( i==pIndex->nColumn );
42554415628aSdrh   }else{
42564b92f98cSdrh     pIndex->aiColumn[i] = XN_ROWID;
4257f19aa5faSdrh     pIndex->azColl[i] = sqlite3StrBINARY;
4258f769cd61Sdan   }
4259f769cd61Sdan   sqlite3DefaultRowEst(pIndex);
4260f769cd61Sdan   if( pParse->pNewTable==0 ) estimateIndexWidth(pIndex);
4261f769cd61Sdan 
4262e1dd0608Sdrh   /* If this index contains every column of its table, then mark
4263e1dd0608Sdrh   ** it as a covering index */
4264f769cd61Sdan   assert( HasRowid(pTab)
4265b9bcf7caSdrh       || pTab->iPKey<0 || sqlite3TableColumnToIndex(pIndex, pTab->iPKey)>=0 );
42661fe3ac73Sdrh   recomputeColumnsNotIndexed(pIndex);
4267e1dd0608Sdrh   if( pTblName!=0 && pIndex->nColumn>=pTab->nCol ){
4268e1dd0608Sdrh     pIndex->isCovering = 1;
4269e1dd0608Sdrh     for(j=0; j<pTab->nCol; j++){
4270e1dd0608Sdrh       if( j==pTab->iPKey ) continue;
4271b9bcf7caSdrh       if( sqlite3TableColumnToIndex(pIndex,j)>=0 ) continue;
4272e1dd0608Sdrh       pIndex->isCovering = 0;
4273e1dd0608Sdrh       break;
4274e1dd0608Sdrh     }
4275e1dd0608Sdrh   }
427675897234Sdrh 
4277d8123366Sdanielk1977   if( pTab==pParse->pNewTable ){
4278d8123366Sdanielk1977     /* This routine has been called to create an automatic index as a
4279d8123366Sdanielk1977     ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
4280d8123366Sdanielk1977     ** a PRIMARY KEY or UNIQUE clause following the column definitions.
4281d8123366Sdanielk1977     ** i.e. one of:
4282d8123366Sdanielk1977     **
4283d8123366Sdanielk1977     ** CREATE TABLE t(x PRIMARY KEY, y);
4284d8123366Sdanielk1977     ** CREATE TABLE t(x, y, UNIQUE(x, y));
4285d8123366Sdanielk1977     **
4286d8123366Sdanielk1977     ** Either way, check to see if the table already has such an index. If
4287d8123366Sdanielk1977     ** so, don't bother creating this one. This only applies to
4288d8123366Sdanielk1977     ** automatically created indices. Users can do as they wish with
4289d8123366Sdanielk1977     ** explicit indices.
4290d3001711Sdrh     **
4291d3001711Sdrh     ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent
4292d3001711Sdrh     ** (and thus suppressing the second one) even if they have different
4293d3001711Sdrh     ** sort orders.
4294d3001711Sdrh     **
4295d3001711Sdrh     ** If there are different collating sequences or if the columns of
4296d3001711Sdrh     ** the constraint occur in different orders, then the constraints are
4297d3001711Sdrh     ** considered distinct and both result in separate indices.
4298d8123366Sdanielk1977     */
4299d8123366Sdanielk1977     Index *pIdx;
4300d8123366Sdanielk1977     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
4301d8123366Sdanielk1977       int k;
43025f1d1d9cSdrh       assert( IsUniqueIndex(pIdx) );
430348dd1d8eSdrh       assert( pIdx->idxType!=SQLITE_IDXTYPE_APPDEF );
43045f1d1d9cSdrh       assert( IsUniqueIndex(pIndex) );
4305d8123366Sdanielk1977 
4306bbbdc83bSdrh       if( pIdx->nKeyCol!=pIndex->nKeyCol ) continue;
4307bbbdc83bSdrh       for(k=0; k<pIdx->nKeyCol; k++){
4308d3001711Sdrh         const char *z1;
4309d3001711Sdrh         const char *z2;
43101f9ca2c8Sdrh         assert( pIdx->aiColumn[k]>=0 );
4311d8123366Sdanielk1977         if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
4312d3001711Sdrh         z1 = pIdx->azColl[k];
4313d3001711Sdrh         z2 = pIndex->azColl[k];
4314c41c132cSdrh         if( sqlite3StrICmp(z1, z2) ) break;
4315d8123366Sdanielk1977       }
4316bbbdc83bSdrh       if( k==pIdx->nKeyCol ){
4317f736b771Sdanielk1977         if( pIdx->onError!=pIndex->onError ){
4318f736b771Sdanielk1977           /* This constraint creates the same index as a previous
4319f736b771Sdanielk1977           ** constraint specified somewhere in the CREATE TABLE statement.
4320f736b771Sdanielk1977           ** However the ON CONFLICT clauses are different. If both this
4321f736b771Sdanielk1977           ** constraint and the previous equivalent constraint have explicit
4322f736b771Sdanielk1977           ** ON CONFLICT clauses this is an error. Otherwise, use the
432348864df9Smistachkin           ** explicitly specified behavior for the index.
4324d8123366Sdanielk1977           */
4325f736b771Sdanielk1977           if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
4326f736b771Sdanielk1977             sqlite3ErrorMsg(pParse,
4327f736b771Sdanielk1977                 "conflicting ON CONFLICT clauses specified", 0);
4328f736b771Sdanielk1977           }
4329f736b771Sdanielk1977           if( pIdx->onError==OE_Default ){
4330f736b771Sdanielk1977             pIdx->onError = pIndex->onError;
4331f736b771Sdanielk1977           }
4332f736b771Sdanielk1977         }
4333273bfe9fSdrh         if( idxType==SQLITE_IDXTYPE_PRIMARYKEY ) pIdx->idxType = idxType;
4334885eeb67Sdrh         if( IN_RENAME_OBJECT ){
4335885eeb67Sdrh           pIndex->pNext = pParse->pNewIndex;
4336885eeb67Sdrh           pParse->pNewIndex = pIndex;
4337885eeb67Sdrh           pIndex = 0;
4338885eeb67Sdrh         }
4339d8123366Sdanielk1977         goto exit_create_index;
4340d8123366Sdanielk1977       }
4341d8123366Sdanielk1977     }
4342d8123366Sdanielk1977   }
4343d8123366Sdanielk1977 
4344c9461eccSdan   if( !IN_RENAME_OBJECT ){
4345cf8f2895Sdan 
434675897234Sdrh     /* Link the new Index structure to its table and to the other
4347adbca9cfSdrh     ** in-memory database structures.
434875897234Sdrh     */
43497d3d9daeSdrh     assert( pParse->nErr==0 );
4350cc971738Sdrh     if( db->init.busy ){
43516d4abfbeSdrh       Index *p;
4352cf8f2895Sdan       assert( !IN_SPECIAL_PARSE );
43532120608eSdrh       assert( sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
4354234c39dfSdrh       if( pTblName!=0 ){
43551d85d931Sdrh         pIndex->tnum = db->init.newTnum;
43568d40673cSdrh         if( sqlite3IndexHasDuplicateRootPage(pIndex) ){
43578d40673cSdrh           sqlite3ErrorMsg(pParse, "invalid rootpage");
43588d40673cSdrh           pParse->rc = SQLITE_CORRUPT_BKPT;
43598d40673cSdrh           goto exit_create_index;
43608d40673cSdrh         }
4361d78eeee1Sdrh       }
4362da7a4c0fSdan       p = sqlite3HashInsert(&pIndex->pSchema->idxHash,
4363da7a4c0fSdan           pIndex->zName, pIndex);
4364da7a4c0fSdan       if( p ){
4365da7a4c0fSdan         assert( p==pIndex );  /* Malloc must have failed */
4366da7a4c0fSdan         sqlite3OomFault(db);
4367da7a4c0fSdan         goto exit_create_index;
4368da7a4c0fSdan       }
4369da7a4c0fSdan       db->mDbFlags |= DBFLAG_SchemaChange;
4370234c39dfSdrh     }
4371d78eeee1Sdrh 
43725838340bSdrh     /* If this is the initial CREATE INDEX statement (or CREATE TABLE if the
43735838340bSdrh     ** index is an implied index for a UNIQUE or PRIMARY KEY constraint) then
43745838340bSdrh     ** emit code to allocate the index rootpage on disk and make an entry for
43751e32bed3Sdrh     ** the index in the sqlite_schema table and populate the index with
43761e32bed3Sdrh     ** content.  But, do not do this if we are simply reading the sqlite_schema
43775838340bSdrh     ** table to parse the schema, or if this index is the PRIMARY KEY index
43785838340bSdrh     ** of a WITHOUT ROWID table.
437975897234Sdrh     **
43805838340bSdrh     ** If pTblName==0 it means this index is generated as an implied PRIMARY KEY
43815838340bSdrh     ** or UNIQUE index in a CREATE TABLE statement.  Since the table
4382382c0247Sdrh     ** has just been created, it contains no data and the index initialization
4383382c0247Sdrh     ** step can be skipped.
438475897234Sdrh     */
43857d3d9daeSdrh     else if( HasRowid(pTab) || pTblName!=0 ){
4386adbca9cfSdrh       Vdbe *v;
4387063336a5Sdrh       char *zStmt;
43880a07c107Sdrh       int iMem = ++pParse->nMem;
438975897234Sdrh 
43904adee20fSdanielk1977       v = sqlite3GetVdbe(pParse);
439175897234Sdrh       if( v==0 ) goto exit_create_index;
4392063336a5Sdrh 
4393aee128dcSdrh       sqlite3BeginWriteOperation(pParse, 1, iDb);
4394c5b73585Sdan 
4395c5b73585Sdan       /* Create the rootpage for the index using CreateIndex. But before
4396c5b73585Sdan       ** doing so, code a Noop instruction and store its address in
4397c5b73585Sdan       ** Index.tnum. This is required in case this index is actually a
4398c5b73585Sdan       ** PRIMARY KEY and the table is actually a WITHOUT ROWID table. In
4399c5b73585Sdan       ** that case the convertToWithoutRowidTable() routine will replace
4400c5b73585Sdan       ** the Noop with a Goto to jump over the VDBE code generated below. */
4401abc38158Sdrh       pIndex->tnum = (Pgno)sqlite3VdbeAddOp0(v, OP_Noop);
44020f3f7664Sdrh       sqlite3VdbeAddOp3(v, OP_CreateBtree, iDb, iMem, BTREE_BLOBKEY);
4403063336a5Sdrh 
4404063336a5Sdrh       /* Gather the complete text of the CREATE INDEX statement into
4405063336a5Sdrh       ** the zStmt variable
4406063336a5Sdrh       */
440755f66b34Sdrh       assert( pName!=0 || pStart==0 );
4408d3001711Sdrh       if( pStart ){
440977dfd5bbSdrh         int n = (int)(pParse->sLastToken.z - pName->z) + pParse->sLastToken.n;
44108a9789b6Sdrh         if( pName->z[n-1]==';' ) n--;
4411063336a5Sdrh         /* A named index with an explicit CREATE INDEX statement */
44121e536953Sdanielk1977         zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
44138a9789b6Sdrh             onError==OE_None ? "" : " UNIQUE", n, pName->z);
44140202b29eSdanielk1977       }else{
4415063336a5Sdrh         /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
4416e497f005Sdrh         /* zStmt = sqlite3MPrintf(""); */
4417e497f005Sdrh         zStmt = 0;
44180202b29eSdanielk1977       }
4419063336a5Sdrh 
44201e32bed3Sdrh       /* Add an entry in sqlite_schema for this index
4421063336a5Sdrh       */
4422063336a5Sdrh       sqlite3NestedParse(pParse,
4423a4a871c2Sdrh          "INSERT INTO %Q." LEGACY_SCHEMA_TABLE " VALUES('index',%Q,%Q,#%d,%Q);",
4424346a70caSdrh          db->aDb[iDb].zDbSName,
4425063336a5Sdrh          pIndex->zName,
4426063336a5Sdrh          pTab->zName,
4427b7654111Sdrh          iMem,
4428063336a5Sdrh          zStmt
4429063336a5Sdrh       );
4430633e6d57Sdrh       sqlite3DbFree(db, zStmt);
4431063336a5Sdrh 
4432a21c6b6fSdanielk1977       /* Fill the index with data and reparse the schema. Code an OP_Expire
4433a21c6b6fSdanielk1977       ** to invalidate all pre-compiled statements.
4434063336a5Sdrh       */
4435cbb18d22Sdanielk1977       if( pTblName ){
4436063336a5Sdrh         sqlite3RefillIndex(pParse, pIndex, iMem);
44379cbf3425Sdrh         sqlite3ChangeCookie(pParse, iDb);
44385d9c9da6Sdrh         sqlite3VdbeAddParseSchemaOp(v, iDb,
44396a5a13dfSdan             sqlite3MPrintf(db, "name='%q' AND type='index'", pIndex->zName), 0);
4440ba968dbfSdrh         sqlite3VdbeAddOp2(v, OP_Expire, 0, 1);
444175897234Sdrh       }
4442c5b73585Sdan 
4443abc38158Sdrh       sqlite3VdbeJumpHere(v, (int)pIndex->tnum);
444475897234Sdrh     }
4445cf8f2895Sdan   }
4446234c39dfSdrh   if( db->init.busy || pTblName==0 ){
4447d8123366Sdanielk1977     pIndex->pNext = pTab->pIndex;
4448d8123366Sdanielk1977     pTab->pIndex = pIndex;
4449d8123366Sdanielk1977     pIndex = 0;
4450234c39dfSdrh   }
4451c9461eccSdan   else if( IN_RENAME_OBJECT ){
4452cf8f2895Sdan     assert( pParse->pNewIndex==0 );
4453cf8f2895Sdan     pParse->pNewIndex = pIndex;
4454cf8f2895Sdan     pIndex = 0;
4455cf8f2895Sdan   }
4456d8123366Sdanielk1977 
445775897234Sdrh   /* Clean up before exiting */
445875897234Sdrh exit_create_index:
4459cf8f2895Sdan   if( pIndex ) sqlite3FreeIndex(db, pIndex);
446097060e5aSdrh   if( pTab ){
446197060e5aSdrh     /* Ensure all REPLACE indexes on pTab are at the end of the pIndex list.
446297060e5aSdrh     ** The list was already ordered when this routine was entered, so at this
446397060e5aSdrh     ** point at most a single index (the newly added index) will be out of
446497060e5aSdrh     ** order.  So we have to reorder at most one index. */
4465e85e1da0Sdrh     Index **ppFrom;
4466d35bdd6cSdrh     Index *pThis;
4467d35bdd6cSdrh     for(ppFrom=&pTab->pIndex; (pThis = *ppFrom)!=0; ppFrom=&pThis->pNext){
4468d35bdd6cSdrh       Index *pNext;
4469d35bdd6cSdrh       if( pThis->onError!=OE_Replace ) continue;
4470d35bdd6cSdrh       while( (pNext = pThis->pNext)!=0 && pNext->onError!=OE_Replace ){
4471d35bdd6cSdrh         *ppFrom = pNext;
4472d35bdd6cSdrh         pThis->pNext = pNext->pNext;
4473d35bdd6cSdrh         pNext->pNext = pThis;
4474d35bdd6cSdrh         ppFrom = &pNext->pNext;
4475d35bdd6cSdrh       }
4476d35bdd6cSdrh       break;
4477d35bdd6cSdrh     }
447897060e5aSdrh #ifdef SQLITE_DEBUG
447997060e5aSdrh     /* Verify that all REPLACE indexes really are now at the end
448097060e5aSdrh     ** of the index list.  In other words, no other index type ever
448197060e5aSdrh     ** comes after a REPLACE index on the list. */
448297060e5aSdrh     for(pThis = pTab->pIndex; pThis; pThis=pThis->pNext){
448397060e5aSdrh       assert( pThis->onError!=OE_Replace
448497060e5aSdrh            || pThis->pNext==0
448597060e5aSdrh            || pThis->pNext->onError==OE_Replace );
448697060e5aSdrh     }
448797060e5aSdrh #endif
4488d35bdd6cSdrh   }
44891fe0537eSdrh   sqlite3ExprDelete(db, pPIWhere);
4490633e6d57Sdrh   sqlite3ExprListDelete(db, pList);
4491633e6d57Sdrh   sqlite3SrcListDelete(db, pTblName);
4492633e6d57Sdrh   sqlite3DbFree(db, zName);
449375897234Sdrh }
449475897234Sdrh 
449575897234Sdrh /*
449651147baaSdrh ** Fill the Index.aiRowEst[] array with default information - information
449791124b35Sdrh ** to be used when we have not run the ANALYZE command.
449828c4cf42Sdrh **
449960ec914cSpeter.d.reid ** aiRowEst[0] is supposed to contain the number of elements in the index.
450028c4cf42Sdrh ** Since we do not know, guess 1 million.  aiRowEst[1] is an estimate of the
450128c4cf42Sdrh ** number of rows in the table that match any particular value of the
450228c4cf42Sdrh ** first column of the index.  aiRowEst[2] is an estimate of the number
4503cfc9df76Sdan ** of rows that match any particular combination of the first 2 columns
450428c4cf42Sdrh ** of the index.  And so forth.  It must always be the case that
450528c4cf42Sdrh *
450628c4cf42Sdrh **           aiRowEst[N]<=aiRowEst[N-1]
450728c4cf42Sdrh **           aiRowEst[N]>=1
450828c4cf42Sdrh **
450928c4cf42Sdrh ** Apart from that, we have little to go on besides intuition as to
451028c4cf42Sdrh ** how aiRowEst[] should be initialized.  The numbers generated here
451128c4cf42Sdrh ** are based on typical values found in actual indices.
451251147baaSdrh */
sqlite3DefaultRowEst(Index * pIdx)451351147baaSdrh void sqlite3DefaultRowEst(Index *pIdx){
4514264d2b97Sdan                /*                10,  9,  8,  7,  6 */
451556c65c92Sdrh   static const LogEst aVal[] = { 33, 32, 30, 28, 26 };
4516cfc9df76Sdan   LogEst *a = pIdx->aiRowLogEst;
451756c65c92Sdrh   LogEst x;
4518cfc9df76Sdan   int nCopy = MIN(ArraySize(aVal), pIdx->nKeyCol);
451951147baaSdrh   int i;
4520cfc9df76Sdan 
452133bec3f5Sdrh   /* Indexes with default row estimates should not have stat1 data */
452233bec3f5Sdrh   assert( !pIdx->hasStat1 );
452333bec3f5Sdrh 
4524264d2b97Sdan   /* Set the first entry (number of rows in the index) to the estimated
45258dc570b6Sdrh   ** number of rows in the table, or half the number of rows in the table
452656c65c92Sdrh   ** for a partial index.
452756c65c92Sdrh   **
452856c65c92Sdrh   ** 2020-05-27:  If some of the stat data is coming from the sqlite_stat1
452956c65c92Sdrh   ** table but other parts we are having to guess at, then do not let the
453056c65c92Sdrh   ** estimated number of rows in the table be less than 1000 (LogEst 99).
453156c65c92Sdrh   ** Failure to do this can cause the indexes for which we do not have
45328c1fbe81Sdrh   ** stat1 data to be ignored by the query planner.
453356c65c92Sdrh   */
453456c65c92Sdrh   x = pIdx->pTable->nRowLogEst;
453556c65c92Sdrh   assert( 99==sqlite3LogEst(1000) );
453656c65c92Sdrh   if( x<99 ){
453756c65c92Sdrh     pIdx->pTable->nRowLogEst = x = 99;
453856c65c92Sdrh   }
45395f086ddeSdrh   if( pIdx->pPartIdxWhere!=0 ){ x -= 10;  assert( 10==sqlite3LogEst(2) ); }
454056c65c92Sdrh   a[0] = x;
4541264d2b97Sdan 
4542264d2b97Sdan   /* Estimate that a[1] is 10, a[2] is 9, a[3] is 8, a[4] is 7, a[5] is
4543264d2b97Sdan   ** 6 and each subsequent value (if any) is 5.  */
4544cfc9df76Sdan   memcpy(&a[1], aVal, nCopy*sizeof(LogEst));
4545264d2b97Sdan   for(i=nCopy+1; i<=pIdx->nKeyCol; i++){
4546264d2b97Sdan     a[i] = 23;                    assert( 23==sqlite3LogEst(5) );
454728c4cf42Sdrh   }
4548264d2b97Sdan 
4549264d2b97Sdan   assert( 0==sqlite3LogEst(1) );
45505f1d1d9cSdrh   if( IsUniqueIndex(pIdx) ) a[pIdx->nKeyCol] = 0;
455151147baaSdrh }
455251147baaSdrh 
455351147baaSdrh /*
455474e24cd0Sdrh ** This routine will drop an existing named index.  This routine
455574e24cd0Sdrh ** implements the DROP INDEX statement.
455675897234Sdrh */
sqlite3DropIndex(Parse * pParse,SrcList * pName,int ifExists)45574d91a701Sdrh void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
455875897234Sdrh   Index *pIndex;
455975897234Sdrh   Vdbe *v;
45609bb575fdSdrh   sqlite3 *db = pParse->db;
4561da184236Sdanielk1977   int iDb;
456275897234Sdrh 
45638af73d41Sdrh   if( db->mallocFailed ){
4564d5d56523Sdanielk1977     goto exit_drop_index;
4565d5d56523Sdanielk1977   }
45663cdb1394Sdrh   assert( pParse->nErr==0 );   /* Never called with prior non-OOM errors */
4567d24cc427Sdrh   assert( pName->nSrc==1 );
4568d5d56523Sdanielk1977   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
4569d5d56523Sdanielk1977     goto exit_drop_index;
4570d5d56523Sdanielk1977   }
45714adee20fSdanielk1977   pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
457275897234Sdrh   if( pIndex==0 ){
45734d91a701Sdrh     if( !ifExists ){
4574a979993bSdrh       sqlite3ErrorMsg(pParse, "no such index: %S", pName->a);
457557966753Sdan     }else{
457657966753Sdan       sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
457731da7be9Sdrh       sqlite3ForceNotReadOnly(pParse);
45784d91a701Sdrh     }
4579a6ecd338Sdrh     pParse->checkSchema = 1;
4580d24cc427Sdrh     goto exit_drop_index;
458175897234Sdrh   }
458248dd1d8eSdrh   if( pIndex->idxType!=SQLITE_IDXTYPE_APPDEF ){
45834adee20fSdanielk1977     sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
4584485b39b4Sdrh       "or PRIMARY KEY constraint cannot be dropped", 0);
4585d24cc427Sdrh     goto exit_drop_index;
4586d24cc427Sdrh   }
4587da184236Sdanielk1977   iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
4588e5f9c644Sdrh #ifndef SQLITE_OMIT_AUTHORIZATION
4589e5f9c644Sdrh   {
4590e5f9c644Sdrh     int code = SQLITE_DROP_INDEX;
4591e5f9c644Sdrh     Table *pTab = pIndex->pTable;
459269c33826Sdrh     const char *zDb = db->aDb[iDb].zDbSName;
4593da184236Sdanielk1977     const char *zTab = SCHEMA_TABLE(iDb);
45944adee20fSdanielk1977     if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
4595d24cc427Sdrh       goto exit_drop_index;
4596ed6c8671Sdrh     }
459793fd5420Sdrh     if( !OMIT_TEMPDB && iDb==1 ) code = SQLITE_DROP_TEMP_INDEX;
45984adee20fSdanielk1977     if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
4599d24cc427Sdrh       goto exit_drop_index;
4600e5f9c644Sdrh     }
4601e5f9c644Sdrh   }
4602e5f9c644Sdrh #endif
460375897234Sdrh 
4604067b92baSdrh   /* Generate code to remove the index and from the schema table */
46054adee20fSdanielk1977   v = sqlite3GetVdbe(pParse);
460675897234Sdrh   if( v ){
460777658e2fSdrh     sqlite3BeginWriteOperation(pParse, 1, iDb);
4608b17131a0Sdrh     sqlite3NestedParse(pParse,
4609a4a871c2Sdrh        "DELETE FROM %Q." LEGACY_SCHEMA_TABLE " WHERE name=%Q AND type='index'",
4610346a70caSdrh        db->aDb[iDb].zDbSName, pIndex->zName
4611b17131a0Sdrh     );
4612a5ae4c33Sdrh     sqlite3ClearStatTables(pParse, iDb, "idx", pIndex->zName);
46139cbf3425Sdrh     sqlite3ChangeCookie(pParse, iDb);
4614b17131a0Sdrh     destroyRootPage(pParse, pIndex->tnum, iDb);
461566a5167bSdrh     sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
461675897234Sdrh   }
461775897234Sdrh 
4618d24cc427Sdrh exit_drop_index:
4619633e6d57Sdrh   sqlite3SrcListDelete(db, pName);
462075897234Sdrh }
462175897234Sdrh 
462275897234Sdrh /*
4623cf643729Sdrh ** pArray is a pointer to an array of objects. Each object in the
46249ace112cSdan ** array is szEntry bytes in size. This routine uses sqlite3DbRealloc()
46259ace112cSdan ** to extend the array so that there is space for a new object at the end.
462613449892Sdrh **
46279ace112cSdan ** When this function is called, *pnEntry contains the current size of
46289ace112cSdan ** the array (in entries - so the allocation is ((*pnEntry) * szEntry) bytes
46299ace112cSdan ** in total).
463013449892Sdrh **
46319ace112cSdan ** If the realloc() is successful (i.e. if no OOM condition occurs), the
46329ace112cSdan ** space allocated for the new object is zeroed, *pnEntry updated to
46339ace112cSdan ** reflect the new size of the array and a pointer to the new allocation
46349ace112cSdan ** returned. *pIdx is set to the index of the new array entry in this case.
463513449892Sdrh **
46369ace112cSdan ** Otherwise, if the realloc() fails, *pIdx is set to -1, *pnEntry remains
46379ace112cSdan ** unchanged and a copy of pArray returned.
463813449892Sdrh */
sqlite3ArrayAllocate(sqlite3 * db,void * pArray,int szEntry,int * pnEntry,int * pIdx)4639cf643729Sdrh void *sqlite3ArrayAllocate(
464017435752Sdrh   sqlite3 *db,      /* Connection to notify of malloc failures */
4641cf643729Sdrh   void *pArray,     /* Array of objects.  Might be reallocated */
4642cf643729Sdrh   int szEntry,      /* Size of each object in the array */
4643cf643729Sdrh   int *pnEntry,     /* Number of objects currently in use */
4644cf643729Sdrh   int *pIdx         /* Write the index of a new slot here */
4645cf643729Sdrh ){
4646cf643729Sdrh   char *z;
4647f6ad201aSdrh   sqlite3_int64 n = *pIdx = *pnEntry;
46486c535158Sdrh   if( (n & (n-1))==0 ){
46490aa3231fSdrh     sqlite3_int64 sz = (n==0) ? 1 : 2*n;
46506c535158Sdrh     void *pNew = sqlite3DbRealloc(db, pArray, sz*szEntry);
465113449892Sdrh     if( pNew==0 ){
4652cf643729Sdrh       *pIdx = -1;
4653cf643729Sdrh       return pArray;
465413449892Sdrh     }
4655cf643729Sdrh     pArray = pNew;
465613449892Sdrh   }
4657cf643729Sdrh   z = (char*)pArray;
46586c535158Sdrh   memset(&z[n * szEntry], 0, szEntry);
4659cf643729Sdrh   ++*pnEntry;
4660cf643729Sdrh   return pArray;
466113449892Sdrh }
466213449892Sdrh 
466313449892Sdrh /*
466475897234Sdrh ** Append a new element to the given IdList.  Create a new IdList if
466575897234Sdrh ** need be.
4666daffd0e5Sdrh **
4667daffd0e5Sdrh ** A new IdList is returned, or NULL if malloc() fails.
466875897234Sdrh */
sqlite3IdListAppend(Parse * pParse,IdList * pList,Token * pToken)46695496d6a2Sdan IdList *sqlite3IdListAppend(Parse *pParse, IdList *pList, Token *pToken){
46705496d6a2Sdan   sqlite3 *db = pParse->db;
467113449892Sdrh   int i;
467275897234Sdrh   if( pList==0 ){
467317435752Sdrh     pList = sqlite3DbMallocZero(db, sizeof(IdList) );
467475897234Sdrh     if( pList==0 ) return 0;
4675a99e3254Sdrh   }else{
4676a99e3254Sdrh     IdList *pNew;
4677a99e3254Sdrh     pNew = sqlite3DbRealloc(db, pList,
4678a99e3254Sdrh                  sizeof(IdList) + pList->nId*sizeof(pList->a));
4679a99e3254Sdrh     if( pNew==0 ){
4680633e6d57Sdrh       sqlite3IdListDelete(db, pList);
4681daffd0e5Sdrh       return 0;
468275897234Sdrh     }
4683a99e3254Sdrh     pList = pNew;
4684a99e3254Sdrh   }
4685a99e3254Sdrh   i = pList->nId++;
468617435752Sdrh   pList->a[i].zName = sqlite3NameFromToken(db, pToken);
4687c9461eccSdan   if( IN_RENAME_OBJECT && pList->a[i].zName ){
468807e95233Sdan     sqlite3RenameTokenMap(pParse, (void*)pList->a[i].zName, pToken);
46895496d6a2Sdan   }
469075897234Sdrh   return pList;
469175897234Sdrh }
469275897234Sdrh 
469375897234Sdrh /*
4694fe05af87Sdrh ** Delete an IdList.
4695fe05af87Sdrh */
sqlite3IdListDelete(sqlite3 * db,IdList * pList)4696633e6d57Sdrh void sqlite3IdListDelete(sqlite3 *db, IdList *pList){
4697fe05af87Sdrh   int i;
469841ce47c4Sdrh   assert( db!=0 );
4699fe05af87Sdrh   if( pList==0 ) return;
4700f80bb195Sdrh   assert( pList->eU4!=EU4_EXPR ); /* EU4_EXPR mode is not currently used */
4701fe05af87Sdrh   for(i=0; i<pList->nId; i++){
4702633e6d57Sdrh     sqlite3DbFree(db, pList->a[i].zName);
4703fe05af87Sdrh   }
470441ce47c4Sdrh   sqlite3DbNNFreeNN(db, pList);
4705fe05af87Sdrh }
4706fe05af87Sdrh 
4707fe05af87Sdrh /*
4708fe05af87Sdrh ** Return the index in pList of the identifier named zId.  Return -1
4709fe05af87Sdrh ** if not found.
4710fe05af87Sdrh */
sqlite3IdListIndex(IdList * pList,const char * zName)4711fe05af87Sdrh int sqlite3IdListIndex(IdList *pList, const char *zName){
4712fe05af87Sdrh   int i;
4713d44f8b23Sdrh   assert( pList!=0 );
4714fe05af87Sdrh   for(i=0; i<pList->nId; i++){
4715fe05af87Sdrh     if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
4716fe05af87Sdrh   }
4717fe05af87Sdrh   return -1;
4718fe05af87Sdrh }
4719fe05af87Sdrh 
4720fe05af87Sdrh /*
47210ad7aa81Sdrh ** Maximum size of a SrcList object.
47220ad7aa81Sdrh ** The SrcList object is used to represent the FROM clause of a
47230ad7aa81Sdrh ** SELECT statement, and the query planner cannot deal with more
47240ad7aa81Sdrh ** than 64 tables in a join.  So any value larger than 64 here
47250ad7aa81Sdrh ** is sufficient for most uses.  Smaller values, like say 10, are
47260ad7aa81Sdrh ** appropriate for small and memory-limited applications.
47270ad7aa81Sdrh */
47280ad7aa81Sdrh #ifndef SQLITE_MAX_SRCLIST
47290ad7aa81Sdrh # define SQLITE_MAX_SRCLIST 200
47300ad7aa81Sdrh #endif
47310ad7aa81Sdrh 
47320ad7aa81Sdrh /*
4733a78c22c4Sdrh ** Expand the space allocated for the given SrcList object by
4734a78c22c4Sdrh ** creating nExtra new slots beginning at iStart.  iStart is zero based.
4735a78c22c4Sdrh ** New slots are zeroed.
4736a78c22c4Sdrh **
4737a78c22c4Sdrh ** For example, suppose a SrcList initially contains two entries: A,B.
4738a78c22c4Sdrh ** To append 3 new entries onto the end, do this:
4739a78c22c4Sdrh **
4740a78c22c4Sdrh **    sqlite3SrcListEnlarge(db, pSrclist, 3, 2);
4741a78c22c4Sdrh **
4742a78c22c4Sdrh ** After the call above it would contain:  A, B, nil, nil, nil.
4743a78c22c4Sdrh ** If the iStart argument had been 1 instead of 2, then the result
4744a78c22c4Sdrh ** would have been:  A, nil, nil, nil, B.  To prepend the new slots,
4745a78c22c4Sdrh ** the iStart value would be 0.  The result then would
4746a78c22c4Sdrh ** be: nil, nil, nil, A, B.
4747a78c22c4Sdrh **
474829c992cbSdrh ** If a memory allocation fails or the SrcList becomes too large, leave
474929c992cbSdrh ** the original SrcList unchanged, return NULL, and leave an error message
475029c992cbSdrh ** in pParse.
4751a78c22c4Sdrh */
sqlite3SrcListEnlarge(Parse * pParse,SrcList * pSrc,int nExtra,int iStart)4752a78c22c4Sdrh SrcList *sqlite3SrcListEnlarge(
475329c992cbSdrh   Parse *pParse,     /* Parsing context into which errors are reported */
4754a78c22c4Sdrh   SrcList *pSrc,     /* The SrcList to be enlarged */
4755a78c22c4Sdrh   int nExtra,        /* Number of new slots to add to pSrc->a[] */
4756a78c22c4Sdrh   int iStart         /* Index in pSrc->a[] of first new slot */
4757a78c22c4Sdrh ){
4758a78c22c4Sdrh   int i;
4759a78c22c4Sdrh 
4760a78c22c4Sdrh   /* Sanity checking on calling parameters */
4761a78c22c4Sdrh   assert( iStart>=0 );
4762a78c22c4Sdrh   assert( nExtra>=1 );
47638af73d41Sdrh   assert( pSrc!=0 );
47648af73d41Sdrh   assert( iStart<=pSrc->nSrc );
4765a78c22c4Sdrh 
4766a78c22c4Sdrh   /* Allocate additional space if needed */
4767fc5717ccSdrh   if( (u32)pSrc->nSrc+nExtra>pSrc->nAlloc ){
4768a78c22c4Sdrh     SrcList *pNew;
47690aa3231fSdrh     sqlite3_int64 nAlloc = 2*(sqlite3_int64)pSrc->nSrc+nExtra;
477029c992cbSdrh     sqlite3 *db = pParse->db;
47710ad7aa81Sdrh 
47720ad7aa81Sdrh     if( pSrc->nSrc+nExtra>=SQLITE_MAX_SRCLIST ){
477329c992cbSdrh       sqlite3ErrorMsg(pParse, "too many FROM clause terms, max: %d",
477429c992cbSdrh                       SQLITE_MAX_SRCLIST);
477529c992cbSdrh       return 0;
47760ad7aa81Sdrh     }
47770ad7aa81Sdrh     if( nAlloc>SQLITE_MAX_SRCLIST ) nAlloc = SQLITE_MAX_SRCLIST;
4778a78c22c4Sdrh     pNew = sqlite3DbRealloc(db, pSrc,
4779a78c22c4Sdrh                sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) );
4780a78c22c4Sdrh     if( pNew==0 ){
4781a78c22c4Sdrh       assert( db->mallocFailed );
478229c992cbSdrh       return 0;
4783a78c22c4Sdrh     }
4784a78c22c4Sdrh     pSrc = pNew;
4785d0ee3a1eSdrh     pSrc->nAlloc = nAlloc;
4786a78c22c4Sdrh   }
4787a78c22c4Sdrh 
4788a78c22c4Sdrh   /* Move existing slots that come after the newly inserted slots
4789a78c22c4Sdrh   ** out of the way */
4790a78c22c4Sdrh   for(i=pSrc->nSrc-1; i>=iStart; i--){
4791a78c22c4Sdrh     pSrc->a[i+nExtra] = pSrc->a[i];
4792a78c22c4Sdrh   }
47936d1626ebSdrh   pSrc->nSrc += nExtra;
4794a78c22c4Sdrh 
4795a78c22c4Sdrh   /* Zero the newly allocated slots */
4796a78c22c4Sdrh   memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
4797a78c22c4Sdrh   for(i=iStart; i<iStart+nExtra; i++){
4798a78c22c4Sdrh     pSrc->a[i].iCursor = -1;
4799a78c22c4Sdrh   }
4800a78c22c4Sdrh 
4801a78c22c4Sdrh   /* Return a pointer to the enlarged SrcList */
4802a78c22c4Sdrh   return pSrc;
4803a78c22c4Sdrh }
4804a78c22c4Sdrh 
4805a78c22c4Sdrh 
4806a78c22c4Sdrh /*
4807ad3cab52Sdrh ** Append a new table name to the given SrcList.  Create a new SrcList if
4808b7916a78Sdrh ** need be.  A new entry is created in the SrcList even if pTable is NULL.
4809ad3cab52Sdrh **
481029c992cbSdrh ** A SrcList is returned, or NULL if there is an OOM error or if the
481129c992cbSdrh ** SrcList grows to large.  The returned
4812a78c22c4Sdrh ** SrcList might be the same as the SrcList that was input or it might be
4813a78c22c4Sdrh ** a new one.  If an OOM error does occurs, then the prior value of pList
4814a78c22c4Sdrh ** that is input to this routine is automatically freed.
4815113088ecSdrh **
4816113088ecSdrh ** If pDatabase is not null, it means that the table has an optional
4817113088ecSdrh ** database name prefix.  Like this:  "database.table".  The pDatabase
4818113088ecSdrh ** points to the table name and the pTable points to the database name.
4819113088ecSdrh ** The SrcList.a[].zName field is filled with the table name which might
4820113088ecSdrh ** come from pTable (if pDatabase is NULL) or from pDatabase.
4821113088ecSdrh ** SrcList.a[].zDatabase is filled with the database name from pTable,
4822113088ecSdrh ** or with NULL if no database is specified.
4823113088ecSdrh **
4824113088ecSdrh ** In other words, if call like this:
4825113088ecSdrh **
482617435752Sdrh **         sqlite3SrcListAppend(D,A,B,0);
4827113088ecSdrh **
4828113088ecSdrh ** Then B is a table name and the database name is unspecified.  If called
4829113088ecSdrh ** like this:
4830113088ecSdrh **
483117435752Sdrh **         sqlite3SrcListAppend(D,A,B,C);
4832113088ecSdrh **
4833d3001711Sdrh ** Then C is the table name and B is the database name.  If C is defined
4834d3001711Sdrh ** then so is B.  In other words, we never have a case where:
4835d3001711Sdrh **
4836d3001711Sdrh **         sqlite3SrcListAppend(D,A,0,C);
4837b7916a78Sdrh **
4838b7916a78Sdrh ** Both pTable and pDatabase are assumed to be quoted.  They are dequoted
4839b7916a78Sdrh ** before being added to the SrcList.
4840ad3cab52Sdrh */
sqlite3SrcListAppend(Parse * pParse,SrcList * pList,Token * pTable,Token * pDatabase)484117435752Sdrh SrcList *sqlite3SrcListAppend(
484229c992cbSdrh   Parse *pParse,      /* Parsing context, in which errors are reported */
484317435752Sdrh   SrcList *pList,     /* Append to this SrcList. NULL creates a new SrcList */
484417435752Sdrh   Token *pTable,      /* Table to append */
484517435752Sdrh   Token *pDatabase    /* Database of the table */
484617435752Sdrh ){
48477601294aSdrh   SrcItem *pItem;
484829c992cbSdrh   sqlite3 *db;
4849d3001711Sdrh   assert( pDatabase==0 || pTable!=0 );  /* Cannot have C without B */
485029c992cbSdrh   assert( pParse!=0 );
485129c992cbSdrh   assert( pParse->db!=0 );
485229c992cbSdrh   db = pParse->db;
4853ad3cab52Sdrh   if( pList==0 ){
485429c992cbSdrh     pList = sqlite3DbMallocRawNN(pParse->db, sizeof(SrcList) );
4855ad3cab52Sdrh     if( pList==0 ) return 0;
48564305d103Sdrh     pList->nAlloc = 1;
4857ac178b3dSdrh     pList->nSrc = 1;
4858ac178b3dSdrh     memset(&pList->a[0], 0, sizeof(pList->a[0]));
4859ac178b3dSdrh     pList->a[0].iCursor = -1;
4860ac178b3dSdrh   }else{
486129c992cbSdrh     SrcList *pNew = sqlite3SrcListEnlarge(pParse, pList, 1, pList->nSrc);
486229c992cbSdrh     if( pNew==0 ){
4863633e6d57Sdrh       sqlite3SrcListDelete(db, pList);
4864ad3cab52Sdrh       return 0;
486529c992cbSdrh     }else{
486629c992cbSdrh       pList = pNew;
486729c992cbSdrh     }
4868ad3cab52Sdrh   }
4869a78c22c4Sdrh   pItem = &pList->a[pList->nSrc-1];
4870113088ecSdrh   if( pDatabase && pDatabase->z==0 ){
4871113088ecSdrh     pDatabase = 0;
4872113088ecSdrh   }
4873d3001711Sdrh   if( pDatabase ){
4874169a689fSdrh     pItem->zName = sqlite3NameFromToken(db, pDatabase);
4875169a689fSdrh     pItem->zDatabase = sqlite3NameFromToken(db, pTable);
4876169a689fSdrh   }else{
487717435752Sdrh     pItem->zName = sqlite3NameFromToken(db, pTable);
4878169a689fSdrh     pItem->zDatabase = 0;
4879169a689fSdrh   }
4880ad3cab52Sdrh   return pList;
4881ad3cab52Sdrh }
4882ad3cab52Sdrh 
4883ad3cab52Sdrh /*
4884dfe88eceSdrh ** Assign VdbeCursor index numbers to all tables in a SrcList
488563eb5f29Sdrh */
sqlite3SrcListAssignCursors(Parse * pParse,SrcList * pList)48864adee20fSdanielk1977 void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
488763eb5f29Sdrh   int i;
48887601294aSdrh   SrcItem *pItem;
488992a2824cSdrh   assert( pList || pParse->db->mallocFailed );
48909da977f1Sdrh   if( ALWAYS(pList) ){
48919b3187e1Sdrh     for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
489234055854Sdrh       if( pItem->iCursor>=0 ) continue;
48939b3187e1Sdrh       pItem->iCursor = pParse->nTab++;
48949b3187e1Sdrh       if( pItem->pSelect ){
48959b3187e1Sdrh         sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
489663eb5f29Sdrh       }
489763eb5f29Sdrh     }
489863eb5f29Sdrh   }
4899261919ccSdanielk1977 }
490063eb5f29Sdrh 
490163eb5f29Sdrh /*
4902ad3cab52Sdrh ** Delete an entire SrcList including all its substructure.
4903ad3cab52Sdrh */
sqlite3SrcListDelete(sqlite3 * db,SrcList * pList)4904633e6d57Sdrh void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){
4905ad3cab52Sdrh   int i;
49067601294aSdrh   SrcItem *pItem;
490741ce47c4Sdrh   assert( db!=0 );
4908ad3cab52Sdrh   if( pList==0 ) return;
4909be5c89acSdrh   for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
491041ce47c4Sdrh     if( pItem->zDatabase ) sqlite3DbNNFreeNN(db, pItem->zDatabase);
491141ce47c4Sdrh     if( pItem->zName ) sqlite3DbNNFreeNN(db, pItem->zName);
491241ce47c4Sdrh     if( pItem->zAlias ) sqlite3DbNNFreeNN(db, pItem->zAlias);
49138a48b9c0Sdrh     if( pItem->fg.isIndexedBy ) sqlite3DbFree(db, pItem->u1.zIndexedBy);
49148a48b9c0Sdrh     if( pItem->fg.isTabFunc ) sqlite3ExprListDelete(db, pItem->u1.pFuncArg);
49151feeaed2Sdan     sqlite3DeleteTable(db, pItem->pTab);
491645d827cbSdrh     if( pItem->pSelect ) sqlite3SelectDelete(db, pItem->pSelect);
4917d44f8b23Sdrh     if( pItem->fg.isUsing ){
4918d44f8b23Sdrh       sqlite3IdListDelete(db, pItem->u3.pUsing);
4919d44f8b23Sdrh     }else if( pItem->u3.pOn ){
4920d44f8b23Sdrh       sqlite3ExprDelete(db, pItem->u3.pOn);
4921d44f8b23Sdrh     }
492275897234Sdrh   }
492341ce47c4Sdrh   sqlite3DbNNFreeNN(db, pList);
492475897234Sdrh }
492575897234Sdrh 
4926982cef7eSdrh /*
492761dfc31dSdrh ** This routine is called by the parser to add a new term to the
492861dfc31dSdrh ** end of a growing FROM clause.  The "p" parameter is the part of
492961dfc31dSdrh ** the FROM clause that has already been constructed.  "p" is NULL
493061dfc31dSdrh ** if this is the first term of the FROM clause.  pTable and pDatabase
493161dfc31dSdrh ** are the name of the table and database named in the FROM clause term.
493261dfc31dSdrh ** pDatabase is NULL if the database name qualifier is missing - the
493360ec914cSpeter.d.reid ** usual case.  If the term has an alias, then pAlias points to the
493461dfc31dSdrh ** alias token.  If the term is a subquery, then pSubquery is the
493561dfc31dSdrh ** SELECT statement that the subquery encodes.  The pTable and
493661dfc31dSdrh ** pDatabase parameters are NULL for subqueries.  The pOn and pUsing
493761dfc31dSdrh ** parameters are the content of the ON and USING clauses.
493861dfc31dSdrh **
493961dfc31dSdrh ** Return a new SrcList which encodes is the FROM with the new
494061dfc31dSdrh ** term added.
494161dfc31dSdrh */
sqlite3SrcListAppendFromTerm(Parse * pParse,SrcList * p,Token * pTable,Token * pDatabase,Token * pAlias,Select * pSubquery,OnOrUsing * pOnUsing)494261dfc31dSdrh SrcList *sqlite3SrcListAppendFromTerm(
494317435752Sdrh   Parse *pParse,          /* Parsing context */
494461dfc31dSdrh   SrcList *p,             /* The left part of the FROM clause already seen */
494561dfc31dSdrh   Token *pTable,          /* Name of the table to add to the FROM clause */
494661dfc31dSdrh   Token *pDatabase,       /* Name of the database containing pTable */
494761dfc31dSdrh   Token *pAlias,          /* The right-hand side of the AS subexpression */
494861dfc31dSdrh   Select *pSubquery,      /* A subquery used in place of a table name */
4949d44f8b23Sdrh   OnOrUsing *pOnUsing     /* Either the ON clause or the USING clause */
495061dfc31dSdrh ){
49517601294aSdrh   SrcItem *pItem;
495217435752Sdrh   sqlite3 *db = pParse->db;
4953d44f8b23Sdrh   if( !p && pOnUsing!=0 && (pOnUsing->pOn || pOnUsing->pUsing) ){
4954bd1a0a4fSdanielk1977     sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s",
4955d44f8b23Sdrh       (pOnUsing->pOn ? "ON" : "USING")
4956bd1a0a4fSdanielk1977     );
4957bd1a0a4fSdanielk1977     goto append_from_error;
4958bd1a0a4fSdanielk1977   }
495929c992cbSdrh   p = sqlite3SrcListAppend(pParse, p, pTable, pDatabase);
49609d9c41e2Sdrh   if( p==0 ){
4961bd1a0a4fSdanielk1977     goto append_from_error;
496261dfc31dSdrh   }
49639d9c41e2Sdrh   assert( p->nSrc>0 );
496461dfc31dSdrh   pItem = &p->a[p->nSrc-1];
4965a488ec9fSdrh   assert( (pTable==0)==(pDatabase==0) );
4966a488ec9fSdrh   assert( pItem->zName==0 || pDatabase!=0 );
4967c9461eccSdan   if( IN_RENAME_OBJECT && pItem->zName ){
4968a488ec9fSdrh     Token *pToken = (ALWAYS(pDatabase) && pDatabase->z) ? pDatabase : pTable;
4969c9461eccSdan     sqlite3RenameTokenMap(pParse, pItem->zName, pToken);
4970c9461eccSdan   }
49718af73d41Sdrh   assert( pAlias!=0 );
49728af73d41Sdrh   if( pAlias->n ){
497317435752Sdrh     pItem->zAlias = sqlite3NameFromToken(db, pAlias);
497461dfc31dSdrh   }
4975815b782eSdrh   if( pSubquery ){
497661dfc31dSdrh     pItem->pSelect = pSubquery;
4977815b782eSdrh     if( pSubquery->selFlags & SF_NestedFrom ){
4978815b782eSdrh       pItem->fg.isNestedFrom = 1;
4979815b782eSdrh     }
4980815b782eSdrh   }
4981d44f8b23Sdrh   assert( pOnUsing==0 || pOnUsing->pOn==0 || pOnUsing->pUsing==0 );
4982d44f8b23Sdrh   assert( pItem->fg.isUsing==0 );
4983d44f8b23Sdrh   if( pOnUsing==0 ){
4984d44f8b23Sdrh     pItem->u3.pOn = 0;
4985d44f8b23Sdrh   }else if( pOnUsing->pUsing ){
4986d44f8b23Sdrh     pItem->fg.isUsing = 1;
4987d44f8b23Sdrh     pItem->u3.pUsing = pOnUsing->pUsing;
4988d44f8b23Sdrh   }else{
4989d44f8b23Sdrh     pItem->u3.pOn = pOnUsing->pOn;
4990d44f8b23Sdrh   }
4991bd1a0a4fSdanielk1977   return p;
4992bd1a0a4fSdanielk1977 
4993bd1a0a4fSdanielk1977 append_from_error:
4994bd1a0a4fSdanielk1977   assert( p==0 );
4995d44f8b23Sdrh   sqlite3ClearOnOrUsing(db, pOnUsing);
4996bd1a0a4fSdanielk1977   sqlite3SelectDelete(db, pSubquery);
4997bd1a0a4fSdanielk1977   return 0;
499861dfc31dSdrh }
499961dfc31dSdrh 
500061dfc31dSdrh /*
5001b1c685b0Sdanielk1977 ** Add an INDEXED BY or NOT INDEXED clause to the most recently added
5002b1c685b0Sdanielk1977 ** element of the source-list passed as the second argument.
5003b1c685b0Sdanielk1977 */
sqlite3SrcListIndexedBy(Parse * pParse,SrcList * p,Token * pIndexedBy)5004b1c685b0Sdanielk1977 void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){
50058af73d41Sdrh   assert( pIndexedBy!=0 );
50068abc80b2Sdrh   if( p && pIndexedBy->n>0 ){
50077601294aSdrh     SrcItem *pItem;
50088abc80b2Sdrh     assert( p->nSrc>0 );
50098abc80b2Sdrh     pItem = &p->a[p->nSrc-1];
50108a48b9c0Sdrh     assert( pItem->fg.notIndexed==0 );
50118a48b9c0Sdrh     assert( pItem->fg.isIndexedBy==0 );
50128a48b9c0Sdrh     assert( pItem->fg.isTabFunc==0 );
5013b1c685b0Sdanielk1977     if( pIndexedBy->n==1 && !pIndexedBy->z ){
5014b1c685b0Sdanielk1977       /* A "NOT INDEXED" clause was supplied. See parse.y
5015b1c685b0Sdanielk1977       ** construct "indexed_opt" for details. */
50168a48b9c0Sdrh       pItem->fg.notIndexed = 1;
5017b1c685b0Sdanielk1977     }else{
50188a48b9c0Sdrh       pItem->u1.zIndexedBy = sqlite3NameFromToken(pParse->db, pIndexedBy);
50198abc80b2Sdrh       pItem->fg.isIndexedBy = 1;
5020dbfbb5a0Sdrh       assert( pItem->fg.isCte==0 );  /* No collision on union u2 */
5021b1c685b0Sdanielk1977     }
5022b1c685b0Sdanielk1977   }
5023b1c685b0Sdanielk1977 }
5024b1c685b0Sdanielk1977 
5025b1c685b0Sdanielk1977 /*
502669887c99Sdan ** Append the contents of SrcList p2 to SrcList p1 and return the resulting
502769887c99Sdan ** SrcList. Or, if an error occurs, return NULL. In all cases, p1 and p2
502869887c99Sdan ** are deleted by this function.
502969887c99Sdan */
sqlite3SrcListAppendList(Parse * pParse,SrcList * p1,SrcList * p2)503069887c99Sdan SrcList *sqlite3SrcListAppendList(Parse *pParse, SrcList *p1, SrcList *p2){
50318b023cf5Sdan   assert( p1 && p1->nSrc==1 );
50328b023cf5Sdan   if( p2 ){
50338b023cf5Sdan     SrcList *pNew = sqlite3SrcListEnlarge(pParse, p1, p2->nSrc, 1);
50348b023cf5Sdan     if( pNew==0 ){
50358b023cf5Sdan       sqlite3SrcListDelete(pParse->db, p2);
50368b023cf5Sdan     }else{
50378b023cf5Sdan       p1 = pNew;
50387601294aSdrh       memcpy(&p1->a[1], p2->a, p2->nSrc*sizeof(SrcItem));
5039525326efSdrh       sqlite3DbFree(pParse->db, p2);
5040d973268cSdrh       p1->a[0].fg.jointype |= (JT_LTORJ & p1->a[1].fg.jointype);
504169887c99Sdan     }
504269887c99Sdan   }
504369887c99Sdan   return p1;
504469887c99Sdan }
504569887c99Sdan 
504669887c99Sdan /*
504701d230ceSdrh ** Add the list of function arguments to the SrcList entry for a
504801d230ceSdrh ** table-valued-function.
504901d230ceSdrh */
sqlite3SrcListFuncArgs(Parse * pParse,SrcList * p,ExprList * pList)505001d230ceSdrh void sqlite3SrcListFuncArgs(Parse *pParse, SrcList *p, ExprList *pList){
505120292310Sdrh   if( p ){
50527601294aSdrh     SrcItem *pItem = &p->a[p->nSrc-1];
505301d230ceSdrh     assert( pItem->fg.notIndexed==0 );
505401d230ceSdrh     assert( pItem->fg.isIndexedBy==0 );
505501d230ceSdrh     assert( pItem->fg.isTabFunc==0 );
505601d230ceSdrh     pItem->u1.pFuncArg = pList;
505701d230ceSdrh     pItem->fg.isTabFunc = 1;
5058d8b1bfc6Sdrh   }else{
5059d8b1bfc6Sdrh     sqlite3ExprListDelete(pParse->db, pList);
506001d230ceSdrh   }
506101d230ceSdrh }
506201d230ceSdrh 
506301d230ceSdrh /*
506461dfc31dSdrh ** When building up a FROM clause in the parser, the join operator
506561dfc31dSdrh ** is initially attached to the left operand.  But the code generator
506661dfc31dSdrh ** expects the join operator to be on the right operand.  This routine
506761dfc31dSdrh ** Shifts all join operators from left to right for an entire FROM
506861dfc31dSdrh ** clause.
506961dfc31dSdrh **
507061dfc31dSdrh ** Example: Suppose the join is like this:
507161dfc31dSdrh **
507261dfc31dSdrh **           A natural cross join B
507361dfc31dSdrh **
507461dfc31dSdrh ** The operator is "natural cross join".  The A and B operands are stored
507561dfc31dSdrh ** in p->a[0] and p->a[1], respectively.  The parser initially stores the
507661dfc31dSdrh ** operator with A.  This routine shifts that operator over to B.
507762ed36bbSdrh **
507862ed36bbSdrh ** Additional changes:
507962ed36bbSdrh **
508062ed36bbSdrh **   *   All tables to the left of the right-most RIGHT JOIN are tagged with
508162ed36bbSdrh **       JT_LTORJ (mnemonic: Left Table Of Right Join) so that the
508262ed36bbSdrh **       code generator can easily tell that the table is part of
508362ed36bbSdrh **       the left operand of at least one RIGHT JOIN.
508461dfc31dSdrh */
sqlite3SrcListShiftJoinType(Parse * pParse,SrcList * p)5085fdc621aeSdrh void sqlite3SrcListShiftJoinType(Parse *pParse, SrcList *p){
50866dab33bfSdrh   (void)pParse;
508762ed36bbSdrh   if( p && p->nSrc>1 ){
508862ed36bbSdrh     int i = p->nSrc-1;
5089a76ac88aSdrh     u8 allFlags = 0;
509062ed36bbSdrh     do{
5091a76ac88aSdrh       allFlags |= p->a[i].fg.jointype = p->a[i-1].fg.jointype;
509262ed36bbSdrh     }while( (--i)>0 );
50938a48b9c0Sdrh     p->a[0].fg.jointype = 0;
5094a76ac88aSdrh 
5095a76ac88aSdrh     /* All terms to the left of a RIGHT JOIN should be tagged with the
5096a76ac88aSdrh     ** JT_LTORJ flags */
5097a76ac88aSdrh     if( allFlags & JT_RIGHT ){
5098a76ac88aSdrh       for(i=p->nSrc-1; ALWAYS(i>0) && (p->a[i].fg.jointype&JT_RIGHT)==0; i--){}
5099a76ac88aSdrh       i--;
5100a76ac88aSdrh       assert( i>=0 );
5101a76ac88aSdrh       do{
5102fdc621aeSdrh         p->a[i].fg.jointype |= JT_LTORJ;
5103fdc621aeSdrh       }while( (--i)>=0 );
5104a76ac88aSdrh     }
510561dfc31dSdrh   }
510661dfc31dSdrh }
510761dfc31dSdrh 
510861dfc31dSdrh /*
5109b0c88651Sdrh ** Generate VDBE code for a BEGIN statement.
5110c4a3c779Sdrh */
sqlite3BeginTransaction(Parse * pParse,int type)5111684917c2Sdrh void sqlite3BeginTransaction(Parse *pParse, int type){
51129bb575fdSdrh   sqlite3 *db;
51131d850a72Sdanielk1977   Vdbe *v;
5114684917c2Sdrh   int i;
51155e00f6c7Sdrh 
5116d3001711Sdrh   assert( pParse!=0 );
5117d3001711Sdrh   db = pParse->db;
5118d3001711Sdrh   assert( db!=0 );
5119d3001711Sdrh   if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){
5120d3001711Sdrh     return;
5121d3001711Sdrh   }
51221d850a72Sdanielk1977   v = sqlite3GetVdbe(pParse);
51231d850a72Sdanielk1977   if( !v ) return;
5124684917c2Sdrh   if( type!=TK_DEFERRED ){
5125684917c2Sdrh     for(i=0; i<db->nDb; i++){
51261ca037f4Sdrh       int eTxnType;
51271ca037f4Sdrh       Btree *pBt = db->aDb[i].pBt;
51281ca037f4Sdrh       if( pBt && sqlite3BtreeIsReadonly(pBt) ){
51291ca037f4Sdrh         eTxnType = 0;  /* Read txn */
51301ca037f4Sdrh       }else if( type==TK_EXCLUSIVE ){
51311ca037f4Sdrh         eTxnType = 2;  /* Exclusive txn */
51321ca037f4Sdrh       }else{
51331ca037f4Sdrh         eTxnType = 1;  /* Write txn */
51341ca037f4Sdrh       }
51351ca037f4Sdrh       sqlite3VdbeAddOp2(v, OP_Transaction, i, eTxnType);
5136fb98264aSdrh       sqlite3VdbeUsesBtree(v, i);
5137684917c2Sdrh     }
5138684917c2Sdrh   }
5139b0c88651Sdrh   sqlite3VdbeAddOp0(v, OP_AutoCommit);
514002f75f19Sdrh }
5141c4a3c779Sdrh 
5142c4a3c779Sdrh /*
514307a3b11aSdrh ** Generate VDBE code for a COMMIT or ROLLBACK statement.
514407a3b11aSdrh ** Code for ROLLBACK is generated if eType==TK_ROLLBACK.  Otherwise
514507a3b11aSdrh ** code is generated for a COMMIT.
5146c4a3c779Sdrh */
sqlite3EndTransaction(Parse * pParse,int eType)514707a3b11aSdrh void sqlite3EndTransaction(Parse *pParse, int eType){
51481d850a72Sdanielk1977   Vdbe *v;
514907a3b11aSdrh   int isRollback;
51505e00f6c7Sdrh 
5151d3001711Sdrh   assert( pParse!=0 );
5152b07028f7Sdrh   assert( pParse->db!=0 );
515307a3b11aSdrh   assert( eType==TK_COMMIT || eType==TK_END || eType==TK_ROLLBACK );
515407a3b11aSdrh   isRollback = eType==TK_ROLLBACK;
515507a3b11aSdrh   if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION,
515607a3b11aSdrh        isRollback ? "ROLLBACK" : "COMMIT", 0, 0) ){
5157d3001711Sdrh     return;
5158d3001711Sdrh   }
51591d850a72Sdanielk1977   v = sqlite3GetVdbe(pParse);
51601d850a72Sdanielk1977   if( v ){
516107a3b11aSdrh     sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, isRollback);
5162c4a3c779Sdrh   }
516302f75f19Sdrh }
5164f57b14a6Sdrh 
5165f57b14a6Sdrh /*
5166fd7f0452Sdanielk1977 ** This function is called by the parser when it parses a command to create,
5167fd7f0452Sdanielk1977 ** release or rollback an SQL savepoint.
5168fd7f0452Sdanielk1977 */
sqlite3Savepoint(Parse * pParse,int op,Token * pName)5169fd7f0452Sdanielk1977 void sqlite3Savepoint(Parse *pParse, int op, Token *pName){
5170ab9b703fSdanielk1977   char *zName = sqlite3NameFromToken(pParse->db, pName);
5171ab9b703fSdanielk1977   if( zName ){
5172ab9b703fSdanielk1977     Vdbe *v = sqlite3GetVdbe(pParse);
5173ab9b703fSdanielk1977 #ifndef SQLITE_OMIT_AUTHORIZATION
5174558814f8Sdan     static const char * const az[] = { "BEGIN", "RELEASE", "ROLLBACK" };
5175ab9b703fSdanielk1977     assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 );
5176ab9b703fSdanielk1977 #endif
5177ab9b703fSdanielk1977     if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){
5178ab9b703fSdanielk1977       sqlite3DbFree(pParse->db, zName);
5179ab9b703fSdanielk1977       return;
5180ab9b703fSdanielk1977     }
5181ab9b703fSdanielk1977     sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC);
5182fd7f0452Sdanielk1977   }
5183fd7f0452Sdanielk1977 }
5184fd7f0452Sdanielk1977 
5185fd7f0452Sdanielk1977 /*
5186dc3ff9c3Sdrh ** Make sure the TEMP database is open and available for use.  Return
5187dc3ff9c3Sdrh ** the number of errors.  Leave any error messages in the pParse structure.
5188dc3ff9c3Sdrh */
sqlite3OpenTempDatabase(Parse * pParse)5189ddfb2f03Sdanielk1977 int sqlite3OpenTempDatabase(Parse *pParse){
5190dc3ff9c3Sdrh   sqlite3 *db = pParse->db;
5191dc3ff9c3Sdrh   if( db->aDb[1].pBt==0 && !pParse->explain ){
519233f4e02aSdrh     int rc;
519310a76c90Sdrh     Btree *pBt;
519433f4e02aSdrh     static const int flags =
519533f4e02aSdrh           SQLITE_OPEN_READWRITE |
519633f4e02aSdrh           SQLITE_OPEN_CREATE |
519733f4e02aSdrh           SQLITE_OPEN_EXCLUSIVE |
519833f4e02aSdrh           SQLITE_OPEN_DELETEONCLOSE |
519933f4e02aSdrh           SQLITE_OPEN_TEMP_DB;
520033f4e02aSdrh 
52013a6d8aecSdan     rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pBt, 0, flags);
5202dc3ff9c3Sdrh     if( rc!=SQLITE_OK ){
5203dc3ff9c3Sdrh       sqlite3ErrorMsg(pParse, "unable to open a temporary database "
5204dc3ff9c3Sdrh         "file for storing temporary tables");
5205dc3ff9c3Sdrh       pParse->rc = rc;
5206dc3ff9c3Sdrh       return 1;
5207dc3ff9c3Sdrh     }
520810a76c90Sdrh     db->aDb[1].pBt = pBt;
520914db2665Sdanielk1977     assert( db->aDb[1].pSchema );
5210e937df81Sdrh     if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, 0, 0) ){
52114a642b60Sdrh       sqlite3OomFault(db);
52127c9c9868Sdrh       return 1;
521310a76c90Sdrh     }
5214dc3ff9c3Sdrh   }
5215dc3ff9c3Sdrh   return 0;
5216dc3ff9c3Sdrh }
5217dc3ff9c3Sdrh 
5218dc3ff9c3Sdrh /*
5219aceb31b1Sdrh ** Record the fact that the schema cookie will need to be verified
5220aceb31b1Sdrh ** for database iDb.  The code to actually verify the schema cookie
5221aceb31b1Sdrh ** will occur at the end of the top-level VDBE and will be generated
5222aceb31b1Sdrh ** later, by sqlite3FinishCoding().
5223001bbcbbSdrh */
sqlite3CodeVerifySchemaAtToplevel(Parse * pToplevel,int iDb)52241d8f892aSdrh static void sqlite3CodeVerifySchemaAtToplevel(Parse *pToplevel, int iDb){
52251d8f892aSdrh   assert( iDb>=0 && iDb<pToplevel->db->nDb );
52261d8f892aSdrh   assert( pToplevel->db->aDb[iDb].pBt!=0 || iDb==1 );
5227099b385dSdrh   assert( iDb<SQLITE_MAX_DB );
52281d8f892aSdrh   assert( sqlite3SchemaMutexHeld(pToplevel->db, iDb, 0) );
5229a7ab6d81Sdrh   if( DbMaskTest(pToplevel->cookieMask, iDb)==0 ){
5230a7ab6d81Sdrh     DbMaskSet(pToplevel->cookieMask, iDb);
523153c0f748Sdanielk1977     if( !OMIT_TEMPDB && iDb==1 ){
523265a7cd16Sdan       sqlite3OpenTempDatabase(pToplevel);
5233dc3ff9c3Sdrh     }
5234001bbcbbSdrh   }
5235c275b4eaSdrh }
sqlite3CodeVerifySchema(Parse * pParse,int iDb)52361d8f892aSdrh void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
52371d8f892aSdrh   sqlite3CodeVerifySchemaAtToplevel(sqlite3ParseToplevel(pParse), iDb);
52381d8f892aSdrh }
52391d8f892aSdrh 
5240001bbcbbSdrh 
5241001bbcbbSdrh /*
524257966753Sdan ** If argument zDb is NULL, then call sqlite3CodeVerifySchema() for each
524357966753Sdan ** attached database. Otherwise, invoke it for the database named zDb only.
524457966753Sdan */
sqlite3CodeVerifyNamedSchema(Parse * pParse,const char * zDb)524557966753Sdan void sqlite3CodeVerifyNamedSchema(Parse *pParse, const char *zDb){
524657966753Sdan   sqlite3 *db = pParse->db;
524757966753Sdan   int i;
524857966753Sdan   for(i=0; i<db->nDb; i++){
524957966753Sdan     Db *pDb = &db->aDb[i];
525069c33826Sdrh     if( pDb->pBt && (!zDb || 0==sqlite3StrICmp(zDb, pDb->zDbSName)) ){
525157966753Sdan       sqlite3CodeVerifySchema(pParse, i);
525257966753Sdan     }
525357966753Sdan   }
525457966753Sdan }
525557966753Sdan 
525657966753Sdan /*
52571c92853dSdrh ** Generate VDBE code that prepares for doing an operation that
5258c977f7f5Sdrh ** might change the database.
5259c977f7f5Sdrh **
5260c977f7f5Sdrh ** This routine starts a new transaction if we are not already within
5261c977f7f5Sdrh ** a transaction.  If we are already within a transaction, then a checkpoint
52627f0f12e3Sdrh ** is set if the setStatement parameter is true.  A checkpoint should
5263c977f7f5Sdrh ** be set for operations that might fail (due to a constraint) part of
5264c977f7f5Sdrh ** the way through and which will need to undo some writes without having to
5265c977f7f5Sdrh ** rollback the whole transaction.  For operations where all constraints
5266c977f7f5Sdrh ** can be checked before any changes are made to the database, it is never
5267c977f7f5Sdrh ** necessary to undo a write and the checkpoint should not be set.
52681c92853dSdrh */
sqlite3BeginWriteOperation(Parse * pParse,int setStatement,int iDb)52697f0f12e3Sdrh void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
527065a7cd16Sdan   Parse *pToplevel = sqlite3ParseToplevel(pParse);
52711d8f892aSdrh   sqlite3CodeVerifySchemaAtToplevel(pToplevel, iDb);
5272a7ab6d81Sdrh   DbMaskSet(pToplevel->writeMask, iDb);
5273e0af83acSdan   pToplevel->isMultiWrite |= setStatement;
52741d850a72Sdanielk1977 }
5275e0af83acSdan 
5276e0af83acSdan /*
5277ff738bceSdrh ** Indicate that the statement currently under construction might write
5278ff738bceSdrh ** more than one entry (example: deleting one row then inserting another,
5279ff738bceSdrh ** inserting multiple rows in a table, or inserting a row and index entries.)
5280ff738bceSdrh ** If an abort occurs after some of these writes have completed, then it will
5281ff738bceSdrh ** be necessary to undo the completed writes.
5282ff738bceSdrh */
sqlite3MultiWrite(Parse * pParse)5283ff738bceSdrh void sqlite3MultiWrite(Parse *pParse){
5284ff738bceSdrh   Parse *pToplevel = sqlite3ParseToplevel(pParse);
5285ff738bceSdrh   pToplevel->isMultiWrite = 1;
5286ff738bceSdrh }
5287ff738bceSdrh 
5288ff738bceSdrh /*
5289ff738bceSdrh ** The code generator calls this routine if is discovers that it is
5290ff738bceSdrh ** possible to abort a statement prior to completion.  In order to
5291ff738bceSdrh ** perform this abort without corrupting the database, we need to make
5292ff738bceSdrh ** sure that the statement is protected by a statement transaction.
5293ff738bceSdrh **
5294ff738bceSdrh ** Technically, we only need to set the mayAbort flag if the
5295ff738bceSdrh ** isMultiWrite flag was previously set.  There is a time dependency
5296ff738bceSdrh ** such that the abort must occur after the multiwrite.  This makes
5297ff738bceSdrh ** some statements involving the REPLACE conflict resolution algorithm
5298ff738bceSdrh ** go a little faster.  But taking advantage of this time dependency
5299ff738bceSdrh ** makes it more difficult to prove that the code is correct (in
5300ff738bceSdrh ** particular, it prevents us from writing an effective
5301ff738bceSdrh ** implementation of sqlite3AssertMayAbort()) and so we have chosen
5302ff738bceSdrh ** to take the safe route and skip the optimization.
5303e0af83acSdan */
sqlite3MayAbort(Parse * pParse)5304e0af83acSdan void sqlite3MayAbort(Parse *pParse){
5305e0af83acSdan   Parse *pToplevel = sqlite3ParseToplevel(pParse);
5306e0af83acSdan   pToplevel->mayAbort = 1;
5307e0af83acSdan }
5308e0af83acSdan 
5309e0af83acSdan /*
5310e0af83acSdan ** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT
5311e0af83acSdan ** error. The onError parameter determines which (if any) of the statement
5312e0af83acSdan ** and/or current transaction is rolled back.
5313e0af83acSdan */
sqlite3HaltConstraint(Parse * pParse,int errCode,int onError,char * p4,i8 p4type,u8 p5Errmsg)5314d91c1a17Sdrh void sqlite3HaltConstraint(
5315d91c1a17Sdrh   Parse *pParse,    /* Parsing context */
5316d91c1a17Sdrh   int errCode,      /* extended error code */
5317d91c1a17Sdrh   int onError,      /* Constraint type */
5318d91c1a17Sdrh   char *p4,         /* Error message */
5319f9c8ce3cSdrh   i8 p4type,        /* P4_STATIC or P4_TRANSIENT */
5320f9c8ce3cSdrh   u8 p5Errmsg       /* P5_ErrMsg type */
5321d91c1a17Sdrh ){
5322289a0c84Sdrh   Vdbe *v;
5323289a0c84Sdrh   assert( pParse->pVdbe!=0 );
5324289a0c84Sdrh   v = sqlite3GetVdbe(pParse);
53259e5fdc41Sdrh   assert( (errCode&0xff)==SQLITE_CONSTRAINT || pParse->nested );
5326e0af83acSdan   if( onError==OE_Abort ){
5327e0af83acSdan     sqlite3MayAbort(pParse);
5328e0af83acSdan   }
5329d91c1a17Sdrh   sqlite3VdbeAddOp4(v, OP_Halt, errCode, onError, 0, p4, p4type);
53309b34abeeSdrh   sqlite3VdbeChangeP5(v, p5Errmsg);
5331f9c8ce3cSdrh }
5332f9c8ce3cSdrh 
5333f9c8ce3cSdrh /*
5334f9c8ce3cSdrh ** Code an OP_Halt due to UNIQUE or PRIMARY KEY constraint violation.
5335f9c8ce3cSdrh */
sqlite3UniqueConstraint(Parse * pParse,int onError,Index * pIdx)5336f9c8ce3cSdrh void sqlite3UniqueConstraint(
5337f9c8ce3cSdrh   Parse *pParse,    /* Parsing context */
5338f9c8ce3cSdrh   int onError,      /* Constraint type */
5339f9c8ce3cSdrh   Index *pIdx       /* The index that triggers the constraint */
5340f9c8ce3cSdrh ){
5341f9c8ce3cSdrh   char *zErr;
5342f9c8ce3cSdrh   int j;
5343f9c8ce3cSdrh   StrAccum errMsg;
5344f9c8ce3cSdrh   Table *pTab = pIdx->pTable;
5345f9c8ce3cSdrh 
534686ec1eddSdrh   sqlite3StrAccumInit(&errMsg, pParse->db, 0, 0,
534786ec1eddSdrh                       pParse->db->aLimit[SQLITE_LIMIT_LENGTH]);
53488b576422Sdrh   if( pIdx->aColExpr ){
53490cdbe1aeSdrh     sqlite3_str_appendf(&errMsg, "index '%q'", pIdx->zName);
53508b576422Sdrh   }else{
5351f9c8ce3cSdrh     for(j=0; j<pIdx->nKeyCol; j++){
53521f9ca2c8Sdrh       char *zCol;
53531f9ca2c8Sdrh       assert( pIdx->aiColumn[j]>=0 );
5354cf9d36d1Sdrh       zCol = pTab->aCol[pIdx->aiColumn[j]].zCnName;
53550cdbe1aeSdrh       if( j ) sqlite3_str_append(&errMsg, ", ", 2);
53560cdbe1aeSdrh       sqlite3_str_appendall(&errMsg, pTab->zName);
53570cdbe1aeSdrh       sqlite3_str_append(&errMsg, ".", 1);
53580cdbe1aeSdrh       sqlite3_str_appendall(&errMsg, zCol);
53598b576422Sdrh     }
5360f9c8ce3cSdrh   }
5361f9c8ce3cSdrh   zErr = sqlite3StrAccumFinish(&errMsg);
5362f9c8ce3cSdrh   sqlite3HaltConstraint(pParse,
536348dd1d8eSdrh     IsPrimaryKeyIndex(pIdx) ? SQLITE_CONSTRAINT_PRIMARYKEY
536448dd1d8eSdrh                             : SQLITE_CONSTRAINT_UNIQUE,
536593889d93Sdan     onError, zErr, P4_DYNAMIC, P5_ConstraintUnique);
5366f9c8ce3cSdrh }
5367f9c8ce3cSdrh 
5368f9c8ce3cSdrh 
5369f9c8ce3cSdrh /*
5370f9c8ce3cSdrh ** Code an OP_Halt due to non-unique rowid.
5371f9c8ce3cSdrh */
sqlite3RowidConstraint(Parse * pParse,int onError,Table * pTab)5372f9c8ce3cSdrh void sqlite3RowidConstraint(
5373f9c8ce3cSdrh   Parse *pParse,    /* Parsing context */
5374f9c8ce3cSdrh   int onError,      /* Conflict resolution algorithm */
5375f9c8ce3cSdrh   Table *pTab       /* The table with the non-unique rowid */
5376f9c8ce3cSdrh ){
5377f9c8ce3cSdrh   char *zMsg;
5378f9c8ce3cSdrh   int rc;
5379f9c8ce3cSdrh   if( pTab->iPKey>=0 ){
5380f9c8ce3cSdrh     zMsg = sqlite3MPrintf(pParse->db, "%s.%s", pTab->zName,
5381cf9d36d1Sdrh                           pTab->aCol[pTab->iPKey].zCnName);
5382f9c8ce3cSdrh     rc = SQLITE_CONSTRAINT_PRIMARYKEY;
5383f9c8ce3cSdrh   }else{
5384f9c8ce3cSdrh     zMsg = sqlite3MPrintf(pParse->db, "%s.rowid", pTab->zName);
5385f9c8ce3cSdrh     rc = SQLITE_CONSTRAINT_ROWID;
5386f9c8ce3cSdrh   }
5387f9c8ce3cSdrh   sqlite3HaltConstraint(pParse, rc, onError, zMsg, P4_DYNAMIC,
5388f9c8ce3cSdrh                         P5_ConstraintUnique);
5389663fc63aSdrh }
5390663fc63aSdrh 
53914343fea2Sdrh /*
53924343fea2Sdrh ** Check to see if pIndex uses the collating sequence pColl.  Return
53934343fea2Sdrh ** true if it does and false if it does not.
53944343fea2Sdrh */
53954343fea2Sdrh #ifndef SQLITE_OMIT_REINDEX
collationMatch(const char * zColl,Index * pIndex)5396b3bf556eSdanielk1977 static int collationMatch(const char *zColl, Index *pIndex){
5397b3bf556eSdanielk1977   int i;
53980449171eSdrh   assert( zColl!=0 );
5399b3bf556eSdanielk1977   for(i=0; i<pIndex->nColumn; i++){
5400b3bf556eSdanielk1977     const char *z = pIndex->azColl[i];
5401bbbdc83bSdrh     assert( z!=0 || pIndex->aiColumn[i]<0 );
5402bbbdc83bSdrh     if( pIndex->aiColumn[i]>=0 && 0==sqlite3StrICmp(z, zColl) ){
5403b3bf556eSdanielk1977       return 1;
5404b3bf556eSdanielk1977     }
54054343fea2Sdrh   }
54064343fea2Sdrh   return 0;
54074343fea2Sdrh }
54084343fea2Sdrh #endif
54094343fea2Sdrh 
54104343fea2Sdrh /*
54114343fea2Sdrh ** Recompute all indices of pTab that use the collating sequence pColl.
54124343fea2Sdrh ** If pColl==0 then recompute all indices of pTab.
54134343fea2Sdrh */
54144343fea2Sdrh #ifndef SQLITE_OMIT_REINDEX
reindexTable(Parse * pParse,Table * pTab,char const * zColl)5415b3bf556eSdanielk1977 static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
5416e6370e9cSdan   if( !IsVirtual(pTab) ){
54174343fea2Sdrh     Index *pIndex;              /* An index associated with pTab */
54184343fea2Sdrh 
54194343fea2Sdrh     for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
5420b3bf556eSdanielk1977       if( zColl==0 || collationMatch(zColl, pIndex) ){
5421da184236Sdanielk1977         int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
5422da184236Sdanielk1977         sqlite3BeginWriteOperation(pParse, 0, iDb);
54234343fea2Sdrh         sqlite3RefillIndex(pParse, pIndex, -1);
54244343fea2Sdrh       }
54254343fea2Sdrh     }
54264343fea2Sdrh   }
5427e6370e9cSdan }
54284343fea2Sdrh #endif
54294343fea2Sdrh 
54304343fea2Sdrh /*
54314343fea2Sdrh ** Recompute all indices of all tables in all databases where the
54324343fea2Sdrh ** indices use the collating sequence pColl.  If pColl==0 then recompute
54334343fea2Sdrh ** all indices everywhere.
54344343fea2Sdrh */
54354343fea2Sdrh #ifndef SQLITE_OMIT_REINDEX
reindexDatabases(Parse * pParse,char const * zColl)5436b3bf556eSdanielk1977 static void reindexDatabases(Parse *pParse, char const *zColl){
54374343fea2Sdrh   Db *pDb;                    /* A single database */
54384343fea2Sdrh   int iDb;                    /* The database index number */
54394343fea2Sdrh   sqlite3 *db = pParse->db;   /* The database connection */
54404343fea2Sdrh   HashElem *k;                /* For looping over tables in pDb */
54414343fea2Sdrh   Table *pTab;                /* A table in the database */
54424343fea2Sdrh 
54432120608eSdrh   assert( sqlite3BtreeHoldsAllMutexes(db) );  /* Needed for schema access */
54444343fea2Sdrh   for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
544543617e9aSdrh     assert( pDb!=0 );
5446da184236Sdanielk1977     for(k=sqliteHashFirst(&pDb->pSchema->tblHash);  k; k=sqliteHashNext(k)){
54474343fea2Sdrh       pTab = (Table*)sqliteHashData(k);
5448b3bf556eSdanielk1977       reindexTable(pParse, pTab, zColl);
54494343fea2Sdrh     }
54504343fea2Sdrh   }
54514343fea2Sdrh }
54524343fea2Sdrh #endif
54534343fea2Sdrh 
54544343fea2Sdrh /*
5455eee46cf3Sdrh ** Generate code for the REINDEX command.
5456eee46cf3Sdrh **
5457eee46cf3Sdrh **        REINDEX                            -- 1
5458eee46cf3Sdrh **        REINDEX  <collation>               -- 2
5459eee46cf3Sdrh **        REINDEX  ?<database>.?<tablename>  -- 3
5460eee46cf3Sdrh **        REINDEX  ?<database>.?<indexname>  -- 4
5461eee46cf3Sdrh **
5462eee46cf3Sdrh ** Form 1 causes all indices in all attached databases to be rebuilt.
5463eee46cf3Sdrh ** Form 2 rebuilds all indices in all databases that use the named
5464eee46cf3Sdrh ** collating function.  Forms 3 and 4 rebuild the named index or all
5465eee46cf3Sdrh ** indices associated with the named table.
54664343fea2Sdrh */
54674343fea2Sdrh #ifndef SQLITE_OMIT_REINDEX
sqlite3Reindex(Parse * pParse,Token * pName1,Token * pName2)54684343fea2Sdrh void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
54694343fea2Sdrh   CollSeq *pColl;             /* Collating sequence to be reindexed, or NULL */
54704343fea2Sdrh   char *z;                    /* Name of a table or index */
54714343fea2Sdrh   const char *zDb;            /* Name of the database */
54724343fea2Sdrh   Table *pTab;                /* A table in the database */
54734343fea2Sdrh   Index *pIndex;              /* An index associated with pTab */
54744343fea2Sdrh   int iDb;                    /* The database index number */
54754343fea2Sdrh   sqlite3 *db = pParse->db;   /* The database connection */
54764343fea2Sdrh   Token *pObjName;            /* Name of the table or index to be reindexed */
54774343fea2Sdrh 
547833a5edc3Sdanielk1977   /* Read the database schema. If an error occurs, leave an error message
547933a5edc3Sdanielk1977   ** and code in pParse and return NULL. */
548033a5edc3Sdanielk1977   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
5481e63739a8Sdanielk1977     return;
548233a5edc3Sdanielk1977   }
548333a5edc3Sdanielk1977 
54848af73d41Sdrh   if( pName1==0 ){
54854343fea2Sdrh     reindexDatabases(pParse, 0);
54864343fea2Sdrh     return;
5487d3001711Sdrh   }else if( NEVER(pName2==0) || pName2->z==0 ){
548839002505Sdanielk1977     char *zColl;
5489b3bf556eSdanielk1977     assert( pName1->z );
549039002505Sdanielk1977     zColl = sqlite3NameFromToken(pParse->db, pName1);
549139002505Sdanielk1977     if( !zColl ) return;
5492c4a64facSdrh     pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
54934343fea2Sdrh     if( pColl ){
5494f0113000Sdanielk1977       reindexDatabases(pParse, zColl);
5495633e6d57Sdrh       sqlite3DbFree(db, zColl);
54964343fea2Sdrh       return;
54974343fea2Sdrh     }
5498633e6d57Sdrh     sqlite3DbFree(db, zColl);
54994343fea2Sdrh   }
55004343fea2Sdrh   iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
55014343fea2Sdrh   if( iDb<0 ) return;
550217435752Sdrh   z = sqlite3NameFromToken(db, pObjName);
550384f31128Sdrh   if( z==0 ) return;
550469c33826Sdrh   zDb = db->aDb[iDb].zDbSName;
55054343fea2Sdrh   pTab = sqlite3FindTable(db, z, zDb);
55064343fea2Sdrh   if( pTab ){
55074343fea2Sdrh     reindexTable(pParse, pTab, 0);
5508633e6d57Sdrh     sqlite3DbFree(db, z);
55094343fea2Sdrh     return;
55104343fea2Sdrh   }
55114343fea2Sdrh   pIndex = sqlite3FindIndex(db, z, zDb);
5512633e6d57Sdrh   sqlite3DbFree(db, z);
55134343fea2Sdrh   if( pIndex ){
55144343fea2Sdrh     sqlite3BeginWriteOperation(pParse, 0, iDb);
55154343fea2Sdrh     sqlite3RefillIndex(pParse, pIndex, -1);
55164343fea2Sdrh     return;
55174343fea2Sdrh   }
55184343fea2Sdrh   sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
55194343fea2Sdrh }
55204343fea2Sdrh #endif
5521b3bf556eSdanielk1977 
5522b3bf556eSdanielk1977 /*
55232ec2fb22Sdrh ** Return a KeyInfo structure that is appropriate for the given Index.
5524b3bf556eSdanielk1977 **
55252ec2fb22Sdrh ** The caller should invoke sqlite3KeyInfoUnref() on the returned object
55262ec2fb22Sdrh ** when it has finished using it.
5527b3bf556eSdanielk1977 */
sqlite3KeyInfoOfIndex(Parse * pParse,Index * pIdx)55282ec2fb22Sdrh KeyInfo *sqlite3KeyInfoOfIndex(Parse *pParse, Index *pIdx){
5529b3bf556eSdanielk1977   int i;
5530ad124329Sdrh   int nCol = pIdx->nColumn;
5531ad124329Sdrh   int nKey = pIdx->nKeyCol;
5532323df790Sdrh   KeyInfo *pKey;
553318b67f3fSdrh   if( pParse->nErr ) return 0;
55341153c7b2Sdrh   if( pIdx->uniqNotNull ){
5535ad124329Sdrh     pKey = sqlite3KeyInfoAlloc(pParse->db, nKey, nCol-nKey);
55361153c7b2Sdrh   }else{
55371153c7b2Sdrh     pKey = sqlite3KeyInfoAlloc(pParse->db, nCol, 0);
55381153c7b2Sdrh   }
5539b3bf556eSdanielk1977   if( pKey ){
55402ec2fb22Sdrh     assert( sqlite3KeyInfoIsWriteable(pKey) );
5541b3bf556eSdanielk1977     for(i=0; i<nCol; i++){
5542f19aa5faSdrh       const char *zColl = pIdx->azColl[i];
5543f19aa5faSdrh       pKey->aColl[i] = zColl==sqlite3StrBINARY ? 0 :
5544b8a9bb4fSdrh                         sqlite3LocateCollSeq(pParse, zColl);
55456e11892dSdan       pKey->aSortFlags[i] = pIdx->aSortOrder[i];
55466e11892dSdan       assert( 0==(pKey->aSortFlags[i] & KEYINFO_ORDER_BIGNULL) );
5547b3bf556eSdanielk1977     }
5548b3bf556eSdanielk1977     if( pParse->nErr ){
55497e8515d8Sdrh       assert( pParse->rc==SQLITE_ERROR_MISSING_COLLSEQ );
55507e8515d8Sdrh       if( pIdx->bNoQuery==0 ){
55517e8515d8Sdrh         /* Deactivate the index because it contains an unknown collating
55527e8515d8Sdrh         ** sequence.  The only way to reactive the index is to reload the
55537e8515d8Sdrh         ** schema.  Adding the missing collating sequence later does not
55547e8515d8Sdrh         ** reactive the index.  The application had the chance to register
55557e8515d8Sdrh         ** the missing index using the collation-needed callback.  For
55567e8515d8Sdrh         ** simplicity, SQLite will not give the application a second chance.
55577e8515d8Sdrh         */
55587e8515d8Sdrh         pIdx->bNoQuery = 1;
55597e8515d8Sdrh         pParse->rc = SQLITE_ERROR_RETRY;
55607e8515d8Sdrh       }
55612ec2fb22Sdrh       sqlite3KeyInfoUnref(pKey);
556218b67f3fSdrh       pKey = 0;
5563b3bf556eSdanielk1977     }
55642ec2fb22Sdrh   }
556518b67f3fSdrh   return pKey;
5566b3bf556eSdanielk1977 }
55678b471863Sdrh 
55688b471863Sdrh #ifndef SQLITE_OMIT_CTE
55697d562dbeSdan /*
5570f824b41eSdrh ** Create a new CTE object
5571f824b41eSdrh */
sqlite3CteNew(Parse * pParse,Token * pName,ExprList * pArglist,Select * pQuery,u8 eM10d)5572f824b41eSdrh Cte *sqlite3CteNew(
5573f824b41eSdrh   Parse *pParse,          /* Parsing context */
5574f824b41eSdrh   Token *pName,           /* Name of the common-table */
5575f824b41eSdrh   ExprList *pArglist,     /* Optional column name list for the table */
5576745912efSdrh   Select *pQuery,         /* Query used to initialize the table */
5577745912efSdrh   u8 eM10d                /* The MATERIALIZED flag */
5578f824b41eSdrh ){
5579f824b41eSdrh   Cte *pNew;
5580f824b41eSdrh   sqlite3 *db = pParse->db;
5581f824b41eSdrh 
5582f824b41eSdrh   pNew = sqlite3DbMallocZero(db, sizeof(*pNew));
5583f824b41eSdrh   assert( pNew!=0 || db->mallocFailed );
5584f824b41eSdrh 
5585f824b41eSdrh   if( db->mallocFailed ){
5586f824b41eSdrh     sqlite3ExprListDelete(db, pArglist);
5587f824b41eSdrh     sqlite3SelectDelete(db, pQuery);
5588f824b41eSdrh   }else{
5589f824b41eSdrh     pNew->pSelect = pQuery;
5590f824b41eSdrh     pNew->pCols = pArglist;
5591f824b41eSdrh     pNew->zName = sqlite3NameFromToken(pParse->db, pName);
5592745912efSdrh     pNew->eM10d = eM10d;
5593f824b41eSdrh   }
5594f824b41eSdrh   return pNew;
5595f824b41eSdrh }
5596f824b41eSdrh 
5597f824b41eSdrh /*
5598f824b41eSdrh ** Clear information from a Cte object, but do not deallocate storage
5599f824b41eSdrh ** for the object itself.
5600f824b41eSdrh */
cteClear(sqlite3 * db,Cte * pCte)5601f824b41eSdrh static void cteClear(sqlite3 *db, Cte *pCte){
5602f824b41eSdrh   assert( pCte!=0 );
5603f824b41eSdrh   sqlite3ExprListDelete(db, pCte->pCols);
5604f824b41eSdrh   sqlite3SelectDelete(db, pCte->pSelect);
5605f824b41eSdrh   sqlite3DbFree(db, pCte->zName);
5606f824b41eSdrh }
5607f824b41eSdrh 
5608f824b41eSdrh /*
5609f824b41eSdrh ** Free the contents of the CTE object passed as the second argument.
5610f824b41eSdrh */
sqlite3CteDelete(sqlite3 * db,Cte * pCte)5611f824b41eSdrh void sqlite3CteDelete(sqlite3 *db, Cte *pCte){
5612f824b41eSdrh   assert( pCte!=0 );
5613f824b41eSdrh   cteClear(db, pCte);
5614f824b41eSdrh   sqlite3DbFree(db, pCte);
5615f824b41eSdrh }
5616f824b41eSdrh 
5617f824b41eSdrh /*
56187d562dbeSdan ** This routine is invoked once per CTE by the parser while parsing a
5619f824b41eSdrh ** WITH clause.  The CTE described by teh third argument is added to
5620f824b41eSdrh ** the WITH clause of the second argument.  If the second argument is
5621f824b41eSdrh ** NULL, then a new WITH argument is created.
56228b471863Sdrh */
sqlite3WithAdd(Parse * pParse,With * pWith,Cte * pCte)56237d562dbeSdan With *sqlite3WithAdd(
56248b471863Sdrh   Parse *pParse,          /* Parsing context */
56257d562dbeSdan   With *pWith,            /* Existing WITH clause, or NULL */
5626f824b41eSdrh   Cte *pCte               /* CTE to add to the WITH clause */
56278b471863Sdrh ){
56284e9119d9Sdan   sqlite3 *db = pParse->db;
56294e9119d9Sdan   With *pNew;
56304e9119d9Sdan   char *zName;
56314e9119d9Sdan 
5632f824b41eSdrh   if( pCte==0 ){
5633f824b41eSdrh     return pWith;
5634f824b41eSdrh   }
5635f824b41eSdrh 
56364e9119d9Sdan   /* Check that the CTE name is unique within this WITH clause. If
56374e9119d9Sdan   ** not, store an error in the Parse structure. */
5638f824b41eSdrh   zName = pCte->zName;
56394e9119d9Sdan   if( zName && pWith ){
56404e9119d9Sdan     int i;
56414e9119d9Sdan     for(i=0; i<pWith->nCte; i++){
56424e9119d9Sdan       if( sqlite3StrICmp(zName, pWith->a[i].zName)==0 ){
5643727a99f1Sdrh         sqlite3ErrorMsg(pParse, "duplicate WITH table name: %s", zName);
56444e9119d9Sdan       }
56454e9119d9Sdan     }
56464e9119d9Sdan   }
56474e9119d9Sdan 
56484e9119d9Sdan   if( pWith ){
56490aa3231fSdrh     sqlite3_int64 nByte = sizeof(*pWith) + (sizeof(pWith->a[1]) * pWith->nCte);
56504e9119d9Sdan     pNew = sqlite3DbRealloc(db, pWith, nByte);
56514e9119d9Sdan   }else{
56524e9119d9Sdan     pNew = sqlite3DbMallocZero(db, sizeof(*pWith));
56534e9119d9Sdan   }
5654b84e574cSdrh   assert( (pNew!=0 && zName!=0) || db->mallocFailed );
56554e9119d9Sdan 
5656b84e574cSdrh   if( db->mallocFailed ){
5657f824b41eSdrh     sqlite3CteDelete(db, pCte);
5658a9f5c13dSdan     pNew = pWith;
56594e9119d9Sdan   }else{
5660f824b41eSdrh     pNew->a[pNew->nCte++] = *pCte;
5661f824b41eSdrh     sqlite3DbFree(db, pCte);
56624e9119d9Sdan   }
56634e9119d9Sdan 
56644e9119d9Sdan   return pNew;
56658b471863Sdrh }
56668b471863Sdrh 
56677d562dbeSdan /*
56687d562dbeSdan ** Free the contents of the With object passed as the second argument.
56698b471863Sdrh */
sqlite3WithDelete(sqlite3 * db,With * pWith)56707d562dbeSdan void sqlite3WithDelete(sqlite3 *db, With *pWith){
56714e9119d9Sdan   if( pWith ){
56724e9119d9Sdan     int i;
56734e9119d9Sdan     for(i=0; i<pWith->nCte; i++){
5674f824b41eSdrh       cteClear(db, &pWith->a[i]);
56754e9119d9Sdan     }
56764e9119d9Sdan     sqlite3DbFree(db, pWith);
56774e9119d9Sdan   }
56788b471863Sdrh }
56798b471863Sdrh #endif /* !defined(SQLITE_OMIT_CTE) */
5680