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