xref: /sqlite-3.40.0/src/build.c (revision af94adf0)
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].sortFlags;
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].sortFlags = 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     DisableLookaside;
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     EnableLookaside;
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+7, "stat", 4)!=0
2820     && sqlite3StrNICmp(pTab->zName+7, "parameters", 10)!=0 ){
2821     sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
2822     goto exit_drop_table;
2823   }
2824 
2825 #ifndef SQLITE_OMIT_VIEW
2826   /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
2827   ** on a table.
2828   */
2829   if( isView && pTab->pSelect==0 ){
2830     sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
2831     goto exit_drop_table;
2832   }
2833   if( !isView && pTab->pSelect ){
2834     sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
2835     goto exit_drop_table;
2836   }
2837 #endif
2838 
2839   /* Generate code to remove the table from the master table
2840   ** on disk.
2841   */
2842   v = sqlite3GetVdbe(pParse);
2843   if( v ){
2844     sqlite3BeginWriteOperation(pParse, 1, iDb);
2845     if( !isView ){
2846       sqlite3ClearStatTables(pParse, iDb, "tbl", pTab->zName);
2847       sqlite3FkDropTable(pParse, pName, pTab);
2848     }
2849     sqlite3CodeDropTable(pParse, pTab, iDb, isView);
2850   }
2851 
2852 exit_drop_table:
2853   sqlite3SrcListDelete(db, pName);
2854 }
2855 
2856 /*
2857 ** This routine is called to create a new foreign key on the table
2858 ** currently under construction.  pFromCol determines which columns
2859 ** in the current table point to the foreign key.  If pFromCol==0 then
2860 ** connect the key to the last column inserted.  pTo is the name of
2861 ** the table referred to (a.k.a the "parent" table).  pToCol is a list
2862 ** of tables in the parent pTo table.  flags contains all
2863 ** information about the conflict resolution algorithms specified
2864 ** in the ON DELETE, ON UPDATE and ON INSERT clauses.
2865 **
2866 ** An FKey structure is created and added to the table currently
2867 ** under construction in the pParse->pNewTable field.
2868 **
2869 ** The foreign key is set for IMMEDIATE processing.  A subsequent call
2870 ** to sqlite3DeferForeignKey() might change this to DEFERRED.
2871 */
2872 void sqlite3CreateForeignKey(
2873   Parse *pParse,       /* Parsing context */
2874   ExprList *pFromCol,  /* Columns in this table that point to other table */
2875   Token *pTo,          /* Name of the other table */
2876   ExprList *pToCol,    /* Columns in the other table */
2877   int flags            /* Conflict resolution algorithms. */
2878 ){
2879   sqlite3 *db = pParse->db;
2880 #ifndef SQLITE_OMIT_FOREIGN_KEY
2881   FKey *pFKey = 0;
2882   FKey *pNextTo;
2883   Table *p = pParse->pNewTable;
2884   int nByte;
2885   int i;
2886   int nCol;
2887   char *z;
2888 
2889   assert( pTo!=0 );
2890   if( p==0 || IN_DECLARE_VTAB ) goto fk_end;
2891   if( pFromCol==0 ){
2892     int iCol = p->nCol-1;
2893     if( NEVER(iCol<0) ) goto fk_end;
2894     if( pToCol && pToCol->nExpr!=1 ){
2895       sqlite3ErrorMsg(pParse, "foreign key on %s"
2896          " should reference only one column of table %T",
2897          p->aCol[iCol].zName, pTo);
2898       goto fk_end;
2899     }
2900     nCol = 1;
2901   }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
2902     sqlite3ErrorMsg(pParse,
2903         "number of columns in foreign key does not match the number of "
2904         "columns in the referenced table");
2905     goto fk_end;
2906   }else{
2907     nCol = pFromCol->nExpr;
2908   }
2909   nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1;
2910   if( pToCol ){
2911     for(i=0; i<pToCol->nExpr; i++){
2912       nByte += sqlite3Strlen30(pToCol->a[i].zName) + 1;
2913     }
2914   }
2915   pFKey = sqlite3DbMallocZero(db, nByte );
2916   if( pFKey==0 ){
2917     goto fk_end;
2918   }
2919   pFKey->pFrom = p;
2920   pFKey->pNextFrom = p->pFKey;
2921   z = (char*)&pFKey->aCol[nCol];
2922   pFKey->zTo = z;
2923   if( IN_RENAME_OBJECT ){
2924     sqlite3RenameTokenMap(pParse, (void*)z, pTo);
2925   }
2926   memcpy(z, pTo->z, pTo->n);
2927   z[pTo->n] = 0;
2928   sqlite3Dequote(z);
2929   z += pTo->n+1;
2930   pFKey->nCol = nCol;
2931   if( pFromCol==0 ){
2932     pFKey->aCol[0].iFrom = p->nCol-1;
2933   }else{
2934     for(i=0; i<nCol; i++){
2935       int j;
2936       for(j=0; j<p->nCol; j++){
2937         if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
2938           pFKey->aCol[i].iFrom = j;
2939           break;
2940         }
2941       }
2942       if( j>=p->nCol ){
2943         sqlite3ErrorMsg(pParse,
2944           "unknown column \"%s\" in foreign key definition",
2945           pFromCol->a[i].zName);
2946         goto fk_end;
2947       }
2948       if( IN_RENAME_OBJECT ){
2949         sqlite3RenameTokenRemap(pParse, &pFKey->aCol[i], pFromCol->a[i].zName);
2950       }
2951     }
2952   }
2953   if( pToCol ){
2954     for(i=0; i<nCol; i++){
2955       int n = sqlite3Strlen30(pToCol->a[i].zName);
2956       pFKey->aCol[i].zCol = z;
2957       if( IN_RENAME_OBJECT ){
2958         sqlite3RenameTokenRemap(pParse, z, pToCol->a[i].zName);
2959       }
2960       memcpy(z, pToCol->a[i].zName, n);
2961       z[n] = 0;
2962       z += n+1;
2963     }
2964   }
2965   pFKey->isDeferred = 0;
2966   pFKey->aAction[0] = (u8)(flags & 0xff);            /* ON DELETE action */
2967   pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff);    /* ON UPDATE action */
2968 
2969   assert( sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
2970   pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash,
2971       pFKey->zTo, (void *)pFKey
2972   );
2973   if( pNextTo==pFKey ){
2974     sqlite3OomFault(db);
2975     goto fk_end;
2976   }
2977   if( pNextTo ){
2978     assert( pNextTo->pPrevTo==0 );
2979     pFKey->pNextTo = pNextTo;
2980     pNextTo->pPrevTo = pFKey;
2981   }
2982 
2983   /* Link the foreign key to the table as the last step.
2984   */
2985   p->pFKey = pFKey;
2986   pFKey = 0;
2987 
2988 fk_end:
2989   sqlite3DbFree(db, pFKey);
2990 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
2991   sqlite3ExprListDelete(db, pFromCol);
2992   sqlite3ExprListDelete(db, pToCol);
2993 }
2994 
2995 /*
2996 ** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
2997 ** clause is seen as part of a foreign key definition.  The isDeferred
2998 ** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
2999 ** The behavior of the most recently created foreign key is adjusted
3000 ** accordingly.
3001 */
3002 void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
3003 #ifndef SQLITE_OMIT_FOREIGN_KEY
3004   Table *pTab;
3005   FKey *pFKey;
3006   if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
3007   assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */
3008   pFKey->isDeferred = (u8)isDeferred;
3009 #endif
3010 }
3011 
3012 /*
3013 ** Generate code that will erase and refill index *pIdx.  This is
3014 ** used to initialize a newly created index or to recompute the
3015 ** content of an index in response to a REINDEX command.
3016 **
3017 ** if memRootPage is not negative, it means that the index is newly
3018 ** created.  The register specified by memRootPage contains the
3019 ** root page number of the index.  If memRootPage is negative, then
3020 ** the index already exists and must be cleared before being refilled and
3021 ** the root page number of the index is taken from pIndex->tnum.
3022 */
3023 static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
3024   Table *pTab = pIndex->pTable;  /* The table that is indexed */
3025   int iTab = pParse->nTab++;     /* Btree cursor used for pTab */
3026   int iIdx = pParse->nTab++;     /* Btree cursor used for pIndex */
3027   int iSorter;                   /* Cursor opened by OpenSorter (if in use) */
3028   int addr1;                     /* Address of top of loop */
3029   int addr2;                     /* Address to jump to for next iteration */
3030   int tnum;                      /* Root page of index */
3031   int iPartIdxLabel;             /* Jump to this label to skip a row */
3032   Vdbe *v;                       /* Generate code into this virtual machine */
3033   KeyInfo *pKey;                 /* KeyInfo for index */
3034   int regRecord;                 /* Register holding assembled index record */
3035   sqlite3 *db = pParse->db;      /* The database connection */
3036   int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
3037 
3038 #ifndef SQLITE_OMIT_AUTHORIZATION
3039   if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
3040       db->aDb[iDb].zDbSName ) ){
3041     return;
3042   }
3043 #endif
3044 
3045   /* Require a write-lock on the table to perform this operation */
3046   sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
3047 
3048   v = sqlite3GetVdbe(pParse);
3049   if( v==0 ) return;
3050   if( memRootPage>=0 ){
3051     tnum = memRootPage;
3052   }else{
3053     tnum = pIndex->tnum;
3054   }
3055   pKey = sqlite3KeyInfoOfIndex(pParse, pIndex);
3056   assert( pKey!=0 || db->mallocFailed || pParse->nErr );
3057 
3058   /* Open the sorter cursor if we are to use one. */
3059   iSorter = pParse->nTab++;
3060   sqlite3VdbeAddOp4(v, OP_SorterOpen, iSorter, 0, pIndex->nKeyCol, (char*)
3061                     sqlite3KeyInfoRef(pKey), P4_KEYINFO);
3062 
3063   /* Open the table. Loop through all rows of the table, inserting index
3064   ** records into the sorter. */
3065   sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
3066   addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0); VdbeCoverage(v);
3067   regRecord = sqlite3GetTempReg(pParse);
3068   sqlite3MultiWrite(pParse);
3069 
3070   sqlite3GenerateIndexKey(pParse,pIndex,iTab,regRecord,0,&iPartIdxLabel,0,0);
3071   sqlite3VdbeAddOp2(v, OP_SorterInsert, iSorter, regRecord);
3072   sqlite3ResolvePartIdxLabel(pParse, iPartIdxLabel);
3073   sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1); VdbeCoverage(v);
3074   sqlite3VdbeJumpHere(v, addr1);
3075   if( memRootPage<0 ) sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
3076   sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb,
3077                     (char *)pKey, P4_KEYINFO);
3078   sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR|((memRootPage>=0)?OPFLAG_P2ISREG:0));
3079 
3080   addr1 = sqlite3VdbeAddOp2(v, OP_SorterSort, iSorter, 0); VdbeCoverage(v);
3081   if( IsUniqueIndex(pIndex) ){
3082     int j2 = sqlite3VdbeGoto(v, 1);
3083     addr2 = sqlite3VdbeCurrentAddr(v);
3084     sqlite3VdbeVerifyAbortable(v, OE_Abort);
3085     sqlite3VdbeAddOp4Int(v, OP_SorterCompare, iSorter, j2, regRecord,
3086                          pIndex->nKeyCol); VdbeCoverage(v);
3087     sqlite3UniqueConstraint(pParse, OE_Abort, pIndex);
3088     sqlite3VdbeJumpHere(v, j2);
3089   }else{
3090     /* Most CREATE INDEX and REINDEX statements that are not UNIQUE can not
3091     ** abort. The exception is if one of the indexed expressions contains a
3092     ** user function that throws an exception when it is evaluated. But the
3093     ** overhead of adding a statement journal to a CREATE INDEX statement is
3094     ** very small (since most of the pages written do not contain content that
3095     ** needs to be restored if the statement aborts), so we call
3096     ** sqlite3MayAbort() for all CREATE INDEX statements.  */
3097     sqlite3MayAbort(pParse);
3098     addr2 = sqlite3VdbeCurrentAddr(v);
3099   }
3100   sqlite3VdbeAddOp3(v, OP_SorterData, iSorter, regRecord, iIdx);
3101   if( !pIndex->bAscKeyBug ){
3102     /* This OP_SeekEnd opcode makes index insert for a REINDEX go much
3103     ** faster by avoiding unnecessary seeks.  But the optimization does
3104     ** not work for UNIQUE constraint indexes on WITHOUT ROWID tables
3105     ** with DESC primary keys, since those indexes have there keys in
3106     ** a different order from the main table.
3107     ** See ticket: https://www.sqlite.org/src/info/bba7b69f9849b5bf
3108     */
3109     sqlite3VdbeAddOp1(v, OP_SeekEnd, iIdx);
3110   }
3111   sqlite3VdbeAddOp2(v, OP_IdxInsert, iIdx, regRecord);
3112   sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
3113   sqlite3ReleaseTempReg(pParse, regRecord);
3114   sqlite3VdbeAddOp2(v, OP_SorterNext, iSorter, addr2); VdbeCoverage(v);
3115   sqlite3VdbeJumpHere(v, addr1);
3116 
3117   sqlite3VdbeAddOp1(v, OP_Close, iTab);
3118   sqlite3VdbeAddOp1(v, OP_Close, iIdx);
3119   sqlite3VdbeAddOp1(v, OP_Close, iSorter);
3120 }
3121 
3122 /*
3123 ** Allocate heap space to hold an Index object with nCol columns.
3124 **
3125 ** Increase the allocation size to provide an extra nExtra bytes
3126 ** of 8-byte aligned space after the Index object and return a
3127 ** pointer to this extra space in *ppExtra.
3128 */
3129 Index *sqlite3AllocateIndexObject(
3130   sqlite3 *db,         /* Database connection */
3131   i16 nCol,            /* Total number of columns in the index */
3132   int nExtra,          /* Number of bytes of extra space to alloc */
3133   char **ppExtra       /* Pointer to the "extra" space */
3134 ){
3135   Index *p;            /* Allocated index object */
3136   int nByte;           /* Bytes of space for Index object + arrays */
3137 
3138   nByte = ROUND8(sizeof(Index)) +              /* Index structure  */
3139           ROUND8(sizeof(char*)*nCol) +         /* Index.azColl     */
3140           ROUND8(sizeof(LogEst)*(nCol+1) +     /* Index.aiRowLogEst   */
3141                  sizeof(i16)*nCol +            /* Index.aiColumn   */
3142                  sizeof(u8)*nCol);             /* Index.aSortOrder */
3143   p = sqlite3DbMallocZero(db, nByte + nExtra);
3144   if( p ){
3145     char *pExtra = ((char*)p)+ROUND8(sizeof(Index));
3146     p->azColl = (const char**)pExtra; pExtra += ROUND8(sizeof(char*)*nCol);
3147     p->aiRowLogEst = (LogEst*)pExtra; pExtra += sizeof(LogEst)*(nCol+1);
3148     p->aiColumn = (i16*)pExtra;       pExtra += sizeof(i16)*nCol;
3149     p->aSortOrder = (u8*)pExtra;
3150     p->nColumn = nCol;
3151     p->nKeyCol = nCol - 1;
3152     *ppExtra = ((char*)p) + nByte;
3153   }
3154   return p;
3155 }
3156 
3157 /*
3158 ** If expression list pList contains an expression that was parsed with
3159 ** an explicit "NULLS FIRST" or "NULLS LAST" clause, leave an error in
3160 ** pParse and return non-zero. Otherwise, return zero.
3161 */
3162 int sqlite3HasExplicitNulls(Parse *pParse, ExprList *pList){
3163   if( pList ){
3164     int i;
3165     for(i=0; i<pList->nExpr; i++){
3166       if( pList->a[i].bNulls ){
3167         u8 sf = pList->a[i].sortFlags;
3168         sqlite3ErrorMsg(pParse, "unsupported use of NULLS %s",
3169             (sf==0 || sf==3) ? "FIRST" : "LAST"
3170         );
3171         return 1;
3172       }
3173     }
3174   }
3175   return 0;
3176 }
3177 
3178 /*
3179 ** Create a new index for an SQL table.  pName1.pName2 is the name of the index
3180 ** and pTblList is the name of the table that is to be indexed.  Both will
3181 ** be NULL for a primary key or an index that is created to satisfy a
3182 ** UNIQUE constraint.  If pTable and pIndex are NULL, use pParse->pNewTable
3183 ** as the table to be indexed.  pParse->pNewTable is a table that is
3184 ** currently being constructed by a CREATE TABLE statement.
3185 **
3186 ** pList is a list of columns to be indexed.  pList will be NULL if this
3187 ** is a primary key or unique-constraint on the most recent column added
3188 ** to the table currently under construction.
3189 */
3190 void sqlite3CreateIndex(
3191   Parse *pParse,     /* All information about this parse */
3192   Token *pName1,     /* First part of index name. May be NULL */
3193   Token *pName2,     /* Second part of index name. May be NULL */
3194   SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
3195   ExprList *pList,   /* A list of columns to be indexed */
3196   int onError,       /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
3197   Token *pStart,     /* The CREATE token that begins this statement */
3198   Expr *pPIWhere,    /* WHERE clause for partial indices */
3199   int sortOrder,     /* Sort order of primary key when pList==NULL */
3200   int ifNotExist,    /* Omit error if index already exists */
3201   u8 idxType         /* The index type */
3202 ){
3203   Table *pTab = 0;     /* Table to be indexed */
3204   Index *pIndex = 0;   /* The index to be created */
3205   char *zName = 0;     /* Name of the index */
3206   int nName;           /* Number of characters in zName */
3207   int i, j;
3208   DbFixer sFix;        /* For assigning database names to pTable */
3209   int sortOrderMask;   /* 1 to honor DESC in index.  0 to ignore. */
3210   sqlite3 *db = pParse->db;
3211   Db *pDb;             /* The specific table containing the indexed database */
3212   int iDb;             /* Index of the database that is being written */
3213   Token *pName = 0;    /* Unqualified name of the index to create */
3214   struct ExprList_item *pListItem; /* For looping over pList */
3215   int nExtra = 0;                  /* Space allocated for zExtra[] */
3216   int nExtraCol;                   /* Number of extra columns needed */
3217   char *zExtra = 0;                /* Extra space after the Index object */
3218   Index *pPk = 0;      /* PRIMARY KEY index for WITHOUT ROWID tables */
3219 
3220   if( db->mallocFailed || pParse->nErr>0 ){
3221     goto exit_create_index;
3222   }
3223   if( IN_DECLARE_VTAB && idxType!=SQLITE_IDXTYPE_PRIMARYKEY ){
3224     goto exit_create_index;
3225   }
3226   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
3227     goto exit_create_index;
3228   }
3229   if( sqlite3HasExplicitNulls(pParse, pList) ){
3230     goto exit_create_index;
3231   }
3232 
3233   /*
3234   ** Find the table that is to be indexed.  Return early if not found.
3235   */
3236   if( pTblName!=0 ){
3237 
3238     /* Use the two-part index name to determine the database
3239     ** to search for the table. 'Fix' the table name to this db
3240     ** before looking up the table.
3241     */
3242     assert( pName1 && pName2 );
3243     iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
3244     if( iDb<0 ) goto exit_create_index;
3245     assert( pName && pName->z );
3246 
3247 #ifndef SQLITE_OMIT_TEMPDB
3248     /* If the index name was unqualified, check if the table
3249     ** is a temp table. If so, set the database to 1. Do not do this
3250     ** if initialising a database schema.
3251     */
3252     if( !db->init.busy ){
3253       pTab = sqlite3SrcListLookup(pParse, pTblName);
3254       if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
3255         iDb = 1;
3256       }
3257     }
3258 #endif
3259 
3260     sqlite3FixInit(&sFix, pParse, iDb, "index", pName);
3261     if( sqlite3FixSrcList(&sFix, pTblName) ){
3262       /* Because the parser constructs pTblName from a single identifier,
3263       ** sqlite3FixSrcList can never fail. */
3264       assert(0);
3265     }
3266     pTab = sqlite3LocateTableItem(pParse, 0, &pTblName->a[0]);
3267     assert( db->mallocFailed==0 || pTab==0 );
3268     if( pTab==0 ) goto exit_create_index;
3269     if( iDb==1 && db->aDb[iDb].pSchema!=pTab->pSchema ){
3270       sqlite3ErrorMsg(pParse,
3271            "cannot create a TEMP index on non-TEMP table \"%s\"",
3272            pTab->zName);
3273       goto exit_create_index;
3274     }
3275     if( !HasRowid(pTab) ) pPk = sqlite3PrimaryKeyIndex(pTab);
3276   }else{
3277     assert( pName==0 );
3278     assert( pStart==0 );
3279     pTab = pParse->pNewTable;
3280     if( !pTab ) goto exit_create_index;
3281     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
3282   }
3283   pDb = &db->aDb[iDb];
3284 
3285   assert( pTab!=0 );
3286   assert( pParse->nErr==0 );
3287   if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
3288        && db->init.busy==0
3289        && pTblName!=0
3290 #if SQLITE_USER_AUTHENTICATION
3291        && sqlite3UserAuthTable(pTab->zName)==0
3292 #endif
3293 #ifdef SQLITE_ALLOW_SQLITE_MASTER_INDEX
3294        && sqlite3StrICmp(&pTab->zName[7],"master")!=0
3295 #endif
3296  ){
3297     sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
3298     goto exit_create_index;
3299   }
3300 #ifndef SQLITE_OMIT_VIEW
3301   if( pTab->pSelect ){
3302     sqlite3ErrorMsg(pParse, "views may not be indexed");
3303     goto exit_create_index;
3304   }
3305 #endif
3306 #ifndef SQLITE_OMIT_VIRTUALTABLE
3307   if( IsVirtual(pTab) ){
3308     sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
3309     goto exit_create_index;
3310   }
3311 #endif
3312 
3313   /*
3314   ** Find the name of the index.  Make sure there is not already another
3315   ** index or table with the same name.
3316   **
3317   ** Exception:  If we are reading the names of permanent indices from the
3318   ** sqlite_master table (because some other process changed the schema) and
3319   ** one of the index names collides with the name of a temporary table or
3320   ** index, then we will continue to process this index.
3321   **
3322   ** If pName==0 it means that we are
3323   ** dealing with a primary key or UNIQUE constraint.  We have to invent our
3324   ** own name.
3325   */
3326   if( pName ){
3327     zName = sqlite3NameFromToken(db, pName);
3328     if( zName==0 ) goto exit_create_index;
3329     assert( pName->z!=0 );
3330     if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName,"index",pTab->zName) ){
3331       goto exit_create_index;
3332     }
3333     if( !IN_RENAME_OBJECT ){
3334       if( !db->init.busy ){
3335         if( sqlite3FindTable(db, zName, 0)!=0 ){
3336           sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
3337           goto exit_create_index;
3338         }
3339       }
3340       if( sqlite3FindIndex(db, zName, pDb->zDbSName)!=0 ){
3341         if( !ifNotExist ){
3342           sqlite3ErrorMsg(pParse, "index %s already exists", zName);
3343         }else{
3344           assert( !db->init.busy );
3345           sqlite3CodeVerifySchema(pParse, iDb);
3346         }
3347         goto exit_create_index;
3348       }
3349     }
3350   }else{
3351     int n;
3352     Index *pLoop;
3353     for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
3354     zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n);
3355     if( zName==0 ){
3356       goto exit_create_index;
3357     }
3358 
3359     /* Automatic index names generated from within sqlite3_declare_vtab()
3360     ** must have names that are distinct from normal automatic index names.
3361     ** The following statement converts "sqlite3_autoindex..." into
3362     ** "sqlite3_butoindex..." in order to make the names distinct.
3363     ** The "vtab_err.test" test demonstrates the need of this statement. */
3364     if( IN_SPECIAL_PARSE ) zName[7]++;
3365   }
3366 
3367   /* Check for authorization to create an index.
3368   */
3369 #ifndef SQLITE_OMIT_AUTHORIZATION
3370   if( !IN_RENAME_OBJECT ){
3371     const char *zDb = pDb->zDbSName;
3372     if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
3373       goto exit_create_index;
3374     }
3375     i = SQLITE_CREATE_INDEX;
3376     if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
3377     if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
3378       goto exit_create_index;
3379     }
3380   }
3381 #endif
3382 
3383   /* If pList==0, it means this routine was called to make a primary
3384   ** key out of the last column added to the table under construction.
3385   ** So create a fake list to simulate this.
3386   */
3387   if( pList==0 ){
3388     Token prevCol;
3389     Column *pCol = &pTab->aCol[pTab->nCol-1];
3390     pCol->colFlags |= COLFLAG_UNIQUE;
3391     sqlite3TokenInit(&prevCol, pCol->zName);
3392     pList = sqlite3ExprListAppend(pParse, 0,
3393               sqlite3ExprAlloc(db, TK_ID, &prevCol, 0));
3394     if( pList==0 ) goto exit_create_index;
3395     assert( pList->nExpr==1 );
3396     sqlite3ExprListSetSortOrder(pList, sortOrder, SQLITE_SO_UNDEFINED);
3397   }else{
3398     sqlite3ExprListCheckLength(pParse, pList, "index");
3399     if( pParse->nErr ) goto exit_create_index;
3400   }
3401 
3402   /* Figure out how many bytes of space are required to store explicitly
3403   ** specified collation sequence names.
3404   */
3405   for(i=0; i<pList->nExpr; i++){
3406     Expr *pExpr = pList->a[i].pExpr;
3407     assert( pExpr!=0 );
3408     if( pExpr->op==TK_COLLATE ){
3409       nExtra += (1 + sqlite3Strlen30(pExpr->u.zToken));
3410     }
3411   }
3412 
3413   /*
3414   ** Allocate the index structure.
3415   */
3416   nName = sqlite3Strlen30(zName);
3417   nExtraCol = pPk ? pPk->nKeyCol : 1;
3418   assert( pList->nExpr + nExtraCol <= 32767 /* Fits in i16 */ );
3419   pIndex = sqlite3AllocateIndexObject(db, pList->nExpr + nExtraCol,
3420                                       nName + nExtra + 1, &zExtra);
3421   if( db->mallocFailed ){
3422     goto exit_create_index;
3423   }
3424   assert( EIGHT_BYTE_ALIGNMENT(pIndex->aiRowLogEst) );
3425   assert( EIGHT_BYTE_ALIGNMENT(pIndex->azColl) );
3426   pIndex->zName = zExtra;
3427   zExtra += nName + 1;
3428   memcpy(pIndex->zName, zName, nName+1);
3429   pIndex->pTable = pTab;
3430   pIndex->onError = (u8)onError;
3431   pIndex->uniqNotNull = onError!=OE_None;
3432   pIndex->idxType = idxType;
3433   pIndex->pSchema = db->aDb[iDb].pSchema;
3434   pIndex->nKeyCol = pList->nExpr;
3435   if( pPIWhere ){
3436     sqlite3ResolveSelfReference(pParse, pTab, NC_PartIdx, pPIWhere, 0);
3437     pIndex->pPartIdxWhere = pPIWhere;
3438     pPIWhere = 0;
3439   }
3440   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
3441 
3442   /* Check to see if we should honor DESC requests on index columns
3443   */
3444   if( pDb->pSchema->file_format>=4 ){
3445     sortOrderMask = -1;   /* Honor DESC */
3446   }else{
3447     sortOrderMask = 0;    /* Ignore DESC */
3448   }
3449 
3450   /* Analyze the list of expressions that form the terms of the index and
3451   ** report any errors.  In the common case where the expression is exactly
3452   ** a table column, store that column in aiColumn[].  For general expressions,
3453   ** populate pIndex->aColExpr and store XN_EXPR (-2) in aiColumn[].
3454   **
3455   ** TODO: Issue a warning if two or more columns of the index are identical.
3456   ** TODO: Issue a warning if the table primary key is used as part of the
3457   ** index key.
3458   */
3459   pListItem = pList->a;
3460   if( IN_RENAME_OBJECT ){
3461     pIndex->aColExpr = pList;
3462     pList = 0;
3463   }
3464   for(i=0; i<pIndex->nKeyCol; i++, pListItem++){
3465     Expr *pCExpr;                  /* The i-th index expression */
3466     int requestedSortOrder;        /* ASC or DESC on the i-th expression */
3467     const char *zColl;             /* Collation sequence name */
3468 
3469     sqlite3StringToId(pListItem->pExpr);
3470     sqlite3ResolveSelfReference(pParse, pTab, NC_IdxExpr, pListItem->pExpr, 0);
3471     if( pParse->nErr ) goto exit_create_index;
3472     pCExpr = sqlite3ExprSkipCollate(pListItem->pExpr);
3473     if( pCExpr->op!=TK_COLUMN ){
3474       if( pTab==pParse->pNewTable ){
3475         sqlite3ErrorMsg(pParse, "expressions prohibited in PRIMARY KEY and "
3476                                 "UNIQUE constraints");
3477         goto exit_create_index;
3478       }
3479       if( pIndex->aColExpr==0 ){
3480         pIndex->aColExpr = pList;
3481         pList = 0;
3482       }
3483       j = XN_EXPR;
3484       pIndex->aiColumn[i] = XN_EXPR;
3485       pIndex->uniqNotNull = 0;
3486     }else{
3487       j = pCExpr->iColumn;
3488       assert( j<=0x7fff );
3489       if( j<0 ){
3490         j = pTab->iPKey;
3491       }else if( pTab->aCol[j].notNull==0 ){
3492         pIndex->uniqNotNull = 0;
3493       }
3494       pIndex->aiColumn[i] = (i16)j;
3495     }
3496     zColl = 0;
3497     if( pListItem->pExpr->op==TK_COLLATE ){
3498       int nColl;
3499       zColl = pListItem->pExpr->u.zToken;
3500       nColl = sqlite3Strlen30(zColl) + 1;
3501       assert( nExtra>=nColl );
3502       memcpy(zExtra, zColl, nColl);
3503       zColl = zExtra;
3504       zExtra += nColl;
3505       nExtra -= nColl;
3506     }else if( j>=0 ){
3507       zColl = pTab->aCol[j].zColl;
3508     }
3509     if( !zColl ) zColl = sqlite3StrBINARY;
3510     if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){
3511       goto exit_create_index;
3512     }
3513     pIndex->azColl[i] = zColl;
3514     requestedSortOrder = pListItem->sortFlags & sortOrderMask;
3515     pIndex->aSortOrder[i] = (u8)requestedSortOrder;
3516   }
3517 
3518   /* Append the table key to the end of the index.  For WITHOUT ROWID
3519   ** tables (when pPk!=0) this will be the declared PRIMARY KEY.  For
3520   ** normal tables (when pPk==0) this will be the rowid.
3521   */
3522   if( pPk ){
3523     for(j=0; j<pPk->nKeyCol; j++){
3524       int x = pPk->aiColumn[j];
3525       assert( x>=0 );
3526       if( isDupColumn(pIndex, pIndex->nKeyCol, pPk, j) ){
3527         pIndex->nColumn--;
3528       }else{
3529         testcase( hasColumn(pIndex->aiColumn,pIndex->nKeyCol,x) );
3530         pIndex->aiColumn[i] = x;
3531         pIndex->azColl[i] = pPk->azColl[j];
3532         pIndex->aSortOrder[i] = pPk->aSortOrder[j];
3533         i++;
3534       }
3535     }
3536     assert( i==pIndex->nColumn );
3537   }else{
3538     pIndex->aiColumn[i] = XN_ROWID;
3539     pIndex->azColl[i] = sqlite3StrBINARY;
3540   }
3541   sqlite3DefaultRowEst(pIndex);
3542   if( pParse->pNewTable==0 ) estimateIndexWidth(pIndex);
3543 
3544   /* If this index contains every column of its table, then mark
3545   ** it as a covering index */
3546   assert( HasRowid(pTab)
3547       || pTab->iPKey<0 || sqlite3ColumnOfIndex(pIndex, pTab->iPKey)>=0 );
3548   recomputeColumnsNotIndexed(pIndex);
3549   if( pTblName!=0 && pIndex->nColumn>=pTab->nCol ){
3550     pIndex->isCovering = 1;
3551     for(j=0; j<pTab->nCol; j++){
3552       if( j==pTab->iPKey ) continue;
3553       if( sqlite3ColumnOfIndex(pIndex,j)>=0 ) continue;
3554       pIndex->isCovering = 0;
3555       break;
3556     }
3557   }
3558 
3559   if( pTab==pParse->pNewTable ){
3560     /* This routine has been called to create an automatic index as a
3561     ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
3562     ** a PRIMARY KEY or UNIQUE clause following the column definitions.
3563     ** i.e. one of:
3564     **
3565     ** CREATE TABLE t(x PRIMARY KEY, y);
3566     ** CREATE TABLE t(x, y, UNIQUE(x, y));
3567     **
3568     ** Either way, check to see if the table already has such an index. If
3569     ** so, don't bother creating this one. This only applies to
3570     ** automatically created indices. Users can do as they wish with
3571     ** explicit indices.
3572     **
3573     ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent
3574     ** (and thus suppressing the second one) even if they have different
3575     ** sort orders.
3576     **
3577     ** If there are different collating sequences or if the columns of
3578     ** the constraint occur in different orders, then the constraints are
3579     ** considered distinct and both result in separate indices.
3580     */
3581     Index *pIdx;
3582     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
3583       int k;
3584       assert( IsUniqueIndex(pIdx) );
3585       assert( pIdx->idxType!=SQLITE_IDXTYPE_APPDEF );
3586       assert( IsUniqueIndex(pIndex) );
3587 
3588       if( pIdx->nKeyCol!=pIndex->nKeyCol ) continue;
3589       for(k=0; k<pIdx->nKeyCol; k++){
3590         const char *z1;
3591         const char *z2;
3592         assert( pIdx->aiColumn[k]>=0 );
3593         if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
3594         z1 = pIdx->azColl[k];
3595         z2 = pIndex->azColl[k];
3596         if( sqlite3StrICmp(z1, z2) ) break;
3597       }
3598       if( k==pIdx->nKeyCol ){
3599         if( pIdx->onError!=pIndex->onError ){
3600           /* This constraint creates the same index as a previous
3601           ** constraint specified somewhere in the CREATE TABLE statement.
3602           ** However the ON CONFLICT clauses are different. If both this
3603           ** constraint and the previous equivalent constraint have explicit
3604           ** ON CONFLICT clauses this is an error. Otherwise, use the
3605           ** explicitly specified behavior for the index.
3606           */
3607           if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
3608             sqlite3ErrorMsg(pParse,
3609                 "conflicting ON CONFLICT clauses specified", 0);
3610           }
3611           if( pIdx->onError==OE_Default ){
3612             pIdx->onError = pIndex->onError;
3613           }
3614         }
3615         if( idxType==SQLITE_IDXTYPE_PRIMARYKEY ) pIdx->idxType = idxType;
3616         if( IN_RENAME_OBJECT ){
3617           pIndex->pNext = pParse->pNewIndex;
3618           pParse->pNewIndex = pIndex;
3619           pIndex = 0;
3620         }
3621         goto exit_create_index;
3622       }
3623     }
3624   }
3625 
3626   if( !IN_RENAME_OBJECT ){
3627 
3628     /* Link the new Index structure to its table and to the other
3629     ** in-memory database structures.
3630     */
3631     assert( pParse->nErr==0 );
3632     if( db->init.busy ){
3633       Index *p;
3634       assert( !IN_SPECIAL_PARSE );
3635       assert( sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
3636       if( pTblName!=0 ){
3637         pIndex->tnum = db->init.newTnum;
3638         if( sqlite3IndexHasDuplicateRootPage(pIndex) ){
3639           sqlite3ErrorMsg(pParse, "invalid rootpage");
3640           pParse->rc = SQLITE_CORRUPT_BKPT;
3641           goto exit_create_index;
3642         }
3643       }
3644       p = sqlite3HashInsert(&pIndex->pSchema->idxHash,
3645           pIndex->zName, pIndex);
3646       if( p ){
3647         assert( p==pIndex );  /* Malloc must have failed */
3648         sqlite3OomFault(db);
3649         goto exit_create_index;
3650       }
3651       db->mDbFlags |= DBFLAG_SchemaChange;
3652     }
3653 
3654     /* If this is the initial CREATE INDEX statement (or CREATE TABLE if the
3655     ** index is an implied index for a UNIQUE or PRIMARY KEY constraint) then
3656     ** emit code to allocate the index rootpage on disk and make an entry for
3657     ** the index in the sqlite_master table and populate the index with
3658     ** content.  But, do not do this if we are simply reading the sqlite_master
3659     ** table to parse the schema, or if this index is the PRIMARY KEY index
3660     ** of a WITHOUT ROWID table.
3661     **
3662     ** If pTblName==0 it means this index is generated as an implied PRIMARY KEY
3663     ** or UNIQUE index in a CREATE TABLE statement.  Since the table
3664     ** has just been created, it contains no data and the index initialization
3665     ** step can be skipped.
3666     */
3667     else if( HasRowid(pTab) || pTblName!=0 ){
3668       Vdbe *v;
3669       char *zStmt;
3670       int iMem = ++pParse->nMem;
3671 
3672       v = sqlite3GetVdbe(pParse);
3673       if( v==0 ) goto exit_create_index;
3674 
3675       sqlite3BeginWriteOperation(pParse, 1, iDb);
3676 
3677       /* Create the rootpage for the index using CreateIndex. But before
3678       ** doing so, code a Noop instruction and store its address in
3679       ** Index.tnum. This is required in case this index is actually a
3680       ** PRIMARY KEY and the table is actually a WITHOUT ROWID table. In
3681       ** that case the convertToWithoutRowidTable() routine will replace
3682       ** the Noop with a Goto to jump over the VDBE code generated below. */
3683       pIndex->tnum = sqlite3VdbeAddOp0(v, OP_Noop);
3684       sqlite3VdbeAddOp3(v, OP_CreateBtree, iDb, iMem, BTREE_BLOBKEY);
3685 
3686       /* Gather the complete text of the CREATE INDEX statement into
3687       ** the zStmt variable
3688       */
3689       assert( pName!=0 || pStart==0 );
3690       if( pStart ){
3691         int n = (int)(pParse->sLastToken.z - pName->z) + pParse->sLastToken.n;
3692         if( pName->z[n-1]==';' ) n--;
3693         /* A named index with an explicit CREATE INDEX statement */
3694         zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
3695             onError==OE_None ? "" : " UNIQUE", n, pName->z);
3696       }else{
3697         /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
3698         /* zStmt = sqlite3MPrintf(""); */
3699         zStmt = 0;
3700       }
3701 
3702       /* Add an entry in sqlite_master for this index
3703       */
3704       sqlite3NestedParse(pParse,
3705           "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);",
3706           db->aDb[iDb].zDbSName, MASTER_NAME,
3707           pIndex->zName,
3708           pTab->zName,
3709           iMem,
3710           zStmt
3711           );
3712       sqlite3DbFree(db, zStmt);
3713 
3714       /* Fill the index with data and reparse the schema. Code an OP_Expire
3715       ** to invalidate all pre-compiled statements.
3716       */
3717       if( pTblName ){
3718         sqlite3RefillIndex(pParse, pIndex, iMem);
3719         sqlite3ChangeCookie(pParse, iDb);
3720         sqlite3VdbeAddParseSchemaOp(v, iDb,
3721             sqlite3MPrintf(db, "name='%q' AND type='index'", pIndex->zName));
3722         sqlite3VdbeAddOp2(v, OP_Expire, 0, 1);
3723       }
3724 
3725       sqlite3VdbeJumpHere(v, pIndex->tnum);
3726     }
3727   }
3728 
3729   /* When adding an index to the list of indices for a table, make
3730   ** sure all indices labeled OE_Replace come after all those labeled
3731   ** OE_Ignore.  This is necessary for the correct constraint check
3732   ** processing (in sqlite3GenerateConstraintChecks()) as part of
3733   ** UPDATE and INSERT statements.
3734   */
3735   if( db->init.busy || pTblName==0 ){
3736     if( onError!=OE_Replace || pTab->pIndex==0
3737          || pTab->pIndex->onError==OE_Replace){
3738       pIndex->pNext = pTab->pIndex;
3739       pTab->pIndex = pIndex;
3740     }else{
3741       Index *pOther = pTab->pIndex;
3742       while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
3743         pOther = pOther->pNext;
3744       }
3745       pIndex->pNext = pOther->pNext;
3746       pOther->pNext = pIndex;
3747     }
3748     pIndex = 0;
3749   }
3750   else if( IN_RENAME_OBJECT ){
3751     assert( pParse->pNewIndex==0 );
3752     pParse->pNewIndex = pIndex;
3753     pIndex = 0;
3754   }
3755 
3756   /* Clean up before exiting */
3757 exit_create_index:
3758   if( pIndex ) sqlite3FreeIndex(db, pIndex);
3759   sqlite3ExprDelete(db, pPIWhere);
3760   sqlite3ExprListDelete(db, pList);
3761   sqlite3SrcListDelete(db, pTblName);
3762   sqlite3DbFree(db, zName);
3763 }
3764 
3765 /*
3766 ** Fill the Index.aiRowEst[] array with default information - information
3767 ** to be used when we have not run the ANALYZE command.
3768 **
3769 ** aiRowEst[0] is supposed to contain the number of elements in the index.
3770 ** Since we do not know, guess 1 million.  aiRowEst[1] is an estimate of the
3771 ** number of rows in the table that match any particular value of the
3772 ** first column of the index.  aiRowEst[2] is an estimate of the number
3773 ** of rows that match any particular combination of the first 2 columns
3774 ** of the index.  And so forth.  It must always be the case that
3775 *
3776 **           aiRowEst[N]<=aiRowEst[N-1]
3777 **           aiRowEst[N]>=1
3778 **
3779 ** Apart from that, we have little to go on besides intuition as to
3780 ** how aiRowEst[] should be initialized.  The numbers generated here
3781 ** are based on typical values found in actual indices.
3782 */
3783 void sqlite3DefaultRowEst(Index *pIdx){
3784   /*                10,  9,  8,  7,  6 */
3785   LogEst aVal[] = { 33, 32, 30, 28, 26 };
3786   LogEst *a = pIdx->aiRowLogEst;
3787   int nCopy = MIN(ArraySize(aVal), pIdx->nKeyCol);
3788   int i;
3789 
3790   /* Indexes with default row estimates should not have stat1 data */
3791   assert( !pIdx->hasStat1 );
3792 
3793   /* Set the first entry (number of rows in the index) to the estimated
3794   ** number of rows in the table, or half the number of rows in the table
3795   ** for a partial index.   But do not let the estimate drop below 10. */
3796   a[0] = pIdx->pTable->nRowLogEst;
3797   if( pIdx->pPartIdxWhere!=0 ) a[0] -= 10;  assert( 10==sqlite3LogEst(2) );
3798   if( a[0]<33 ) a[0] = 33;                  assert( 33==sqlite3LogEst(10) );
3799 
3800   /* Estimate that a[1] is 10, a[2] is 9, a[3] is 8, a[4] is 7, a[5] is
3801   ** 6 and each subsequent value (if any) is 5.  */
3802   memcpy(&a[1], aVal, nCopy*sizeof(LogEst));
3803   for(i=nCopy+1; i<=pIdx->nKeyCol; i++){
3804     a[i] = 23;                    assert( 23==sqlite3LogEst(5) );
3805   }
3806 
3807   assert( 0==sqlite3LogEst(1) );
3808   if( IsUniqueIndex(pIdx) ) a[pIdx->nKeyCol] = 0;
3809 }
3810 
3811 /*
3812 ** This routine will drop an existing named index.  This routine
3813 ** implements the DROP INDEX statement.
3814 */
3815 void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
3816   Index *pIndex;
3817   Vdbe *v;
3818   sqlite3 *db = pParse->db;
3819   int iDb;
3820 
3821   assert( pParse->nErr==0 );   /* Never called with prior errors */
3822   if( db->mallocFailed ){
3823     goto exit_drop_index;
3824   }
3825   assert( pName->nSrc==1 );
3826   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
3827     goto exit_drop_index;
3828   }
3829   pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
3830   if( pIndex==0 ){
3831     if( !ifExists ){
3832       sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
3833     }else{
3834       sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
3835     }
3836     pParse->checkSchema = 1;
3837     goto exit_drop_index;
3838   }
3839   if( pIndex->idxType!=SQLITE_IDXTYPE_APPDEF ){
3840     sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
3841       "or PRIMARY KEY constraint cannot be dropped", 0);
3842     goto exit_drop_index;
3843   }
3844   iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
3845 #ifndef SQLITE_OMIT_AUTHORIZATION
3846   {
3847     int code = SQLITE_DROP_INDEX;
3848     Table *pTab = pIndex->pTable;
3849     const char *zDb = db->aDb[iDb].zDbSName;
3850     const char *zTab = SCHEMA_TABLE(iDb);
3851     if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
3852       goto exit_drop_index;
3853     }
3854     if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
3855     if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
3856       goto exit_drop_index;
3857     }
3858   }
3859 #endif
3860 
3861   /* Generate code to remove the index and from the master table */
3862   v = sqlite3GetVdbe(pParse);
3863   if( v ){
3864     sqlite3BeginWriteOperation(pParse, 1, iDb);
3865     sqlite3NestedParse(pParse,
3866        "DELETE FROM %Q.%s WHERE name=%Q AND type='index'",
3867        db->aDb[iDb].zDbSName, MASTER_NAME, pIndex->zName
3868     );
3869     sqlite3ClearStatTables(pParse, iDb, "idx", pIndex->zName);
3870     sqlite3ChangeCookie(pParse, iDb);
3871     destroyRootPage(pParse, pIndex->tnum, iDb);
3872     sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
3873   }
3874 
3875 exit_drop_index:
3876   sqlite3SrcListDelete(db, pName);
3877 }
3878 
3879 /*
3880 ** pArray is a pointer to an array of objects. Each object in the
3881 ** array is szEntry bytes in size. This routine uses sqlite3DbRealloc()
3882 ** to extend the array so that there is space for a new object at the end.
3883 **
3884 ** When this function is called, *pnEntry contains the current size of
3885 ** the array (in entries - so the allocation is ((*pnEntry) * szEntry) bytes
3886 ** in total).
3887 **
3888 ** If the realloc() is successful (i.e. if no OOM condition occurs), the
3889 ** space allocated for the new object is zeroed, *pnEntry updated to
3890 ** reflect the new size of the array and a pointer to the new allocation
3891 ** returned. *pIdx is set to the index of the new array entry in this case.
3892 **
3893 ** Otherwise, if the realloc() fails, *pIdx is set to -1, *pnEntry remains
3894 ** unchanged and a copy of pArray returned.
3895 */
3896 void *sqlite3ArrayAllocate(
3897   sqlite3 *db,      /* Connection to notify of malloc failures */
3898   void *pArray,     /* Array of objects.  Might be reallocated */
3899   int szEntry,      /* Size of each object in the array */
3900   int *pnEntry,     /* Number of objects currently in use */
3901   int *pIdx         /* Write the index of a new slot here */
3902 ){
3903   char *z;
3904   sqlite3_int64 n = *pIdx = *pnEntry;
3905   if( (n & (n-1))==0 ){
3906     sqlite3_int64 sz = (n==0) ? 1 : 2*n;
3907     void *pNew = sqlite3DbRealloc(db, pArray, sz*szEntry);
3908     if( pNew==0 ){
3909       *pIdx = -1;
3910       return pArray;
3911     }
3912     pArray = pNew;
3913   }
3914   z = (char*)pArray;
3915   memset(&z[n * szEntry], 0, szEntry);
3916   ++*pnEntry;
3917   return pArray;
3918 }
3919 
3920 /*
3921 ** Append a new element to the given IdList.  Create a new IdList if
3922 ** need be.
3923 **
3924 ** A new IdList is returned, or NULL if malloc() fails.
3925 */
3926 IdList *sqlite3IdListAppend(Parse *pParse, IdList *pList, Token *pToken){
3927   sqlite3 *db = pParse->db;
3928   int i;
3929   if( pList==0 ){
3930     pList = sqlite3DbMallocZero(db, sizeof(IdList) );
3931     if( pList==0 ) return 0;
3932   }
3933   pList->a = sqlite3ArrayAllocate(
3934       db,
3935       pList->a,
3936       sizeof(pList->a[0]),
3937       &pList->nId,
3938       &i
3939   );
3940   if( i<0 ){
3941     sqlite3IdListDelete(db, pList);
3942     return 0;
3943   }
3944   pList->a[i].zName = sqlite3NameFromToken(db, pToken);
3945   if( IN_RENAME_OBJECT && pList->a[i].zName ){
3946     sqlite3RenameTokenMap(pParse, (void*)pList->a[i].zName, pToken);
3947   }
3948   return pList;
3949 }
3950 
3951 /*
3952 ** Delete an IdList.
3953 */
3954 void sqlite3IdListDelete(sqlite3 *db, IdList *pList){
3955   int i;
3956   if( pList==0 ) return;
3957   for(i=0; i<pList->nId; i++){
3958     sqlite3DbFree(db, pList->a[i].zName);
3959   }
3960   sqlite3DbFree(db, pList->a);
3961   sqlite3DbFreeNN(db, pList);
3962 }
3963 
3964 /*
3965 ** Return the index in pList of the identifier named zId.  Return -1
3966 ** if not found.
3967 */
3968 int sqlite3IdListIndex(IdList *pList, const char *zName){
3969   int i;
3970   if( pList==0 ) return -1;
3971   for(i=0; i<pList->nId; i++){
3972     if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
3973   }
3974   return -1;
3975 }
3976 
3977 /*
3978 ** Maximum size of a SrcList object.
3979 ** The SrcList object is used to represent the FROM clause of a
3980 ** SELECT statement, and the query planner cannot deal with more
3981 ** than 64 tables in a join.  So any value larger than 64 here
3982 ** is sufficient for most uses.  Smaller values, like say 10, are
3983 ** appropriate for small and memory-limited applications.
3984 */
3985 #ifndef SQLITE_MAX_SRCLIST
3986 # define SQLITE_MAX_SRCLIST 200
3987 #endif
3988 
3989 /*
3990 ** Expand the space allocated for the given SrcList object by
3991 ** creating nExtra new slots beginning at iStart.  iStart is zero based.
3992 ** New slots are zeroed.
3993 **
3994 ** For example, suppose a SrcList initially contains two entries: A,B.
3995 ** To append 3 new entries onto the end, do this:
3996 **
3997 **    sqlite3SrcListEnlarge(db, pSrclist, 3, 2);
3998 **
3999 ** After the call above it would contain:  A, B, nil, nil, nil.
4000 ** If the iStart argument had been 1 instead of 2, then the result
4001 ** would have been:  A, nil, nil, nil, B.  To prepend the new slots,
4002 ** the iStart value would be 0.  The result then would
4003 ** be: nil, nil, nil, A, B.
4004 **
4005 ** If a memory allocation fails or the SrcList becomes too large, leave
4006 ** the original SrcList unchanged, return NULL, and leave an error message
4007 ** in pParse.
4008 */
4009 SrcList *sqlite3SrcListEnlarge(
4010   Parse *pParse,     /* Parsing context into which errors are reported */
4011   SrcList *pSrc,     /* The SrcList to be enlarged */
4012   int nExtra,        /* Number of new slots to add to pSrc->a[] */
4013   int iStart         /* Index in pSrc->a[] of first new slot */
4014 ){
4015   int i;
4016 
4017   /* Sanity checking on calling parameters */
4018   assert( iStart>=0 );
4019   assert( nExtra>=1 );
4020   assert( pSrc!=0 );
4021   assert( iStart<=pSrc->nSrc );
4022 
4023   /* Allocate additional space if needed */
4024   if( (u32)pSrc->nSrc+nExtra>pSrc->nAlloc ){
4025     SrcList *pNew;
4026     sqlite3_int64 nAlloc = 2*(sqlite3_int64)pSrc->nSrc+nExtra;
4027     sqlite3 *db = pParse->db;
4028 
4029     if( pSrc->nSrc+nExtra>=SQLITE_MAX_SRCLIST ){
4030       sqlite3ErrorMsg(pParse, "too many FROM clause terms, max: %d",
4031                       SQLITE_MAX_SRCLIST);
4032       return 0;
4033     }
4034     if( nAlloc>SQLITE_MAX_SRCLIST ) nAlloc = SQLITE_MAX_SRCLIST;
4035     pNew = sqlite3DbRealloc(db, pSrc,
4036                sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) );
4037     if( pNew==0 ){
4038       assert( db->mallocFailed );
4039       return 0;
4040     }
4041     pSrc = pNew;
4042     pSrc->nAlloc = nAlloc;
4043   }
4044 
4045   /* Move existing slots that come after the newly inserted slots
4046   ** out of the way */
4047   for(i=pSrc->nSrc-1; i>=iStart; i--){
4048     pSrc->a[i+nExtra] = pSrc->a[i];
4049   }
4050   pSrc->nSrc += nExtra;
4051 
4052   /* Zero the newly allocated slots */
4053   memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
4054   for(i=iStart; i<iStart+nExtra; i++){
4055     pSrc->a[i].iCursor = -1;
4056   }
4057 
4058   /* Return a pointer to the enlarged SrcList */
4059   return pSrc;
4060 }
4061 
4062 
4063 /*
4064 ** Append a new table name to the given SrcList.  Create a new SrcList if
4065 ** need be.  A new entry is created in the SrcList even if pTable is NULL.
4066 **
4067 ** A SrcList is returned, or NULL if there is an OOM error or if the
4068 ** SrcList grows to large.  The returned
4069 ** SrcList might be the same as the SrcList that was input or it might be
4070 ** a new one.  If an OOM error does occurs, then the prior value of pList
4071 ** that is input to this routine is automatically freed.
4072 **
4073 ** If pDatabase is not null, it means that the table has an optional
4074 ** database name prefix.  Like this:  "database.table".  The pDatabase
4075 ** points to the table name and the pTable points to the database name.
4076 ** The SrcList.a[].zName field is filled with the table name which might
4077 ** come from pTable (if pDatabase is NULL) or from pDatabase.
4078 ** SrcList.a[].zDatabase is filled with the database name from pTable,
4079 ** or with NULL if no database is specified.
4080 **
4081 ** In other words, if call like this:
4082 **
4083 **         sqlite3SrcListAppend(D,A,B,0);
4084 **
4085 ** Then B is a table name and the database name is unspecified.  If called
4086 ** like this:
4087 **
4088 **         sqlite3SrcListAppend(D,A,B,C);
4089 **
4090 ** Then C is the table name and B is the database name.  If C is defined
4091 ** then so is B.  In other words, we never have a case where:
4092 **
4093 **         sqlite3SrcListAppend(D,A,0,C);
4094 **
4095 ** Both pTable and pDatabase are assumed to be quoted.  They are dequoted
4096 ** before being added to the SrcList.
4097 */
4098 SrcList *sqlite3SrcListAppend(
4099   Parse *pParse,      /* Parsing context, in which errors are reported */
4100   SrcList *pList,     /* Append to this SrcList. NULL creates a new SrcList */
4101   Token *pTable,      /* Table to append */
4102   Token *pDatabase    /* Database of the table */
4103 ){
4104   struct SrcList_item *pItem;
4105   sqlite3 *db;
4106   assert( pDatabase==0 || pTable!=0 );  /* Cannot have C without B */
4107   assert( pParse!=0 );
4108   assert( pParse->db!=0 );
4109   db = pParse->db;
4110   if( pList==0 ){
4111     pList = sqlite3DbMallocRawNN(pParse->db, sizeof(SrcList) );
4112     if( pList==0 ) return 0;
4113     pList->nAlloc = 1;
4114     pList->nSrc = 1;
4115     memset(&pList->a[0], 0, sizeof(pList->a[0]));
4116     pList->a[0].iCursor = -1;
4117   }else{
4118     SrcList *pNew = sqlite3SrcListEnlarge(pParse, pList, 1, pList->nSrc);
4119     if( pNew==0 ){
4120       sqlite3SrcListDelete(db, pList);
4121       return 0;
4122     }else{
4123       pList = pNew;
4124     }
4125   }
4126   pItem = &pList->a[pList->nSrc-1];
4127   if( pDatabase && pDatabase->z==0 ){
4128     pDatabase = 0;
4129   }
4130   if( pDatabase ){
4131     pItem->zName = sqlite3NameFromToken(db, pDatabase);
4132     pItem->zDatabase = sqlite3NameFromToken(db, pTable);
4133   }else{
4134     pItem->zName = sqlite3NameFromToken(db, pTable);
4135     pItem->zDatabase = 0;
4136   }
4137   return pList;
4138 }
4139 
4140 /*
4141 ** Assign VdbeCursor index numbers to all tables in a SrcList
4142 */
4143 void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
4144   int i;
4145   struct SrcList_item *pItem;
4146   assert(pList || pParse->db->mallocFailed );
4147   if( pList ){
4148     for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
4149       if( pItem->iCursor>=0 ) break;
4150       pItem->iCursor = pParse->nTab++;
4151       if( pItem->pSelect ){
4152         sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
4153       }
4154     }
4155   }
4156 }
4157 
4158 /*
4159 ** Delete an entire SrcList including all its substructure.
4160 */
4161 void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){
4162   int i;
4163   struct SrcList_item *pItem;
4164   if( pList==0 ) return;
4165   for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
4166     sqlite3DbFree(db, pItem->zDatabase);
4167     sqlite3DbFree(db, pItem->zName);
4168     sqlite3DbFree(db, pItem->zAlias);
4169     if( pItem->fg.isIndexedBy ) sqlite3DbFree(db, pItem->u1.zIndexedBy);
4170     if( pItem->fg.isTabFunc ) sqlite3ExprListDelete(db, pItem->u1.pFuncArg);
4171     sqlite3DeleteTable(db, pItem->pTab);
4172     sqlite3SelectDelete(db, pItem->pSelect);
4173     sqlite3ExprDelete(db, pItem->pOn);
4174     sqlite3IdListDelete(db, pItem->pUsing);
4175   }
4176   sqlite3DbFreeNN(db, pList);
4177 }
4178 
4179 /*
4180 ** This routine is called by the parser to add a new term to the
4181 ** end of a growing FROM clause.  The "p" parameter is the part of
4182 ** the FROM clause that has already been constructed.  "p" is NULL
4183 ** if this is the first term of the FROM clause.  pTable and pDatabase
4184 ** are the name of the table and database named in the FROM clause term.
4185 ** pDatabase is NULL if the database name qualifier is missing - the
4186 ** usual case.  If the term has an alias, then pAlias points to the
4187 ** alias token.  If the term is a subquery, then pSubquery is the
4188 ** SELECT statement that the subquery encodes.  The pTable and
4189 ** pDatabase parameters are NULL for subqueries.  The pOn and pUsing
4190 ** parameters are the content of the ON and USING clauses.
4191 **
4192 ** Return a new SrcList which encodes is the FROM with the new
4193 ** term added.
4194 */
4195 SrcList *sqlite3SrcListAppendFromTerm(
4196   Parse *pParse,          /* Parsing context */
4197   SrcList *p,             /* The left part of the FROM clause already seen */
4198   Token *pTable,          /* Name of the table to add to the FROM clause */
4199   Token *pDatabase,       /* Name of the database containing pTable */
4200   Token *pAlias,          /* The right-hand side of the AS subexpression */
4201   Select *pSubquery,      /* A subquery used in place of a table name */
4202   Expr *pOn,              /* The ON clause of a join */
4203   IdList *pUsing          /* The USING clause of a join */
4204 ){
4205   struct SrcList_item *pItem;
4206   sqlite3 *db = pParse->db;
4207   if( !p && (pOn || pUsing) ){
4208     sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s",
4209       (pOn ? "ON" : "USING")
4210     );
4211     goto append_from_error;
4212   }
4213   p = sqlite3SrcListAppend(pParse, p, pTable, pDatabase);
4214   if( p==0 ){
4215     goto append_from_error;
4216   }
4217   assert( p->nSrc>0 );
4218   pItem = &p->a[p->nSrc-1];
4219   assert( (pTable==0)==(pDatabase==0) );
4220   assert( pItem->zName==0 || pDatabase!=0 );
4221   if( IN_RENAME_OBJECT && pItem->zName ){
4222     Token *pToken = (ALWAYS(pDatabase) && pDatabase->z) ? pDatabase : pTable;
4223     sqlite3RenameTokenMap(pParse, pItem->zName, pToken);
4224   }
4225   assert( pAlias!=0 );
4226   if( pAlias->n ){
4227     pItem->zAlias = sqlite3NameFromToken(db, pAlias);
4228   }
4229   pItem->pSelect = pSubquery;
4230   pItem->pOn = pOn;
4231   pItem->pUsing = pUsing;
4232   return p;
4233 
4234  append_from_error:
4235   assert( p==0 );
4236   sqlite3ExprDelete(db, pOn);
4237   sqlite3IdListDelete(db, pUsing);
4238   sqlite3SelectDelete(db, pSubquery);
4239   return 0;
4240 }
4241 
4242 /*
4243 ** Add an INDEXED BY or NOT INDEXED clause to the most recently added
4244 ** element of the source-list passed as the second argument.
4245 */
4246 void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){
4247   assert( pIndexedBy!=0 );
4248   if( p && pIndexedBy->n>0 ){
4249     struct SrcList_item *pItem;
4250     assert( p->nSrc>0 );
4251     pItem = &p->a[p->nSrc-1];
4252     assert( pItem->fg.notIndexed==0 );
4253     assert( pItem->fg.isIndexedBy==0 );
4254     assert( pItem->fg.isTabFunc==0 );
4255     if( pIndexedBy->n==1 && !pIndexedBy->z ){
4256       /* A "NOT INDEXED" clause was supplied. See parse.y
4257       ** construct "indexed_opt" for details. */
4258       pItem->fg.notIndexed = 1;
4259     }else{
4260       pItem->u1.zIndexedBy = sqlite3NameFromToken(pParse->db, pIndexedBy);
4261       pItem->fg.isIndexedBy = 1;
4262     }
4263   }
4264 }
4265 
4266 /*
4267 ** Add the list of function arguments to the SrcList entry for a
4268 ** table-valued-function.
4269 */
4270 void sqlite3SrcListFuncArgs(Parse *pParse, SrcList *p, ExprList *pList){
4271   if( p ){
4272     struct SrcList_item *pItem = &p->a[p->nSrc-1];
4273     assert( pItem->fg.notIndexed==0 );
4274     assert( pItem->fg.isIndexedBy==0 );
4275     assert( pItem->fg.isTabFunc==0 );
4276     pItem->u1.pFuncArg = pList;
4277     pItem->fg.isTabFunc = 1;
4278   }else{
4279     sqlite3ExprListDelete(pParse->db, pList);
4280   }
4281 }
4282 
4283 /*
4284 ** When building up a FROM clause in the parser, the join operator
4285 ** is initially attached to the left operand.  But the code generator
4286 ** expects the join operator to be on the right operand.  This routine
4287 ** Shifts all join operators from left to right for an entire FROM
4288 ** clause.
4289 **
4290 ** Example: Suppose the join is like this:
4291 **
4292 **           A natural cross join B
4293 **
4294 ** The operator is "natural cross join".  The A and B operands are stored
4295 ** in p->a[0] and p->a[1], respectively.  The parser initially stores the
4296 ** operator with A.  This routine shifts that operator over to B.
4297 */
4298 void sqlite3SrcListShiftJoinType(SrcList *p){
4299   if( p ){
4300     int i;
4301     for(i=p->nSrc-1; i>0; i--){
4302       p->a[i].fg.jointype = p->a[i-1].fg.jointype;
4303     }
4304     p->a[0].fg.jointype = 0;
4305   }
4306 }
4307 
4308 /*
4309 ** Generate VDBE code for a BEGIN statement.
4310 */
4311 void sqlite3BeginTransaction(Parse *pParse, int type){
4312   sqlite3 *db;
4313   Vdbe *v;
4314   int i;
4315 
4316   assert( pParse!=0 );
4317   db = pParse->db;
4318   assert( db!=0 );
4319   if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){
4320     return;
4321   }
4322   v = sqlite3GetVdbe(pParse);
4323   if( !v ) return;
4324   if( type!=TK_DEFERRED ){
4325     for(i=0; i<db->nDb; i++){
4326       sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
4327       sqlite3VdbeUsesBtree(v, i);
4328     }
4329   }
4330   sqlite3VdbeAddOp0(v, OP_AutoCommit);
4331 }
4332 
4333 /*
4334 ** Generate VDBE code for a COMMIT or ROLLBACK statement.
4335 ** Code for ROLLBACK is generated if eType==TK_ROLLBACK.  Otherwise
4336 ** code is generated for a COMMIT.
4337 */
4338 void sqlite3EndTransaction(Parse *pParse, int eType){
4339   Vdbe *v;
4340   int isRollback;
4341 
4342   assert( pParse!=0 );
4343   assert( pParse->db!=0 );
4344   assert( eType==TK_COMMIT || eType==TK_END || eType==TK_ROLLBACK );
4345   isRollback = eType==TK_ROLLBACK;
4346   if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION,
4347        isRollback ? "ROLLBACK" : "COMMIT", 0, 0) ){
4348     return;
4349   }
4350   v = sqlite3GetVdbe(pParse);
4351   if( v ){
4352     sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, isRollback);
4353   }
4354 }
4355 
4356 /*
4357 ** This function is called by the parser when it parses a command to create,
4358 ** release or rollback an SQL savepoint.
4359 */
4360 void sqlite3Savepoint(Parse *pParse, int op, Token *pName){
4361   char *zName = sqlite3NameFromToken(pParse->db, pName);
4362   if( zName ){
4363     Vdbe *v = sqlite3GetVdbe(pParse);
4364 #ifndef SQLITE_OMIT_AUTHORIZATION
4365     static const char * const az[] = { "BEGIN", "RELEASE", "ROLLBACK" };
4366     assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 );
4367 #endif
4368     if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){
4369       sqlite3DbFree(pParse->db, zName);
4370       return;
4371     }
4372     sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC);
4373   }
4374 }
4375 
4376 /*
4377 ** Make sure the TEMP database is open and available for use.  Return
4378 ** the number of errors.  Leave any error messages in the pParse structure.
4379 */
4380 int sqlite3OpenTempDatabase(Parse *pParse){
4381   sqlite3 *db = pParse->db;
4382   if( db->aDb[1].pBt==0 && !pParse->explain ){
4383     int rc;
4384     Btree *pBt;
4385     static const int flags =
4386           SQLITE_OPEN_READWRITE |
4387           SQLITE_OPEN_CREATE |
4388           SQLITE_OPEN_EXCLUSIVE |
4389           SQLITE_OPEN_DELETEONCLOSE |
4390           SQLITE_OPEN_TEMP_DB;
4391 
4392     rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pBt, 0, flags);
4393     if( rc!=SQLITE_OK ){
4394       sqlite3ErrorMsg(pParse, "unable to open a temporary database "
4395         "file for storing temporary tables");
4396       pParse->rc = rc;
4397       return 1;
4398     }
4399     db->aDb[1].pBt = pBt;
4400     assert( db->aDb[1].pSchema );
4401     if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){
4402       sqlite3OomFault(db);
4403       return 1;
4404     }
4405   }
4406   return 0;
4407 }
4408 
4409 /*
4410 ** Record the fact that the schema cookie will need to be verified
4411 ** for database iDb.  The code to actually verify the schema cookie
4412 ** will occur at the end of the top-level VDBE and will be generated
4413 ** later, by sqlite3FinishCoding().
4414 */
4415 void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
4416   Parse *pToplevel = sqlite3ParseToplevel(pParse);
4417 
4418   assert( iDb>=0 && iDb<pParse->db->nDb );
4419   assert( pParse->db->aDb[iDb].pBt!=0 || iDb==1 );
4420   assert( iDb<SQLITE_MAX_ATTACHED+2 );
4421   assert( sqlite3SchemaMutexHeld(pParse->db, iDb, 0) );
4422   if( DbMaskTest(pToplevel->cookieMask, iDb)==0 ){
4423     DbMaskSet(pToplevel->cookieMask, iDb);
4424     if( !OMIT_TEMPDB && iDb==1 ){
4425       sqlite3OpenTempDatabase(pToplevel);
4426     }
4427   }
4428 }
4429 
4430 /*
4431 ** If argument zDb is NULL, then call sqlite3CodeVerifySchema() for each
4432 ** attached database. Otherwise, invoke it for the database named zDb only.
4433 */
4434 void sqlite3CodeVerifyNamedSchema(Parse *pParse, const char *zDb){
4435   sqlite3 *db = pParse->db;
4436   int i;
4437   for(i=0; i<db->nDb; i++){
4438     Db *pDb = &db->aDb[i];
4439     if( pDb->pBt && (!zDb || 0==sqlite3StrICmp(zDb, pDb->zDbSName)) ){
4440       sqlite3CodeVerifySchema(pParse, i);
4441     }
4442   }
4443 }
4444 
4445 /*
4446 ** Generate VDBE code that prepares for doing an operation that
4447 ** might change the database.
4448 **
4449 ** This routine starts a new transaction if we are not already within
4450 ** a transaction.  If we are already within a transaction, then a checkpoint
4451 ** is set if the setStatement parameter is true.  A checkpoint should
4452 ** be set for operations that might fail (due to a constraint) part of
4453 ** the way through and which will need to undo some writes without having to
4454 ** rollback the whole transaction.  For operations where all constraints
4455 ** can be checked before any changes are made to the database, it is never
4456 ** necessary to undo a write and the checkpoint should not be set.
4457 */
4458 void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
4459   Parse *pToplevel = sqlite3ParseToplevel(pParse);
4460   sqlite3CodeVerifySchema(pParse, iDb);
4461   DbMaskSet(pToplevel->writeMask, iDb);
4462   pToplevel->isMultiWrite |= setStatement;
4463 }
4464 
4465 /*
4466 ** Indicate that the statement currently under construction might write
4467 ** more than one entry (example: deleting one row then inserting another,
4468 ** inserting multiple rows in a table, or inserting a row and index entries.)
4469 ** If an abort occurs after some of these writes have completed, then it will
4470 ** be necessary to undo the completed writes.
4471 */
4472 void sqlite3MultiWrite(Parse *pParse){
4473   Parse *pToplevel = sqlite3ParseToplevel(pParse);
4474   pToplevel->isMultiWrite = 1;
4475 }
4476 
4477 /*
4478 ** The code generator calls this routine if is discovers that it is
4479 ** possible to abort a statement prior to completion.  In order to
4480 ** perform this abort without corrupting the database, we need to make
4481 ** sure that the statement is protected by a statement transaction.
4482 **
4483 ** Technically, we only need to set the mayAbort flag if the
4484 ** isMultiWrite flag was previously set.  There is a time dependency
4485 ** such that the abort must occur after the multiwrite.  This makes
4486 ** some statements involving the REPLACE conflict resolution algorithm
4487 ** go a little faster.  But taking advantage of this time dependency
4488 ** makes it more difficult to prove that the code is correct (in
4489 ** particular, it prevents us from writing an effective
4490 ** implementation of sqlite3AssertMayAbort()) and so we have chosen
4491 ** to take the safe route and skip the optimization.
4492 */
4493 void sqlite3MayAbort(Parse *pParse){
4494   Parse *pToplevel = sqlite3ParseToplevel(pParse);
4495   pToplevel->mayAbort = 1;
4496 }
4497 
4498 /*
4499 ** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT
4500 ** error. The onError parameter determines which (if any) of the statement
4501 ** and/or current transaction is rolled back.
4502 */
4503 void sqlite3HaltConstraint(
4504   Parse *pParse,    /* Parsing context */
4505   int errCode,      /* extended error code */
4506   int onError,      /* Constraint type */
4507   char *p4,         /* Error message */
4508   i8 p4type,        /* P4_STATIC or P4_TRANSIENT */
4509   u8 p5Errmsg       /* P5_ErrMsg type */
4510 ){
4511   Vdbe *v = sqlite3GetVdbe(pParse);
4512   assert( (errCode&0xff)==SQLITE_CONSTRAINT );
4513   if( onError==OE_Abort ){
4514     sqlite3MayAbort(pParse);
4515   }
4516   sqlite3VdbeAddOp4(v, OP_Halt, errCode, onError, 0, p4, p4type);
4517   sqlite3VdbeChangeP5(v, p5Errmsg);
4518 }
4519 
4520 /*
4521 ** Code an OP_Halt due to UNIQUE or PRIMARY KEY constraint violation.
4522 */
4523 void sqlite3UniqueConstraint(
4524   Parse *pParse,    /* Parsing context */
4525   int onError,      /* Constraint type */
4526   Index *pIdx       /* The index that triggers the constraint */
4527 ){
4528   char *zErr;
4529   int j;
4530   StrAccum errMsg;
4531   Table *pTab = pIdx->pTable;
4532 
4533   sqlite3StrAccumInit(&errMsg, pParse->db, 0, 0,
4534                       pParse->db->aLimit[SQLITE_LIMIT_LENGTH]);
4535   if( pIdx->aColExpr ){
4536     sqlite3_str_appendf(&errMsg, "index '%q'", pIdx->zName);
4537   }else{
4538     for(j=0; j<pIdx->nKeyCol; j++){
4539       char *zCol;
4540       assert( pIdx->aiColumn[j]>=0 );
4541       zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
4542       if( j ) sqlite3_str_append(&errMsg, ", ", 2);
4543       sqlite3_str_appendall(&errMsg, pTab->zName);
4544       sqlite3_str_append(&errMsg, ".", 1);
4545       sqlite3_str_appendall(&errMsg, zCol);
4546     }
4547   }
4548   zErr = sqlite3StrAccumFinish(&errMsg);
4549   sqlite3HaltConstraint(pParse,
4550     IsPrimaryKeyIndex(pIdx) ? SQLITE_CONSTRAINT_PRIMARYKEY
4551                             : SQLITE_CONSTRAINT_UNIQUE,
4552     onError, zErr, P4_DYNAMIC, P5_ConstraintUnique);
4553 }
4554 
4555 
4556 /*
4557 ** Code an OP_Halt due to non-unique rowid.
4558 */
4559 void sqlite3RowidConstraint(
4560   Parse *pParse,    /* Parsing context */
4561   int onError,      /* Conflict resolution algorithm */
4562   Table *pTab       /* The table with the non-unique rowid */
4563 ){
4564   char *zMsg;
4565   int rc;
4566   if( pTab->iPKey>=0 ){
4567     zMsg = sqlite3MPrintf(pParse->db, "%s.%s", pTab->zName,
4568                           pTab->aCol[pTab->iPKey].zName);
4569     rc = SQLITE_CONSTRAINT_PRIMARYKEY;
4570   }else{
4571     zMsg = sqlite3MPrintf(pParse->db, "%s.rowid", pTab->zName);
4572     rc = SQLITE_CONSTRAINT_ROWID;
4573   }
4574   sqlite3HaltConstraint(pParse, rc, onError, zMsg, P4_DYNAMIC,
4575                         P5_ConstraintUnique);
4576 }
4577 
4578 /*
4579 ** Check to see if pIndex uses the collating sequence pColl.  Return
4580 ** true if it does and false if it does not.
4581 */
4582 #ifndef SQLITE_OMIT_REINDEX
4583 static int collationMatch(const char *zColl, Index *pIndex){
4584   int i;
4585   assert( zColl!=0 );
4586   for(i=0; i<pIndex->nColumn; i++){
4587     const char *z = pIndex->azColl[i];
4588     assert( z!=0 || pIndex->aiColumn[i]<0 );
4589     if( pIndex->aiColumn[i]>=0 && 0==sqlite3StrICmp(z, zColl) ){
4590       return 1;
4591     }
4592   }
4593   return 0;
4594 }
4595 #endif
4596 
4597 /*
4598 ** Recompute all indices of pTab that use the collating sequence pColl.
4599 ** If pColl==0 then recompute all indices of pTab.
4600 */
4601 #ifndef SQLITE_OMIT_REINDEX
4602 static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
4603   if( !IsVirtual(pTab) ){
4604     Index *pIndex;              /* An index associated with pTab */
4605 
4606     for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
4607       if( zColl==0 || collationMatch(zColl, pIndex) ){
4608         int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
4609         sqlite3BeginWriteOperation(pParse, 0, iDb);
4610         sqlite3RefillIndex(pParse, pIndex, -1);
4611       }
4612     }
4613   }
4614 }
4615 #endif
4616 
4617 /*
4618 ** Recompute all indices of all tables in all databases where the
4619 ** indices use the collating sequence pColl.  If pColl==0 then recompute
4620 ** all indices everywhere.
4621 */
4622 #ifndef SQLITE_OMIT_REINDEX
4623 static void reindexDatabases(Parse *pParse, char const *zColl){
4624   Db *pDb;                    /* A single database */
4625   int iDb;                    /* The database index number */
4626   sqlite3 *db = pParse->db;   /* The database connection */
4627   HashElem *k;                /* For looping over tables in pDb */
4628   Table *pTab;                /* A table in the database */
4629 
4630   assert( sqlite3BtreeHoldsAllMutexes(db) );  /* Needed for schema access */
4631   for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
4632     assert( pDb!=0 );
4633     for(k=sqliteHashFirst(&pDb->pSchema->tblHash);  k; k=sqliteHashNext(k)){
4634       pTab = (Table*)sqliteHashData(k);
4635       reindexTable(pParse, pTab, zColl);
4636     }
4637   }
4638 }
4639 #endif
4640 
4641 /*
4642 ** Generate code for the REINDEX command.
4643 **
4644 **        REINDEX                            -- 1
4645 **        REINDEX  <collation>               -- 2
4646 **        REINDEX  ?<database>.?<tablename>  -- 3
4647 **        REINDEX  ?<database>.?<indexname>  -- 4
4648 **
4649 ** Form 1 causes all indices in all attached databases to be rebuilt.
4650 ** Form 2 rebuilds all indices in all databases that use the named
4651 ** collating function.  Forms 3 and 4 rebuild the named index or all
4652 ** indices associated with the named table.
4653 */
4654 #ifndef SQLITE_OMIT_REINDEX
4655 void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
4656   CollSeq *pColl;             /* Collating sequence to be reindexed, or NULL */
4657   char *z;                    /* Name of a table or index */
4658   const char *zDb;            /* Name of the database */
4659   Table *pTab;                /* A table in the database */
4660   Index *pIndex;              /* An index associated with pTab */
4661   int iDb;                    /* The database index number */
4662   sqlite3 *db = pParse->db;   /* The database connection */
4663   Token *pObjName;            /* Name of the table or index to be reindexed */
4664 
4665   /* Read the database schema. If an error occurs, leave an error message
4666   ** and code in pParse and return NULL. */
4667   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
4668     return;
4669   }
4670 
4671   if( pName1==0 ){
4672     reindexDatabases(pParse, 0);
4673     return;
4674   }else if( NEVER(pName2==0) || pName2->z==0 ){
4675     char *zColl;
4676     assert( pName1->z );
4677     zColl = sqlite3NameFromToken(pParse->db, pName1);
4678     if( !zColl ) return;
4679     pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
4680     if( pColl ){
4681       reindexDatabases(pParse, zColl);
4682       sqlite3DbFree(db, zColl);
4683       return;
4684     }
4685     sqlite3DbFree(db, zColl);
4686   }
4687   iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
4688   if( iDb<0 ) return;
4689   z = sqlite3NameFromToken(db, pObjName);
4690   if( z==0 ) return;
4691   zDb = db->aDb[iDb].zDbSName;
4692   pTab = sqlite3FindTable(db, z, zDb);
4693   if( pTab ){
4694     reindexTable(pParse, pTab, 0);
4695     sqlite3DbFree(db, z);
4696     return;
4697   }
4698   pIndex = sqlite3FindIndex(db, z, zDb);
4699   sqlite3DbFree(db, z);
4700   if( pIndex ){
4701     sqlite3BeginWriteOperation(pParse, 0, iDb);
4702     sqlite3RefillIndex(pParse, pIndex, -1);
4703     return;
4704   }
4705   sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
4706 }
4707 #endif
4708 
4709 /*
4710 ** Return a KeyInfo structure that is appropriate for the given Index.
4711 **
4712 ** The caller should invoke sqlite3KeyInfoUnref() on the returned object
4713 ** when it has finished using it.
4714 */
4715 KeyInfo *sqlite3KeyInfoOfIndex(Parse *pParse, Index *pIdx){
4716   int i;
4717   int nCol = pIdx->nColumn;
4718   int nKey = pIdx->nKeyCol;
4719   KeyInfo *pKey;
4720   if( pParse->nErr ) return 0;
4721   if( pIdx->uniqNotNull ){
4722     pKey = sqlite3KeyInfoAlloc(pParse->db, nKey, nCol-nKey);
4723   }else{
4724     pKey = sqlite3KeyInfoAlloc(pParse->db, nCol, 0);
4725   }
4726   if( pKey ){
4727     assert( sqlite3KeyInfoIsWriteable(pKey) );
4728     for(i=0; i<nCol; i++){
4729       const char *zColl = pIdx->azColl[i];
4730       pKey->aColl[i] = zColl==sqlite3StrBINARY ? 0 :
4731                         sqlite3LocateCollSeq(pParse, zColl);
4732       pKey->aSortFlags[i] = pIdx->aSortOrder[i];
4733       assert( 0==(pKey->aSortFlags[i] & KEYINFO_ORDER_BIGNULL) );
4734     }
4735     if( pParse->nErr ){
4736       assert( pParse->rc==SQLITE_ERROR_MISSING_COLLSEQ );
4737       if( pIdx->bNoQuery==0 ){
4738         /* Deactivate the index because it contains an unknown collating
4739         ** sequence.  The only way to reactive the index is to reload the
4740         ** schema.  Adding the missing collating sequence later does not
4741         ** reactive the index.  The application had the chance to register
4742         ** the missing index using the collation-needed callback.  For
4743         ** simplicity, SQLite will not give the application a second chance.
4744         */
4745         pIdx->bNoQuery = 1;
4746         pParse->rc = SQLITE_ERROR_RETRY;
4747       }
4748       sqlite3KeyInfoUnref(pKey);
4749       pKey = 0;
4750     }
4751   }
4752   return pKey;
4753 }
4754 
4755 #ifndef SQLITE_OMIT_CTE
4756 /*
4757 ** This routine is invoked once per CTE by the parser while parsing a
4758 ** WITH clause.
4759 */
4760 With *sqlite3WithAdd(
4761   Parse *pParse,          /* Parsing context */
4762   With *pWith,            /* Existing WITH clause, or NULL */
4763   Token *pName,           /* Name of the common-table */
4764   ExprList *pArglist,     /* Optional column name list for the table */
4765   Select *pQuery          /* Query used to initialize the table */
4766 ){
4767   sqlite3 *db = pParse->db;
4768   With *pNew;
4769   char *zName;
4770 
4771   /* Check that the CTE name is unique within this WITH clause. If
4772   ** not, store an error in the Parse structure. */
4773   zName = sqlite3NameFromToken(pParse->db, pName);
4774   if( zName && pWith ){
4775     int i;
4776     for(i=0; i<pWith->nCte; i++){
4777       if( sqlite3StrICmp(zName, pWith->a[i].zName)==0 ){
4778         sqlite3ErrorMsg(pParse, "duplicate WITH table name: %s", zName);
4779       }
4780     }
4781   }
4782 
4783   if( pWith ){
4784     sqlite3_int64 nByte = sizeof(*pWith) + (sizeof(pWith->a[1]) * pWith->nCte);
4785     pNew = sqlite3DbRealloc(db, pWith, nByte);
4786   }else{
4787     pNew = sqlite3DbMallocZero(db, sizeof(*pWith));
4788   }
4789   assert( (pNew!=0 && zName!=0) || db->mallocFailed );
4790 
4791   if( db->mallocFailed ){
4792     sqlite3ExprListDelete(db, pArglist);
4793     sqlite3SelectDelete(db, pQuery);
4794     sqlite3DbFree(db, zName);
4795     pNew = pWith;
4796   }else{
4797     pNew->a[pNew->nCte].pSelect = pQuery;
4798     pNew->a[pNew->nCte].pCols = pArglist;
4799     pNew->a[pNew->nCte].zName = zName;
4800     pNew->a[pNew->nCte].zCteErr = 0;
4801     pNew->nCte++;
4802   }
4803 
4804   return pNew;
4805 }
4806 
4807 /*
4808 ** Free the contents of the With object passed as the second argument.
4809 */
4810 void sqlite3WithDelete(sqlite3 *db, With *pWith){
4811   if( pWith ){
4812     int i;
4813     for(i=0; i<pWith->nCte; i++){
4814       struct Cte *pCte = &pWith->a[i];
4815       sqlite3ExprListDelete(db, pCte->pCols);
4816       sqlite3SelectDelete(db, pCte->pSelect);
4817       sqlite3DbFree(db, pCte->zName);
4818     }
4819     sqlite3DbFree(db, pWith);
4820   }
4821 }
4822 #endif /* !defined(SQLITE_OMIT_CTE) */
4823