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