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