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