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