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