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