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