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