xref: /sqlite-3.40.0/src/build.c (revision a8e41eca)
1 /*
2 ** 2001 September 15
3 **
4 ** The author disclaims copyright to this source code.  In place of
5 ** a legal notice, here is a blessing:
6 **
7 **    May you do good and not evil.
8 **    May you find forgiveness for yourself and forgive others.
9 **    May you share freely, never taking more than you give.
10 **
11 *************************************************************************
12 ** This file contains C code routines that are called by the SQLite parser
13 ** when syntax rules are reduced.  The routines in this file handle the
14 ** following kinds of SQL syntax:
15 **
16 **     CREATE TABLE
17 **     DROP TABLE
18 **     CREATE INDEX
19 **     DROP INDEX
20 **     creating ID lists
21 **     BEGIN TRANSACTION
22 **     COMMIT
23 **     ROLLBACK
24 */
25 #include "sqliteInt.h"
26 
27 #ifndef SQLITE_OMIT_SHARED_CACHE
28 /*
29 ** The TableLock structure is only used by the sqlite3TableLock() and
30 ** codeTableLocks() functions.
31 */
32 struct TableLock {
33   int iDb;               /* The database containing the table to be locked */
34   int iTab;              /* The root page of the table to be locked */
35   u8 isWriteLock;        /* True for write lock.  False for a read lock */
36   const char *zLockName; /* Name of the table */
37 };
38 
39 /*
40 ** Record the fact that we want to lock a table at run-time.
41 **
42 ** The table to be locked has root page iTab and is found in database iDb.
43 ** A read or a write lock can be taken depending on isWritelock.
44 **
45 ** This routine just records the fact that the lock is desired.  The
46 ** code to make the lock occur is generated by a later call to
47 ** codeTableLocks() which occurs during sqlite3FinishCoding().
48 */
49 void sqlite3TableLock(
50   Parse *pParse,     /* Parsing context */
51   int iDb,           /* Index of the database containing the table to lock */
52   int iTab,          /* Root page number of the table to be locked */
53   u8 isWriteLock,    /* True for a write lock */
54   const char *zName  /* Name of the table to be locked */
55 ){
56   Parse *pToplevel = sqlite3ParseToplevel(pParse);
57   int i;
58   int nBytes;
59   TableLock *p;
60   assert( iDb>=0 );
61 
62   if( iDb==1 ) return;
63   if( !sqlite3BtreeSharable(pParse->db->aDb[iDb].pBt) ) return;
64   for(i=0; i<pToplevel->nTableLock; i++){
65     p = &pToplevel->aTableLock[i];
66     if( p->iDb==iDb && p->iTab==iTab ){
67       p->isWriteLock = (p->isWriteLock || isWriteLock);
68       return;
69     }
70   }
71 
72   nBytes = sizeof(TableLock) * (pToplevel->nTableLock+1);
73   pToplevel->aTableLock =
74       sqlite3DbReallocOrFree(pToplevel->db, pToplevel->aTableLock, nBytes);
75   if( pToplevel->aTableLock ){
76     p = &pToplevel->aTableLock[pToplevel->nTableLock++];
77     p->iDb = iDb;
78     p->iTab = iTab;
79     p->isWriteLock = isWriteLock;
80     p->zLockName = zName;
81   }else{
82     pToplevel->nTableLock = 0;
83     sqlite3OomFault(pToplevel->db);
84   }
85 }
86 
87 /*
88 ** Code an OP_TableLock instruction for each table locked by the
89 ** statement (configured by calls to sqlite3TableLock()).
90 */
91 static void codeTableLocks(Parse *pParse){
92   int i;
93   Vdbe *pVdbe;
94 
95   pVdbe = sqlite3GetVdbe(pParse);
96   assert( pVdbe!=0 ); /* sqlite3GetVdbe cannot fail: VDBE already allocated */
97 
98   for(i=0; i<pParse->nTableLock; i++){
99     TableLock *p = &pParse->aTableLock[i];
100     int p1 = p->iDb;
101     sqlite3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, p->isWriteLock,
102                       p->zLockName, P4_STATIC);
103   }
104 }
105 #else
106   #define codeTableLocks(x)
107 #endif
108 
109 /*
110 ** Return TRUE if the given yDbMask object is empty - if it contains no
111 ** 1 bits.  This routine is used by the DbMaskAllZero() and DbMaskNotZero()
112 ** macros when SQLITE_MAX_ATTACHED is greater than 30.
113 */
114 #if SQLITE_MAX_ATTACHED>30
115 int sqlite3DbMaskAllZero(yDbMask m){
116   int i;
117   for(i=0; i<sizeof(yDbMask); i++) if( m[i] ) return 0;
118   return 1;
119 }
120 #endif
121 
122 /*
123 ** This routine is called after a single SQL statement has been
124 ** parsed and a VDBE program to execute that statement has been
125 ** prepared.  This routine puts the finishing touches on the
126 ** VDBE program and resets the pParse structure for the next
127 ** parse.
128 **
129 ** Note that if an error occurred, it might be the case that
130 ** no VDBE code was generated.
131 */
132 void sqlite3FinishCoding(Parse *pParse){
133   sqlite3 *db;
134   Vdbe *v;
135 
136   assert( pParse->pToplevel==0 );
137   db = pParse->db;
138   if( pParse->nested ) return;
139   if( db->mallocFailed || pParse->nErr ){
140     if( pParse->rc==SQLITE_OK ) pParse->rc = SQLITE_ERROR;
141     return;
142   }
143 
144   /* Begin by generating some termination code at the end of the
145   ** vdbe program
146   */
147   v = sqlite3GetVdbe(pParse);
148   assert( !pParse->isMultiWrite
149        || sqlite3VdbeAssertMayAbort(v, pParse->mayAbort));
150   if( v ){
151     sqlite3VdbeAddOp0(v, OP_Halt);
152 
153 #if SQLITE_USER_AUTHENTICATION
154     if( pParse->nTableLock>0 && db->init.busy==0 ){
155       sqlite3UserAuthInit(db);
156       if( db->auth.authLevel<UAUTH_User ){
157         sqlite3ErrorMsg(pParse, "user not authenticated");
158         pParse->rc = SQLITE_AUTH_USER;
159         return;
160       }
161     }
162 #endif
163 
164     /* The cookie mask contains one bit for each database file open.
165     ** (Bit 0 is for main, bit 1 is for temp, and so forth.)  Bits are
166     ** set for each database that is used.  Generate code to start a
167     ** transaction on each used database and to verify the schema cookie
168     ** on each used database.
169     */
170     if( db->mallocFailed==0
171      && (DbMaskNonZero(pParse->cookieMask) || pParse->pConstExpr)
172     ){
173       int iDb, i;
174       assert( sqlite3VdbeGetOp(v, 0)->opcode==OP_Init );
175       sqlite3VdbeJumpHere(v, 0);
176       for(iDb=0; iDb<db->nDb; iDb++){
177         Schema *pSchema;
178         if( DbMaskTest(pParse->cookieMask, iDb)==0 ) continue;
179         sqlite3VdbeUsesBtree(v, iDb);
180         pSchema = db->aDb[iDb].pSchema;
181         sqlite3VdbeAddOp4Int(v,
182           OP_Transaction,                    /* Opcode */
183           iDb,                               /* P1 */
184           DbMaskTest(pParse->writeMask,iDb), /* P2 */
185           pSchema->schema_cookie,            /* P3 */
186           pSchema->iGeneration               /* P4 */
187         );
188         if( db->init.busy==0 ) sqlite3VdbeChangeP5(v, 1);
189         VdbeComment((v,
190               "usesStmtJournal=%d", pParse->mayAbort && pParse->isMultiWrite));
191       }
192 #ifndef SQLITE_OMIT_VIRTUALTABLE
193       for(i=0; i<pParse->nVtabLock; i++){
194         char *vtab = (char *)sqlite3GetVTable(db, pParse->apVtabLock[i]);
195         sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB);
196       }
197       pParse->nVtabLock = 0;
198 #endif
199 
200       /* Once all the cookies have been verified and transactions opened,
201       ** obtain the required table-locks. This is a no-op unless the
202       ** shared-cache feature is enabled.
203       */
204       codeTableLocks(pParse);
205 
206       /* Initialize any AUTOINCREMENT data structures required.
207       */
208       sqlite3AutoincrementBegin(pParse);
209 
210       /* Code constant expressions that where factored out of inner loops */
211       if( pParse->pConstExpr ){
212         ExprList *pEL = pParse->pConstExpr;
213         pParse->okConstFactor = 0;
214         for(i=0; i<pEL->nExpr; i++){
215           sqlite3ExprCode(pParse, pEL->a[i].pExpr, pEL->a[i].u.iConstExprReg);
216         }
217       }
218 
219       /* Finally, jump back to the beginning of the executable code. */
220       sqlite3VdbeGoto(v, 1);
221     }
222   }
223 
224 
225   /* Get the VDBE program ready for execution
226   */
227   if( v && pParse->nErr==0 && !db->mallocFailed ){
228     /* A minimum of one cursor is required if autoincrement is used
229     *  See ticket [a696379c1f08866] */
230     assert( pParse->pAinc==0 || pParse->nTab>0 );
231     sqlite3VdbeMakeReady(v, pParse);
232     pParse->rc = SQLITE_DONE;
233   }else{
234     pParse->rc = SQLITE_ERROR;
235   }
236 }
237 
238 /*
239 ** Run the parser and code generator recursively in order to generate
240 ** code for the SQL statement given onto the end of the pParse context
241 ** currently under construction.  When the parser is run recursively
242 ** this way, the final OP_Halt is not appended and other initialization
243 ** and finalization steps are omitted because those are handling by the
244 ** outermost parser.
245 **
246 ** Not everything is nestable.  This facility is designed to permit
247 ** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER.  Use
248 ** care if you decide to try to use this routine for some other purposes.
249 */
250 void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
251   va_list ap;
252   char *zSql;
253   char *zErrMsg = 0;
254   sqlite3 *db = pParse->db;
255   char saveBuf[PARSE_TAIL_SZ];
256 
257   if( pParse->nErr ) return;
258   assert( pParse->nested<10 );  /* Nesting should only be of limited depth */
259   va_start(ap, zFormat);
260   zSql = sqlite3VMPrintf(db, zFormat, ap);
261   va_end(ap);
262   if( zSql==0 ){
263     /* This can result either from an OOM or because the formatted string
264     ** exceeds SQLITE_LIMIT_LENGTH.  In the latter case, we need to set
265     ** an error */
266     if( !db->mallocFailed ) pParse->rc = SQLITE_TOOBIG;
267     pParse->nErr++;
268     return;
269   }
270   pParse->nested++;
271   memcpy(saveBuf, PARSE_TAIL(pParse), PARSE_TAIL_SZ);
272   memset(PARSE_TAIL(pParse), 0, PARSE_TAIL_SZ);
273   sqlite3RunParser(pParse, zSql, &zErrMsg);
274   sqlite3DbFree(db, zErrMsg);
275   sqlite3DbFree(db, zSql);
276   memcpy(PARSE_TAIL(pParse), saveBuf, PARSE_TAIL_SZ);
277   pParse->nested--;
278 }
279 
280 #if SQLITE_USER_AUTHENTICATION
281 /*
282 ** Return TRUE if zTable is the name of the system table that stores the
283 ** list of users and their access credentials.
284 */
285 int sqlite3UserAuthTable(const char *zTable){
286   return sqlite3_stricmp(zTable, "sqlite_user")==0;
287 }
288 #endif
289 
290 /*
291 ** Locate the in-memory structure that describes a particular database
292 ** table given the name of that table and (optionally) the name of the
293 ** database containing the table.  Return NULL if not found.
294 **
295 ** If zDatabase is 0, all databases are searched for the table and the
296 ** first matching table is returned.  (No checking for duplicate table
297 ** names is done.)  The search order is TEMP first, then MAIN, then any
298 ** auxiliary databases added using the ATTACH command.
299 **
300 ** See also sqlite3LocateTable().
301 */
302 Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
303   Table *p = 0;
304   int i;
305 
306   /* All mutexes are required for schema access.  Make sure we hold them. */
307   assert( zDatabase!=0 || sqlite3BtreeHoldsAllMutexes(db) );
308 #if SQLITE_USER_AUTHENTICATION
309   /* Only the admin user is allowed to know that the sqlite_user table
310   ** exists */
311   if( db->auth.authLevel<UAUTH_Admin && sqlite3UserAuthTable(zName)!=0 ){
312     return 0;
313   }
314 #endif
315   while(1){
316     for(i=OMIT_TEMPDB; i<db->nDb; i++){
317       int j = (i<2) ? i^1 : i;   /* Search TEMP before MAIN */
318       if( zDatabase==0 || sqlite3DbIsNamed(db, j, zDatabase) ){
319         assert( sqlite3SchemaMutexHeld(db, j, 0) );
320         p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName);
321         if( p ) return p;
322       }
323     }
324     /* Not found.  If the name we were looking for was temp.sqlite_master
325     ** then change the name to sqlite_temp_master and try again. */
326     if( sqlite3StrICmp(zName, MASTER_NAME)!=0 ) break;
327     if( sqlite3_stricmp(zDatabase, db->aDb[1].zDbSName)!=0 ) break;
328     zName = TEMP_MASTER_NAME;
329   }
330   return 0;
331 }
332 
333 /*
334 ** Locate the in-memory structure that describes a particular database
335 ** table given the name of that table and (optionally) the name of the
336 ** database containing the table.  Return NULL if not found.  Also leave an
337 ** error message in pParse->zErrMsg.
338 **
339 ** The difference between this routine and sqlite3FindTable() is that this
340 ** routine leaves an error message in pParse->zErrMsg where
341 ** sqlite3FindTable() does not.
342 */
343 Table *sqlite3LocateTable(
344   Parse *pParse,         /* context in which to report errors */
345   u32 flags,             /* LOCATE_VIEW or LOCATE_NOERR */
346   const char *zName,     /* Name of the table we are looking for */
347   const char *zDbase     /* Name of the database.  Might be NULL */
348 ){
349   Table *p;
350   sqlite3 *db = pParse->db;
351 
352   /* Read the database schema. If an error occurs, leave an error message
353   ** and code in pParse and return NULL. */
354   if( (db->mDbFlags & DBFLAG_SchemaKnownOk)==0
355    && SQLITE_OK!=sqlite3ReadSchema(pParse)
356   ){
357     return 0;
358   }
359 
360   p = sqlite3FindTable(db, zName, zDbase);
361   if( p==0 ){
362 #ifndef SQLITE_OMIT_VIRTUALTABLE
363     /* If zName is the not the name of a table in the schema created using
364     ** CREATE, then check to see if it is the name of an virtual table that
365     ** can be an eponymous virtual table. */
366     if( pParse->disableVtab==0 ){
367       Module *pMod = (Module*)sqlite3HashFind(&db->aModule, zName);
368       if( pMod==0 && sqlite3_strnicmp(zName, "pragma_", 7)==0 ){
369         pMod = sqlite3PragmaVtabRegister(db, zName);
370       }
371       if( pMod && sqlite3VtabEponymousTableInit(pParse, pMod) ){
372         return pMod->pEpoTab;
373       }
374     }
375 #endif
376     if( flags & LOCATE_NOERR ) return 0;
377     pParse->checkSchema = 1;
378   }else if( IsVirtual(p) && pParse->disableVtab ){
379     p = 0;
380   }
381 
382   if( p==0 ){
383     const char *zMsg = flags & LOCATE_VIEW ? "no such view" : "no such table";
384     if( zDbase ){
385       sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName);
386     }else{
387       sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName);
388     }
389   }
390 
391   return p;
392 }
393 
394 /*
395 ** Locate the table identified by *p.
396 **
397 ** This is a wrapper around sqlite3LocateTable(). The difference between
398 ** sqlite3LocateTable() and this function is that this function restricts
399 ** the search to schema (p->pSchema) if it is not NULL. p->pSchema may be
400 ** non-NULL if it is part of a view or trigger program definition. See
401 ** sqlite3FixSrcList() for details.
402 */
403 Table *sqlite3LocateTableItem(
404   Parse *pParse,
405   u32 flags,
406   struct SrcList_item *p
407 ){
408   const char *zDb;
409   assert( p->pSchema==0 || p->zDatabase==0 );
410   if( p->pSchema ){
411     int iDb = sqlite3SchemaToIndex(pParse->db, p->pSchema);
412     zDb = pParse->db->aDb[iDb].zDbSName;
413   }else{
414     zDb = p->zDatabase;
415   }
416   return sqlite3LocateTable(pParse, flags, p->zName, zDb);
417 }
418 
419 /*
420 ** Locate the in-memory structure that describes
421 ** a particular index given the name of that index
422 ** and the name of the database that contains the index.
423 ** Return NULL if not found.
424 **
425 ** If zDatabase is 0, all databases are searched for the
426 ** table and the first matching index is returned.  (No checking
427 ** for duplicate index names is done.)  The search order is
428 ** TEMP first, then MAIN, then any auxiliary databases added
429 ** using the ATTACH command.
430 */
431 Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
432   Index *p = 0;
433   int i;
434   /* All mutexes are required for schema access.  Make sure we hold them. */
435   assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
436   for(i=OMIT_TEMPDB; i<db->nDb; i++){
437     int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
438     Schema *pSchema = db->aDb[j].pSchema;
439     assert( pSchema );
440     if( zDb && sqlite3DbIsNamed(db, j, zDb)==0 ) continue;
441     assert( sqlite3SchemaMutexHeld(db, j, 0) );
442     p = sqlite3HashFind(&pSchema->idxHash, zName);
443     if( p ) break;
444   }
445   return p;
446 }
447 
448 /*
449 ** Reclaim the memory used by an index
450 */
451 void sqlite3FreeIndex(sqlite3 *db, Index *p){
452 #ifndef SQLITE_OMIT_ANALYZE
453   sqlite3DeleteIndexSamples(db, p);
454 #endif
455   sqlite3ExprDelete(db, p->pPartIdxWhere);
456   sqlite3ExprListDelete(db, p->aColExpr);
457   sqlite3DbFree(db, p->zColAff);
458   if( p->isResized ) sqlite3DbFree(db, (void *)p->azColl);
459 #ifdef SQLITE_ENABLE_STAT4
460   sqlite3_free(p->aiRowEst);
461 #endif
462   sqlite3DbFree(db, p);
463 }
464 
465 /*
466 ** For the index called zIdxName which is found in the database iDb,
467 ** unlike that index from its Table then remove the index from
468 ** the index hash table and free all memory structures associated
469 ** with the index.
470 */
471 void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
472   Index *pIndex;
473   Hash *pHash;
474 
475   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
476   pHash = &db->aDb[iDb].pSchema->idxHash;
477   pIndex = sqlite3HashInsert(pHash, zIdxName, 0);
478   if( ALWAYS(pIndex) ){
479     if( pIndex->pTable->pIndex==pIndex ){
480       pIndex->pTable->pIndex = pIndex->pNext;
481     }else{
482       Index *p;
483       /* Justification of ALWAYS();  The index must be on the list of
484       ** indices. */
485       p = pIndex->pTable->pIndex;
486       while( ALWAYS(p) && p->pNext!=pIndex ){ p = p->pNext; }
487       if( ALWAYS(p && p->pNext==pIndex) ){
488         p->pNext = pIndex->pNext;
489       }
490     }
491     sqlite3FreeIndex(db, pIndex);
492   }
493   db->mDbFlags |= DBFLAG_SchemaChange;
494 }
495 
496 /*
497 ** Look through the list of open database files in db->aDb[] and if
498 ** any have been closed, remove them from the list.  Reallocate the
499 ** db->aDb[] structure to a smaller size, if possible.
500 **
501 ** Entry 0 (the "main" database) and entry 1 (the "temp" database)
502 ** are never candidates for being collapsed.
503 */
504 void sqlite3CollapseDatabaseArray(sqlite3 *db){
505   int i, j;
506   for(i=j=2; i<db->nDb; i++){
507     struct Db *pDb = &db->aDb[i];
508     if( pDb->pBt==0 ){
509       sqlite3DbFree(db, pDb->zDbSName);
510       pDb->zDbSName = 0;
511       continue;
512     }
513     if( j<i ){
514       db->aDb[j] = db->aDb[i];
515     }
516     j++;
517   }
518   db->nDb = j;
519   if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
520     memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
521     sqlite3DbFree(db, db->aDb);
522     db->aDb = db->aDbStatic;
523   }
524 }
525 
526 /*
527 ** Reset the schema for the database at index iDb.  Also reset the
528 ** TEMP schema.  The reset is deferred if db->nSchemaLock is not zero.
529 ** Deferred resets may be run by calling with iDb<0.
530 */
531 void sqlite3ResetOneSchema(sqlite3 *db, int iDb){
532   int i;
533   assert( iDb<db->nDb );
534 
535   if( iDb>=0 ){
536     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
537     DbSetProperty(db, iDb, DB_ResetWanted);
538     DbSetProperty(db, 1, DB_ResetWanted);
539     db->mDbFlags &= ~DBFLAG_SchemaKnownOk;
540   }
541 
542   if( db->nSchemaLock==0 ){
543     for(i=0; i<db->nDb; i++){
544       if( DbHasProperty(db, i, DB_ResetWanted) ){
545         sqlite3SchemaClear(db->aDb[i].pSchema);
546       }
547     }
548   }
549 }
550 
551 /*
552 ** Erase all schema information from all attached databases (including
553 ** "main" and "temp") for a single database connection.
554 */
555 void sqlite3ResetAllSchemasOfConnection(sqlite3 *db){
556   int i;
557   sqlite3BtreeEnterAll(db);
558   for(i=0; i<db->nDb; i++){
559     Db *pDb = &db->aDb[i];
560     if( pDb->pSchema ){
561       if( db->nSchemaLock==0 ){
562         sqlite3SchemaClear(pDb->pSchema);
563       }else{
564         DbSetProperty(db, i, DB_ResetWanted);
565       }
566     }
567   }
568   db->mDbFlags &= ~(DBFLAG_SchemaChange|DBFLAG_SchemaKnownOk);
569   sqlite3VtabUnlockList(db);
570   sqlite3BtreeLeaveAll(db);
571   if( db->nSchemaLock==0 ){
572     sqlite3CollapseDatabaseArray(db);
573   }
574 }
575 
576 /*
577 ** This routine is called when a commit occurs.
578 */
579 void sqlite3CommitInternalChanges(sqlite3 *db){
580   db->mDbFlags &= ~DBFLAG_SchemaChange;
581 }
582 
583 /*
584 ** Delete memory allocated for the column names of a table or view (the
585 ** Table.aCol[] array).
586 */
587 void sqlite3DeleteColumnNames(sqlite3 *db, Table *pTable){
588   int i;
589   Column *pCol;
590   assert( pTable!=0 );
591   if( (pCol = pTable->aCol)!=0 ){
592     for(i=0; i<pTable->nCol; i++, pCol++){
593       assert( pCol->zName==0 || pCol->hName==sqlite3StrIHash(pCol->zName) );
594       sqlite3DbFree(db, pCol->zName);
595       sqlite3ExprDelete(db, pCol->pDflt);
596       sqlite3DbFree(db, pCol->zColl);
597     }
598     sqlite3DbFree(db, pTable->aCol);
599   }
600 }
601 
602 /*
603 ** Remove the memory data structures associated with the given
604 ** Table.  No changes are made to disk by this routine.
605 **
606 ** This routine just deletes the data structure.  It does not unlink
607 ** the table data structure from the hash table.  But it does destroy
608 ** memory structures of the indices and foreign keys associated with
609 ** the table.
610 **
611 ** The db parameter is optional.  It is needed if the Table object
612 ** contains lookaside memory.  (Table objects in the schema do not use
613 ** lookaside memory, but some ephemeral Table objects do.)  Or the
614 ** db parameter can be used with db->pnBytesFreed to measure the memory
615 ** used by the Table object.
616 */
617 static void SQLITE_NOINLINE deleteTable(sqlite3 *db, Table *pTable){
618   Index *pIndex, *pNext;
619 
620 #ifdef SQLITE_DEBUG
621   /* Record the number of outstanding lookaside allocations in schema Tables
622   ** prior to doing any free() operations. Since schema Tables do not use
623   ** lookaside, this number should not change.
624   **
625   ** If malloc has already failed, it may be that it failed while allocating
626   ** a Table object that was going to be marked ephemeral. So do not check
627   ** that no lookaside memory is used in this case either. */
628   int nLookaside = 0;
629   if( db && !db->mallocFailed && (pTable->tabFlags & TF_Ephemeral)==0 ){
630     nLookaside = sqlite3LookasideUsed(db, 0);
631   }
632 #endif
633 
634   /* Delete all indices associated with this table. */
635   for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
636     pNext = pIndex->pNext;
637     assert( pIndex->pSchema==pTable->pSchema
638          || (IsVirtual(pTable) && pIndex->idxType!=SQLITE_IDXTYPE_APPDEF) );
639     if( (db==0 || db->pnBytesFreed==0) && !IsVirtual(pTable) ){
640       char *zName = pIndex->zName;
641       TESTONLY ( Index *pOld = ) sqlite3HashInsert(
642          &pIndex->pSchema->idxHash, zName, 0
643       );
644       assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
645       assert( pOld==pIndex || pOld==0 );
646     }
647     sqlite3FreeIndex(db, pIndex);
648   }
649 
650   /* Delete any foreign keys attached to this table. */
651   sqlite3FkDelete(db, pTable);
652 
653   /* Delete the Table structure itself.
654   */
655   sqlite3DeleteColumnNames(db, pTable);
656   sqlite3DbFree(db, pTable->zName);
657   sqlite3DbFree(db, pTable->zColAff);
658   sqlite3SelectDelete(db, pTable->pSelect);
659   sqlite3ExprListDelete(db, pTable->pCheck);
660 #ifndef SQLITE_OMIT_VIRTUALTABLE
661   sqlite3VtabClear(db, pTable);
662 #endif
663   sqlite3DbFree(db, pTable);
664 
665   /* Verify that no lookaside memory was used by schema tables */
666   assert( nLookaside==0 || nLookaside==sqlite3LookasideUsed(db,0) );
667 }
668 void sqlite3DeleteTable(sqlite3 *db, Table *pTable){
669   /* Do not delete the table until the reference count reaches zero. */
670   if( !pTable ) return;
671   if( ((!db || db->pnBytesFreed==0) && (--pTable->nTabRef)>0) ) return;
672   deleteTable(db, pTable);
673 }
674 
675 
676 /*
677 ** Unlink the given table from the hash tables and the delete the
678 ** table structure with all its indices and foreign keys.
679 */
680 void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
681   Table *p;
682   Db *pDb;
683 
684   assert( db!=0 );
685   assert( iDb>=0 && iDb<db->nDb );
686   assert( zTabName );
687   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
688   testcase( zTabName[0]==0 );  /* Zero-length table names are allowed */
689   pDb = &db->aDb[iDb];
690   p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName, 0);
691   sqlite3DeleteTable(db, p);
692   db->mDbFlags |= DBFLAG_SchemaChange;
693 }
694 
695 /*
696 ** Given a token, return a string that consists of the text of that
697 ** token.  Space to hold the returned string
698 ** is obtained from sqliteMalloc() and must be freed by the calling
699 ** function.
700 **
701 ** Any quotation marks (ex:  "name", 'name', [name], or `name`) that
702 ** surround the body of the token are removed.
703 **
704 ** Tokens are often just pointers into the original SQL text and so
705 ** are not \000 terminated and are not persistent.  The returned string
706 ** is \000 terminated and is persistent.
707 */
708 char *sqlite3NameFromToken(sqlite3 *db, Token *pName){
709   char *zName;
710   if( pName ){
711     zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n);
712     sqlite3Dequote(zName);
713   }else{
714     zName = 0;
715   }
716   return zName;
717 }
718 
719 /*
720 ** Open the sqlite_master table stored in database number iDb for
721 ** writing. The table is opened using cursor 0.
722 */
723 void sqlite3OpenMasterTable(Parse *p, int iDb){
724   Vdbe *v = sqlite3GetVdbe(p);
725   sqlite3TableLock(p, iDb, MASTER_ROOT, 1, MASTER_NAME);
726   sqlite3VdbeAddOp4Int(v, OP_OpenWrite, 0, MASTER_ROOT, iDb, 5);
727   if( p->nTab==0 ){
728     p->nTab = 1;
729   }
730 }
731 
732 /*
733 ** Parameter zName points to a nul-terminated buffer containing the name
734 ** of a database ("main", "temp" or the name of an attached db). This
735 ** function returns the index of the named database in db->aDb[], or
736 ** -1 if the named db cannot be found.
737 */
738 int sqlite3FindDbName(sqlite3 *db, const char *zName){
739   int i = -1;         /* Database number */
740   if( zName ){
741     Db *pDb;
742     for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
743       if( 0==sqlite3_stricmp(pDb->zDbSName, zName) ) break;
744       /* "main" is always an acceptable alias for the primary database
745       ** even if it has been renamed using SQLITE_DBCONFIG_MAINDBNAME. */
746       if( i==0 && 0==sqlite3_stricmp("main", zName) ) break;
747     }
748   }
749   return i;
750 }
751 
752 /*
753 ** The token *pName contains the name of a database (either "main" or
754 ** "temp" or the name of an attached db). This routine returns the
755 ** index of the named database in db->aDb[], or -1 if the named db
756 ** does not exist.
757 */
758 int sqlite3FindDb(sqlite3 *db, Token *pName){
759   int i;                               /* Database number */
760   char *zName;                         /* Name we are searching for */
761   zName = sqlite3NameFromToken(db, pName);
762   i = sqlite3FindDbName(db, zName);
763   sqlite3DbFree(db, zName);
764   return i;
765 }
766 
767 /* The table or view or trigger name is passed to this routine via tokens
768 ** pName1 and pName2. If the table name was fully qualified, for example:
769 **
770 ** CREATE TABLE xxx.yyy (...);
771 **
772 ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
773 ** the table name is not fully qualified, i.e.:
774 **
775 ** CREATE TABLE yyy(...);
776 **
777 ** Then pName1 is set to "yyy" and pName2 is "".
778 **
779 ** This routine sets the *ppUnqual pointer to point at the token (pName1 or
780 ** pName2) that stores the unqualified table name.  The index of the
781 ** database "xxx" is returned.
782 */
783 int sqlite3TwoPartName(
784   Parse *pParse,      /* Parsing and code generating context */
785   Token *pName1,      /* The "xxx" in the name "xxx.yyy" or "xxx" */
786   Token *pName2,      /* The "yyy" in the name "xxx.yyy" */
787   Token **pUnqual     /* Write the unqualified object name here */
788 ){
789   int iDb;                    /* Database holding the object */
790   sqlite3 *db = pParse->db;
791 
792   assert( pName2!=0 );
793   if( pName2->n>0 ){
794     if( db->init.busy ) {
795       sqlite3ErrorMsg(pParse, "corrupt database");
796       return -1;
797     }
798     *pUnqual = pName2;
799     iDb = sqlite3FindDb(db, pName1);
800     if( iDb<0 ){
801       sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
802       return -1;
803     }
804   }else{
805     assert( db->init.iDb==0 || db->init.busy || IN_RENAME_OBJECT
806              || (db->mDbFlags & DBFLAG_Vacuum)!=0);
807     iDb = db->init.iDb;
808     *pUnqual = pName1;
809   }
810   return iDb;
811 }
812 
813 /*
814 ** True if PRAGMA writable_schema is ON
815 */
816 int sqlite3WritableSchema(sqlite3 *db){
817   testcase( (db->flags&(SQLITE_WriteSchema|SQLITE_Defensive))==0 );
818   testcase( (db->flags&(SQLITE_WriteSchema|SQLITE_Defensive))==
819                SQLITE_WriteSchema );
820   testcase( (db->flags&(SQLITE_WriteSchema|SQLITE_Defensive))==
821                SQLITE_Defensive );
822   testcase( (db->flags&(SQLITE_WriteSchema|SQLITE_Defensive))==
823                (SQLITE_WriteSchema|SQLITE_Defensive) );
824   return (db->flags&(SQLITE_WriteSchema|SQLITE_Defensive))==SQLITE_WriteSchema;
825 }
826 
827 /*
828 ** This routine is used to check if the UTF-8 string zName is a legal
829 ** unqualified name for a new schema object (table, index, view or
830 ** trigger). All names are legal except those that begin with the string
831 ** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
832 ** is reserved for internal use.
833 **
834 ** When parsing the sqlite_master table, this routine also checks to
835 ** make sure the "type", "name", and "tbl_name" columns are consistent
836 ** with the SQL.
837 */
838 int sqlite3CheckObjectName(
839   Parse *pParse,            /* Parsing context */
840   const char *zName,        /* Name of the object to check */
841   const char *zType,        /* Type of this object */
842   const char *zTblName      /* Parent table name for triggers and indexes */
843 ){
844   sqlite3 *db = pParse->db;
845   if( sqlite3WritableSchema(db) || db->init.imposterTable ){
846     /* Skip these error checks for writable_schema=ON */
847     return SQLITE_OK;
848   }
849   if( db->init.busy ){
850     if( sqlite3_stricmp(zType, db->init.azInit[0])
851      || sqlite3_stricmp(zName, db->init.azInit[1])
852      || sqlite3_stricmp(zTblName, db->init.azInit[2])
853     ){
854       if( sqlite3Config.bExtraSchemaChecks ){
855         sqlite3ErrorMsg(pParse, ""); /* corruptSchema() will supply the error */
856         return SQLITE_ERROR;
857       }
858     }
859   }else{
860     if( (pParse->nested==0 && 0==sqlite3StrNICmp(zName, "sqlite_", 7))
861      || (sqlite3ReadOnlyShadowTables(db) && sqlite3ShadowTableName(db, zName))
862     ){
863       sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s",
864                       zName);
865       return SQLITE_ERROR;
866     }
867 
868   }
869   return SQLITE_OK;
870 }
871 
872 /*
873 ** Return the PRIMARY KEY index of a table
874 */
875 Index *sqlite3PrimaryKeyIndex(Table *pTab){
876   Index *p;
877   for(p=pTab->pIndex; p && !IsPrimaryKeyIndex(p); p=p->pNext){}
878   return p;
879 }
880 
881 /*
882 ** Convert an table column number into a index column number.  That is,
883 ** for the column iCol in the table (as defined by the CREATE TABLE statement)
884 ** find the (first) offset of that column in index pIdx.  Or return -1
885 ** if column iCol is not used in index pIdx.
886 */
887 i16 sqlite3TableColumnToIndex(Index *pIdx, i16 iCol){
888   int i;
889   for(i=0; i<pIdx->nColumn; i++){
890     if( iCol==pIdx->aiColumn[i] ) return i;
891   }
892   return -1;
893 }
894 
895 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
896 /* Convert a storage column number into a table column number.
897 **
898 ** The storage column number (0,1,2,....) is the index of the value
899 ** as it appears in the record on disk.  The true column number
900 ** is the index (0,1,2,...) of the column in the CREATE TABLE statement.
901 **
902 ** The storage column number is less than the table column number if
903 ** and only there are VIRTUAL columns to the left.
904 **
905 ** If SQLITE_OMIT_GENERATED_COLUMNS, this routine is a no-op macro.
906 */
907 i16 sqlite3StorageColumnToTable(Table *pTab, i16 iCol){
908   if( pTab->tabFlags & TF_HasVirtual ){
909     int i;
910     for(i=0; i<=iCol; i++){
911       if( pTab->aCol[i].colFlags & COLFLAG_VIRTUAL ) iCol++;
912     }
913   }
914   return iCol;
915 }
916 #endif
917 
918 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
919 /* Convert a table column number into a storage column number.
920 **
921 ** The storage column number (0,1,2,....) is the index of the value
922 ** as it appears in the record on disk.  Or, if the input column is
923 ** the N-th virtual column (zero-based) then the storage number is
924 ** the number of non-virtual columns in the table plus N.
925 **
926 ** The true column number is the index (0,1,2,...) of the column in
927 ** the CREATE TABLE statement.
928 **
929 ** If the input column is a VIRTUAL column, then it should not appear
930 ** in storage.  But the value sometimes is cached in registers that
931 ** follow the range of registers used to construct storage.  This
932 ** avoids computing the same VIRTUAL column multiple times, and provides
933 ** values for use by OP_Param opcodes in triggers.  Hence, if the
934 ** input column is a VIRTUAL table, put it after all the other columns.
935 **
936 ** In the following, N means "normal column", S means STORED, and
937 ** V means VIRTUAL.  Suppose the CREATE TABLE has columns like this:
938 **
939 **        CREATE TABLE ex(N,S,V,N,S,V,N,S,V);
940 **                     -- 0 1 2 3 4 5 6 7 8
941 **
942 ** Then the mapping from this function is as follows:
943 **
944 **    INPUTS:     0 1 2 3 4 5 6 7 8
945 **    OUTPUTS:    0 1 6 2 3 7 4 5 8
946 **
947 ** So, in other words, this routine shifts all the virtual columns to
948 ** the end.
949 **
950 ** If SQLITE_OMIT_GENERATED_COLUMNS then there are no virtual columns and
951 ** this routine is a no-op macro.  If the pTab does not have any virtual
952 ** columns, then this routine is no-op that always return iCol.  If iCol
953 ** is negative (indicating the ROWID column) then this routine return iCol.
954 */
955 i16 sqlite3TableColumnToStorage(Table *pTab, i16 iCol){
956   int i;
957   i16 n;
958   assert( iCol<pTab->nCol );
959   if( (pTab->tabFlags & TF_HasVirtual)==0 || iCol<0 ) return iCol;
960   for(i=0, n=0; i<iCol; i++){
961     if( (pTab->aCol[i].colFlags & COLFLAG_VIRTUAL)==0 ) n++;
962   }
963   if( pTab->aCol[i].colFlags & COLFLAG_VIRTUAL ){
964     /* iCol is a virtual column itself */
965     return pTab->nNVCol + i - n;
966   }else{
967     /* iCol is a normal or stored column */
968     return n;
969   }
970 }
971 #endif
972 
973 /*
974 ** Begin constructing a new table representation in memory.  This is
975 ** the first of several action routines that get called in response
976 ** to a CREATE TABLE statement.  In particular, this routine is called
977 ** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
978 ** flag is true if the table should be stored in the auxiliary database
979 ** file instead of in the main database file.  This is normally the case
980 ** when the "TEMP" or "TEMPORARY" keyword occurs in between
981 ** CREATE and TABLE.
982 **
983 ** The new table record is initialized and put in pParse->pNewTable.
984 ** As more of the CREATE TABLE statement is parsed, additional action
985 ** routines will be called to add more information to this record.
986 ** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
987 ** is called to complete the construction of the new table record.
988 */
989 void sqlite3StartTable(
990   Parse *pParse,   /* Parser context */
991   Token *pName1,   /* First part of the name of the table or view */
992   Token *pName2,   /* Second part of the name of the table or view */
993   int isTemp,      /* True if this is a TEMP table */
994   int isView,      /* True if this is a VIEW */
995   int isVirtual,   /* True if this is a VIRTUAL table */
996   int noErr        /* Do nothing if table already exists */
997 ){
998   Table *pTable;
999   char *zName = 0; /* The name of the new table */
1000   sqlite3 *db = pParse->db;
1001   Vdbe *v;
1002   int iDb;         /* Database number to create the table in */
1003   Token *pName;    /* Unqualified name of the table to create */
1004 
1005   if( db->init.busy && db->init.newTnum==1 ){
1006     /* Special case:  Parsing the sqlite_master or sqlite_temp_master schema */
1007     iDb = db->init.iDb;
1008     zName = sqlite3DbStrDup(db, SCHEMA_TABLE(iDb));
1009     pName = pName1;
1010   }else{
1011     /* The common case */
1012     iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
1013     if( iDb<0 ) return;
1014     if( !OMIT_TEMPDB && isTemp && pName2->n>0 && iDb!=1 ){
1015       /* If creating a temp table, the name may not be qualified. Unless
1016       ** the database name is "temp" anyway.  */
1017       sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
1018       return;
1019     }
1020     if( !OMIT_TEMPDB && isTemp ) iDb = 1;
1021     zName = sqlite3NameFromToken(db, pName);
1022     if( IN_RENAME_OBJECT ){
1023       sqlite3RenameTokenMap(pParse, (void*)zName, pName);
1024     }
1025   }
1026   pParse->sNameToken = *pName;
1027   if( zName==0 ) return;
1028   if( sqlite3CheckObjectName(pParse, zName, isView?"view":"table", zName) ){
1029     goto begin_table_error;
1030   }
1031   if( db->init.iDb==1 ) isTemp = 1;
1032 #ifndef SQLITE_OMIT_AUTHORIZATION
1033   assert( isTemp==0 || isTemp==1 );
1034   assert( isView==0 || isView==1 );
1035   {
1036     static const u8 aCode[] = {
1037        SQLITE_CREATE_TABLE,
1038        SQLITE_CREATE_TEMP_TABLE,
1039        SQLITE_CREATE_VIEW,
1040        SQLITE_CREATE_TEMP_VIEW
1041     };
1042     char *zDb = db->aDb[iDb].zDbSName;
1043     if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
1044       goto begin_table_error;
1045     }
1046     if( !isVirtual && sqlite3AuthCheck(pParse, (int)aCode[isTemp+2*isView],
1047                                        zName, 0, zDb) ){
1048       goto begin_table_error;
1049     }
1050   }
1051 #endif
1052 
1053   /* Make sure the new table name does not collide with an existing
1054   ** index or table name in the same database.  Issue an error message if
1055   ** it does. The exception is if the statement being parsed was passed
1056   ** to an sqlite3_declare_vtab() call. In that case only the column names
1057   ** and types will be used, so there is no need to test for namespace
1058   ** collisions.
1059   */
1060   if( !IN_SPECIAL_PARSE ){
1061     char *zDb = db->aDb[iDb].zDbSName;
1062     if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
1063       goto begin_table_error;
1064     }
1065     pTable = sqlite3FindTable(db, zName, zDb);
1066     if( pTable ){
1067       if( !noErr ){
1068         sqlite3ErrorMsg(pParse, "table %T already exists", pName);
1069       }else{
1070         assert( !db->init.busy || CORRUPT_DB );
1071         sqlite3CodeVerifySchema(pParse, iDb);
1072       }
1073       goto begin_table_error;
1074     }
1075     if( sqlite3FindIndex(db, zName, zDb)!=0 ){
1076       sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
1077       goto begin_table_error;
1078     }
1079   }
1080 
1081   pTable = sqlite3DbMallocZero(db, sizeof(Table));
1082   if( pTable==0 ){
1083     assert( db->mallocFailed );
1084     pParse->rc = SQLITE_NOMEM_BKPT;
1085     pParse->nErr++;
1086     goto begin_table_error;
1087   }
1088   pTable->zName = zName;
1089   pTable->iPKey = -1;
1090   pTable->pSchema = db->aDb[iDb].pSchema;
1091   pTable->nTabRef = 1;
1092 #ifdef SQLITE_DEFAULT_ROWEST
1093   pTable->nRowLogEst = sqlite3LogEst(SQLITE_DEFAULT_ROWEST);
1094 #else
1095   pTable->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
1096 #endif
1097   assert( pParse->pNewTable==0 );
1098   pParse->pNewTable = pTable;
1099 
1100   /* If this is the magic sqlite_sequence table used by autoincrement,
1101   ** then record a pointer to this table in the main database structure
1102   ** so that INSERT can find the table easily.
1103   */
1104 #ifndef SQLITE_OMIT_AUTOINCREMENT
1105   if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){
1106     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
1107     pTable->pSchema->pSeqTab = pTable;
1108   }
1109 #endif
1110 
1111   /* Begin generating the code that will insert the table record into
1112   ** the SQLITE_MASTER table.  Note in particular that we must go ahead
1113   ** and allocate the record number for the table entry now.  Before any
1114   ** PRIMARY KEY or UNIQUE keywords are parsed.  Those keywords will cause
1115   ** indices to be created and the table record must come before the
1116   ** indices.  Hence, the record number for the table must be allocated
1117   ** now.
1118   */
1119   if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
1120     int addr1;
1121     int fileFormat;
1122     int reg1, reg2, reg3;
1123     /* nullRow[] is an OP_Record encoding of a row containing 5 NULLs */
1124     static const char nullRow[] = { 6, 0, 0, 0, 0, 0 };
1125     sqlite3BeginWriteOperation(pParse, 1, iDb);
1126 
1127 #ifndef SQLITE_OMIT_VIRTUALTABLE
1128     if( isVirtual ){
1129       sqlite3VdbeAddOp0(v, OP_VBegin);
1130     }
1131 #endif
1132 
1133     /* If the file format and encoding in the database have not been set,
1134     ** set them now.
1135     */
1136     reg1 = pParse->regRowid = ++pParse->nMem;
1137     reg2 = pParse->regRoot = ++pParse->nMem;
1138     reg3 = ++pParse->nMem;
1139     sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT);
1140     sqlite3VdbeUsesBtree(v, iDb);
1141     addr1 = sqlite3VdbeAddOp1(v, OP_If, reg3); VdbeCoverage(v);
1142     fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
1143                   1 : SQLITE_MAX_FILE_FORMAT;
1144     sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, fileFormat);
1145     sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, ENC(db));
1146     sqlite3VdbeJumpHere(v, addr1);
1147 
1148     /* This just creates a place-holder record in the sqlite_master table.
1149     ** The record created does not contain anything yet.  It will be replaced
1150     ** by the real entry in code generated at sqlite3EndTable().
1151     **
1152     ** The rowid for the new entry is left in register pParse->regRowid.
1153     ** The root page number of the new table is left in reg pParse->regRoot.
1154     ** The rowid and root page number values are needed by the code that
1155     ** sqlite3EndTable will generate.
1156     */
1157 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
1158     if( isView || isVirtual ){
1159       sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2);
1160     }else
1161 #endif
1162     {
1163       pParse->addrCrTab =
1164          sqlite3VdbeAddOp3(v, OP_CreateBtree, iDb, reg2, BTREE_INTKEY);
1165     }
1166     sqlite3OpenMasterTable(pParse, iDb);
1167     sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1);
1168     sqlite3VdbeAddOp4(v, OP_Blob, 6, reg3, 0, nullRow, P4_STATIC);
1169     sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1);
1170     sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
1171     sqlite3VdbeAddOp0(v, OP_Close);
1172   }
1173 
1174   /* Normal (non-error) return. */
1175   return;
1176 
1177   /* If an error occurs, we jump here */
1178 begin_table_error:
1179   sqlite3DbFree(db, zName);
1180   return;
1181 }
1182 
1183 /* Set properties of a table column based on the (magical)
1184 ** name of the column.
1185 */
1186 #if SQLITE_ENABLE_HIDDEN_COLUMNS
1187 void sqlite3ColumnPropertiesFromName(Table *pTab, Column *pCol){
1188   if( sqlite3_strnicmp(pCol->zName, "__hidden__", 10)==0 ){
1189     pCol->colFlags |= COLFLAG_HIDDEN;
1190   }else if( pTab && pCol!=pTab->aCol && (pCol[-1].colFlags & COLFLAG_HIDDEN) ){
1191     pTab->tabFlags |= TF_OOOHidden;
1192   }
1193 }
1194 #endif
1195 
1196 
1197 /*
1198 ** Add a new column to the table currently being constructed.
1199 **
1200 ** The parser calls this routine once for each column declaration
1201 ** in a CREATE TABLE statement.  sqlite3StartTable() gets called
1202 ** first to get things going.  Then this routine is called for each
1203 ** column.
1204 */
1205 void sqlite3AddColumn(Parse *pParse, Token *pName, Token *pType){
1206   Table *p;
1207   int i;
1208   char *z;
1209   char *zType;
1210   Column *pCol;
1211   sqlite3 *db = pParse->db;
1212   if( (p = pParse->pNewTable)==0 ) return;
1213   if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){
1214     sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
1215     return;
1216   }
1217   z = sqlite3DbMallocRaw(db, pName->n + pType->n + 2);
1218   if( z==0 ) return;
1219   if( IN_RENAME_OBJECT ) sqlite3RenameTokenMap(pParse, (void*)z, pName);
1220   memcpy(z, pName->z, pName->n);
1221   z[pName->n] = 0;
1222   sqlite3Dequote(z);
1223   for(i=0; i<p->nCol; i++){
1224     if( sqlite3_stricmp(z, p->aCol[i].zName)==0 ){
1225       sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
1226       sqlite3DbFree(db, z);
1227       return;
1228     }
1229   }
1230   if( (p->nCol & 0x7)==0 ){
1231     Column *aNew;
1232     aNew = sqlite3DbRealloc(db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0]));
1233     if( aNew==0 ){
1234       sqlite3DbFree(db, z);
1235       return;
1236     }
1237     p->aCol = aNew;
1238   }
1239   pCol = &p->aCol[p->nCol];
1240   memset(pCol, 0, sizeof(p->aCol[0]));
1241   pCol->zName = z;
1242   pCol->hName = sqlite3StrIHash(z);
1243   sqlite3ColumnPropertiesFromName(p, pCol);
1244 
1245   if( pType->n==0 ){
1246     /* If there is no type specified, columns have the default affinity
1247     ** 'BLOB' with a default size of 4 bytes. */
1248     pCol->affinity = SQLITE_AFF_BLOB;
1249     pCol->szEst = 1;
1250 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
1251     if( 4>=sqlite3GlobalConfig.szSorterRef ){
1252       pCol->colFlags |= COLFLAG_SORTERREF;
1253     }
1254 #endif
1255   }else{
1256     zType = z + sqlite3Strlen30(z) + 1;
1257     memcpy(zType, pType->z, pType->n);
1258     zType[pType->n] = 0;
1259     sqlite3Dequote(zType);
1260     pCol->affinity = sqlite3AffinityType(zType, pCol);
1261     pCol->colFlags |= COLFLAG_HASTYPE;
1262   }
1263   p->nCol++;
1264   p->nNVCol++;
1265   pParse->constraintName.n = 0;
1266 }
1267 
1268 /*
1269 ** This routine is called by the parser while in the middle of
1270 ** parsing a CREATE TABLE statement.  A "NOT NULL" constraint has
1271 ** been seen on a column.  This routine sets the notNull flag on
1272 ** the column currently under construction.
1273 */
1274 void sqlite3AddNotNull(Parse *pParse, int onError){
1275   Table *p;
1276   Column *pCol;
1277   p = pParse->pNewTable;
1278   if( p==0 || NEVER(p->nCol<1) ) return;
1279   pCol = &p->aCol[p->nCol-1];
1280   pCol->notNull = (u8)onError;
1281   p->tabFlags |= TF_HasNotNull;
1282 
1283   /* Set the uniqNotNull flag on any UNIQUE or PK indexes already created
1284   ** on this column.  */
1285   if( pCol->colFlags & COLFLAG_UNIQUE ){
1286     Index *pIdx;
1287     for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
1288       assert( pIdx->nKeyCol==1 && pIdx->onError!=OE_None );
1289       if( pIdx->aiColumn[0]==p->nCol-1 ){
1290         pIdx->uniqNotNull = 1;
1291       }
1292     }
1293   }
1294 }
1295 
1296 /*
1297 ** Scan the column type name zType (length nType) and return the
1298 ** associated affinity type.
1299 **
1300 ** This routine does a case-independent search of zType for the
1301 ** substrings in the following table. If one of the substrings is
1302 ** found, the corresponding affinity is returned. If zType contains
1303 ** more than one of the substrings, entries toward the top of
1304 ** the table take priority. For example, if zType is 'BLOBINT',
1305 ** SQLITE_AFF_INTEGER is returned.
1306 **
1307 ** Substring     | Affinity
1308 ** --------------------------------
1309 ** 'INT'         | SQLITE_AFF_INTEGER
1310 ** 'CHAR'        | SQLITE_AFF_TEXT
1311 ** 'CLOB'        | SQLITE_AFF_TEXT
1312 ** 'TEXT'        | SQLITE_AFF_TEXT
1313 ** 'BLOB'        | SQLITE_AFF_BLOB
1314 ** 'REAL'        | SQLITE_AFF_REAL
1315 ** 'FLOA'        | SQLITE_AFF_REAL
1316 ** 'DOUB'        | SQLITE_AFF_REAL
1317 **
1318 ** If none of the substrings in the above table are found,
1319 ** SQLITE_AFF_NUMERIC is returned.
1320 */
1321 char sqlite3AffinityType(const char *zIn, Column *pCol){
1322   u32 h = 0;
1323   char aff = SQLITE_AFF_NUMERIC;
1324   const char *zChar = 0;
1325 
1326   assert( zIn!=0 );
1327   while( zIn[0] ){
1328     h = (h<<8) + sqlite3UpperToLower[(*zIn)&0xff];
1329     zIn++;
1330     if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){             /* CHAR */
1331       aff = SQLITE_AFF_TEXT;
1332       zChar = zIn;
1333     }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){       /* CLOB */
1334       aff = SQLITE_AFF_TEXT;
1335     }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){       /* TEXT */
1336       aff = SQLITE_AFF_TEXT;
1337     }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b')          /* BLOB */
1338         && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
1339       aff = SQLITE_AFF_BLOB;
1340       if( zIn[0]=='(' ) zChar = zIn;
1341 #ifndef SQLITE_OMIT_FLOATING_POINT
1342     }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l')          /* REAL */
1343         && aff==SQLITE_AFF_NUMERIC ){
1344       aff = SQLITE_AFF_REAL;
1345     }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a')          /* FLOA */
1346         && aff==SQLITE_AFF_NUMERIC ){
1347       aff = SQLITE_AFF_REAL;
1348     }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b')          /* DOUB */
1349         && aff==SQLITE_AFF_NUMERIC ){
1350       aff = SQLITE_AFF_REAL;
1351 #endif
1352     }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){    /* INT */
1353       aff = SQLITE_AFF_INTEGER;
1354       break;
1355     }
1356   }
1357 
1358   /* If pCol is not NULL, store an estimate of the field size.  The
1359   ** estimate is scaled so that the size of an integer is 1.  */
1360   if( pCol ){
1361     int v = 0;   /* default size is approx 4 bytes */
1362     if( aff<SQLITE_AFF_NUMERIC ){
1363       if( zChar ){
1364         while( zChar[0] ){
1365           if( sqlite3Isdigit(zChar[0]) ){
1366             /* BLOB(k), VARCHAR(k), CHAR(k) -> r=(k/4+1) */
1367             sqlite3GetInt32(zChar, &v);
1368             break;
1369           }
1370           zChar++;
1371         }
1372       }else{
1373         v = 16;   /* BLOB, TEXT, CLOB -> r=5  (approx 20 bytes)*/
1374       }
1375     }
1376 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
1377     if( v>=sqlite3GlobalConfig.szSorterRef ){
1378       pCol->colFlags |= COLFLAG_SORTERREF;
1379     }
1380 #endif
1381     v = v/4 + 1;
1382     if( v>255 ) v = 255;
1383     pCol->szEst = v;
1384   }
1385   return aff;
1386 }
1387 
1388 /*
1389 ** The expression is the default value for the most recently added column
1390 ** of the table currently under construction.
1391 **
1392 ** Default value expressions must be constant.  Raise an exception if this
1393 ** is not the case.
1394 **
1395 ** This routine is called by the parser while in the middle of
1396 ** parsing a CREATE TABLE statement.
1397 */
1398 void sqlite3AddDefaultValue(
1399   Parse *pParse,           /* Parsing context */
1400   Expr *pExpr,             /* The parsed expression of the default value */
1401   const char *zStart,      /* Start of the default value text */
1402   const char *zEnd         /* First character past end of defaut value text */
1403 ){
1404   Table *p;
1405   Column *pCol;
1406   sqlite3 *db = pParse->db;
1407   p = pParse->pNewTable;
1408   if( p!=0 ){
1409     int isInit = db->init.busy && db->init.iDb!=1;
1410     pCol = &(p->aCol[p->nCol-1]);
1411     if( !sqlite3ExprIsConstantOrFunction(pExpr, isInit) ){
1412       sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
1413           pCol->zName);
1414 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
1415     }else if( pCol->colFlags & COLFLAG_GENERATED ){
1416       testcase( pCol->colFlags & COLFLAG_VIRTUAL );
1417       testcase( pCol->colFlags & COLFLAG_STORED );
1418       sqlite3ErrorMsg(pParse, "cannot use DEFAULT on a generated column");
1419 #endif
1420     }else{
1421       /* A copy of pExpr is used instead of the original, as pExpr contains
1422       ** tokens that point to volatile memory.
1423       */
1424       Expr x;
1425       sqlite3ExprDelete(db, pCol->pDflt);
1426       memset(&x, 0, sizeof(x));
1427       x.op = TK_SPAN;
1428       x.u.zToken = sqlite3DbSpanDup(db, zStart, zEnd);
1429       x.pLeft = pExpr;
1430       x.flags = EP_Skip;
1431       pCol->pDflt = sqlite3ExprDup(db, &x, EXPRDUP_REDUCE);
1432       sqlite3DbFree(db, x.u.zToken);
1433     }
1434   }
1435   if( IN_RENAME_OBJECT ){
1436     sqlite3RenameExprUnmap(pParse, pExpr);
1437   }
1438   sqlite3ExprDelete(db, pExpr);
1439 }
1440 
1441 /*
1442 ** Backwards Compatibility Hack:
1443 **
1444 ** Historical versions of SQLite accepted strings as column names in
1445 ** indexes and PRIMARY KEY constraints and in UNIQUE constraints.  Example:
1446 **
1447 **     CREATE TABLE xyz(a,b,c,d,e,PRIMARY KEY('a'),UNIQUE('b','c' COLLATE trim)
1448 **     CREATE INDEX abc ON xyz('c','d' DESC,'e' COLLATE nocase DESC);
1449 **
1450 ** This is goofy.  But to preserve backwards compatibility we continue to
1451 ** accept it.  This routine does the necessary conversion.  It converts
1452 ** the expression given in its argument from a TK_STRING into a TK_ID
1453 ** if the expression is just a TK_STRING with an optional COLLATE clause.
1454 ** If the expression is anything other than TK_STRING, the expression is
1455 ** unchanged.
1456 */
1457 static void sqlite3StringToId(Expr *p){
1458   if( p->op==TK_STRING ){
1459     p->op = TK_ID;
1460   }else if( p->op==TK_COLLATE && p->pLeft->op==TK_STRING ){
1461     p->pLeft->op = TK_ID;
1462   }
1463 }
1464 
1465 /*
1466 ** Tag the given column as being part of the PRIMARY KEY
1467 */
1468 static void makeColumnPartOfPrimaryKey(Parse *pParse, Column *pCol){
1469   pCol->colFlags |= COLFLAG_PRIMKEY;
1470 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
1471   if( pCol->colFlags & COLFLAG_GENERATED ){
1472     testcase( pCol->colFlags & COLFLAG_VIRTUAL );
1473     testcase( pCol->colFlags & COLFLAG_STORED );
1474     sqlite3ErrorMsg(pParse,
1475       "generated columns cannot be part of the PRIMARY KEY");
1476   }
1477 #endif
1478 }
1479 
1480 /*
1481 ** Designate the PRIMARY KEY for the table.  pList is a list of names
1482 ** of columns that form the primary key.  If pList is NULL, then the
1483 ** most recently added column of the table is the primary key.
1484 **
1485 ** A table can have at most one primary key.  If the table already has
1486 ** a primary key (and this is the second primary key) then create an
1487 ** error.
1488 **
1489 ** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
1490 ** then we will try to use that column as the rowid.  Set the Table.iPKey
1491 ** field of the table under construction to be the index of the
1492 ** INTEGER PRIMARY KEY column.  Table.iPKey is set to -1 if there is
1493 ** no INTEGER PRIMARY KEY.
1494 **
1495 ** If the key is not an INTEGER PRIMARY KEY, then create a unique
1496 ** index for the key.  No index is created for INTEGER PRIMARY KEYs.
1497 */
1498 void sqlite3AddPrimaryKey(
1499   Parse *pParse,    /* Parsing context */
1500   ExprList *pList,  /* List of field names to be indexed */
1501   int onError,      /* What to do with a uniqueness conflict */
1502   int autoInc,      /* True if the AUTOINCREMENT keyword is present */
1503   int sortOrder     /* SQLITE_SO_ASC or SQLITE_SO_DESC */
1504 ){
1505   Table *pTab = pParse->pNewTable;
1506   Column *pCol = 0;
1507   int iCol = -1, i;
1508   int nTerm;
1509   if( pTab==0 ) goto primary_key_exit;
1510   if( pTab->tabFlags & TF_HasPrimaryKey ){
1511     sqlite3ErrorMsg(pParse,
1512       "table \"%s\" has more than one primary key", pTab->zName);
1513     goto primary_key_exit;
1514   }
1515   pTab->tabFlags |= TF_HasPrimaryKey;
1516   if( pList==0 ){
1517     iCol = pTab->nCol - 1;
1518     pCol = &pTab->aCol[iCol];
1519     makeColumnPartOfPrimaryKey(pParse, pCol);
1520     nTerm = 1;
1521   }else{
1522     nTerm = pList->nExpr;
1523     for(i=0; i<nTerm; i++){
1524       Expr *pCExpr = sqlite3ExprSkipCollate(pList->a[i].pExpr);
1525       assert( pCExpr!=0 );
1526       sqlite3StringToId(pCExpr);
1527       if( pCExpr->op==TK_ID ){
1528         const char *zCName = pCExpr->u.zToken;
1529         for(iCol=0; iCol<pTab->nCol; iCol++){
1530           if( sqlite3StrICmp(zCName, pTab->aCol[iCol].zName)==0 ){
1531             pCol = &pTab->aCol[iCol];
1532             makeColumnPartOfPrimaryKey(pParse, pCol);
1533             break;
1534           }
1535         }
1536       }
1537     }
1538   }
1539   if( nTerm==1
1540    && pCol
1541    && sqlite3StrICmp(sqlite3ColumnType(pCol,""), "INTEGER")==0
1542    && sortOrder!=SQLITE_SO_DESC
1543   ){
1544     if( IN_RENAME_OBJECT && pList ){
1545       Expr *pCExpr = sqlite3ExprSkipCollate(pList->a[0].pExpr);
1546       sqlite3RenameTokenRemap(pParse, &pTab->iPKey, pCExpr);
1547     }
1548     pTab->iPKey = iCol;
1549     pTab->keyConf = (u8)onError;
1550     assert( autoInc==0 || autoInc==1 );
1551     pTab->tabFlags |= autoInc*TF_Autoincrement;
1552     if( pList ) pParse->iPkSortOrder = pList->a[0].sortFlags;
1553     (void)sqlite3HasExplicitNulls(pParse, pList);
1554   }else if( autoInc ){
1555 #ifndef SQLITE_OMIT_AUTOINCREMENT
1556     sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
1557        "INTEGER PRIMARY KEY");
1558 #endif
1559   }else{
1560     sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0,
1561                            0, sortOrder, 0, SQLITE_IDXTYPE_PRIMARYKEY);
1562     pList = 0;
1563   }
1564 
1565 primary_key_exit:
1566   sqlite3ExprListDelete(pParse->db, pList);
1567   return;
1568 }
1569 
1570 /*
1571 ** Add a new CHECK constraint to the table currently under construction.
1572 */
1573 void sqlite3AddCheckConstraint(
1574   Parse *pParse,    /* Parsing context */
1575   Expr *pCheckExpr  /* The check expression */
1576 ){
1577 #ifndef SQLITE_OMIT_CHECK
1578   Table *pTab = pParse->pNewTable;
1579   sqlite3 *db = pParse->db;
1580   if( pTab && !IN_DECLARE_VTAB
1581    && !sqlite3BtreeIsReadonly(db->aDb[db->init.iDb].pBt)
1582   ){
1583     pTab->pCheck = sqlite3ExprListAppend(pParse, pTab->pCheck, pCheckExpr);
1584     if( pParse->constraintName.n ){
1585       sqlite3ExprListSetName(pParse, pTab->pCheck, &pParse->constraintName, 1);
1586     }
1587   }else
1588 #endif
1589   {
1590     sqlite3ExprDelete(pParse->db, pCheckExpr);
1591   }
1592 }
1593 
1594 /*
1595 ** Set the collation function of the most recently parsed table column
1596 ** to the CollSeq given.
1597 */
1598 void sqlite3AddCollateType(Parse *pParse, Token *pToken){
1599   Table *p;
1600   int i;
1601   char *zColl;              /* Dequoted name of collation sequence */
1602   sqlite3 *db;
1603 
1604   if( (p = pParse->pNewTable)==0 ) return;
1605   i = p->nCol-1;
1606   db = pParse->db;
1607   zColl = sqlite3NameFromToken(db, pToken);
1608   if( !zColl ) return;
1609 
1610   if( sqlite3LocateCollSeq(pParse, zColl) ){
1611     Index *pIdx;
1612     sqlite3DbFree(db, p->aCol[i].zColl);
1613     p->aCol[i].zColl = zColl;
1614 
1615     /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
1616     ** then an index may have been created on this column before the
1617     ** collation type was added. Correct this if it is the case.
1618     */
1619     for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
1620       assert( pIdx->nKeyCol==1 );
1621       if( pIdx->aiColumn[0]==i ){
1622         pIdx->azColl[0] = p->aCol[i].zColl;
1623       }
1624     }
1625   }else{
1626     sqlite3DbFree(db, zColl);
1627   }
1628 }
1629 
1630 /* Change the most recently parsed column to be a GENERATED ALWAYS AS
1631 ** column.
1632 */
1633 void sqlite3AddGenerated(Parse *pParse, Expr *pExpr, Token *pType){
1634 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
1635   u8 eType = COLFLAG_VIRTUAL;
1636   Table *pTab = pParse->pNewTable;
1637   Column *pCol;
1638   if( pTab==0 ){
1639     /* generated column in an CREATE TABLE IF NOT EXISTS that already exists */
1640     goto generated_done;
1641   }
1642   pCol = &(pTab->aCol[pTab->nCol-1]);
1643   if( IN_DECLARE_VTAB ){
1644     sqlite3ErrorMsg(pParse, "virtual tables cannot use computed columns");
1645     goto generated_done;
1646   }
1647   if( pCol->pDflt ) goto generated_error;
1648   if( pType ){
1649     if( pType->n==7 && sqlite3StrNICmp("virtual",pType->z,7)==0 ){
1650       /* no-op */
1651     }else if( pType->n==6 && sqlite3StrNICmp("stored",pType->z,6)==0 ){
1652       eType = COLFLAG_STORED;
1653     }else{
1654       goto generated_error;
1655     }
1656   }
1657   if( eType==COLFLAG_VIRTUAL ) pTab->nNVCol--;
1658   pCol->colFlags |= eType;
1659   assert( TF_HasVirtual==COLFLAG_VIRTUAL );
1660   assert( TF_HasStored==COLFLAG_STORED );
1661   pTab->tabFlags |= eType;
1662   if( pCol->colFlags & COLFLAG_PRIMKEY ){
1663     makeColumnPartOfPrimaryKey(pParse, pCol); /* For the error message */
1664   }
1665   pCol->pDflt = pExpr;
1666   pExpr = 0;
1667   goto generated_done;
1668 
1669 generated_error:
1670   sqlite3ErrorMsg(pParse, "error in generated column \"%s\"",
1671                   pCol->zName);
1672 generated_done:
1673   sqlite3ExprDelete(pParse->db, pExpr);
1674 #else
1675   /* Throw and error for the GENERATED ALWAYS AS clause if the
1676   ** SQLITE_OMIT_GENERATED_COLUMNS compile-time option is used. */
1677   sqlite3ErrorMsg(pParse, "generated columns not supported");
1678   sqlite3ExprDelete(pParse->db, pExpr);
1679 #endif
1680 }
1681 
1682 /*
1683 ** Generate code that will increment the schema cookie.
1684 **
1685 ** The schema cookie is used to determine when the schema for the
1686 ** database changes.  After each schema change, the cookie value
1687 ** changes.  When a process first reads the schema it records the
1688 ** cookie.  Thereafter, whenever it goes to access the database,
1689 ** it checks the cookie to make sure the schema has not changed
1690 ** since it was last read.
1691 **
1692 ** This plan is not completely bullet-proof.  It is possible for
1693 ** the schema to change multiple times and for the cookie to be
1694 ** set back to prior value.  But schema changes are infrequent
1695 ** and the probability of hitting the same cookie value is only
1696 ** 1 chance in 2^32.  So we're safe enough.
1697 **
1698 ** IMPLEMENTATION-OF: R-34230-56049 SQLite automatically increments
1699 ** the schema-version whenever the schema changes.
1700 */
1701 void sqlite3ChangeCookie(Parse *pParse, int iDb){
1702   sqlite3 *db = pParse->db;
1703   Vdbe *v = pParse->pVdbe;
1704   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
1705   sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION,
1706                    (int)(1+(unsigned)db->aDb[iDb].pSchema->schema_cookie));
1707 }
1708 
1709 /*
1710 ** Measure the number of characters needed to output the given
1711 ** identifier.  The number returned includes any quotes used
1712 ** but does not include the null terminator.
1713 **
1714 ** The estimate is conservative.  It might be larger that what is
1715 ** really needed.
1716 */
1717 static int identLength(const char *z){
1718   int n;
1719   for(n=0; *z; n++, z++){
1720     if( *z=='"' ){ n++; }
1721   }
1722   return n + 2;
1723 }
1724 
1725 /*
1726 ** The first parameter is a pointer to an output buffer. The second
1727 ** parameter is a pointer to an integer that contains the offset at
1728 ** which to write into the output buffer. This function copies the
1729 ** nul-terminated string pointed to by the third parameter, zSignedIdent,
1730 ** to the specified offset in the buffer and updates *pIdx to refer
1731 ** to the first byte after the last byte written before returning.
1732 **
1733 ** If the string zSignedIdent consists entirely of alpha-numeric
1734 ** characters, does not begin with a digit and is not an SQL keyword,
1735 ** then it is copied to the output buffer exactly as it is. Otherwise,
1736 ** it is quoted using double-quotes.
1737 */
1738 static void identPut(char *z, int *pIdx, char *zSignedIdent){
1739   unsigned char *zIdent = (unsigned char*)zSignedIdent;
1740   int i, j, needQuote;
1741   i = *pIdx;
1742 
1743   for(j=0; zIdent[j]; j++){
1744     if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
1745   }
1746   needQuote = sqlite3Isdigit(zIdent[0])
1747             || sqlite3KeywordCode(zIdent, j)!=TK_ID
1748             || zIdent[j]!=0
1749             || j==0;
1750 
1751   if( needQuote ) z[i++] = '"';
1752   for(j=0; zIdent[j]; j++){
1753     z[i++] = zIdent[j];
1754     if( zIdent[j]=='"' ) z[i++] = '"';
1755   }
1756   if( needQuote ) z[i++] = '"';
1757   z[i] = 0;
1758   *pIdx = i;
1759 }
1760 
1761 /*
1762 ** Generate a CREATE TABLE statement appropriate for the given
1763 ** table.  Memory to hold the text of the statement is obtained
1764 ** from sqliteMalloc() and must be freed by the calling function.
1765 */
1766 static char *createTableStmt(sqlite3 *db, Table *p){
1767   int i, k, n;
1768   char *zStmt;
1769   char *zSep, *zSep2, *zEnd;
1770   Column *pCol;
1771   n = 0;
1772   for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
1773     n += identLength(pCol->zName) + 5;
1774   }
1775   n += identLength(p->zName);
1776   if( n<50 ){
1777     zSep = "";
1778     zSep2 = ",";
1779     zEnd = ")";
1780   }else{
1781     zSep = "\n  ";
1782     zSep2 = ",\n  ";
1783     zEnd = "\n)";
1784   }
1785   n += 35 + 6*p->nCol;
1786   zStmt = sqlite3DbMallocRaw(0, n);
1787   if( zStmt==0 ){
1788     sqlite3OomFault(db);
1789     return 0;
1790   }
1791   sqlite3_snprintf(n, zStmt, "CREATE TABLE ");
1792   k = sqlite3Strlen30(zStmt);
1793   identPut(zStmt, &k, p->zName);
1794   zStmt[k++] = '(';
1795   for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
1796     static const char * const azType[] = {
1797         /* SQLITE_AFF_BLOB    */ "",
1798         /* SQLITE_AFF_TEXT    */ " TEXT",
1799         /* SQLITE_AFF_NUMERIC */ " NUM",
1800         /* SQLITE_AFF_INTEGER */ " INT",
1801         /* SQLITE_AFF_REAL    */ " REAL"
1802     };
1803     int len;
1804     const char *zType;
1805 
1806     sqlite3_snprintf(n-k, &zStmt[k], zSep);
1807     k += sqlite3Strlen30(&zStmt[k]);
1808     zSep = zSep2;
1809     identPut(zStmt, &k, pCol->zName);
1810     assert( pCol->affinity-SQLITE_AFF_BLOB >= 0 );
1811     assert( pCol->affinity-SQLITE_AFF_BLOB < ArraySize(azType) );
1812     testcase( pCol->affinity==SQLITE_AFF_BLOB );
1813     testcase( pCol->affinity==SQLITE_AFF_TEXT );
1814     testcase( pCol->affinity==SQLITE_AFF_NUMERIC );
1815     testcase( pCol->affinity==SQLITE_AFF_INTEGER );
1816     testcase( pCol->affinity==SQLITE_AFF_REAL );
1817 
1818     zType = azType[pCol->affinity - SQLITE_AFF_BLOB];
1819     len = sqlite3Strlen30(zType);
1820     assert( pCol->affinity==SQLITE_AFF_BLOB
1821             || pCol->affinity==sqlite3AffinityType(zType, 0) );
1822     memcpy(&zStmt[k], zType, len);
1823     k += len;
1824     assert( k<=n );
1825   }
1826   sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
1827   return zStmt;
1828 }
1829 
1830 /*
1831 ** Resize an Index object to hold N columns total.  Return SQLITE_OK
1832 ** on success and SQLITE_NOMEM on an OOM error.
1833 */
1834 static int resizeIndexObject(sqlite3 *db, Index *pIdx, int N){
1835   char *zExtra;
1836   int nByte;
1837   if( pIdx->nColumn>=N ) return SQLITE_OK;
1838   assert( pIdx->isResized==0 );
1839   nByte = (sizeof(char*) + sizeof(i16) + 1)*N;
1840   zExtra = sqlite3DbMallocZero(db, nByte);
1841   if( zExtra==0 ) return SQLITE_NOMEM_BKPT;
1842   memcpy(zExtra, pIdx->azColl, sizeof(char*)*pIdx->nColumn);
1843   pIdx->azColl = (const char**)zExtra;
1844   zExtra += sizeof(char*)*N;
1845   memcpy(zExtra, pIdx->aiColumn, sizeof(i16)*pIdx->nColumn);
1846   pIdx->aiColumn = (i16*)zExtra;
1847   zExtra += sizeof(i16)*N;
1848   memcpy(zExtra, pIdx->aSortOrder, pIdx->nColumn);
1849   pIdx->aSortOrder = (u8*)zExtra;
1850   pIdx->nColumn = N;
1851   pIdx->isResized = 1;
1852   return SQLITE_OK;
1853 }
1854 
1855 /*
1856 ** Estimate the total row width for a table.
1857 */
1858 static void estimateTableWidth(Table *pTab){
1859   unsigned wTable = 0;
1860   const Column *pTabCol;
1861   int i;
1862   for(i=pTab->nCol, pTabCol=pTab->aCol; i>0; i--, pTabCol++){
1863     wTable += pTabCol->szEst;
1864   }
1865   if( pTab->iPKey<0 ) wTable++;
1866   pTab->szTabRow = sqlite3LogEst(wTable*4);
1867 }
1868 
1869 /*
1870 ** Estimate the average size of a row for an index.
1871 */
1872 static void estimateIndexWidth(Index *pIdx){
1873   unsigned wIndex = 0;
1874   int i;
1875   const Column *aCol = pIdx->pTable->aCol;
1876   for(i=0; i<pIdx->nColumn; i++){
1877     i16 x = pIdx->aiColumn[i];
1878     assert( x<pIdx->pTable->nCol );
1879     wIndex += x<0 ? 1 : aCol[pIdx->aiColumn[i]].szEst;
1880   }
1881   pIdx->szIdxRow = sqlite3LogEst(wIndex*4);
1882 }
1883 
1884 /* Return true if column number x is any of the first nCol entries of aiCol[].
1885 ** This is used to determine if the column number x appears in any of the
1886 ** first nCol entries of an index.
1887 */
1888 static int hasColumn(const i16 *aiCol, int nCol, int x){
1889   while( nCol-- > 0 ){
1890     assert( aiCol[0]>=0 );
1891     if( x==*(aiCol++) ){
1892       return 1;
1893     }
1894   }
1895   return 0;
1896 }
1897 
1898 /*
1899 ** Return true if any of the first nKey entries of index pIdx exactly
1900 ** match the iCol-th entry of pPk.  pPk is always a WITHOUT ROWID
1901 ** PRIMARY KEY index.  pIdx is an index on the same table.  pIdx may
1902 ** or may not be the same index as pPk.
1903 **
1904 ** The first nKey entries of pIdx are guaranteed to be ordinary columns,
1905 ** not a rowid or expression.
1906 **
1907 ** This routine differs from hasColumn() in that both the column and the
1908 ** collating sequence must match for this routine, but for hasColumn() only
1909 ** the column name must match.
1910 */
1911 static int isDupColumn(Index *pIdx, int nKey, Index *pPk, int iCol){
1912   int i, j;
1913   assert( nKey<=pIdx->nColumn );
1914   assert( iCol<MAX(pPk->nColumn,pPk->nKeyCol) );
1915   assert( pPk->idxType==SQLITE_IDXTYPE_PRIMARYKEY );
1916   assert( pPk->pTable->tabFlags & TF_WithoutRowid );
1917   assert( pPk->pTable==pIdx->pTable );
1918   testcase( pPk==pIdx );
1919   j = pPk->aiColumn[iCol];
1920   assert( j!=XN_ROWID && j!=XN_EXPR );
1921   for(i=0; i<nKey; i++){
1922     assert( pIdx->aiColumn[i]>=0 || j>=0 );
1923     if( pIdx->aiColumn[i]==j
1924      && sqlite3StrICmp(pIdx->azColl[i], pPk->azColl[iCol])==0
1925     ){
1926       return 1;
1927     }
1928   }
1929   return 0;
1930 }
1931 
1932 /* Recompute the colNotIdxed field of the Index.
1933 **
1934 ** colNotIdxed is a bitmask that has a 0 bit representing each indexed
1935 ** columns that are within the first 63 columns of the table.  The
1936 ** high-order bit of colNotIdxed is always 1.  All unindexed columns
1937 ** of the table have a 1.
1938 **
1939 ** 2019-10-24:  For the purpose of this computation, virtual columns are
1940 ** not considered to be covered by the index, even if they are in the
1941 ** index, because we do not trust the logic in whereIndexExprTrans() to be
1942 ** able to find all instances of a reference to the indexed table column
1943 ** and convert them into references to the index.  Hence we always want
1944 ** the actual table at hand in order to recompute the virtual column, if
1945 ** necessary.
1946 **
1947 ** The colNotIdxed mask is AND-ed with the SrcList.a[].colUsed mask
1948 ** to determine if the index is covering index.
1949 */
1950 static void recomputeColumnsNotIndexed(Index *pIdx){
1951   Bitmask m = 0;
1952   int j;
1953   Table *pTab = pIdx->pTable;
1954   for(j=pIdx->nColumn-1; j>=0; j--){
1955     int x = pIdx->aiColumn[j];
1956     if( x>=0 && (pTab->aCol[x].colFlags & COLFLAG_VIRTUAL)==0 ){
1957       testcase( x==BMS-1 );
1958       testcase( x==BMS-2 );
1959       if( x<BMS-1 ) m |= MASKBIT(x);
1960     }
1961   }
1962   pIdx->colNotIdxed = ~m;
1963   assert( (pIdx->colNotIdxed>>63)==1 );
1964 }
1965 
1966 /*
1967 ** This routine runs at the end of parsing a CREATE TABLE statement that
1968 ** has a WITHOUT ROWID clause.  The job of this routine is to convert both
1969 ** internal schema data structures and the generated VDBE code so that they
1970 ** are appropriate for a WITHOUT ROWID table instead of a rowid table.
1971 ** Changes include:
1972 **
1973 **     (1)  Set all columns of the PRIMARY KEY schema object to be NOT NULL.
1974 **     (2)  Convert P3 parameter of the OP_CreateBtree from BTREE_INTKEY
1975 **          into BTREE_BLOBKEY.
1976 **     (3)  Bypass the creation of the sqlite_master table entry
1977 **          for the PRIMARY KEY as the primary key index is now
1978 **          identified by the sqlite_master table entry of the table itself.
1979 **     (4)  Set the Index.tnum of the PRIMARY KEY Index object in the
1980 **          schema to the rootpage from the main table.
1981 **     (5)  Add all table columns to the PRIMARY KEY Index object
1982 **          so that the PRIMARY KEY is a covering index.  The surplus
1983 **          columns are part of KeyInfo.nAllField and are not used for
1984 **          sorting or lookup or uniqueness checks.
1985 **     (6)  Replace the rowid tail on all automatically generated UNIQUE
1986 **          indices with the PRIMARY KEY columns.
1987 **
1988 ** For virtual tables, only (1) is performed.
1989 */
1990 static void convertToWithoutRowidTable(Parse *pParse, Table *pTab){
1991   Index *pIdx;
1992   Index *pPk;
1993   int nPk;
1994   int nExtra;
1995   int i, j;
1996   sqlite3 *db = pParse->db;
1997   Vdbe *v = pParse->pVdbe;
1998 
1999   /* Mark every PRIMARY KEY column as NOT NULL (except for imposter tables)
2000   */
2001   if( !db->init.imposterTable ){
2002     for(i=0; i<pTab->nCol; i++){
2003       if( (pTab->aCol[i].colFlags & COLFLAG_PRIMKEY)!=0 ){
2004         pTab->aCol[i].notNull = OE_Abort;
2005       }
2006     }
2007     pTab->tabFlags |= TF_HasNotNull;
2008   }
2009 
2010   /* Convert the P3 operand of the OP_CreateBtree opcode from BTREE_INTKEY
2011   ** into BTREE_BLOBKEY.
2012   */
2013   if( pParse->addrCrTab ){
2014     assert( v );
2015     sqlite3VdbeChangeP3(v, pParse->addrCrTab, BTREE_BLOBKEY);
2016   }
2017 
2018   /* Locate the PRIMARY KEY index.  Or, if this table was originally
2019   ** an INTEGER PRIMARY KEY table, create a new PRIMARY KEY index.
2020   */
2021   if( pTab->iPKey>=0 ){
2022     ExprList *pList;
2023     Token ipkToken;
2024     sqlite3TokenInit(&ipkToken, pTab->aCol[pTab->iPKey].zName);
2025     pList = sqlite3ExprListAppend(pParse, 0,
2026                   sqlite3ExprAlloc(db, TK_ID, &ipkToken, 0));
2027     if( pList==0 ) return;
2028     if( IN_RENAME_OBJECT ){
2029       sqlite3RenameTokenRemap(pParse, pList->a[0].pExpr, &pTab->iPKey);
2030     }
2031     pList->a[0].sortFlags = pParse->iPkSortOrder;
2032     assert( pParse->pNewTable==pTab );
2033     pTab->iPKey = -1;
2034     sqlite3CreateIndex(pParse, 0, 0, 0, pList, pTab->keyConf, 0, 0, 0, 0,
2035                        SQLITE_IDXTYPE_PRIMARYKEY);
2036     if( db->mallocFailed || pParse->nErr ) return;
2037     pPk = sqlite3PrimaryKeyIndex(pTab);
2038     assert( pPk->nKeyCol==1 );
2039   }else{
2040     pPk = sqlite3PrimaryKeyIndex(pTab);
2041     assert( pPk!=0 );
2042 
2043     /*
2044     ** Remove all redundant columns from the PRIMARY KEY.  For example, change
2045     ** "PRIMARY KEY(a,b,a,b,c,b,c,d)" into just "PRIMARY KEY(a,b,c,d)".  Later
2046     ** code assumes the PRIMARY KEY contains no repeated columns.
2047     */
2048     for(i=j=1; i<pPk->nKeyCol; i++){
2049       if( isDupColumn(pPk, j, pPk, i) ){
2050         pPk->nColumn--;
2051       }else{
2052         testcase( hasColumn(pPk->aiColumn, j, pPk->aiColumn[i]) );
2053         pPk->azColl[j] = pPk->azColl[i];
2054         pPk->aSortOrder[j] = pPk->aSortOrder[i];
2055         pPk->aiColumn[j++] = pPk->aiColumn[i];
2056       }
2057     }
2058     pPk->nKeyCol = j;
2059   }
2060   assert( pPk!=0 );
2061   pPk->isCovering = 1;
2062   if( !db->init.imposterTable ) pPk->uniqNotNull = 1;
2063   nPk = pPk->nColumn = pPk->nKeyCol;
2064 
2065   /* Bypass the creation of the PRIMARY KEY btree and the sqlite_master
2066   ** table entry. This is only required if currently generating VDBE
2067   ** code for a CREATE TABLE (not when parsing one as part of reading
2068   ** a database schema).  */
2069   if( v && pPk->tnum>0 ){
2070     assert( db->init.busy==0 );
2071     sqlite3VdbeChangeOpcode(v, pPk->tnum, OP_Goto);
2072   }
2073 
2074   /* The root page of the PRIMARY KEY is the table root page */
2075   pPk->tnum = pTab->tnum;
2076 
2077   /* Update the in-memory representation of all UNIQUE indices by converting
2078   ** the final rowid column into one or more columns of the PRIMARY KEY.
2079   */
2080   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
2081     int n;
2082     if( IsPrimaryKeyIndex(pIdx) ) continue;
2083     for(i=n=0; i<nPk; i++){
2084       if( !isDupColumn(pIdx, pIdx->nKeyCol, pPk, i) ){
2085         testcase( hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) );
2086         n++;
2087       }
2088     }
2089     if( n==0 ){
2090       /* This index is a superset of the primary key */
2091       pIdx->nColumn = pIdx->nKeyCol;
2092       continue;
2093     }
2094     if( resizeIndexObject(db, pIdx, pIdx->nKeyCol+n) ) return;
2095     for(i=0, j=pIdx->nKeyCol; i<nPk; i++){
2096       if( !isDupColumn(pIdx, pIdx->nKeyCol, pPk, i) ){
2097         testcase( hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) );
2098         pIdx->aiColumn[j] = pPk->aiColumn[i];
2099         pIdx->azColl[j] = pPk->azColl[i];
2100         if( pPk->aSortOrder[i] ){
2101           /* See ticket https://www.sqlite.org/src/info/bba7b69f9849b5bf */
2102           pIdx->bAscKeyBug = 1;
2103         }
2104         j++;
2105       }
2106     }
2107     assert( pIdx->nColumn>=pIdx->nKeyCol+n );
2108     assert( pIdx->nColumn>=j );
2109   }
2110 
2111   /* Add all table columns to the PRIMARY KEY index
2112   */
2113   nExtra = 0;
2114   for(i=0; i<pTab->nCol; i++){
2115     if( !hasColumn(pPk->aiColumn, nPk, i)
2116      && (pTab->aCol[i].colFlags & COLFLAG_VIRTUAL)==0 ) nExtra++;
2117   }
2118   if( resizeIndexObject(db, pPk, nPk+nExtra) ) return;
2119   for(i=0, j=nPk; i<pTab->nCol; i++){
2120     if( !hasColumn(pPk->aiColumn, j, i)
2121      && (pTab->aCol[i].colFlags & COLFLAG_VIRTUAL)==0
2122     ){
2123       assert( j<pPk->nColumn );
2124       pPk->aiColumn[j] = i;
2125       pPk->azColl[j] = sqlite3StrBINARY;
2126       j++;
2127     }
2128   }
2129   assert( pPk->nColumn==j );
2130   assert( pTab->nNVCol<=j );
2131   recomputeColumnsNotIndexed(pPk);
2132 }
2133 
2134 
2135 #ifndef SQLITE_OMIT_VIRTUALTABLE
2136 /*
2137 ** Return true if pTab is a virtual table and zName is a shadow table name
2138 ** for that virtual table.
2139 */
2140 int sqlite3IsShadowTableOf(sqlite3 *db, Table *pTab, const char *zName){
2141   int nName;                    /* Length of zName */
2142   Module *pMod;                 /* Module for the virtual table */
2143 
2144   if( !IsVirtual(pTab) ) return 0;
2145   nName = sqlite3Strlen30(pTab->zName);
2146   if( sqlite3_strnicmp(zName, pTab->zName, nName)!=0 ) return 0;
2147   if( zName[nName]!='_' ) return 0;
2148   pMod = (Module*)sqlite3HashFind(&db->aModule, pTab->azModuleArg[0]);
2149   if( pMod==0 ) return 0;
2150   if( pMod->pModule->iVersion<3 ) return 0;
2151   if( pMod->pModule->xShadowName==0 ) return 0;
2152   return pMod->pModule->xShadowName(zName+nName+1);
2153 }
2154 #endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
2155 
2156 #ifndef SQLITE_OMIT_VIRTUALTABLE
2157 /*
2158 ** Return true if zName is a shadow table name in the current database
2159 ** connection.
2160 **
2161 ** zName is temporarily modified while this routine is running, but is
2162 ** restored to its original value prior to this routine returning.
2163 */
2164 int sqlite3ShadowTableName(sqlite3 *db, const char *zName){
2165   char *zTail;                  /* Pointer to the last "_" in zName */
2166   Table *pTab;                  /* Table that zName is a shadow of */
2167   zTail = strrchr(zName, '_');
2168   if( zTail==0 ) return 0;
2169   *zTail = 0;
2170   pTab = sqlite3FindTable(db, zName, 0);
2171   *zTail = '_';
2172   if( pTab==0 ) return 0;
2173   if( !IsVirtual(pTab) ) return 0;
2174   return sqlite3IsShadowTableOf(db, pTab, zName);
2175 }
2176 #endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
2177 
2178 
2179 #ifdef SQLITE_DEBUG
2180 /*
2181 ** Mark all nodes of an expression as EP_Immutable, indicating that
2182 ** they should not be changed.  Expressions attached to a table or
2183 ** index definition are tagged this way to help ensure that we do
2184 ** not pass them into code generator routines by mistake.
2185 */
2186 static int markImmutableExprStep(Walker *pWalker, Expr *pExpr){
2187   ExprSetVVAProperty(pExpr, EP_Immutable);
2188   return WRC_Continue;
2189 }
2190 static void markExprListImmutable(ExprList *pList){
2191   if( pList ){
2192     Walker w;
2193     memset(&w, 0, sizeof(w));
2194     w.xExprCallback = markImmutableExprStep;
2195     w.xSelectCallback = sqlite3SelectWalkNoop;
2196     w.xSelectCallback2 = 0;
2197     sqlite3WalkExprList(&w, pList);
2198   }
2199 }
2200 #else
2201 #define markExprListImmutable(X)  /* no-op */
2202 #endif /* SQLITE_DEBUG */
2203 
2204 
2205 /*
2206 ** This routine is called to report the final ")" that terminates
2207 ** a CREATE TABLE statement.
2208 **
2209 ** The table structure that other action routines have been building
2210 ** is added to the internal hash tables, assuming no errors have
2211 ** occurred.
2212 **
2213 ** An entry for the table is made in the master table on disk, unless
2214 ** this is a temporary table or db->init.busy==1.  When db->init.busy==1
2215 ** it means we are reading the sqlite_master table because we just
2216 ** connected to the database or because the sqlite_master table has
2217 ** recently changed, so the entry for this table already exists in
2218 ** the sqlite_master table.  We do not want to create it again.
2219 **
2220 ** If the pSelect argument is not NULL, it means that this routine
2221 ** was called to create a table generated from a
2222 ** "CREATE TABLE ... AS SELECT ..." statement.  The column names of
2223 ** the new table will match the result set of the SELECT.
2224 */
2225 void sqlite3EndTable(
2226   Parse *pParse,          /* Parse context */
2227   Token *pCons,           /* The ',' token after the last column defn. */
2228   Token *pEnd,            /* The ')' before options in the CREATE TABLE */
2229   u8 tabOpts,             /* Extra table options. Usually 0. */
2230   Select *pSelect         /* Select from a "CREATE ... AS SELECT" */
2231 ){
2232   Table *p;                 /* The new table */
2233   sqlite3 *db = pParse->db; /* The database connection */
2234   int iDb;                  /* Database in which the table lives */
2235   Index *pIdx;              /* An implied index of the table */
2236 
2237   if( pEnd==0 && pSelect==0 ){
2238     return;
2239   }
2240   assert( !db->mallocFailed );
2241   p = pParse->pNewTable;
2242   if( p==0 ) return;
2243 
2244   if( pSelect==0 && sqlite3ShadowTableName(db, p->zName) ){
2245     p->tabFlags |= TF_Shadow;
2246   }
2247 
2248   /* If the db->init.busy is 1 it means we are reading the SQL off the
2249   ** "sqlite_master" or "sqlite_temp_master" table on the disk.
2250   ** So do not write to the disk again.  Extract the root page number
2251   ** for the table from the db->init.newTnum field.  (The page number
2252   ** should have been put there by the sqliteOpenCb routine.)
2253   **
2254   ** If the root page number is 1, that means this is the sqlite_master
2255   ** table itself.  So mark it read-only.
2256   */
2257   if( db->init.busy ){
2258     if( pSelect ){
2259       sqlite3ErrorMsg(pParse, "");
2260       return;
2261     }
2262     p->tnum = db->init.newTnum;
2263     if( p->tnum==1 ) p->tabFlags |= TF_Readonly;
2264   }
2265 
2266   assert( (p->tabFlags & TF_HasPrimaryKey)==0
2267        || p->iPKey>=0 || sqlite3PrimaryKeyIndex(p)!=0 );
2268   assert( (p->tabFlags & TF_HasPrimaryKey)!=0
2269        || (p->iPKey<0 && sqlite3PrimaryKeyIndex(p)==0) );
2270 
2271   /* Special processing for WITHOUT ROWID Tables */
2272   if( tabOpts & TF_WithoutRowid ){
2273     if( (p->tabFlags & TF_Autoincrement) ){
2274       sqlite3ErrorMsg(pParse,
2275           "AUTOINCREMENT not allowed on WITHOUT ROWID tables");
2276       return;
2277     }
2278     if( (p->tabFlags & TF_HasPrimaryKey)==0 ){
2279       sqlite3ErrorMsg(pParse, "PRIMARY KEY missing on table %s", p->zName);
2280       return;
2281     }
2282     p->tabFlags |= TF_WithoutRowid | TF_NoVisibleRowid;
2283     convertToWithoutRowidTable(pParse, p);
2284   }
2285   iDb = sqlite3SchemaToIndex(db, p->pSchema);
2286 
2287 #ifndef SQLITE_OMIT_CHECK
2288   /* Resolve names in all CHECK constraint expressions.
2289   */
2290   if( p->pCheck ){
2291     sqlite3ResolveSelfReference(pParse, p, NC_IsCheck, 0, p->pCheck);
2292     if( pParse->nErr ){
2293       /* If errors are seen, delete the CHECK constraints now, else they might
2294       ** actually be used if PRAGMA writable_schema=ON is set. */
2295       sqlite3ExprListDelete(db, p->pCheck);
2296       p->pCheck = 0;
2297     }else{
2298       markExprListImmutable(p->pCheck);
2299     }
2300   }
2301 #endif /* !defined(SQLITE_OMIT_CHECK) */
2302 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
2303   if( p->tabFlags & TF_HasGenerated ){
2304     int ii, nNG = 0;
2305     testcase( p->tabFlags & TF_HasVirtual );
2306     testcase( p->tabFlags & TF_HasStored );
2307     for(ii=0; ii<p->nCol; ii++){
2308       u32 colFlags = p->aCol[ii].colFlags;
2309       if( (colFlags & COLFLAG_GENERATED)!=0 ){
2310         Expr *pX = p->aCol[ii].pDflt;
2311         testcase( colFlags & COLFLAG_VIRTUAL );
2312         testcase( colFlags & COLFLAG_STORED );
2313         if( sqlite3ResolveSelfReference(pParse, p, NC_GenCol, pX, 0) ){
2314           /* If there are errors in resolving the expression, change the
2315           ** expression to a NULL.  This prevents code generators that operate
2316           ** on the expression from inserting extra parts into the expression
2317           ** tree that have been allocated from lookaside memory, which is
2318           ** illegal in a schema and will lead to errors or heap corruption
2319           ** when the database connection closes. */
2320           sqlite3ExprDelete(db, pX);
2321           p->aCol[ii].pDflt = sqlite3ExprAlloc(db, TK_NULL, 0, 0);
2322         }
2323       }else{
2324         nNG++;
2325       }
2326     }
2327     if( nNG==0 ){
2328       sqlite3ErrorMsg(pParse, "must have at least one non-generated column");
2329       return;
2330     }
2331   }
2332 #endif
2333 
2334   /* Estimate the average row size for the table and for all implied indices */
2335   estimateTableWidth(p);
2336   for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
2337     estimateIndexWidth(pIdx);
2338   }
2339 
2340   /* If not initializing, then create a record for the new table
2341   ** in the SQLITE_MASTER table of the database.
2342   **
2343   ** If this is a TEMPORARY table, write the entry into the auxiliary
2344   ** file instead of into the main database file.
2345   */
2346   if( !db->init.busy ){
2347     int n;
2348     Vdbe *v;
2349     char *zType;    /* "view" or "table" */
2350     char *zType2;   /* "VIEW" or "TABLE" */
2351     char *zStmt;    /* Text of the CREATE TABLE or CREATE VIEW statement */
2352 
2353     v = sqlite3GetVdbe(pParse);
2354     if( NEVER(v==0) ) return;
2355 
2356     sqlite3VdbeAddOp1(v, OP_Close, 0);
2357 
2358     /*
2359     ** Initialize zType for the new view or table.
2360     */
2361     if( p->pSelect==0 ){
2362       /* A regular table */
2363       zType = "table";
2364       zType2 = "TABLE";
2365 #ifndef SQLITE_OMIT_VIEW
2366     }else{
2367       /* A view */
2368       zType = "view";
2369       zType2 = "VIEW";
2370 #endif
2371     }
2372 
2373     /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
2374     ** statement to populate the new table. The root-page number for the
2375     ** new table is in register pParse->regRoot.
2376     **
2377     ** Once the SELECT has been coded by sqlite3Select(), it is in a
2378     ** suitable state to query for the column names and types to be used
2379     ** by the new table.
2380     **
2381     ** A shared-cache write-lock is not required to write to the new table,
2382     ** as a schema-lock must have already been obtained to create it. Since
2383     ** a schema-lock excludes all other database users, the write-lock would
2384     ** be redundant.
2385     */
2386     if( pSelect ){
2387       SelectDest dest;    /* Where the SELECT should store results */
2388       int regYield;       /* Register holding co-routine entry-point */
2389       int addrTop;        /* Top of the co-routine */
2390       int regRec;         /* A record to be insert into the new table */
2391       int regRowid;       /* Rowid of the next row to insert */
2392       int addrInsLoop;    /* Top of the loop for inserting rows */
2393       Table *pSelTab;     /* A table that describes the SELECT results */
2394 
2395       regYield = ++pParse->nMem;
2396       regRec = ++pParse->nMem;
2397       regRowid = ++pParse->nMem;
2398       assert(pParse->nTab==1);
2399       sqlite3MayAbort(pParse);
2400       sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb);
2401       sqlite3VdbeChangeP5(v, OPFLAG_P2ISREG);
2402       pParse->nTab = 2;
2403       addrTop = sqlite3VdbeCurrentAddr(v) + 1;
2404       sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, addrTop);
2405       if( pParse->nErr ) return;
2406       pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect, SQLITE_AFF_BLOB);
2407       if( pSelTab==0 ) return;
2408       assert( p->aCol==0 );
2409       p->nCol = p->nNVCol = pSelTab->nCol;
2410       p->aCol = pSelTab->aCol;
2411       pSelTab->nCol = 0;
2412       pSelTab->aCol = 0;
2413       sqlite3DeleteTable(db, pSelTab);
2414       sqlite3SelectDestInit(&dest, SRT_Coroutine, regYield);
2415       sqlite3Select(pParse, pSelect, &dest);
2416       if( pParse->nErr ) return;
2417       sqlite3VdbeEndCoroutine(v, regYield);
2418       sqlite3VdbeJumpHere(v, addrTop - 1);
2419       addrInsLoop = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
2420       VdbeCoverage(v);
2421       sqlite3VdbeAddOp3(v, OP_MakeRecord, dest.iSdst, dest.nSdst, regRec);
2422       sqlite3TableAffinity(v, p, 0);
2423       sqlite3VdbeAddOp2(v, OP_NewRowid, 1, regRowid);
2424       sqlite3VdbeAddOp3(v, OP_Insert, 1, regRec, regRowid);
2425       sqlite3VdbeGoto(v, addrInsLoop);
2426       sqlite3VdbeJumpHere(v, addrInsLoop);
2427       sqlite3VdbeAddOp1(v, OP_Close, 1);
2428     }
2429 
2430     /* Compute the complete text of the CREATE statement */
2431     if( pSelect ){
2432       zStmt = createTableStmt(db, p);
2433     }else{
2434       Token *pEnd2 = tabOpts ? &pParse->sLastToken : pEnd;
2435       n = (int)(pEnd2->z - pParse->sNameToken.z);
2436       if( pEnd2->z[0]!=';' ) n += pEnd2->n;
2437       zStmt = sqlite3MPrintf(db,
2438           "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
2439       );
2440     }
2441 
2442     /* A slot for the record has already been allocated in the
2443     ** SQLITE_MASTER table.  We just need to update that slot with all
2444     ** the information we've collected.
2445     */
2446     sqlite3NestedParse(pParse,
2447       "UPDATE %Q.%s "
2448          "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q "
2449        "WHERE rowid=#%d",
2450       db->aDb[iDb].zDbSName, MASTER_NAME,
2451       zType,
2452       p->zName,
2453       p->zName,
2454       pParse->regRoot,
2455       zStmt,
2456       pParse->regRowid
2457     );
2458     sqlite3DbFree(db, zStmt);
2459     sqlite3ChangeCookie(pParse, iDb);
2460 
2461 #ifndef SQLITE_OMIT_AUTOINCREMENT
2462     /* Check to see if we need to create an sqlite_sequence table for
2463     ** keeping track of autoincrement keys.
2464     */
2465     if( (p->tabFlags & TF_Autoincrement)!=0 ){
2466       Db *pDb = &db->aDb[iDb];
2467       assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
2468       if( pDb->pSchema->pSeqTab==0 ){
2469         sqlite3NestedParse(pParse,
2470           "CREATE TABLE %Q.sqlite_sequence(name,seq)",
2471           pDb->zDbSName
2472         );
2473       }
2474     }
2475 #endif
2476 
2477     /* Reparse everything to update our internal data structures */
2478     sqlite3VdbeAddParseSchemaOp(v, iDb,
2479            sqlite3MPrintf(db, "tbl_name='%q' AND type!='trigger'", p->zName));
2480   }
2481 
2482   /* Add the table to the in-memory representation of the database.
2483   */
2484   if( db->init.busy ){
2485     Table *pOld;
2486     Schema *pSchema = p->pSchema;
2487     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
2488     pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName, p);
2489     if( pOld ){
2490       assert( p==pOld );  /* Malloc must have failed inside HashInsert() */
2491       sqlite3OomFault(db);
2492       return;
2493     }
2494     pParse->pNewTable = 0;
2495     db->mDbFlags |= DBFLAG_SchemaChange;
2496 
2497 #ifndef SQLITE_OMIT_ALTERTABLE
2498     if( !p->pSelect ){
2499       const char *zName = (const char *)pParse->sNameToken.z;
2500       int nName;
2501       assert( !pSelect && pCons && pEnd );
2502       if( pCons->z==0 ){
2503         pCons = pEnd;
2504       }
2505       nName = (int)((const char *)pCons->z - zName);
2506       p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName);
2507     }
2508 #endif
2509   }
2510 }
2511 
2512 #ifndef SQLITE_OMIT_VIEW
2513 /*
2514 ** The parser calls this routine in order to create a new VIEW
2515 */
2516 void sqlite3CreateView(
2517   Parse *pParse,     /* The parsing context */
2518   Token *pBegin,     /* The CREATE token that begins the statement */
2519   Token *pName1,     /* The token that holds the name of the view */
2520   Token *pName2,     /* The token that holds the name of the view */
2521   ExprList *pCNames, /* Optional list of view column names */
2522   Select *pSelect,   /* A SELECT statement that will become the new view */
2523   int isTemp,        /* TRUE for a TEMPORARY view */
2524   int noErr          /* Suppress error messages if VIEW already exists */
2525 ){
2526   Table *p;
2527   int n;
2528   const char *z;
2529   Token sEnd;
2530   DbFixer sFix;
2531   Token *pName = 0;
2532   int iDb;
2533   sqlite3 *db = pParse->db;
2534 
2535   if( pParse->nVar>0 ){
2536     sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
2537     goto create_view_fail;
2538   }
2539   sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
2540   p = pParse->pNewTable;
2541   if( p==0 || pParse->nErr ) goto create_view_fail;
2542   sqlite3TwoPartName(pParse, pName1, pName2, &pName);
2543   iDb = sqlite3SchemaToIndex(db, p->pSchema);
2544   sqlite3FixInit(&sFix, pParse, iDb, "view", pName);
2545   if( sqlite3FixSelect(&sFix, pSelect) ) goto create_view_fail;
2546 
2547   /* Make a copy of the entire SELECT statement that defines the view.
2548   ** This will force all the Expr.token.z values to be dynamically
2549   ** allocated rather than point to the input string - which means that
2550   ** they will persist after the current sqlite3_exec() call returns.
2551   */
2552   pSelect->selFlags |= SF_View;
2553   if( IN_RENAME_OBJECT ){
2554     p->pSelect = pSelect;
2555     pSelect = 0;
2556   }else{
2557     p->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
2558   }
2559   p->pCheck = sqlite3ExprListDup(db, pCNames, EXPRDUP_REDUCE);
2560   if( db->mallocFailed ) goto create_view_fail;
2561 
2562   /* Locate the end of the CREATE VIEW statement.  Make sEnd point to
2563   ** the end.
2564   */
2565   sEnd = pParse->sLastToken;
2566   assert( sEnd.z[0]!=0 || sEnd.n==0 );
2567   if( sEnd.z[0]!=';' ){
2568     sEnd.z += sEnd.n;
2569   }
2570   sEnd.n = 0;
2571   n = (int)(sEnd.z - pBegin->z);
2572   assert( n>0 );
2573   z = pBegin->z;
2574   while( sqlite3Isspace(z[n-1]) ){ n--; }
2575   sEnd.z = &z[n-1];
2576   sEnd.n = 1;
2577 
2578   /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
2579   sqlite3EndTable(pParse, 0, &sEnd, 0, 0);
2580 
2581 create_view_fail:
2582   sqlite3SelectDelete(db, pSelect);
2583   if( IN_RENAME_OBJECT ){
2584     sqlite3RenameExprlistUnmap(pParse, pCNames);
2585   }
2586   sqlite3ExprListDelete(db, pCNames);
2587   return;
2588 }
2589 #endif /* SQLITE_OMIT_VIEW */
2590 
2591 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
2592 /*
2593 ** The Table structure pTable is really a VIEW.  Fill in the names of
2594 ** the columns of the view in the pTable structure.  Return the number
2595 ** of errors.  If an error is seen leave an error message in pParse->zErrMsg.
2596 */
2597 int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
2598   Table *pSelTab;   /* A fake table from which we get the result set */
2599   Select *pSel;     /* Copy of the SELECT that implements the view */
2600   int nErr = 0;     /* Number of errors encountered */
2601   int n;            /* Temporarily holds the number of cursors assigned */
2602   sqlite3 *db = pParse->db;  /* Database connection for malloc errors */
2603 #ifndef SQLITE_OMIT_VIRTUALTABLE
2604   int rc;
2605 #endif
2606 #ifndef SQLITE_OMIT_AUTHORIZATION
2607   sqlite3_xauth xAuth;       /* Saved xAuth pointer */
2608 #endif
2609 
2610   assert( pTable );
2611 
2612 #ifndef SQLITE_OMIT_VIRTUALTABLE
2613   db->nSchemaLock++;
2614   rc = sqlite3VtabCallConnect(pParse, pTable);
2615   db->nSchemaLock--;
2616   if( rc ){
2617     return 1;
2618   }
2619   if( IsVirtual(pTable) ) return 0;
2620 #endif
2621 
2622 #ifndef SQLITE_OMIT_VIEW
2623   /* A positive nCol means the columns names for this view are
2624   ** already known.
2625   */
2626   if( pTable->nCol>0 ) return 0;
2627 
2628   /* A negative nCol is a special marker meaning that we are currently
2629   ** trying to compute the column names.  If we enter this routine with
2630   ** a negative nCol, it means two or more views form a loop, like this:
2631   **
2632   **     CREATE VIEW one AS SELECT * FROM two;
2633   **     CREATE VIEW two AS SELECT * FROM one;
2634   **
2635   ** Actually, the error above is now caught prior to reaching this point.
2636   ** But the following test is still important as it does come up
2637   ** in the following:
2638   **
2639   **     CREATE TABLE main.ex1(a);
2640   **     CREATE TEMP VIEW ex1 AS SELECT a FROM ex1;
2641   **     SELECT * FROM temp.ex1;
2642   */
2643   if( pTable->nCol<0 ){
2644     sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
2645     return 1;
2646   }
2647   assert( pTable->nCol>=0 );
2648 
2649   /* If we get this far, it means we need to compute the table names.
2650   ** Note that the call to sqlite3ResultSetOfSelect() will expand any
2651   ** "*" elements in the results set of the view and will assign cursors
2652   ** to the elements of the FROM clause.  But we do not want these changes
2653   ** to be permanent.  So the computation is done on a copy of the SELECT
2654   ** statement that defines the view.
2655   */
2656   assert( pTable->pSelect );
2657   pSel = sqlite3SelectDup(db, pTable->pSelect, 0);
2658   if( pSel ){
2659 #ifndef SQLITE_OMIT_ALTERTABLE
2660     u8 eParseMode = pParse->eParseMode;
2661     pParse->eParseMode = PARSE_MODE_NORMAL;
2662 #endif
2663     n = pParse->nTab;
2664     sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
2665     pTable->nCol = -1;
2666     DisableLookaside;
2667 #ifndef SQLITE_OMIT_AUTHORIZATION
2668     xAuth = db->xAuth;
2669     db->xAuth = 0;
2670     pSelTab = sqlite3ResultSetOfSelect(pParse, pSel, SQLITE_AFF_NONE);
2671     db->xAuth = xAuth;
2672 #else
2673     pSelTab = sqlite3ResultSetOfSelect(pParse, pSel, SQLITE_AFF_NONE);
2674 #endif
2675     pParse->nTab = n;
2676     if( pSelTab==0 ){
2677       pTable->nCol = 0;
2678       nErr++;
2679     }else if( pTable->pCheck ){
2680       /* CREATE VIEW name(arglist) AS ...
2681       ** The names of the columns in the table are taken from
2682       ** arglist which is stored in pTable->pCheck.  The pCheck field
2683       ** normally holds CHECK constraints on an ordinary table, but for
2684       ** a VIEW it holds the list of column names.
2685       */
2686       sqlite3ColumnsFromExprList(pParse, pTable->pCheck,
2687                                  &pTable->nCol, &pTable->aCol);
2688       if( db->mallocFailed==0
2689        && pParse->nErr==0
2690        && pTable->nCol==pSel->pEList->nExpr
2691       ){
2692         sqlite3SelectAddColumnTypeAndCollation(pParse, pTable, pSel,
2693                                                SQLITE_AFF_NONE);
2694       }
2695     }else{
2696       /* CREATE VIEW name AS...  without an argument list.  Construct
2697       ** the column names from the SELECT statement that defines the view.
2698       */
2699       assert( pTable->aCol==0 );
2700       pTable->nCol = pSelTab->nCol;
2701       pTable->aCol = pSelTab->aCol;
2702       pSelTab->nCol = 0;
2703       pSelTab->aCol = 0;
2704       assert( sqlite3SchemaMutexHeld(db, 0, pTable->pSchema) );
2705     }
2706     pTable->nNVCol = pTable->nCol;
2707     sqlite3DeleteTable(db, pSelTab);
2708     sqlite3SelectDelete(db, pSel);
2709     EnableLookaside;
2710 #ifndef SQLITE_OMIT_ALTERTABLE
2711     pParse->eParseMode = eParseMode;
2712 #endif
2713   } else {
2714     nErr++;
2715   }
2716   pTable->pSchema->schemaFlags |= DB_UnresetViews;
2717   if( db->mallocFailed ){
2718     sqlite3DeleteColumnNames(db, pTable);
2719     pTable->aCol = 0;
2720     pTable->nCol = 0;
2721   }
2722 #endif /* SQLITE_OMIT_VIEW */
2723   return nErr;
2724 }
2725 #endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
2726 
2727 #ifndef SQLITE_OMIT_VIEW
2728 /*
2729 ** Clear the column names from every VIEW in database idx.
2730 */
2731 static void sqliteViewResetAll(sqlite3 *db, int idx){
2732   HashElem *i;
2733   assert( sqlite3SchemaMutexHeld(db, idx, 0) );
2734   if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
2735   for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
2736     Table *pTab = sqliteHashData(i);
2737     if( pTab->pSelect ){
2738       sqlite3DeleteColumnNames(db, pTab);
2739       pTab->aCol = 0;
2740       pTab->nCol = 0;
2741     }
2742   }
2743   DbClearProperty(db, idx, DB_UnresetViews);
2744 }
2745 #else
2746 # define sqliteViewResetAll(A,B)
2747 #endif /* SQLITE_OMIT_VIEW */
2748 
2749 /*
2750 ** This function is called by the VDBE to adjust the internal schema
2751 ** used by SQLite when the btree layer moves a table root page. The
2752 ** root-page of a table or index in database iDb has changed from iFrom
2753 ** to iTo.
2754 **
2755 ** Ticket #1728:  The symbol table might still contain information
2756 ** on tables and/or indices that are the process of being deleted.
2757 ** If you are unlucky, one of those deleted indices or tables might
2758 ** have the same rootpage number as the real table or index that is
2759 ** being moved.  So we cannot stop searching after the first match
2760 ** because the first match might be for one of the deleted indices
2761 ** or tables and not the table/index that is actually being moved.
2762 ** We must continue looping until all tables and indices with
2763 ** rootpage==iFrom have been converted to have a rootpage of iTo
2764 ** in order to be certain that we got the right one.
2765 */
2766 #ifndef SQLITE_OMIT_AUTOVACUUM
2767 void sqlite3RootPageMoved(sqlite3 *db, int iDb, int iFrom, int iTo){
2768   HashElem *pElem;
2769   Hash *pHash;
2770   Db *pDb;
2771 
2772   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
2773   pDb = &db->aDb[iDb];
2774   pHash = &pDb->pSchema->tblHash;
2775   for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
2776     Table *pTab = sqliteHashData(pElem);
2777     if( pTab->tnum==iFrom ){
2778       pTab->tnum = iTo;
2779     }
2780   }
2781   pHash = &pDb->pSchema->idxHash;
2782   for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
2783     Index *pIdx = sqliteHashData(pElem);
2784     if( pIdx->tnum==iFrom ){
2785       pIdx->tnum = iTo;
2786     }
2787   }
2788 }
2789 #endif
2790 
2791 /*
2792 ** Write code to erase the table with root-page iTable from database iDb.
2793 ** Also write code to modify the sqlite_master table and internal schema
2794 ** if a root-page of another table is moved by the btree-layer whilst
2795 ** erasing iTable (this can happen with an auto-vacuum database).
2796 */
2797 static void destroyRootPage(Parse *pParse, int iTable, int iDb){
2798   Vdbe *v = sqlite3GetVdbe(pParse);
2799   int r1 = sqlite3GetTempReg(pParse);
2800   if( iTable<2 ) sqlite3ErrorMsg(pParse, "corrupt schema");
2801   sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
2802   sqlite3MayAbort(pParse);
2803 #ifndef SQLITE_OMIT_AUTOVACUUM
2804   /* OP_Destroy stores an in integer r1. If this integer
2805   ** is non-zero, then it is the root page number of a table moved to
2806   ** location iTable. The following code modifies the sqlite_master table to
2807   ** reflect this.
2808   **
2809   ** The "#NNN" in the SQL is a special constant that means whatever value
2810   ** is in register NNN.  See grammar rules associated with the TK_REGISTER
2811   ** token for additional information.
2812   */
2813   sqlite3NestedParse(pParse,
2814      "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d",
2815      pParse->db->aDb[iDb].zDbSName, MASTER_NAME, iTable, r1, r1);
2816 #endif
2817   sqlite3ReleaseTempReg(pParse, r1);
2818 }
2819 
2820 /*
2821 ** Write VDBE code to erase table pTab and all associated indices on disk.
2822 ** Code to update the sqlite_master tables and internal schema definitions
2823 ** in case a root-page belonging to another table is moved by the btree layer
2824 ** is also added (this can happen with an auto-vacuum database).
2825 */
2826 static void destroyTable(Parse *pParse, Table *pTab){
2827   /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
2828   ** is not defined), then it is important to call OP_Destroy on the
2829   ** table and index root-pages in order, starting with the numerically
2830   ** largest root-page number. This guarantees that none of the root-pages
2831   ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
2832   ** following were coded:
2833   **
2834   ** OP_Destroy 4 0
2835   ** ...
2836   ** OP_Destroy 5 0
2837   **
2838   ** and root page 5 happened to be the largest root-page number in the
2839   ** database, then root page 5 would be moved to page 4 by the
2840   ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
2841   ** a free-list page.
2842   */
2843   int iTab = pTab->tnum;
2844   int iDestroyed = 0;
2845 
2846   while( 1 ){
2847     Index *pIdx;
2848     int iLargest = 0;
2849 
2850     if( iDestroyed==0 || iTab<iDestroyed ){
2851       iLargest = iTab;
2852     }
2853     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
2854       int iIdx = pIdx->tnum;
2855       assert( pIdx->pSchema==pTab->pSchema );
2856       if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
2857         iLargest = iIdx;
2858       }
2859     }
2860     if( iLargest==0 ){
2861       return;
2862     }else{
2863       int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
2864       assert( iDb>=0 && iDb<pParse->db->nDb );
2865       destroyRootPage(pParse, iLargest, iDb);
2866       iDestroyed = iLargest;
2867     }
2868   }
2869 }
2870 
2871 /*
2872 ** Remove entries from the sqlite_statN tables (for N in (1,2,3))
2873 ** after a DROP INDEX or DROP TABLE command.
2874 */
2875 static void sqlite3ClearStatTables(
2876   Parse *pParse,         /* The parsing context */
2877   int iDb,               /* The database number */
2878   const char *zType,     /* "idx" or "tbl" */
2879   const char *zName      /* Name of index or table */
2880 ){
2881   int i;
2882   const char *zDbName = pParse->db->aDb[iDb].zDbSName;
2883   for(i=1; i<=4; i++){
2884     char zTab[24];
2885     sqlite3_snprintf(sizeof(zTab),zTab,"sqlite_stat%d",i);
2886     if( sqlite3FindTable(pParse->db, zTab, zDbName) ){
2887       sqlite3NestedParse(pParse,
2888         "DELETE FROM %Q.%s WHERE %s=%Q",
2889         zDbName, zTab, zType, zName
2890       );
2891     }
2892   }
2893 }
2894 
2895 /*
2896 ** Generate code to drop a table.
2897 */
2898 void sqlite3CodeDropTable(Parse *pParse, Table *pTab, int iDb, int isView){
2899   Vdbe *v;
2900   sqlite3 *db = pParse->db;
2901   Trigger *pTrigger;
2902   Db *pDb = &db->aDb[iDb];
2903 
2904   v = sqlite3GetVdbe(pParse);
2905   assert( v!=0 );
2906   sqlite3BeginWriteOperation(pParse, 1, iDb);
2907 
2908 #ifndef SQLITE_OMIT_VIRTUALTABLE
2909   if( IsVirtual(pTab) ){
2910     sqlite3VdbeAddOp0(v, OP_VBegin);
2911   }
2912 #endif
2913 
2914   /* Drop all triggers associated with the table being dropped. Code
2915   ** is generated to remove entries from sqlite_master and/or
2916   ** sqlite_temp_master if required.
2917   */
2918   pTrigger = sqlite3TriggerList(pParse, pTab);
2919   while( pTrigger ){
2920     assert( pTrigger->pSchema==pTab->pSchema ||
2921         pTrigger->pSchema==db->aDb[1].pSchema );
2922     sqlite3DropTriggerPtr(pParse, pTrigger);
2923     pTrigger = pTrigger->pNext;
2924   }
2925 
2926 #ifndef SQLITE_OMIT_AUTOINCREMENT
2927   /* Remove any entries of the sqlite_sequence table associated with
2928   ** the table being dropped. This is done before the table is dropped
2929   ** at the btree level, in case the sqlite_sequence table needs to
2930   ** move as a result of the drop (can happen in auto-vacuum mode).
2931   */
2932   if( pTab->tabFlags & TF_Autoincrement ){
2933     sqlite3NestedParse(pParse,
2934       "DELETE FROM %Q.sqlite_sequence WHERE name=%Q",
2935       pDb->zDbSName, pTab->zName
2936     );
2937   }
2938 #endif
2939 
2940   /* Drop all SQLITE_MASTER table and index entries that refer to the
2941   ** table. The program name loops through the master table and deletes
2942   ** every row that refers to a table of the same name as the one being
2943   ** dropped. Triggers are handled separately because a trigger can be
2944   ** created in the temp database that refers to a table in another
2945   ** database.
2946   */
2947   sqlite3NestedParse(pParse,
2948       "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
2949       pDb->zDbSName, MASTER_NAME, pTab->zName);
2950   if( !isView && !IsVirtual(pTab) ){
2951     destroyTable(pParse, pTab);
2952   }
2953 
2954   /* Remove the table entry from SQLite's internal schema and modify
2955   ** the schema cookie.
2956   */
2957   if( IsVirtual(pTab) ){
2958     sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
2959     sqlite3MayAbort(pParse);
2960   }
2961   sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
2962   sqlite3ChangeCookie(pParse, iDb);
2963   sqliteViewResetAll(db, iDb);
2964 }
2965 
2966 /*
2967 ** Return TRUE if shadow tables should be read-only in the current
2968 ** context.
2969 */
2970 int sqlite3ReadOnlyShadowTables(sqlite3 *db){
2971 #ifndef SQLITE_OMIT_VIRTUALTABLE
2972   if( (db->flags & SQLITE_Defensive)!=0
2973    && db->pVtabCtx==0
2974    && db->nVdbeExec==0
2975   ){
2976     return 1;
2977   }
2978 #endif
2979   return 0;
2980 }
2981 
2982 /*
2983 ** Return true if it is not allowed to drop the given table
2984 */
2985 static int tableMayNotBeDropped(sqlite3 *db, Table *pTab){
2986   if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
2987     if( sqlite3StrNICmp(pTab->zName+7, "stat", 4)==0 ) return 0;
2988     if( sqlite3StrNICmp(pTab->zName+7, "parameters", 10)==0 ) return 0;
2989     return 1;
2990   }
2991   if( (pTab->tabFlags & TF_Shadow)!=0 && sqlite3ReadOnlyShadowTables(db) ){
2992     return 1;
2993   }
2994   return 0;
2995 }
2996 
2997 /*
2998 ** This routine is called to do the work of a DROP TABLE statement.
2999 ** pName is the name of the table to be dropped.
3000 */
3001 void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
3002   Table *pTab;
3003   Vdbe *v;
3004   sqlite3 *db = pParse->db;
3005   int iDb;
3006 
3007   if( db->mallocFailed ){
3008     goto exit_drop_table;
3009   }
3010   assert( pParse->nErr==0 );
3011   assert( pName->nSrc==1 );
3012   if( sqlite3ReadSchema(pParse) ) goto exit_drop_table;
3013   if( noErr ) db->suppressErr++;
3014   assert( isView==0 || isView==LOCATE_VIEW );
3015   pTab = sqlite3LocateTableItem(pParse, isView, &pName->a[0]);
3016   if( noErr ) db->suppressErr--;
3017 
3018   if( pTab==0 ){
3019     if( noErr ) sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
3020     goto exit_drop_table;
3021   }
3022   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
3023   assert( iDb>=0 && iDb<db->nDb );
3024 
3025   /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
3026   ** it is initialized.
3027   */
3028   if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){
3029     goto exit_drop_table;
3030   }
3031 #ifndef SQLITE_OMIT_AUTHORIZATION
3032   {
3033     int code;
3034     const char *zTab = SCHEMA_TABLE(iDb);
3035     const char *zDb = db->aDb[iDb].zDbSName;
3036     const char *zArg2 = 0;
3037     if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
3038       goto exit_drop_table;
3039     }
3040     if( isView ){
3041       if( !OMIT_TEMPDB && iDb==1 ){
3042         code = SQLITE_DROP_TEMP_VIEW;
3043       }else{
3044         code = SQLITE_DROP_VIEW;
3045       }
3046 #ifndef SQLITE_OMIT_VIRTUALTABLE
3047     }else if( IsVirtual(pTab) ){
3048       code = SQLITE_DROP_VTABLE;
3049       zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName;
3050 #endif
3051     }else{
3052       if( !OMIT_TEMPDB && iDb==1 ){
3053         code = SQLITE_DROP_TEMP_TABLE;
3054       }else{
3055         code = SQLITE_DROP_TABLE;
3056       }
3057     }
3058     if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
3059       goto exit_drop_table;
3060     }
3061     if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
3062       goto exit_drop_table;
3063     }
3064   }
3065 #endif
3066   if( tableMayNotBeDropped(db, pTab) ){
3067     sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
3068     goto exit_drop_table;
3069   }
3070 
3071 #ifndef SQLITE_OMIT_VIEW
3072   /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
3073   ** on a table.
3074   */
3075   if( isView && pTab->pSelect==0 ){
3076     sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
3077     goto exit_drop_table;
3078   }
3079   if( !isView && pTab->pSelect ){
3080     sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
3081     goto exit_drop_table;
3082   }
3083 #endif
3084 
3085   /* Generate code to remove the table from the master table
3086   ** on disk.
3087   */
3088   v = sqlite3GetVdbe(pParse);
3089   if( v ){
3090     sqlite3BeginWriteOperation(pParse, 1, iDb);
3091     if( !isView ){
3092       sqlite3ClearStatTables(pParse, iDb, "tbl", pTab->zName);
3093       sqlite3FkDropTable(pParse, pName, pTab);
3094     }
3095     sqlite3CodeDropTable(pParse, pTab, iDb, isView);
3096   }
3097 
3098 exit_drop_table:
3099   sqlite3SrcListDelete(db, pName);
3100 }
3101 
3102 /*
3103 ** This routine is called to create a new foreign key on the table
3104 ** currently under construction.  pFromCol determines which columns
3105 ** in the current table point to the foreign key.  If pFromCol==0 then
3106 ** connect the key to the last column inserted.  pTo is the name of
3107 ** the table referred to (a.k.a the "parent" table).  pToCol is a list
3108 ** of tables in the parent pTo table.  flags contains all
3109 ** information about the conflict resolution algorithms specified
3110 ** in the ON DELETE, ON UPDATE and ON INSERT clauses.
3111 **
3112 ** An FKey structure is created and added to the table currently
3113 ** under construction in the pParse->pNewTable field.
3114 **
3115 ** The foreign key is set for IMMEDIATE processing.  A subsequent call
3116 ** to sqlite3DeferForeignKey() might change this to DEFERRED.
3117 */
3118 void sqlite3CreateForeignKey(
3119   Parse *pParse,       /* Parsing context */
3120   ExprList *pFromCol,  /* Columns in this table that point to other table */
3121   Token *pTo,          /* Name of the other table */
3122   ExprList *pToCol,    /* Columns in the other table */
3123   int flags            /* Conflict resolution algorithms. */
3124 ){
3125   sqlite3 *db = pParse->db;
3126 #ifndef SQLITE_OMIT_FOREIGN_KEY
3127   FKey *pFKey = 0;
3128   FKey *pNextTo;
3129   Table *p = pParse->pNewTable;
3130   int nByte;
3131   int i;
3132   int nCol;
3133   char *z;
3134 
3135   assert( pTo!=0 );
3136   if( p==0 || IN_DECLARE_VTAB ) goto fk_end;
3137   if( pFromCol==0 ){
3138     int iCol = p->nCol-1;
3139     if( NEVER(iCol<0) ) goto fk_end;
3140     if( pToCol && pToCol->nExpr!=1 ){
3141       sqlite3ErrorMsg(pParse, "foreign key on %s"
3142          " should reference only one column of table %T",
3143          p->aCol[iCol].zName, pTo);
3144       goto fk_end;
3145     }
3146     nCol = 1;
3147   }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
3148     sqlite3ErrorMsg(pParse,
3149         "number of columns in foreign key does not match the number of "
3150         "columns in the referenced table");
3151     goto fk_end;
3152   }else{
3153     nCol = pFromCol->nExpr;
3154   }
3155   nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1;
3156   if( pToCol ){
3157     for(i=0; i<pToCol->nExpr; i++){
3158       nByte += sqlite3Strlen30(pToCol->a[i].zEName) + 1;
3159     }
3160   }
3161   pFKey = sqlite3DbMallocZero(db, nByte );
3162   if( pFKey==0 ){
3163     goto fk_end;
3164   }
3165   pFKey->pFrom = p;
3166   pFKey->pNextFrom = p->pFKey;
3167   z = (char*)&pFKey->aCol[nCol];
3168   pFKey->zTo = z;
3169   if( IN_RENAME_OBJECT ){
3170     sqlite3RenameTokenMap(pParse, (void*)z, pTo);
3171   }
3172   memcpy(z, pTo->z, pTo->n);
3173   z[pTo->n] = 0;
3174   sqlite3Dequote(z);
3175   z += pTo->n+1;
3176   pFKey->nCol = nCol;
3177   if( pFromCol==0 ){
3178     pFKey->aCol[0].iFrom = p->nCol-1;
3179   }else{
3180     for(i=0; i<nCol; i++){
3181       int j;
3182       for(j=0; j<p->nCol; j++){
3183         if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zEName)==0 ){
3184           pFKey->aCol[i].iFrom = j;
3185           break;
3186         }
3187       }
3188       if( j>=p->nCol ){
3189         sqlite3ErrorMsg(pParse,
3190           "unknown column \"%s\" in foreign key definition",
3191           pFromCol->a[i].zEName);
3192         goto fk_end;
3193       }
3194       if( IN_RENAME_OBJECT ){
3195         sqlite3RenameTokenRemap(pParse, &pFKey->aCol[i], pFromCol->a[i].zEName);
3196       }
3197     }
3198   }
3199   if( pToCol ){
3200     for(i=0; i<nCol; i++){
3201       int n = sqlite3Strlen30(pToCol->a[i].zEName);
3202       pFKey->aCol[i].zCol = z;
3203       if( IN_RENAME_OBJECT ){
3204         sqlite3RenameTokenRemap(pParse, z, pToCol->a[i].zEName);
3205       }
3206       memcpy(z, pToCol->a[i].zEName, n);
3207       z[n] = 0;
3208       z += n+1;
3209     }
3210   }
3211   pFKey->isDeferred = 0;
3212   pFKey->aAction[0] = (u8)(flags & 0xff);            /* ON DELETE action */
3213   pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff);    /* ON UPDATE action */
3214 
3215   assert( sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
3216   pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash,
3217       pFKey->zTo, (void *)pFKey
3218   );
3219   if( pNextTo==pFKey ){
3220     sqlite3OomFault(db);
3221     goto fk_end;
3222   }
3223   if( pNextTo ){
3224     assert( pNextTo->pPrevTo==0 );
3225     pFKey->pNextTo = pNextTo;
3226     pNextTo->pPrevTo = pFKey;
3227   }
3228 
3229   /* Link the foreign key to the table as the last step.
3230   */
3231   p->pFKey = pFKey;
3232   pFKey = 0;
3233 
3234 fk_end:
3235   sqlite3DbFree(db, pFKey);
3236 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
3237   sqlite3ExprListDelete(db, pFromCol);
3238   sqlite3ExprListDelete(db, pToCol);
3239 }
3240 
3241 /*
3242 ** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
3243 ** clause is seen as part of a foreign key definition.  The isDeferred
3244 ** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
3245 ** The behavior of the most recently created foreign key is adjusted
3246 ** accordingly.
3247 */
3248 void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
3249 #ifndef SQLITE_OMIT_FOREIGN_KEY
3250   Table *pTab;
3251   FKey *pFKey;
3252   if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
3253   assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */
3254   pFKey->isDeferred = (u8)isDeferred;
3255 #endif
3256 }
3257 
3258 /*
3259 ** Generate code that will erase and refill index *pIdx.  This is
3260 ** used to initialize a newly created index or to recompute the
3261 ** content of an index in response to a REINDEX command.
3262 **
3263 ** if memRootPage is not negative, it means that the index is newly
3264 ** created.  The register specified by memRootPage contains the
3265 ** root page number of the index.  If memRootPage is negative, then
3266 ** the index already exists and must be cleared before being refilled and
3267 ** the root page number of the index is taken from pIndex->tnum.
3268 */
3269 static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
3270   Table *pTab = pIndex->pTable;  /* The table that is indexed */
3271   int iTab = pParse->nTab++;     /* Btree cursor used for pTab */
3272   int iIdx = pParse->nTab++;     /* Btree cursor used for pIndex */
3273   int iSorter;                   /* Cursor opened by OpenSorter (if in use) */
3274   int addr1;                     /* Address of top of loop */
3275   int addr2;                     /* Address to jump to for next iteration */
3276   int tnum;                      /* Root page of index */
3277   int iPartIdxLabel;             /* Jump to this label to skip a row */
3278   Vdbe *v;                       /* Generate code into this virtual machine */
3279   KeyInfo *pKey;                 /* KeyInfo for index */
3280   int regRecord;                 /* Register holding assembled index record */
3281   sqlite3 *db = pParse->db;      /* The database connection */
3282   int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
3283 
3284 #ifndef SQLITE_OMIT_AUTHORIZATION
3285   if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
3286       db->aDb[iDb].zDbSName ) ){
3287     return;
3288   }
3289 #endif
3290 
3291   /* Require a write-lock on the table to perform this operation */
3292   sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
3293 
3294   v = sqlite3GetVdbe(pParse);
3295   if( v==0 ) return;
3296   if( memRootPage>=0 ){
3297     tnum = memRootPage;
3298   }else{
3299     tnum = pIndex->tnum;
3300   }
3301   pKey = sqlite3KeyInfoOfIndex(pParse, pIndex);
3302   assert( pKey!=0 || db->mallocFailed || pParse->nErr );
3303 
3304   /* Open the sorter cursor if we are to use one. */
3305   iSorter = pParse->nTab++;
3306   sqlite3VdbeAddOp4(v, OP_SorterOpen, iSorter, 0, pIndex->nKeyCol, (char*)
3307                     sqlite3KeyInfoRef(pKey), P4_KEYINFO);
3308 
3309   /* Open the table. Loop through all rows of the table, inserting index
3310   ** records into the sorter. */
3311   sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
3312   addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0); VdbeCoverage(v);
3313   regRecord = sqlite3GetTempReg(pParse);
3314   sqlite3MultiWrite(pParse);
3315 
3316   sqlite3GenerateIndexKey(pParse,pIndex,iTab,regRecord,0,&iPartIdxLabel,0,0);
3317   sqlite3VdbeAddOp2(v, OP_SorterInsert, iSorter, regRecord);
3318   sqlite3ResolvePartIdxLabel(pParse, iPartIdxLabel);
3319   sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1); VdbeCoverage(v);
3320   sqlite3VdbeJumpHere(v, addr1);
3321   if( memRootPage<0 ) sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
3322   sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb,
3323                     (char *)pKey, P4_KEYINFO);
3324   sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR|((memRootPage>=0)?OPFLAG_P2ISREG:0));
3325 
3326   addr1 = sqlite3VdbeAddOp2(v, OP_SorterSort, iSorter, 0); VdbeCoverage(v);
3327   if( IsUniqueIndex(pIndex) ){
3328     int j2 = sqlite3VdbeGoto(v, 1);
3329     addr2 = sqlite3VdbeCurrentAddr(v);
3330     sqlite3VdbeVerifyAbortable(v, OE_Abort);
3331     sqlite3VdbeAddOp4Int(v, OP_SorterCompare, iSorter, j2, regRecord,
3332                          pIndex->nKeyCol); VdbeCoverage(v);
3333     sqlite3UniqueConstraint(pParse, OE_Abort, pIndex);
3334     sqlite3VdbeJumpHere(v, j2);
3335   }else{
3336     /* Most CREATE INDEX and REINDEX statements that are not UNIQUE can not
3337     ** abort. The exception is if one of the indexed expressions contains a
3338     ** user function that throws an exception when it is evaluated. But the
3339     ** overhead of adding a statement journal to a CREATE INDEX statement is
3340     ** very small (since most of the pages written do not contain content that
3341     ** needs to be restored if the statement aborts), so we call
3342     ** sqlite3MayAbort() for all CREATE INDEX statements.  */
3343     sqlite3MayAbort(pParse);
3344     addr2 = sqlite3VdbeCurrentAddr(v);
3345   }
3346   sqlite3VdbeAddOp3(v, OP_SorterData, iSorter, regRecord, iIdx);
3347   if( !pIndex->bAscKeyBug ){
3348     /* This OP_SeekEnd opcode makes index insert for a REINDEX go much
3349     ** faster by avoiding unnecessary seeks.  But the optimization does
3350     ** not work for UNIQUE constraint indexes on WITHOUT ROWID tables
3351     ** with DESC primary keys, since those indexes have there keys in
3352     ** a different order from the main table.
3353     ** See ticket: https://www.sqlite.org/src/info/bba7b69f9849b5bf
3354     */
3355     sqlite3VdbeAddOp1(v, OP_SeekEnd, iIdx);
3356   }
3357   sqlite3VdbeAddOp2(v, OP_IdxInsert, iIdx, regRecord);
3358   sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
3359   sqlite3ReleaseTempReg(pParse, regRecord);
3360   sqlite3VdbeAddOp2(v, OP_SorterNext, iSorter, addr2); VdbeCoverage(v);
3361   sqlite3VdbeJumpHere(v, addr1);
3362 
3363   sqlite3VdbeAddOp1(v, OP_Close, iTab);
3364   sqlite3VdbeAddOp1(v, OP_Close, iIdx);
3365   sqlite3VdbeAddOp1(v, OP_Close, iSorter);
3366 }
3367 
3368 /*
3369 ** Allocate heap space to hold an Index object with nCol columns.
3370 **
3371 ** Increase the allocation size to provide an extra nExtra bytes
3372 ** of 8-byte aligned space after the Index object and return a
3373 ** pointer to this extra space in *ppExtra.
3374 */
3375 Index *sqlite3AllocateIndexObject(
3376   sqlite3 *db,         /* Database connection */
3377   i16 nCol,            /* Total number of columns in the index */
3378   int nExtra,          /* Number of bytes of extra space to alloc */
3379   char **ppExtra       /* Pointer to the "extra" space */
3380 ){
3381   Index *p;            /* Allocated index object */
3382   int nByte;           /* Bytes of space for Index object + arrays */
3383 
3384   nByte = ROUND8(sizeof(Index)) +              /* Index structure  */
3385           ROUND8(sizeof(char*)*nCol) +         /* Index.azColl     */
3386           ROUND8(sizeof(LogEst)*(nCol+1) +     /* Index.aiRowLogEst   */
3387                  sizeof(i16)*nCol +            /* Index.aiColumn   */
3388                  sizeof(u8)*nCol);             /* Index.aSortOrder */
3389   p = sqlite3DbMallocZero(db, nByte + nExtra);
3390   if( p ){
3391     char *pExtra = ((char*)p)+ROUND8(sizeof(Index));
3392     p->azColl = (const char**)pExtra; pExtra += ROUND8(sizeof(char*)*nCol);
3393     p->aiRowLogEst = (LogEst*)pExtra; pExtra += sizeof(LogEst)*(nCol+1);
3394     p->aiColumn = (i16*)pExtra;       pExtra += sizeof(i16)*nCol;
3395     p->aSortOrder = (u8*)pExtra;
3396     p->nColumn = nCol;
3397     p->nKeyCol = nCol - 1;
3398     *ppExtra = ((char*)p) + nByte;
3399   }
3400   return p;
3401 }
3402 
3403 /*
3404 ** If expression list pList contains an expression that was parsed with
3405 ** an explicit "NULLS FIRST" or "NULLS LAST" clause, leave an error in
3406 ** pParse and return non-zero. Otherwise, return zero.
3407 */
3408 int sqlite3HasExplicitNulls(Parse *pParse, ExprList *pList){
3409   if( pList ){
3410     int i;
3411     for(i=0; i<pList->nExpr; i++){
3412       if( pList->a[i].bNulls ){
3413         u8 sf = pList->a[i].sortFlags;
3414         sqlite3ErrorMsg(pParse, "unsupported use of NULLS %s",
3415             (sf==0 || sf==3) ? "FIRST" : "LAST"
3416         );
3417         return 1;
3418       }
3419     }
3420   }
3421   return 0;
3422 }
3423 
3424 /*
3425 ** Create a new index for an SQL table.  pName1.pName2 is the name of the index
3426 ** and pTblList is the name of the table that is to be indexed.  Both will
3427 ** be NULL for a primary key or an index that is created to satisfy a
3428 ** UNIQUE constraint.  If pTable and pIndex are NULL, use pParse->pNewTable
3429 ** as the table to be indexed.  pParse->pNewTable is a table that is
3430 ** currently being constructed by a CREATE TABLE statement.
3431 **
3432 ** pList is a list of columns to be indexed.  pList will be NULL if this
3433 ** is a primary key or unique-constraint on the most recent column added
3434 ** to the table currently under construction.
3435 */
3436 void sqlite3CreateIndex(
3437   Parse *pParse,     /* All information about this parse */
3438   Token *pName1,     /* First part of index name. May be NULL */
3439   Token *pName2,     /* Second part of index name. May be NULL */
3440   SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
3441   ExprList *pList,   /* A list of columns to be indexed */
3442   int onError,       /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
3443   Token *pStart,     /* The CREATE token that begins this statement */
3444   Expr *pPIWhere,    /* WHERE clause for partial indices */
3445   int sortOrder,     /* Sort order of primary key when pList==NULL */
3446   int ifNotExist,    /* Omit error if index already exists */
3447   u8 idxType         /* The index type */
3448 ){
3449   Table *pTab = 0;     /* Table to be indexed */
3450   Index *pIndex = 0;   /* The index to be created */
3451   char *zName = 0;     /* Name of the index */
3452   int nName;           /* Number of characters in zName */
3453   int i, j;
3454   DbFixer sFix;        /* For assigning database names to pTable */
3455   int sortOrderMask;   /* 1 to honor DESC in index.  0 to ignore. */
3456   sqlite3 *db = pParse->db;
3457   Db *pDb;             /* The specific table containing the indexed database */
3458   int iDb;             /* Index of the database that is being written */
3459   Token *pName = 0;    /* Unqualified name of the index to create */
3460   struct ExprList_item *pListItem; /* For looping over pList */
3461   int nExtra = 0;                  /* Space allocated for zExtra[] */
3462   int nExtraCol;                   /* Number of extra columns needed */
3463   char *zExtra = 0;                /* Extra space after the Index object */
3464   Index *pPk = 0;      /* PRIMARY KEY index for WITHOUT ROWID tables */
3465 
3466   if( db->mallocFailed || pParse->nErr>0 ){
3467     goto exit_create_index;
3468   }
3469   if( IN_DECLARE_VTAB && idxType!=SQLITE_IDXTYPE_PRIMARYKEY ){
3470     goto exit_create_index;
3471   }
3472   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
3473     goto exit_create_index;
3474   }
3475   if( sqlite3HasExplicitNulls(pParse, pList) ){
3476     goto exit_create_index;
3477   }
3478 
3479   /*
3480   ** Find the table that is to be indexed.  Return early if not found.
3481   */
3482   if( pTblName!=0 ){
3483 
3484     /* Use the two-part index name to determine the database
3485     ** to search for the table. 'Fix' the table name to this db
3486     ** before looking up the table.
3487     */
3488     assert( pName1 && pName2 );
3489     iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
3490     if( iDb<0 ) goto exit_create_index;
3491     assert( pName && pName->z );
3492 
3493 #ifndef SQLITE_OMIT_TEMPDB
3494     /* If the index name was unqualified, check if the table
3495     ** is a temp table. If so, set the database to 1. Do not do this
3496     ** if initialising a database schema.
3497     */
3498     if( !db->init.busy ){
3499       pTab = sqlite3SrcListLookup(pParse, pTblName);
3500       if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
3501         iDb = 1;
3502       }
3503     }
3504 #endif
3505 
3506     sqlite3FixInit(&sFix, pParse, iDb, "index", pName);
3507     if( sqlite3FixSrcList(&sFix, pTblName) ){
3508       /* Because the parser constructs pTblName from a single identifier,
3509       ** sqlite3FixSrcList can never fail. */
3510       assert(0);
3511     }
3512     pTab = sqlite3LocateTableItem(pParse, 0, &pTblName->a[0]);
3513     assert( db->mallocFailed==0 || pTab==0 );
3514     if( pTab==0 ) goto exit_create_index;
3515     if( iDb==1 && db->aDb[iDb].pSchema!=pTab->pSchema ){
3516       sqlite3ErrorMsg(pParse,
3517            "cannot create a TEMP index on non-TEMP table \"%s\"",
3518            pTab->zName);
3519       goto exit_create_index;
3520     }
3521     if( !HasRowid(pTab) ) pPk = sqlite3PrimaryKeyIndex(pTab);
3522   }else{
3523     assert( pName==0 );
3524     assert( pStart==0 );
3525     pTab = pParse->pNewTable;
3526     if( !pTab ) goto exit_create_index;
3527     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
3528   }
3529   pDb = &db->aDb[iDb];
3530 
3531   assert( pTab!=0 );
3532   assert( pParse->nErr==0 );
3533   if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
3534        && db->init.busy==0
3535        && pTblName!=0
3536 #if SQLITE_USER_AUTHENTICATION
3537        && sqlite3UserAuthTable(pTab->zName)==0
3538 #endif
3539 #ifdef SQLITE_ALLOW_SQLITE_MASTER_INDEX
3540        && sqlite3StrICmp(&pTab->zName[7],"master")!=0
3541 #endif
3542  ){
3543     sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
3544     goto exit_create_index;
3545   }
3546 #ifndef SQLITE_OMIT_VIEW
3547   if( pTab->pSelect ){
3548     sqlite3ErrorMsg(pParse, "views may not be indexed");
3549     goto exit_create_index;
3550   }
3551 #endif
3552 #ifndef SQLITE_OMIT_VIRTUALTABLE
3553   if( IsVirtual(pTab) ){
3554     sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
3555     goto exit_create_index;
3556   }
3557 #endif
3558 
3559   /*
3560   ** Find the name of the index.  Make sure there is not already another
3561   ** index or table with the same name.
3562   **
3563   ** Exception:  If we are reading the names of permanent indices from the
3564   ** sqlite_master table (because some other process changed the schema) and
3565   ** one of the index names collides with the name of a temporary table or
3566   ** index, then we will continue to process this index.
3567   **
3568   ** If pName==0 it means that we are
3569   ** dealing with a primary key or UNIQUE constraint.  We have to invent our
3570   ** own name.
3571   */
3572   if( pName ){
3573     zName = sqlite3NameFromToken(db, pName);
3574     if( zName==0 ) goto exit_create_index;
3575     assert( pName->z!=0 );
3576     if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName,"index",pTab->zName) ){
3577       goto exit_create_index;
3578     }
3579     if( !IN_RENAME_OBJECT ){
3580       if( !db->init.busy ){
3581         if( sqlite3FindTable(db, zName, 0)!=0 ){
3582           sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
3583           goto exit_create_index;
3584         }
3585       }
3586       if( sqlite3FindIndex(db, zName, pDb->zDbSName)!=0 ){
3587         if( !ifNotExist ){
3588           sqlite3ErrorMsg(pParse, "index %s already exists", zName);
3589         }else{
3590           assert( !db->init.busy );
3591           sqlite3CodeVerifySchema(pParse, iDb);
3592         }
3593         goto exit_create_index;
3594       }
3595     }
3596   }else{
3597     int n;
3598     Index *pLoop;
3599     for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
3600     zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n);
3601     if( zName==0 ){
3602       goto exit_create_index;
3603     }
3604 
3605     /* Automatic index names generated from within sqlite3_declare_vtab()
3606     ** must have names that are distinct from normal automatic index names.
3607     ** The following statement converts "sqlite3_autoindex..." into
3608     ** "sqlite3_butoindex..." in order to make the names distinct.
3609     ** The "vtab_err.test" test demonstrates the need of this statement. */
3610     if( IN_SPECIAL_PARSE ) zName[7]++;
3611   }
3612 
3613   /* Check for authorization to create an index.
3614   */
3615 #ifndef SQLITE_OMIT_AUTHORIZATION
3616   if( !IN_RENAME_OBJECT ){
3617     const char *zDb = pDb->zDbSName;
3618     if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
3619       goto exit_create_index;
3620     }
3621     i = SQLITE_CREATE_INDEX;
3622     if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
3623     if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
3624       goto exit_create_index;
3625     }
3626   }
3627 #endif
3628 
3629   /* If pList==0, it means this routine was called to make a primary
3630   ** key out of the last column added to the table under construction.
3631   ** So create a fake list to simulate this.
3632   */
3633   if( pList==0 ){
3634     Token prevCol;
3635     Column *pCol = &pTab->aCol[pTab->nCol-1];
3636     pCol->colFlags |= COLFLAG_UNIQUE;
3637     sqlite3TokenInit(&prevCol, pCol->zName);
3638     pList = sqlite3ExprListAppend(pParse, 0,
3639               sqlite3ExprAlloc(db, TK_ID, &prevCol, 0));
3640     if( pList==0 ) goto exit_create_index;
3641     assert( pList->nExpr==1 );
3642     sqlite3ExprListSetSortOrder(pList, sortOrder, SQLITE_SO_UNDEFINED);
3643   }else{
3644     sqlite3ExprListCheckLength(pParse, pList, "index");
3645     if( pParse->nErr ) goto exit_create_index;
3646   }
3647 
3648   /* Figure out how many bytes of space are required to store explicitly
3649   ** specified collation sequence names.
3650   */
3651   for(i=0; i<pList->nExpr; i++){
3652     Expr *pExpr = pList->a[i].pExpr;
3653     assert( pExpr!=0 );
3654     if( pExpr->op==TK_COLLATE ){
3655       nExtra += (1 + sqlite3Strlen30(pExpr->u.zToken));
3656     }
3657   }
3658 
3659   /*
3660   ** Allocate the index structure.
3661   */
3662   nName = sqlite3Strlen30(zName);
3663   nExtraCol = pPk ? pPk->nKeyCol : 1;
3664   assert( pList->nExpr + nExtraCol <= 32767 /* Fits in i16 */ );
3665   pIndex = sqlite3AllocateIndexObject(db, pList->nExpr + nExtraCol,
3666                                       nName + nExtra + 1, &zExtra);
3667   if( db->mallocFailed ){
3668     goto exit_create_index;
3669   }
3670   assert( EIGHT_BYTE_ALIGNMENT(pIndex->aiRowLogEst) );
3671   assert( EIGHT_BYTE_ALIGNMENT(pIndex->azColl) );
3672   pIndex->zName = zExtra;
3673   zExtra += nName + 1;
3674   memcpy(pIndex->zName, zName, nName+1);
3675   pIndex->pTable = pTab;
3676   pIndex->onError = (u8)onError;
3677   pIndex->uniqNotNull = onError!=OE_None;
3678   pIndex->idxType = idxType;
3679   pIndex->pSchema = db->aDb[iDb].pSchema;
3680   pIndex->nKeyCol = pList->nExpr;
3681   if( pPIWhere ){
3682     sqlite3ResolveSelfReference(pParse, pTab, NC_PartIdx, pPIWhere, 0);
3683     pIndex->pPartIdxWhere = pPIWhere;
3684     pPIWhere = 0;
3685   }
3686   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
3687 
3688   /* Check to see if we should honor DESC requests on index columns
3689   */
3690   if( pDb->pSchema->file_format>=4 ){
3691     sortOrderMask = -1;   /* Honor DESC */
3692   }else{
3693     sortOrderMask = 0;    /* Ignore DESC */
3694   }
3695 
3696   /* Analyze the list of expressions that form the terms of the index and
3697   ** report any errors.  In the common case where the expression is exactly
3698   ** a table column, store that column in aiColumn[].  For general expressions,
3699   ** populate pIndex->aColExpr and store XN_EXPR (-2) in aiColumn[].
3700   **
3701   ** TODO: Issue a warning if two or more columns of the index are identical.
3702   ** TODO: Issue a warning if the table primary key is used as part of the
3703   ** index key.
3704   */
3705   pListItem = pList->a;
3706   if( IN_RENAME_OBJECT ){
3707     pIndex->aColExpr = pList;
3708     pList = 0;
3709   }
3710   for(i=0; i<pIndex->nKeyCol; i++, pListItem++){
3711     Expr *pCExpr;                  /* The i-th index expression */
3712     int requestedSortOrder;        /* ASC or DESC on the i-th expression */
3713     const char *zColl;             /* Collation sequence name */
3714 
3715     sqlite3StringToId(pListItem->pExpr);
3716     sqlite3ResolveSelfReference(pParse, pTab, NC_IdxExpr, pListItem->pExpr, 0);
3717     if( pParse->nErr ) goto exit_create_index;
3718     pCExpr = sqlite3ExprSkipCollate(pListItem->pExpr);
3719     if( pCExpr->op!=TK_COLUMN ){
3720       if( pTab==pParse->pNewTable ){
3721         sqlite3ErrorMsg(pParse, "expressions prohibited in PRIMARY KEY and "
3722                                 "UNIQUE constraints");
3723         goto exit_create_index;
3724       }
3725       if( pIndex->aColExpr==0 ){
3726         pIndex->aColExpr = pList;
3727         pList = 0;
3728       }
3729       j = XN_EXPR;
3730       pIndex->aiColumn[i] = XN_EXPR;
3731       pIndex->uniqNotNull = 0;
3732     }else{
3733       j = pCExpr->iColumn;
3734       assert( j<=0x7fff );
3735       if( j<0 ){
3736         j = pTab->iPKey;
3737       }else{
3738         if( pTab->aCol[j].notNull==0 ){
3739           pIndex->uniqNotNull = 0;
3740         }
3741         if( pTab->aCol[j].colFlags & COLFLAG_VIRTUAL ){
3742           pIndex->bHasVCol = 1;
3743         }
3744       }
3745       pIndex->aiColumn[i] = (i16)j;
3746     }
3747     zColl = 0;
3748     if( pListItem->pExpr->op==TK_COLLATE ){
3749       int nColl;
3750       zColl = pListItem->pExpr->u.zToken;
3751       nColl = sqlite3Strlen30(zColl) + 1;
3752       assert( nExtra>=nColl );
3753       memcpy(zExtra, zColl, nColl);
3754       zColl = zExtra;
3755       zExtra += nColl;
3756       nExtra -= nColl;
3757     }else if( j>=0 ){
3758       zColl = pTab->aCol[j].zColl;
3759     }
3760     if( !zColl ) zColl = sqlite3StrBINARY;
3761     if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){
3762       goto exit_create_index;
3763     }
3764     pIndex->azColl[i] = zColl;
3765     requestedSortOrder = pListItem->sortFlags & sortOrderMask;
3766     pIndex->aSortOrder[i] = (u8)requestedSortOrder;
3767   }
3768 
3769   /* Append the table key to the end of the index.  For WITHOUT ROWID
3770   ** tables (when pPk!=0) this will be the declared PRIMARY KEY.  For
3771   ** normal tables (when pPk==0) this will be the rowid.
3772   */
3773   if( pPk ){
3774     for(j=0; j<pPk->nKeyCol; j++){
3775       int x = pPk->aiColumn[j];
3776       assert( x>=0 );
3777       if( isDupColumn(pIndex, pIndex->nKeyCol, pPk, j) ){
3778         pIndex->nColumn--;
3779       }else{
3780         testcase( hasColumn(pIndex->aiColumn,pIndex->nKeyCol,x) );
3781         pIndex->aiColumn[i] = x;
3782         pIndex->azColl[i] = pPk->azColl[j];
3783         pIndex->aSortOrder[i] = pPk->aSortOrder[j];
3784         i++;
3785       }
3786     }
3787     assert( i==pIndex->nColumn );
3788   }else{
3789     pIndex->aiColumn[i] = XN_ROWID;
3790     pIndex->azColl[i] = sqlite3StrBINARY;
3791   }
3792   sqlite3DefaultRowEst(pIndex);
3793   if( pParse->pNewTable==0 ) estimateIndexWidth(pIndex);
3794 
3795   /* If this index contains every column of its table, then mark
3796   ** it as a covering index */
3797   assert( HasRowid(pTab)
3798       || pTab->iPKey<0 || sqlite3TableColumnToIndex(pIndex, pTab->iPKey)>=0 );
3799   recomputeColumnsNotIndexed(pIndex);
3800   if( pTblName!=0 && pIndex->nColumn>=pTab->nCol ){
3801     pIndex->isCovering = 1;
3802     for(j=0; j<pTab->nCol; j++){
3803       if( j==pTab->iPKey ) continue;
3804       if( sqlite3TableColumnToIndex(pIndex,j)>=0 ) continue;
3805       pIndex->isCovering = 0;
3806       break;
3807     }
3808   }
3809 
3810   if( pTab==pParse->pNewTable ){
3811     /* This routine has been called to create an automatic index as a
3812     ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
3813     ** a PRIMARY KEY or UNIQUE clause following the column definitions.
3814     ** i.e. one of:
3815     **
3816     ** CREATE TABLE t(x PRIMARY KEY, y);
3817     ** CREATE TABLE t(x, y, UNIQUE(x, y));
3818     **
3819     ** Either way, check to see if the table already has such an index. If
3820     ** so, don't bother creating this one. This only applies to
3821     ** automatically created indices. Users can do as they wish with
3822     ** explicit indices.
3823     **
3824     ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent
3825     ** (and thus suppressing the second one) even if they have different
3826     ** sort orders.
3827     **
3828     ** If there are different collating sequences or if the columns of
3829     ** the constraint occur in different orders, then the constraints are
3830     ** considered distinct and both result in separate indices.
3831     */
3832     Index *pIdx;
3833     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
3834       int k;
3835       assert( IsUniqueIndex(pIdx) );
3836       assert( pIdx->idxType!=SQLITE_IDXTYPE_APPDEF );
3837       assert( IsUniqueIndex(pIndex) );
3838 
3839       if( pIdx->nKeyCol!=pIndex->nKeyCol ) continue;
3840       for(k=0; k<pIdx->nKeyCol; k++){
3841         const char *z1;
3842         const char *z2;
3843         assert( pIdx->aiColumn[k]>=0 );
3844         if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
3845         z1 = pIdx->azColl[k];
3846         z2 = pIndex->azColl[k];
3847         if( sqlite3StrICmp(z1, z2) ) break;
3848       }
3849       if( k==pIdx->nKeyCol ){
3850         if( pIdx->onError!=pIndex->onError ){
3851           /* This constraint creates the same index as a previous
3852           ** constraint specified somewhere in the CREATE TABLE statement.
3853           ** However the ON CONFLICT clauses are different. If both this
3854           ** constraint and the previous equivalent constraint have explicit
3855           ** ON CONFLICT clauses this is an error. Otherwise, use the
3856           ** explicitly specified behavior for the index.
3857           */
3858           if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
3859             sqlite3ErrorMsg(pParse,
3860                 "conflicting ON CONFLICT clauses specified", 0);
3861           }
3862           if( pIdx->onError==OE_Default ){
3863             pIdx->onError = pIndex->onError;
3864           }
3865         }
3866         if( idxType==SQLITE_IDXTYPE_PRIMARYKEY ) pIdx->idxType = idxType;
3867         if( IN_RENAME_OBJECT ){
3868           pIndex->pNext = pParse->pNewIndex;
3869           pParse->pNewIndex = pIndex;
3870           pIndex = 0;
3871         }
3872         goto exit_create_index;
3873       }
3874     }
3875   }
3876 
3877   if( !IN_RENAME_OBJECT ){
3878 
3879     /* Link the new Index structure to its table and to the other
3880     ** in-memory database structures.
3881     */
3882     assert( pParse->nErr==0 );
3883     if( db->init.busy ){
3884       Index *p;
3885       assert( !IN_SPECIAL_PARSE );
3886       assert( sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
3887       if( pTblName!=0 ){
3888         pIndex->tnum = db->init.newTnum;
3889         if( sqlite3IndexHasDuplicateRootPage(pIndex) ){
3890           sqlite3ErrorMsg(pParse, "invalid rootpage");
3891           pParse->rc = SQLITE_CORRUPT_BKPT;
3892           goto exit_create_index;
3893         }
3894       }
3895       p = sqlite3HashInsert(&pIndex->pSchema->idxHash,
3896           pIndex->zName, pIndex);
3897       if( p ){
3898         assert( p==pIndex );  /* Malloc must have failed */
3899         sqlite3OomFault(db);
3900         goto exit_create_index;
3901       }
3902       db->mDbFlags |= DBFLAG_SchemaChange;
3903     }
3904 
3905     /* If this is the initial CREATE INDEX statement (or CREATE TABLE if the
3906     ** index is an implied index for a UNIQUE or PRIMARY KEY constraint) then
3907     ** emit code to allocate the index rootpage on disk and make an entry for
3908     ** the index in the sqlite_master table and populate the index with
3909     ** content.  But, do not do this if we are simply reading the sqlite_master
3910     ** table to parse the schema, or if this index is the PRIMARY KEY index
3911     ** of a WITHOUT ROWID table.
3912     **
3913     ** If pTblName==0 it means this index is generated as an implied PRIMARY KEY
3914     ** or UNIQUE index in a CREATE TABLE statement.  Since the table
3915     ** has just been created, it contains no data and the index initialization
3916     ** step can be skipped.
3917     */
3918     else if( HasRowid(pTab) || pTblName!=0 ){
3919       Vdbe *v;
3920       char *zStmt;
3921       int iMem = ++pParse->nMem;
3922 
3923       v = sqlite3GetVdbe(pParse);
3924       if( v==0 ) goto exit_create_index;
3925 
3926       sqlite3BeginWriteOperation(pParse, 1, iDb);
3927 
3928       /* Create the rootpage for the index using CreateIndex. But before
3929       ** doing so, code a Noop instruction and store its address in
3930       ** Index.tnum. This is required in case this index is actually a
3931       ** PRIMARY KEY and the table is actually a WITHOUT ROWID table. In
3932       ** that case the convertToWithoutRowidTable() routine will replace
3933       ** the Noop with a Goto to jump over the VDBE code generated below. */
3934       pIndex->tnum = sqlite3VdbeAddOp0(v, OP_Noop);
3935       sqlite3VdbeAddOp3(v, OP_CreateBtree, iDb, iMem, BTREE_BLOBKEY);
3936 
3937       /* Gather the complete text of the CREATE INDEX statement into
3938       ** the zStmt variable
3939       */
3940       assert( pName!=0 || pStart==0 );
3941       if( pStart ){
3942         int n = (int)(pParse->sLastToken.z - pName->z) + pParse->sLastToken.n;
3943         if( pName->z[n-1]==';' ) n--;
3944         /* A named index with an explicit CREATE INDEX statement */
3945         zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
3946             onError==OE_None ? "" : " UNIQUE", n, pName->z);
3947       }else{
3948         /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
3949         /* zStmt = sqlite3MPrintf(""); */
3950         zStmt = 0;
3951       }
3952 
3953       /* Add an entry in sqlite_master for this index
3954       */
3955       sqlite3NestedParse(pParse,
3956           "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);",
3957           db->aDb[iDb].zDbSName, MASTER_NAME,
3958           pIndex->zName,
3959           pTab->zName,
3960           iMem,
3961           zStmt
3962           );
3963       sqlite3DbFree(db, zStmt);
3964 
3965       /* Fill the index with data and reparse the schema. Code an OP_Expire
3966       ** to invalidate all pre-compiled statements.
3967       */
3968       if( pTblName ){
3969         sqlite3RefillIndex(pParse, pIndex, iMem);
3970         sqlite3ChangeCookie(pParse, iDb);
3971         sqlite3VdbeAddParseSchemaOp(v, iDb,
3972             sqlite3MPrintf(db, "name='%q' AND type='index'", pIndex->zName));
3973         sqlite3VdbeAddOp2(v, OP_Expire, 0, 1);
3974       }
3975 
3976       sqlite3VdbeJumpHere(v, pIndex->tnum);
3977     }
3978   }
3979   if( db->init.busy || pTblName==0 ){
3980     pIndex->pNext = pTab->pIndex;
3981     pTab->pIndex = pIndex;
3982     pIndex = 0;
3983   }
3984   else if( IN_RENAME_OBJECT ){
3985     assert( pParse->pNewIndex==0 );
3986     pParse->pNewIndex = pIndex;
3987     pIndex = 0;
3988   }
3989 
3990   /* Clean up before exiting */
3991 exit_create_index:
3992   if( pIndex ) sqlite3FreeIndex(db, pIndex);
3993   if( pTab ){  /* Ensure all REPLACE indexes are at the end of the list */
3994     Index **ppFrom = &pTab->pIndex;
3995     Index *pThis;
3996     for(ppFrom=&pTab->pIndex; (pThis = *ppFrom)!=0; ppFrom=&pThis->pNext){
3997       Index *pNext;
3998       if( pThis->onError!=OE_Replace ) continue;
3999       while( (pNext = pThis->pNext)!=0 && pNext->onError!=OE_Replace ){
4000         *ppFrom = pNext;
4001         pThis->pNext = pNext->pNext;
4002         pNext->pNext = pThis;
4003         ppFrom = &pNext->pNext;
4004       }
4005       break;
4006     }
4007   }
4008   sqlite3ExprDelete(db, pPIWhere);
4009   sqlite3ExprListDelete(db, pList);
4010   sqlite3SrcListDelete(db, pTblName);
4011   sqlite3DbFree(db, zName);
4012 }
4013 
4014 /*
4015 ** Fill the Index.aiRowEst[] array with default information - information
4016 ** to be used when we have not run the ANALYZE command.
4017 **
4018 ** aiRowEst[0] is supposed to contain the number of elements in the index.
4019 ** Since we do not know, guess 1 million.  aiRowEst[1] is an estimate of the
4020 ** number of rows in the table that match any particular value of the
4021 ** first column of the index.  aiRowEst[2] is an estimate of the number
4022 ** of rows that match any particular combination of the first 2 columns
4023 ** of the index.  And so forth.  It must always be the case that
4024 *
4025 **           aiRowEst[N]<=aiRowEst[N-1]
4026 **           aiRowEst[N]>=1
4027 **
4028 ** Apart from that, we have little to go on besides intuition as to
4029 ** how aiRowEst[] should be initialized.  The numbers generated here
4030 ** are based on typical values found in actual indices.
4031 */
4032 void sqlite3DefaultRowEst(Index *pIdx){
4033   /*                10,  9,  8,  7,  6 */
4034   LogEst aVal[] = { 33, 32, 30, 28, 26 };
4035   LogEst *a = pIdx->aiRowLogEst;
4036   int nCopy = MIN(ArraySize(aVal), pIdx->nKeyCol);
4037   int i;
4038 
4039   /* Indexes with default row estimates should not have stat1 data */
4040   assert( !pIdx->hasStat1 );
4041 
4042   /* Set the first entry (number of rows in the index) to the estimated
4043   ** number of rows in the table, or half the number of rows in the table
4044   ** for a partial index.   But do not let the estimate drop below 10. */
4045   a[0] = pIdx->pTable->nRowLogEst;
4046   if( pIdx->pPartIdxWhere!=0 ) a[0] -= 10;  assert( 10==sqlite3LogEst(2) );
4047   if( a[0]<33 ) a[0] = 33;                  assert( 33==sqlite3LogEst(10) );
4048 
4049   /* Estimate that a[1] is 10, a[2] is 9, a[3] is 8, a[4] is 7, a[5] is
4050   ** 6 and each subsequent value (if any) is 5.  */
4051   memcpy(&a[1], aVal, nCopy*sizeof(LogEst));
4052   for(i=nCopy+1; i<=pIdx->nKeyCol; i++){
4053     a[i] = 23;                    assert( 23==sqlite3LogEst(5) );
4054   }
4055 
4056   assert( 0==sqlite3LogEst(1) );
4057   if( IsUniqueIndex(pIdx) ) a[pIdx->nKeyCol] = 0;
4058 }
4059 
4060 /*
4061 ** This routine will drop an existing named index.  This routine
4062 ** implements the DROP INDEX statement.
4063 */
4064 void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
4065   Index *pIndex;
4066   Vdbe *v;
4067   sqlite3 *db = pParse->db;
4068   int iDb;
4069 
4070   assert( pParse->nErr==0 );   /* Never called with prior errors */
4071   if( db->mallocFailed ){
4072     goto exit_drop_index;
4073   }
4074   assert( pName->nSrc==1 );
4075   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
4076     goto exit_drop_index;
4077   }
4078   pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
4079   if( pIndex==0 ){
4080     if( !ifExists ){
4081       sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
4082     }else{
4083       sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
4084     }
4085     pParse->checkSchema = 1;
4086     goto exit_drop_index;
4087   }
4088   if( pIndex->idxType!=SQLITE_IDXTYPE_APPDEF ){
4089     sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
4090       "or PRIMARY KEY constraint cannot be dropped", 0);
4091     goto exit_drop_index;
4092   }
4093   iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
4094 #ifndef SQLITE_OMIT_AUTHORIZATION
4095   {
4096     int code = SQLITE_DROP_INDEX;
4097     Table *pTab = pIndex->pTable;
4098     const char *zDb = db->aDb[iDb].zDbSName;
4099     const char *zTab = SCHEMA_TABLE(iDb);
4100     if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
4101       goto exit_drop_index;
4102     }
4103     if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
4104     if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
4105       goto exit_drop_index;
4106     }
4107   }
4108 #endif
4109 
4110   /* Generate code to remove the index and from the master table */
4111   v = sqlite3GetVdbe(pParse);
4112   if( v ){
4113     sqlite3BeginWriteOperation(pParse, 1, iDb);
4114     sqlite3NestedParse(pParse,
4115        "DELETE FROM %Q.%s WHERE name=%Q AND type='index'",
4116        db->aDb[iDb].zDbSName, MASTER_NAME, pIndex->zName
4117     );
4118     sqlite3ClearStatTables(pParse, iDb, "idx", pIndex->zName);
4119     sqlite3ChangeCookie(pParse, iDb);
4120     destroyRootPage(pParse, pIndex->tnum, iDb);
4121     sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
4122   }
4123 
4124 exit_drop_index:
4125   sqlite3SrcListDelete(db, pName);
4126 }
4127 
4128 /*
4129 ** pArray is a pointer to an array of objects. Each object in the
4130 ** array is szEntry bytes in size. This routine uses sqlite3DbRealloc()
4131 ** to extend the array so that there is space for a new object at the end.
4132 **
4133 ** When this function is called, *pnEntry contains the current size of
4134 ** the array (in entries - so the allocation is ((*pnEntry) * szEntry) bytes
4135 ** in total).
4136 **
4137 ** If the realloc() is successful (i.e. if no OOM condition occurs), the
4138 ** space allocated for the new object is zeroed, *pnEntry updated to
4139 ** reflect the new size of the array and a pointer to the new allocation
4140 ** returned. *pIdx is set to the index of the new array entry in this case.
4141 **
4142 ** Otherwise, if the realloc() fails, *pIdx is set to -1, *pnEntry remains
4143 ** unchanged and a copy of pArray returned.
4144 */
4145 void *sqlite3ArrayAllocate(
4146   sqlite3 *db,      /* Connection to notify of malloc failures */
4147   void *pArray,     /* Array of objects.  Might be reallocated */
4148   int szEntry,      /* Size of each object in the array */
4149   int *pnEntry,     /* Number of objects currently in use */
4150   int *pIdx         /* Write the index of a new slot here */
4151 ){
4152   char *z;
4153   sqlite3_int64 n = *pIdx = *pnEntry;
4154   if( (n & (n-1))==0 ){
4155     sqlite3_int64 sz = (n==0) ? 1 : 2*n;
4156     void *pNew = sqlite3DbRealloc(db, pArray, sz*szEntry);
4157     if( pNew==0 ){
4158       *pIdx = -1;
4159       return pArray;
4160     }
4161     pArray = pNew;
4162   }
4163   z = (char*)pArray;
4164   memset(&z[n * szEntry], 0, szEntry);
4165   ++*pnEntry;
4166   return pArray;
4167 }
4168 
4169 /*
4170 ** Append a new element to the given IdList.  Create a new IdList if
4171 ** need be.
4172 **
4173 ** A new IdList is returned, or NULL if malloc() fails.
4174 */
4175 IdList *sqlite3IdListAppend(Parse *pParse, IdList *pList, Token *pToken){
4176   sqlite3 *db = pParse->db;
4177   int i;
4178   if( pList==0 ){
4179     pList = sqlite3DbMallocZero(db, sizeof(IdList) );
4180     if( pList==0 ) return 0;
4181   }
4182   pList->a = sqlite3ArrayAllocate(
4183       db,
4184       pList->a,
4185       sizeof(pList->a[0]),
4186       &pList->nId,
4187       &i
4188   );
4189   if( i<0 ){
4190     sqlite3IdListDelete(db, pList);
4191     return 0;
4192   }
4193   pList->a[i].zName = sqlite3NameFromToken(db, pToken);
4194   if( IN_RENAME_OBJECT && pList->a[i].zName ){
4195     sqlite3RenameTokenMap(pParse, (void*)pList->a[i].zName, pToken);
4196   }
4197   return pList;
4198 }
4199 
4200 /*
4201 ** Delete an IdList.
4202 */
4203 void sqlite3IdListDelete(sqlite3 *db, IdList *pList){
4204   int i;
4205   if( pList==0 ) return;
4206   for(i=0; i<pList->nId; i++){
4207     sqlite3DbFree(db, pList->a[i].zName);
4208   }
4209   sqlite3DbFree(db, pList->a);
4210   sqlite3DbFreeNN(db, pList);
4211 }
4212 
4213 /*
4214 ** Return the index in pList of the identifier named zId.  Return -1
4215 ** if not found.
4216 */
4217 int sqlite3IdListIndex(IdList *pList, const char *zName){
4218   int i;
4219   if( pList==0 ) return -1;
4220   for(i=0; i<pList->nId; i++){
4221     if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
4222   }
4223   return -1;
4224 }
4225 
4226 /*
4227 ** Maximum size of a SrcList object.
4228 ** The SrcList object is used to represent the FROM clause of a
4229 ** SELECT statement, and the query planner cannot deal with more
4230 ** than 64 tables in a join.  So any value larger than 64 here
4231 ** is sufficient for most uses.  Smaller values, like say 10, are
4232 ** appropriate for small and memory-limited applications.
4233 */
4234 #ifndef SQLITE_MAX_SRCLIST
4235 # define SQLITE_MAX_SRCLIST 200
4236 #endif
4237 
4238 /*
4239 ** Expand the space allocated for the given SrcList object by
4240 ** creating nExtra new slots beginning at iStart.  iStart is zero based.
4241 ** New slots are zeroed.
4242 **
4243 ** For example, suppose a SrcList initially contains two entries: A,B.
4244 ** To append 3 new entries onto the end, do this:
4245 **
4246 **    sqlite3SrcListEnlarge(db, pSrclist, 3, 2);
4247 **
4248 ** After the call above it would contain:  A, B, nil, nil, nil.
4249 ** If the iStart argument had been 1 instead of 2, then the result
4250 ** would have been:  A, nil, nil, nil, B.  To prepend the new slots,
4251 ** the iStart value would be 0.  The result then would
4252 ** be: nil, nil, nil, A, B.
4253 **
4254 ** If a memory allocation fails or the SrcList becomes too large, leave
4255 ** the original SrcList unchanged, return NULL, and leave an error message
4256 ** in pParse.
4257 */
4258 SrcList *sqlite3SrcListEnlarge(
4259   Parse *pParse,     /* Parsing context into which errors are reported */
4260   SrcList *pSrc,     /* The SrcList to be enlarged */
4261   int nExtra,        /* Number of new slots to add to pSrc->a[] */
4262   int iStart         /* Index in pSrc->a[] of first new slot */
4263 ){
4264   int i;
4265 
4266   /* Sanity checking on calling parameters */
4267   assert( iStart>=0 );
4268   assert( nExtra>=1 );
4269   assert( pSrc!=0 );
4270   assert( iStart<=pSrc->nSrc );
4271 
4272   /* Allocate additional space if needed */
4273   if( (u32)pSrc->nSrc+nExtra>pSrc->nAlloc ){
4274     SrcList *pNew;
4275     sqlite3_int64 nAlloc = 2*(sqlite3_int64)pSrc->nSrc+nExtra;
4276     sqlite3 *db = pParse->db;
4277 
4278     if( pSrc->nSrc+nExtra>=SQLITE_MAX_SRCLIST ){
4279       sqlite3ErrorMsg(pParse, "too many FROM clause terms, max: %d",
4280                       SQLITE_MAX_SRCLIST);
4281       return 0;
4282     }
4283     if( nAlloc>SQLITE_MAX_SRCLIST ) nAlloc = SQLITE_MAX_SRCLIST;
4284     pNew = sqlite3DbRealloc(db, pSrc,
4285                sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) );
4286     if( pNew==0 ){
4287       assert( db->mallocFailed );
4288       return 0;
4289     }
4290     pSrc = pNew;
4291     pSrc->nAlloc = nAlloc;
4292   }
4293 
4294   /* Move existing slots that come after the newly inserted slots
4295   ** out of the way */
4296   for(i=pSrc->nSrc-1; i>=iStart; i--){
4297     pSrc->a[i+nExtra] = pSrc->a[i];
4298   }
4299   pSrc->nSrc += nExtra;
4300 
4301   /* Zero the newly allocated slots */
4302   memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
4303   for(i=iStart; i<iStart+nExtra; i++){
4304     pSrc->a[i].iCursor = -1;
4305   }
4306 
4307   /* Return a pointer to the enlarged SrcList */
4308   return pSrc;
4309 }
4310 
4311 
4312 /*
4313 ** Append a new table name to the given SrcList.  Create a new SrcList if
4314 ** need be.  A new entry is created in the SrcList even if pTable is NULL.
4315 **
4316 ** A SrcList is returned, or NULL if there is an OOM error or if the
4317 ** SrcList grows to large.  The returned
4318 ** SrcList might be the same as the SrcList that was input or it might be
4319 ** a new one.  If an OOM error does occurs, then the prior value of pList
4320 ** that is input to this routine is automatically freed.
4321 **
4322 ** If pDatabase is not null, it means that the table has an optional
4323 ** database name prefix.  Like this:  "database.table".  The pDatabase
4324 ** points to the table name and the pTable points to the database name.
4325 ** The SrcList.a[].zName field is filled with the table name which might
4326 ** come from pTable (if pDatabase is NULL) or from pDatabase.
4327 ** SrcList.a[].zDatabase is filled with the database name from pTable,
4328 ** or with NULL if no database is specified.
4329 **
4330 ** In other words, if call like this:
4331 **
4332 **         sqlite3SrcListAppend(D,A,B,0);
4333 **
4334 ** Then B is a table name and the database name is unspecified.  If called
4335 ** like this:
4336 **
4337 **         sqlite3SrcListAppend(D,A,B,C);
4338 **
4339 ** Then C is the table name and B is the database name.  If C is defined
4340 ** then so is B.  In other words, we never have a case where:
4341 **
4342 **         sqlite3SrcListAppend(D,A,0,C);
4343 **
4344 ** Both pTable and pDatabase are assumed to be quoted.  They are dequoted
4345 ** before being added to the SrcList.
4346 */
4347 SrcList *sqlite3SrcListAppend(
4348   Parse *pParse,      /* Parsing context, in which errors are reported */
4349   SrcList *pList,     /* Append to this SrcList. NULL creates a new SrcList */
4350   Token *pTable,      /* Table to append */
4351   Token *pDatabase    /* Database of the table */
4352 ){
4353   struct SrcList_item *pItem;
4354   sqlite3 *db;
4355   assert( pDatabase==0 || pTable!=0 );  /* Cannot have C without B */
4356   assert( pParse!=0 );
4357   assert( pParse->db!=0 );
4358   db = pParse->db;
4359   if( pList==0 ){
4360     pList = sqlite3DbMallocRawNN(pParse->db, sizeof(SrcList) );
4361     if( pList==0 ) return 0;
4362     pList->nAlloc = 1;
4363     pList->nSrc = 1;
4364     memset(&pList->a[0], 0, sizeof(pList->a[0]));
4365     pList->a[0].iCursor = -1;
4366   }else{
4367     SrcList *pNew = sqlite3SrcListEnlarge(pParse, pList, 1, pList->nSrc);
4368     if( pNew==0 ){
4369       sqlite3SrcListDelete(db, pList);
4370       return 0;
4371     }else{
4372       pList = pNew;
4373     }
4374   }
4375   pItem = &pList->a[pList->nSrc-1];
4376   if( pDatabase && pDatabase->z==0 ){
4377     pDatabase = 0;
4378   }
4379   if( pDatabase ){
4380     pItem->zName = sqlite3NameFromToken(db, pDatabase);
4381     pItem->zDatabase = sqlite3NameFromToken(db, pTable);
4382   }else{
4383     pItem->zName = sqlite3NameFromToken(db, pTable);
4384     pItem->zDatabase = 0;
4385   }
4386   return pList;
4387 }
4388 
4389 /*
4390 ** Assign VdbeCursor index numbers to all tables in a SrcList
4391 */
4392 void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
4393   int i;
4394   struct SrcList_item *pItem;
4395   assert(pList || pParse->db->mallocFailed );
4396   if( pList ){
4397     for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
4398       if( pItem->iCursor>=0 ) break;
4399       pItem->iCursor = pParse->nTab++;
4400       if( pItem->pSelect ){
4401         sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
4402       }
4403     }
4404   }
4405 }
4406 
4407 /*
4408 ** Delete an entire SrcList including all its substructure.
4409 */
4410 void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){
4411   int i;
4412   struct SrcList_item *pItem;
4413   if( pList==0 ) return;
4414   for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
4415     sqlite3DbFree(db, pItem->zDatabase);
4416     sqlite3DbFree(db, pItem->zName);
4417     sqlite3DbFree(db, pItem->zAlias);
4418     if( pItem->fg.isIndexedBy ) sqlite3DbFree(db, pItem->u1.zIndexedBy);
4419     if( pItem->fg.isTabFunc ) sqlite3ExprListDelete(db, pItem->u1.pFuncArg);
4420     sqlite3DeleteTable(db, pItem->pTab);
4421     sqlite3SelectDelete(db, pItem->pSelect);
4422     sqlite3ExprDelete(db, pItem->pOn);
4423     sqlite3IdListDelete(db, pItem->pUsing);
4424   }
4425   sqlite3DbFreeNN(db, pList);
4426 }
4427 
4428 /*
4429 ** This routine is called by the parser to add a new term to the
4430 ** end of a growing FROM clause.  The "p" parameter is the part of
4431 ** the FROM clause that has already been constructed.  "p" is NULL
4432 ** if this is the first term of the FROM clause.  pTable and pDatabase
4433 ** are the name of the table and database named in the FROM clause term.
4434 ** pDatabase is NULL if the database name qualifier is missing - the
4435 ** usual case.  If the term has an alias, then pAlias points to the
4436 ** alias token.  If the term is a subquery, then pSubquery is the
4437 ** SELECT statement that the subquery encodes.  The pTable and
4438 ** pDatabase parameters are NULL for subqueries.  The pOn and pUsing
4439 ** parameters are the content of the ON and USING clauses.
4440 **
4441 ** Return a new SrcList which encodes is the FROM with the new
4442 ** term added.
4443 */
4444 SrcList *sqlite3SrcListAppendFromTerm(
4445   Parse *pParse,          /* Parsing context */
4446   SrcList *p,             /* The left part of the FROM clause already seen */
4447   Token *pTable,          /* Name of the table to add to the FROM clause */
4448   Token *pDatabase,       /* Name of the database containing pTable */
4449   Token *pAlias,          /* The right-hand side of the AS subexpression */
4450   Select *pSubquery,      /* A subquery used in place of a table name */
4451   Expr *pOn,              /* The ON clause of a join */
4452   IdList *pUsing          /* The USING clause of a join */
4453 ){
4454   struct SrcList_item *pItem;
4455   sqlite3 *db = pParse->db;
4456   if( !p && (pOn || pUsing) ){
4457     sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s",
4458       (pOn ? "ON" : "USING")
4459     );
4460     goto append_from_error;
4461   }
4462   p = sqlite3SrcListAppend(pParse, p, pTable, pDatabase);
4463   if( p==0 ){
4464     goto append_from_error;
4465   }
4466   assert( p->nSrc>0 );
4467   pItem = &p->a[p->nSrc-1];
4468   assert( (pTable==0)==(pDatabase==0) );
4469   assert( pItem->zName==0 || pDatabase!=0 );
4470   if( IN_RENAME_OBJECT && pItem->zName ){
4471     Token *pToken = (ALWAYS(pDatabase) && pDatabase->z) ? pDatabase : pTable;
4472     sqlite3RenameTokenMap(pParse, pItem->zName, pToken);
4473   }
4474   assert( pAlias!=0 );
4475   if( pAlias->n ){
4476     pItem->zAlias = sqlite3NameFromToken(db, pAlias);
4477   }
4478   pItem->pSelect = pSubquery;
4479   pItem->pOn = pOn;
4480   pItem->pUsing = pUsing;
4481   return p;
4482 
4483  append_from_error:
4484   assert( p==0 );
4485   sqlite3ExprDelete(db, pOn);
4486   sqlite3IdListDelete(db, pUsing);
4487   sqlite3SelectDelete(db, pSubquery);
4488   return 0;
4489 }
4490 
4491 /*
4492 ** Add an INDEXED BY or NOT INDEXED clause to the most recently added
4493 ** element of the source-list passed as the second argument.
4494 */
4495 void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){
4496   assert( pIndexedBy!=0 );
4497   if( p && pIndexedBy->n>0 ){
4498     struct SrcList_item *pItem;
4499     assert( p->nSrc>0 );
4500     pItem = &p->a[p->nSrc-1];
4501     assert( pItem->fg.notIndexed==0 );
4502     assert( pItem->fg.isIndexedBy==0 );
4503     assert( pItem->fg.isTabFunc==0 );
4504     if( pIndexedBy->n==1 && !pIndexedBy->z ){
4505       /* A "NOT INDEXED" clause was supplied. See parse.y
4506       ** construct "indexed_opt" for details. */
4507       pItem->fg.notIndexed = 1;
4508     }else{
4509       pItem->u1.zIndexedBy = sqlite3NameFromToken(pParse->db, pIndexedBy);
4510       pItem->fg.isIndexedBy = 1;
4511     }
4512   }
4513 }
4514 
4515 /*
4516 ** Add the list of function arguments to the SrcList entry for a
4517 ** table-valued-function.
4518 */
4519 void sqlite3SrcListFuncArgs(Parse *pParse, SrcList *p, ExprList *pList){
4520   if( p ){
4521     struct SrcList_item *pItem = &p->a[p->nSrc-1];
4522     assert( pItem->fg.notIndexed==0 );
4523     assert( pItem->fg.isIndexedBy==0 );
4524     assert( pItem->fg.isTabFunc==0 );
4525     pItem->u1.pFuncArg = pList;
4526     pItem->fg.isTabFunc = 1;
4527   }else{
4528     sqlite3ExprListDelete(pParse->db, pList);
4529   }
4530 }
4531 
4532 /*
4533 ** When building up a FROM clause in the parser, the join operator
4534 ** is initially attached to the left operand.  But the code generator
4535 ** expects the join operator to be on the right operand.  This routine
4536 ** Shifts all join operators from left to right for an entire FROM
4537 ** clause.
4538 **
4539 ** Example: Suppose the join is like this:
4540 **
4541 **           A natural cross join B
4542 **
4543 ** The operator is "natural cross join".  The A and B operands are stored
4544 ** in p->a[0] and p->a[1], respectively.  The parser initially stores the
4545 ** operator with A.  This routine shifts that operator over to B.
4546 */
4547 void sqlite3SrcListShiftJoinType(SrcList *p){
4548   if( p ){
4549     int i;
4550     for(i=p->nSrc-1; i>0; i--){
4551       p->a[i].fg.jointype = p->a[i-1].fg.jointype;
4552     }
4553     p->a[0].fg.jointype = 0;
4554   }
4555 }
4556 
4557 /*
4558 ** Generate VDBE code for a BEGIN statement.
4559 */
4560 void sqlite3BeginTransaction(Parse *pParse, int type){
4561   sqlite3 *db;
4562   Vdbe *v;
4563   int i;
4564 
4565   assert( pParse!=0 );
4566   db = pParse->db;
4567   assert( db!=0 );
4568   if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){
4569     return;
4570   }
4571   v = sqlite3GetVdbe(pParse);
4572   if( !v ) return;
4573   if( type!=TK_DEFERRED ){
4574     for(i=0; i<db->nDb; i++){
4575       sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
4576       sqlite3VdbeUsesBtree(v, i);
4577     }
4578   }
4579   sqlite3VdbeAddOp0(v, OP_AutoCommit);
4580 }
4581 
4582 /*
4583 ** Generate VDBE code for a COMMIT or ROLLBACK statement.
4584 ** Code for ROLLBACK is generated if eType==TK_ROLLBACK.  Otherwise
4585 ** code is generated for a COMMIT.
4586 */
4587 void sqlite3EndTransaction(Parse *pParse, int eType){
4588   Vdbe *v;
4589   int isRollback;
4590 
4591   assert( pParse!=0 );
4592   assert( pParse->db!=0 );
4593   assert( eType==TK_COMMIT || eType==TK_END || eType==TK_ROLLBACK );
4594   isRollback = eType==TK_ROLLBACK;
4595   if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION,
4596        isRollback ? "ROLLBACK" : "COMMIT", 0, 0) ){
4597     return;
4598   }
4599   v = sqlite3GetVdbe(pParse);
4600   if( v ){
4601     sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, isRollback);
4602   }
4603 }
4604 
4605 /*
4606 ** This function is called by the parser when it parses a command to create,
4607 ** release or rollback an SQL savepoint.
4608 */
4609 void sqlite3Savepoint(Parse *pParse, int op, Token *pName){
4610   char *zName = sqlite3NameFromToken(pParse->db, pName);
4611   if( zName ){
4612     Vdbe *v = sqlite3GetVdbe(pParse);
4613 #ifndef SQLITE_OMIT_AUTHORIZATION
4614     static const char * const az[] = { "BEGIN", "RELEASE", "ROLLBACK" };
4615     assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 );
4616 #endif
4617     if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){
4618       sqlite3DbFree(pParse->db, zName);
4619       return;
4620     }
4621     sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC);
4622   }
4623 }
4624 
4625 /*
4626 ** Make sure the TEMP database is open and available for use.  Return
4627 ** the number of errors.  Leave any error messages in the pParse structure.
4628 */
4629 int sqlite3OpenTempDatabase(Parse *pParse){
4630   sqlite3 *db = pParse->db;
4631   if( db->aDb[1].pBt==0 && !pParse->explain ){
4632     int rc;
4633     Btree *pBt;
4634     static const int flags =
4635           SQLITE_OPEN_READWRITE |
4636           SQLITE_OPEN_CREATE |
4637           SQLITE_OPEN_EXCLUSIVE |
4638           SQLITE_OPEN_DELETEONCLOSE |
4639           SQLITE_OPEN_TEMP_DB;
4640 
4641     rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pBt, 0, flags);
4642     if( rc!=SQLITE_OK ){
4643       sqlite3ErrorMsg(pParse, "unable to open a temporary database "
4644         "file for storing temporary tables");
4645       pParse->rc = rc;
4646       return 1;
4647     }
4648     db->aDb[1].pBt = pBt;
4649     assert( db->aDb[1].pSchema );
4650     if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, 0, 0) ){
4651       sqlite3OomFault(db);
4652       return 1;
4653     }
4654   }
4655   return 0;
4656 }
4657 
4658 /*
4659 ** Record the fact that the schema cookie will need to be verified
4660 ** for database iDb.  The code to actually verify the schema cookie
4661 ** will occur at the end of the top-level VDBE and will be generated
4662 ** later, by sqlite3FinishCoding().
4663 */
4664 void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
4665   Parse *pToplevel = sqlite3ParseToplevel(pParse);
4666 
4667   assert( iDb>=0 && iDb<pParse->db->nDb );
4668   assert( pParse->db->aDb[iDb].pBt!=0 || iDb==1 );
4669   assert( iDb<SQLITE_MAX_ATTACHED+2 );
4670   assert( sqlite3SchemaMutexHeld(pParse->db, iDb, 0) );
4671   if( DbMaskTest(pToplevel->cookieMask, iDb)==0 ){
4672     DbMaskSet(pToplevel->cookieMask, iDb);
4673     if( !OMIT_TEMPDB && iDb==1 ){
4674       sqlite3OpenTempDatabase(pToplevel);
4675     }
4676   }
4677 }
4678 
4679 /*
4680 ** If argument zDb is NULL, then call sqlite3CodeVerifySchema() for each
4681 ** attached database. Otherwise, invoke it for the database named zDb only.
4682 */
4683 void sqlite3CodeVerifyNamedSchema(Parse *pParse, const char *zDb){
4684   sqlite3 *db = pParse->db;
4685   int i;
4686   for(i=0; i<db->nDb; i++){
4687     Db *pDb = &db->aDb[i];
4688     if( pDb->pBt && (!zDb || 0==sqlite3StrICmp(zDb, pDb->zDbSName)) ){
4689       sqlite3CodeVerifySchema(pParse, i);
4690     }
4691   }
4692 }
4693 
4694 /*
4695 ** Generate VDBE code that prepares for doing an operation that
4696 ** might change the database.
4697 **
4698 ** This routine starts a new transaction if we are not already within
4699 ** a transaction.  If we are already within a transaction, then a checkpoint
4700 ** is set if the setStatement parameter is true.  A checkpoint should
4701 ** be set for operations that might fail (due to a constraint) part of
4702 ** the way through and which will need to undo some writes without having to
4703 ** rollback the whole transaction.  For operations where all constraints
4704 ** can be checked before any changes are made to the database, it is never
4705 ** necessary to undo a write and the checkpoint should not be set.
4706 */
4707 void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
4708   Parse *pToplevel = sqlite3ParseToplevel(pParse);
4709   sqlite3CodeVerifySchema(pParse, iDb);
4710   DbMaskSet(pToplevel->writeMask, iDb);
4711   pToplevel->isMultiWrite |= setStatement;
4712 }
4713 
4714 /*
4715 ** Indicate that the statement currently under construction might write
4716 ** more than one entry (example: deleting one row then inserting another,
4717 ** inserting multiple rows in a table, or inserting a row and index entries.)
4718 ** If an abort occurs after some of these writes have completed, then it will
4719 ** be necessary to undo the completed writes.
4720 */
4721 void sqlite3MultiWrite(Parse *pParse){
4722   Parse *pToplevel = sqlite3ParseToplevel(pParse);
4723   pToplevel->isMultiWrite = 1;
4724 }
4725 
4726 /*
4727 ** The code generator calls this routine if is discovers that it is
4728 ** possible to abort a statement prior to completion.  In order to
4729 ** perform this abort without corrupting the database, we need to make
4730 ** sure that the statement is protected by a statement transaction.
4731 **
4732 ** Technically, we only need to set the mayAbort flag if the
4733 ** isMultiWrite flag was previously set.  There is a time dependency
4734 ** such that the abort must occur after the multiwrite.  This makes
4735 ** some statements involving the REPLACE conflict resolution algorithm
4736 ** go a little faster.  But taking advantage of this time dependency
4737 ** makes it more difficult to prove that the code is correct (in
4738 ** particular, it prevents us from writing an effective
4739 ** implementation of sqlite3AssertMayAbort()) and so we have chosen
4740 ** to take the safe route and skip the optimization.
4741 */
4742 void sqlite3MayAbort(Parse *pParse){
4743   Parse *pToplevel = sqlite3ParseToplevel(pParse);
4744   pToplevel->mayAbort = 1;
4745 }
4746 
4747 /*
4748 ** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT
4749 ** error. The onError parameter determines which (if any) of the statement
4750 ** and/or current transaction is rolled back.
4751 */
4752 void sqlite3HaltConstraint(
4753   Parse *pParse,    /* Parsing context */
4754   int errCode,      /* extended error code */
4755   int onError,      /* Constraint type */
4756   char *p4,         /* Error message */
4757   i8 p4type,        /* P4_STATIC or P4_TRANSIENT */
4758   u8 p5Errmsg       /* P5_ErrMsg type */
4759 ){
4760   Vdbe *v = sqlite3GetVdbe(pParse);
4761   assert( (errCode&0xff)==SQLITE_CONSTRAINT || pParse->nested );
4762   if( onError==OE_Abort ){
4763     sqlite3MayAbort(pParse);
4764   }
4765   sqlite3VdbeAddOp4(v, OP_Halt, errCode, onError, 0, p4, p4type);
4766   sqlite3VdbeChangeP5(v, p5Errmsg);
4767 }
4768 
4769 /*
4770 ** Code an OP_Halt due to UNIQUE or PRIMARY KEY constraint violation.
4771 */
4772 void sqlite3UniqueConstraint(
4773   Parse *pParse,    /* Parsing context */
4774   int onError,      /* Constraint type */
4775   Index *pIdx       /* The index that triggers the constraint */
4776 ){
4777   char *zErr;
4778   int j;
4779   StrAccum errMsg;
4780   Table *pTab = pIdx->pTable;
4781 
4782   sqlite3StrAccumInit(&errMsg, pParse->db, 0, 0,
4783                       pParse->db->aLimit[SQLITE_LIMIT_LENGTH]);
4784   if( pIdx->aColExpr ){
4785     sqlite3_str_appendf(&errMsg, "index '%q'", pIdx->zName);
4786   }else{
4787     for(j=0; j<pIdx->nKeyCol; j++){
4788       char *zCol;
4789       assert( pIdx->aiColumn[j]>=0 );
4790       zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
4791       if( j ) sqlite3_str_append(&errMsg, ", ", 2);
4792       sqlite3_str_appendall(&errMsg, pTab->zName);
4793       sqlite3_str_append(&errMsg, ".", 1);
4794       sqlite3_str_appendall(&errMsg, zCol);
4795     }
4796   }
4797   zErr = sqlite3StrAccumFinish(&errMsg);
4798   sqlite3HaltConstraint(pParse,
4799     IsPrimaryKeyIndex(pIdx) ? SQLITE_CONSTRAINT_PRIMARYKEY
4800                             : SQLITE_CONSTRAINT_UNIQUE,
4801     onError, zErr, P4_DYNAMIC, P5_ConstraintUnique);
4802 }
4803 
4804 
4805 /*
4806 ** Code an OP_Halt due to non-unique rowid.
4807 */
4808 void sqlite3RowidConstraint(
4809   Parse *pParse,    /* Parsing context */
4810   int onError,      /* Conflict resolution algorithm */
4811   Table *pTab       /* The table with the non-unique rowid */
4812 ){
4813   char *zMsg;
4814   int rc;
4815   if( pTab->iPKey>=0 ){
4816     zMsg = sqlite3MPrintf(pParse->db, "%s.%s", pTab->zName,
4817                           pTab->aCol[pTab->iPKey].zName);
4818     rc = SQLITE_CONSTRAINT_PRIMARYKEY;
4819   }else{
4820     zMsg = sqlite3MPrintf(pParse->db, "%s.rowid", pTab->zName);
4821     rc = SQLITE_CONSTRAINT_ROWID;
4822   }
4823   sqlite3HaltConstraint(pParse, rc, onError, zMsg, P4_DYNAMIC,
4824                         P5_ConstraintUnique);
4825 }
4826 
4827 /*
4828 ** Check to see if pIndex uses the collating sequence pColl.  Return
4829 ** true if it does and false if it does not.
4830 */
4831 #ifndef SQLITE_OMIT_REINDEX
4832 static int collationMatch(const char *zColl, Index *pIndex){
4833   int i;
4834   assert( zColl!=0 );
4835   for(i=0; i<pIndex->nColumn; i++){
4836     const char *z = pIndex->azColl[i];
4837     assert( z!=0 || pIndex->aiColumn[i]<0 );
4838     if( pIndex->aiColumn[i]>=0 && 0==sqlite3StrICmp(z, zColl) ){
4839       return 1;
4840     }
4841   }
4842   return 0;
4843 }
4844 #endif
4845 
4846 /*
4847 ** Recompute all indices of pTab that use the collating sequence pColl.
4848 ** If pColl==0 then recompute all indices of pTab.
4849 */
4850 #ifndef SQLITE_OMIT_REINDEX
4851 static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
4852   if( !IsVirtual(pTab) ){
4853     Index *pIndex;              /* An index associated with pTab */
4854 
4855     for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
4856       if( zColl==0 || collationMatch(zColl, pIndex) ){
4857         int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
4858         sqlite3BeginWriteOperation(pParse, 0, iDb);
4859         sqlite3RefillIndex(pParse, pIndex, -1);
4860       }
4861     }
4862   }
4863 }
4864 #endif
4865 
4866 /*
4867 ** Recompute all indices of all tables in all databases where the
4868 ** indices use the collating sequence pColl.  If pColl==0 then recompute
4869 ** all indices everywhere.
4870 */
4871 #ifndef SQLITE_OMIT_REINDEX
4872 static void reindexDatabases(Parse *pParse, char const *zColl){
4873   Db *pDb;                    /* A single database */
4874   int iDb;                    /* The database index number */
4875   sqlite3 *db = pParse->db;   /* The database connection */
4876   HashElem *k;                /* For looping over tables in pDb */
4877   Table *pTab;                /* A table in the database */
4878 
4879   assert( sqlite3BtreeHoldsAllMutexes(db) );  /* Needed for schema access */
4880   for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
4881     assert( pDb!=0 );
4882     for(k=sqliteHashFirst(&pDb->pSchema->tblHash);  k; k=sqliteHashNext(k)){
4883       pTab = (Table*)sqliteHashData(k);
4884       reindexTable(pParse, pTab, zColl);
4885     }
4886   }
4887 }
4888 #endif
4889 
4890 /*
4891 ** Generate code for the REINDEX command.
4892 **
4893 **        REINDEX                            -- 1
4894 **        REINDEX  <collation>               -- 2
4895 **        REINDEX  ?<database>.?<tablename>  -- 3
4896 **        REINDEX  ?<database>.?<indexname>  -- 4
4897 **
4898 ** Form 1 causes all indices in all attached databases to be rebuilt.
4899 ** Form 2 rebuilds all indices in all databases that use the named
4900 ** collating function.  Forms 3 and 4 rebuild the named index or all
4901 ** indices associated with the named table.
4902 */
4903 #ifndef SQLITE_OMIT_REINDEX
4904 void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
4905   CollSeq *pColl;             /* Collating sequence to be reindexed, or NULL */
4906   char *z;                    /* Name of a table or index */
4907   const char *zDb;            /* Name of the database */
4908   Table *pTab;                /* A table in the database */
4909   Index *pIndex;              /* An index associated with pTab */
4910   int iDb;                    /* The database index number */
4911   sqlite3 *db = pParse->db;   /* The database connection */
4912   Token *pObjName;            /* Name of the table or index to be reindexed */
4913 
4914   /* Read the database schema. If an error occurs, leave an error message
4915   ** and code in pParse and return NULL. */
4916   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
4917     return;
4918   }
4919 
4920   if( pName1==0 ){
4921     reindexDatabases(pParse, 0);
4922     return;
4923   }else if( NEVER(pName2==0) || pName2->z==0 ){
4924     char *zColl;
4925     assert( pName1->z );
4926     zColl = sqlite3NameFromToken(pParse->db, pName1);
4927     if( !zColl ) return;
4928     pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
4929     if( pColl ){
4930       reindexDatabases(pParse, zColl);
4931       sqlite3DbFree(db, zColl);
4932       return;
4933     }
4934     sqlite3DbFree(db, zColl);
4935   }
4936   iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
4937   if( iDb<0 ) return;
4938   z = sqlite3NameFromToken(db, pObjName);
4939   if( z==0 ) return;
4940   zDb = db->aDb[iDb].zDbSName;
4941   pTab = sqlite3FindTable(db, z, zDb);
4942   if( pTab ){
4943     reindexTable(pParse, pTab, 0);
4944     sqlite3DbFree(db, z);
4945     return;
4946   }
4947   pIndex = sqlite3FindIndex(db, z, zDb);
4948   sqlite3DbFree(db, z);
4949   if( pIndex ){
4950     sqlite3BeginWriteOperation(pParse, 0, iDb);
4951     sqlite3RefillIndex(pParse, pIndex, -1);
4952     return;
4953   }
4954   sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
4955 }
4956 #endif
4957 
4958 /*
4959 ** Return a KeyInfo structure that is appropriate for the given Index.
4960 **
4961 ** The caller should invoke sqlite3KeyInfoUnref() on the returned object
4962 ** when it has finished using it.
4963 */
4964 KeyInfo *sqlite3KeyInfoOfIndex(Parse *pParse, Index *pIdx){
4965   int i;
4966   int nCol = pIdx->nColumn;
4967   int nKey = pIdx->nKeyCol;
4968   KeyInfo *pKey;
4969   if( pParse->nErr ) return 0;
4970   if( pIdx->uniqNotNull ){
4971     pKey = sqlite3KeyInfoAlloc(pParse->db, nKey, nCol-nKey);
4972   }else{
4973     pKey = sqlite3KeyInfoAlloc(pParse->db, nCol, 0);
4974   }
4975   if( pKey ){
4976     assert( sqlite3KeyInfoIsWriteable(pKey) );
4977     for(i=0; i<nCol; i++){
4978       const char *zColl = pIdx->azColl[i];
4979       pKey->aColl[i] = zColl==sqlite3StrBINARY ? 0 :
4980                         sqlite3LocateCollSeq(pParse, zColl);
4981       pKey->aSortFlags[i] = pIdx->aSortOrder[i];
4982       assert( 0==(pKey->aSortFlags[i] & KEYINFO_ORDER_BIGNULL) );
4983     }
4984     if( pParse->nErr ){
4985       assert( pParse->rc==SQLITE_ERROR_MISSING_COLLSEQ );
4986       if( pIdx->bNoQuery==0 ){
4987         /* Deactivate the index because it contains an unknown collating
4988         ** sequence.  The only way to reactive the index is to reload the
4989         ** schema.  Adding the missing collating sequence later does not
4990         ** reactive the index.  The application had the chance to register
4991         ** the missing index using the collation-needed callback.  For
4992         ** simplicity, SQLite will not give the application a second chance.
4993         */
4994         pIdx->bNoQuery = 1;
4995         pParse->rc = SQLITE_ERROR_RETRY;
4996       }
4997       sqlite3KeyInfoUnref(pKey);
4998       pKey = 0;
4999     }
5000   }
5001   return pKey;
5002 }
5003 
5004 #ifndef SQLITE_OMIT_CTE
5005 /*
5006 ** This routine is invoked once per CTE by the parser while parsing a
5007 ** WITH clause.
5008 */
5009 With *sqlite3WithAdd(
5010   Parse *pParse,          /* Parsing context */
5011   With *pWith,            /* Existing WITH clause, or NULL */
5012   Token *pName,           /* Name of the common-table */
5013   ExprList *pArglist,     /* Optional column name list for the table */
5014   Select *pQuery          /* Query used to initialize the table */
5015 ){
5016   sqlite3 *db = pParse->db;
5017   With *pNew;
5018   char *zName;
5019 
5020   /* Check that the CTE name is unique within this WITH clause. If
5021   ** not, store an error in the Parse structure. */
5022   zName = sqlite3NameFromToken(pParse->db, pName);
5023   if( zName && pWith ){
5024     int i;
5025     for(i=0; i<pWith->nCte; i++){
5026       if( sqlite3StrICmp(zName, pWith->a[i].zName)==0 ){
5027         sqlite3ErrorMsg(pParse, "duplicate WITH table name: %s", zName);
5028       }
5029     }
5030   }
5031 
5032   if( pWith ){
5033     sqlite3_int64 nByte = sizeof(*pWith) + (sizeof(pWith->a[1]) * pWith->nCte);
5034     pNew = sqlite3DbRealloc(db, pWith, nByte);
5035   }else{
5036     pNew = sqlite3DbMallocZero(db, sizeof(*pWith));
5037   }
5038   assert( (pNew!=0 && zName!=0) || db->mallocFailed );
5039 
5040   if( db->mallocFailed ){
5041     sqlite3ExprListDelete(db, pArglist);
5042     sqlite3SelectDelete(db, pQuery);
5043     sqlite3DbFree(db, zName);
5044     pNew = pWith;
5045   }else{
5046     pNew->a[pNew->nCte].pSelect = pQuery;
5047     pNew->a[pNew->nCte].pCols = pArglist;
5048     pNew->a[pNew->nCte].zName = zName;
5049     pNew->a[pNew->nCte].zCteErr = 0;
5050     pNew->nCte++;
5051   }
5052 
5053   return pNew;
5054 }
5055 
5056 /*
5057 ** Free the contents of the With object passed as the second argument.
5058 */
5059 void sqlite3WithDelete(sqlite3 *db, With *pWith){
5060   if( pWith ){
5061     int i;
5062     for(i=0; i<pWith->nCte; i++){
5063       struct Cte *pCte = &pWith->a[i];
5064       sqlite3ExprListDelete(db, pCte->pCols);
5065       sqlite3SelectDelete(db, pCte->pSelect);
5066       sqlite3DbFree(db, pCte->zName);
5067     }
5068     sqlite3DbFree(db, pWith);
5069   }
5070 }
5071 #endif /* !defined(SQLITE_OMIT_CTE) */
5072