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