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