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