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