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