xref: /sqlite-3.40.0/src/build.c (revision b43be55e)
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 */
1735   for(i=0; i<nPk; i++){
1736     pTab->aCol[pPk->aiColumn[i]].notNull = 1;
1737   }
1738   pPk->uniqNotNull = 1;
1739 
1740   /* The root page of the PRIMARY KEY is the table root page */
1741   pPk->tnum = pTab->tnum;
1742 
1743   /* Update the in-memory representation of all UNIQUE indices by converting
1744   ** the final rowid column into one or more columns of the PRIMARY KEY.
1745   */
1746   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
1747     int n;
1748     if( IsPrimaryKeyIndex(pIdx) ) continue;
1749     for(i=n=0; i<nPk; i++){
1750       if( !hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) ) n++;
1751     }
1752     if( n==0 ){
1753       /* This index is a superset of the primary key */
1754       pIdx->nColumn = pIdx->nKeyCol;
1755       continue;
1756     }
1757     if( resizeIndexObject(db, pIdx, pIdx->nKeyCol+n) ) return;
1758     for(i=0, j=pIdx->nKeyCol; i<nPk; i++){
1759       if( !hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) ){
1760         pIdx->aiColumn[j] = pPk->aiColumn[i];
1761         pIdx->azColl[j] = pPk->azColl[i];
1762         j++;
1763       }
1764     }
1765     assert( pIdx->nColumn>=pIdx->nKeyCol+n );
1766     assert( pIdx->nColumn>=j );
1767   }
1768 
1769   /* Add all table columns to the PRIMARY KEY index
1770   */
1771   if( nPk<pTab->nCol ){
1772     if( resizeIndexObject(db, pPk, pTab->nCol) ) return;
1773     for(i=0, j=nPk; i<pTab->nCol; i++){
1774       if( !hasColumn(pPk->aiColumn, j, i) ){
1775         assert( j<pPk->nColumn );
1776         pPk->aiColumn[j] = i;
1777         pPk->azColl[j] = "BINARY";
1778         j++;
1779       }
1780     }
1781     assert( pPk->nColumn==j );
1782     assert( pTab->nCol==j );
1783   }else{
1784     pPk->nColumn = pTab->nCol;
1785   }
1786 }
1787 
1788 /*
1789 ** This routine is called to report the final ")" that terminates
1790 ** a CREATE TABLE statement.
1791 **
1792 ** The table structure that other action routines have been building
1793 ** is added to the internal hash tables, assuming no errors have
1794 ** occurred.
1795 **
1796 ** An entry for the table is made in the master table on disk, unless
1797 ** this is a temporary table or db->init.busy==1.  When db->init.busy==1
1798 ** it means we are reading the sqlite_master table because we just
1799 ** connected to the database or because the sqlite_master table has
1800 ** recently changed, so the entry for this table already exists in
1801 ** the sqlite_master table.  We do not want to create it again.
1802 **
1803 ** If the pSelect argument is not NULL, it means that this routine
1804 ** was called to create a table generated from a
1805 ** "CREATE TABLE ... AS SELECT ..." statement.  The column names of
1806 ** the new table will match the result set of the SELECT.
1807 */
1808 void sqlite3EndTable(
1809   Parse *pParse,          /* Parse context */
1810   Token *pCons,           /* The ',' token after the last column defn. */
1811   Token *pEnd,            /* The ')' before options in the CREATE TABLE */
1812   u8 tabOpts,             /* Extra table options. Usually 0. */
1813   Select *pSelect         /* Select from a "CREATE ... AS SELECT" */
1814 ){
1815   Table *p;                 /* The new table */
1816   sqlite3 *db = pParse->db; /* The database connection */
1817   int iDb;                  /* Database in which the table lives */
1818   Index *pIdx;              /* An implied index of the table */
1819 
1820   if( (pEnd==0 && pSelect==0) || db->mallocFailed ){
1821     return;
1822   }
1823   p = pParse->pNewTable;
1824   if( p==0 ) return;
1825 
1826   assert( !db->init.busy || !pSelect );
1827 
1828   /* If the db->init.busy is 1 it means we are reading the SQL off the
1829   ** "sqlite_master" or "sqlite_temp_master" table on the disk.
1830   ** So do not write to the disk again.  Extract the root page number
1831   ** for the table from the db->init.newTnum field.  (The page number
1832   ** should have been put there by the sqliteOpenCb routine.)
1833   */
1834   if( db->init.busy ){
1835     p->tnum = db->init.newTnum;
1836   }
1837 
1838   /* Special processing for WITHOUT ROWID Tables */
1839   if( tabOpts & TF_WithoutRowid ){
1840     if( (p->tabFlags & TF_Autoincrement) ){
1841       sqlite3ErrorMsg(pParse,
1842           "AUTOINCREMENT not allowed on WITHOUT ROWID tables");
1843       return;
1844     }
1845     if( (p->tabFlags & TF_HasPrimaryKey)==0 ){
1846       sqlite3ErrorMsg(pParse, "PRIMARY KEY missing on table %s", p->zName);
1847     }else{
1848       p->tabFlags |= TF_WithoutRowid;
1849       convertToWithoutRowidTable(pParse, p);
1850     }
1851   }
1852 
1853   iDb = sqlite3SchemaToIndex(db, p->pSchema);
1854 
1855 #ifndef SQLITE_OMIT_CHECK
1856   /* Resolve names in all CHECK constraint expressions.
1857   */
1858   if( p->pCheck ){
1859     sqlite3ResolveSelfReference(pParse, p, NC_IsCheck, 0, p->pCheck);
1860   }
1861 #endif /* !defined(SQLITE_OMIT_CHECK) */
1862 
1863   /* Estimate the average row size for the table and for all implied indices */
1864   estimateTableWidth(p);
1865   for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
1866     estimateIndexWidth(pIdx);
1867   }
1868 
1869   /* If not initializing, then create a record for the new table
1870   ** in the SQLITE_MASTER table of the database.
1871   **
1872   ** If this is a TEMPORARY table, write the entry into the auxiliary
1873   ** file instead of into the main database file.
1874   */
1875   if( !db->init.busy ){
1876     int n;
1877     Vdbe *v;
1878     char *zType;    /* "view" or "table" */
1879     char *zType2;   /* "VIEW" or "TABLE" */
1880     char *zStmt;    /* Text of the CREATE TABLE or CREATE VIEW statement */
1881 
1882     v = sqlite3GetVdbe(pParse);
1883     if( NEVER(v==0) ) return;
1884 
1885     sqlite3VdbeAddOp1(v, OP_Close, 0);
1886 
1887     /*
1888     ** Initialize zType for the new view or table.
1889     */
1890     if( p->pSelect==0 ){
1891       /* A regular table */
1892       zType = "table";
1893       zType2 = "TABLE";
1894 #ifndef SQLITE_OMIT_VIEW
1895     }else{
1896       /* A view */
1897       zType = "view";
1898       zType2 = "VIEW";
1899 #endif
1900     }
1901 
1902     /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
1903     ** statement to populate the new table. The root-page number for the
1904     ** new table is in register pParse->regRoot.
1905     **
1906     ** Once the SELECT has been coded by sqlite3Select(), it is in a
1907     ** suitable state to query for the column names and types to be used
1908     ** by the new table.
1909     **
1910     ** A shared-cache write-lock is not required to write to the new table,
1911     ** as a schema-lock must have already been obtained to create it. Since
1912     ** a schema-lock excludes all other database users, the write-lock would
1913     ** be redundant.
1914     */
1915     if( pSelect ){
1916       SelectDest dest;
1917       Table *pSelTab;
1918 
1919       assert(pParse->nTab==1);
1920       sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb);
1921       sqlite3VdbeChangeP5(v, OPFLAG_P2ISREG);
1922       pParse->nTab = 2;
1923       sqlite3SelectDestInit(&dest, SRT_Table, 1);
1924       sqlite3Select(pParse, pSelect, &dest);
1925       sqlite3VdbeAddOp1(v, OP_Close, 1);
1926       if( pParse->nErr==0 ){
1927         pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect);
1928         if( pSelTab==0 ) return;
1929         assert( p->aCol==0 );
1930         p->nCol = pSelTab->nCol;
1931         p->aCol = pSelTab->aCol;
1932         pSelTab->nCol = 0;
1933         pSelTab->aCol = 0;
1934         sqlite3DeleteTable(db, pSelTab);
1935       }
1936     }
1937 
1938     /* Compute the complete text of the CREATE statement */
1939     if( pSelect ){
1940       zStmt = createTableStmt(db, p);
1941     }else{
1942       Token *pEnd2 = tabOpts ? &pParse->sLastToken : pEnd;
1943       n = (int)(pEnd2->z - pParse->sNameToken.z);
1944       if( pEnd2->z[0]!=';' ) n += pEnd2->n;
1945       zStmt = sqlite3MPrintf(db,
1946           "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
1947       );
1948     }
1949 
1950     /* A slot for the record has already been allocated in the
1951     ** SQLITE_MASTER table.  We just need to update that slot with all
1952     ** the information we've collected.
1953     */
1954     sqlite3NestedParse(pParse,
1955       "UPDATE %Q.%s "
1956          "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q "
1957        "WHERE rowid=#%d",
1958       db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
1959       zType,
1960       p->zName,
1961       p->zName,
1962       pParse->regRoot,
1963       zStmt,
1964       pParse->regRowid
1965     );
1966     sqlite3DbFree(db, zStmt);
1967     sqlite3ChangeCookie(pParse, iDb);
1968 
1969 #ifndef SQLITE_OMIT_AUTOINCREMENT
1970     /* Check to see if we need to create an sqlite_sequence table for
1971     ** keeping track of autoincrement keys.
1972     */
1973     if( p->tabFlags & TF_Autoincrement ){
1974       Db *pDb = &db->aDb[iDb];
1975       assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
1976       if( pDb->pSchema->pSeqTab==0 ){
1977         sqlite3NestedParse(pParse,
1978           "CREATE TABLE %Q.sqlite_sequence(name,seq)",
1979           pDb->zName
1980         );
1981       }
1982     }
1983 #endif
1984 
1985     /* Reparse everything to update our internal data structures */
1986     sqlite3VdbeAddParseSchemaOp(v, iDb,
1987            sqlite3MPrintf(db, "tbl_name='%q' AND type!='trigger'", p->zName));
1988   }
1989 
1990 
1991   /* Add the table to the in-memory representation of the database.
1992   */
1993   if( db->init.busy ){
1994     Table *pOld;
1995     Schema *pSchema = p->pSchema;
1996     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
1997     pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName, p);
1998     if( pOld ){
1999       assert( p==pOld );  /* Malloc must have failed inside HashInsert() */
2000       db->mallocFailed = 1;
2001       return;
2002     }
2003     pParse->pNewTable = 0;
2004     db->flags |= SQLITE_InternChanges;
2005 
2006 #ifndef SQLITE_OMIT_ALTERTABLE
2007     if( !p->pSelect ){
2008       const char *zName = (const char *)pParse->sNameToken.z;
2009       int nName;
2010       assert( !pSelect && pCons && pEnd );
2011       if( pCons->z==0 ){
2012         pCons = pEnd;
2013       }
2014       nName = (int)((const char *)pCons->z - zName);
2015       p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName);
2016     }
2017 #endif
2018   }
2019 }
2020 
2021 #ifndef SQLITE_OMIT_VIEW
2022 /*
2023 ** The parser calls this routine in order to create a new VIEW
2024 */
2025 void sqlite3CreateView(
2026   Parse *pParse,     /* The parsing context */
2027   Token *pBegin,     /* The CREATE token that begins the statement */
2028   Token *pName1,     /* The token that holds the name of the view */
2029   Token *pName2,     /* The token that holds the name of the view */
2030   Select *pSelect,   /* A SELECT statement that will become the new view */
2031   int isTemp,        /* TRUE for a TEMPORARY view */
2032   int noErr          /* Suppress error messages if VIEW already exists */
2033 ){
2034   Table *p;
2035   int n;
2036   const char *z;
2037   Token sEnd;
2038   DbFixer sFix;
2039   Token *pName = 0;
2040   int iDb;
2041   sqlite3 *db = pParse->db;
2042 
2043   if( pParse->nVar>0 ){
2044     sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
2045     sqlite3SelectDelete(db, pSelect);
2046     return;
2047   }
2048   sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
2049   p = pParse->pNewTable;
2050   if( p==0 || pParse->nErr ){
2051     sqlite3SelectDelete(db, pSelect);
2052     return;
2053   }
2054   sqlite3TwoPartName(pParse, pName1, pName2, &pName);
2055   iDb = sqlite3SchemaToIndex(db, p->pSchema);
2056   sqlite3FixInit(&sFix, pParse, iDb, "view", pName);
2057   if( sqlite3FixSelect(&sFix, pSelect) ){
2058     sqlite3SelectDelete(db, pSelect);
2059     return;
2060   }
2061 
2062   /* Make a copy of the entire SELECT statement that defines the view.
2063   ** This will force all the Expr.token.z values to be dynamically
2064   ** allocated rather than point to the input string - which means that
2065   ** they will persist after the current sqlite3_exec() call returns.
2066   */
2067   p->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
2068   sqlite3SelectDelete(db, pSelect);
2069   if( db->mallocFailed ){
2070     return;
2071   }
2072   if( !db->init.busy ){
2073     sqlite3ViewGetColumnNames(pParse, p);
2074   }
2075 
2076   /* Locate the end of the CREATE VIEW statement.  Make sEnd point to
2077   ** the end.
2078   */
2079   sEnd = pParse->sLastToken;
2080   if( ALWAYS(sEnd.z[0]!=0) && sEnd.z[0]!=';' ){
2081     sEnd.z += sEnd.n;
2082   }
2083   sEnd.n = 0;
2084   n = (int)(sEnd.z - pBegin->z);
2085   z = pBegin->z;
2086   while( ALWAYS(n>0) && sqlite3Isspace(z[n-1]) ){ n--; }
2087   sEnd.z = &z[n-1];
2088   sEnd.n = 1;
2089 
2090   /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
2091   sqlite3EndTable(pParse, 0, &sEnd, 0, 0);
2092   return;
2093 }
2094 #endif /* SQLITE_OMIT_VIEW */
2095 
2096 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
2097 /*
2098 ** The Table structure pTable is really a VIEW.  Fill in the names of
2099 ** the columns of the view in the pTable structure.  Return the number
2100 ** of errors.  If an error is seen leave an error message in pParse->zErrMsg.
2101 */
2102 int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
2103   Table *pSelTab;   /* A fake table from which we get the result set */
2104   Select *pSel;     /* Copy of the SELECT that implements the view */
2105   int nErr = 0;     /* Number of errors encountered */
2106   int n;            /* Temporarily holds the number of cursors assigned */
2107   sqlite3 *db = pParse->db;  /* Database connection for malloc errors */
2108   sqlite3_xauth xAuth;       /* Saved xAuth pointer */
2109 
2110   assert( pTable );
2111 
2112 #ifndef SQLITE_OMIT_VIRTUALTABLE
2113   if( sqlite3VtabCallConnect(pParse, pTable) ){
2114     return SQLITE_ERROR;
2115   }
2116   if( IsVirtual(pTable) ) return 0;
2117 #endif
2118 
2119 #ifndef SQLITE_OMIT_VIEW
2120   /* A positive nCol means the columns names for this view are
2121   ** already known.
2122   */
2123   if( pTable->nCol>0 ) return 0;
2124 
2125   /* A negative nCol is a special marker meaning that we are currently
2126   ** trying to compute the column names.  If we enter this routine with
2127   ** a negative nCol, it means two or more views form a loop, like this:
2128   **
2129   **     CREATE VIEW one AS SELECT * FROM two;
2130   **     CREATE VIEW two AS SELECT * FROM one;
2131   **
2132   ** Actually, the error above is now caught prior to reaching this point.
2133   ** But the following test is still important as it does come up
2134   ** in the following:
2135   **
2136   **     CREATE TABLE main.ex1(a);
2137   **     CREATE TEMP VIEW ex1 AS SELECT a FROM ex1;
2138   **     SELECT * FROM temp.ex1;
2139   */
2140   if( pTable->nCol<0 ){
2141     sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
2142     return 1;
2143   }
2144   assert( pTable->nCol>=0 );
2145 
2146   /* If we get this far, it means we need to compute the table names.
2147   ** Note that the call to sqlite3ResultSetOfSelect() will expand any
2148   ** "*" elements in the results set of the view and will assign cursors
2149   ** to the elements of the FROM clause.  But we do not want these changes
2150   ** to be permanent.  So the computation is done on a copy of the SELECT
2151   ** statement that defines the view.
2152   */
2153   assert( pTable->pSelect );
2154   pSel = sqlite3SelectDup(db, pTable->pSelect, 0);
2155   if( pSel ){
2156     u8 enableLookaside = db->lookaside.bEnabled;
2157     n = pParse->nTab;
2158     sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
2159     pTable->nCol = -1;
2160     db->lookaside.bEnabled = 0;
2161 #ifndef SQLITE_OMIT_AUTHORIZATION
2162     xAuth = db->xAuth;
2163     db->xAuth = 0;
2164     pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
2165     db->xAuth = xAuth;
2166 #else
2167     pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
2168 #endif
2169     db->lookaside.bEnabled = enableLookaside;
2170     pParse->nTab = n;
2171     if( pSelTab ){
2172       assert( pTable->aCol==0 );
2173       pTable->nCol = pSelTab->nCol;
2174       pTable->aCol = pSelTab->aCol;
2175       pSelTab->nCol = 0;
2176       pSelTab->aCol = 0;
2177       sqlite3DeleteTable(db, pSelTab);
2178       assert( sqlite3SchemaMutexHeld(db, 0, pTable->pSchema) );
2179       pTable->pSchema->schemaFlags |= DB_UnresetViews;
2180     }else{
2181       pTable->nCol = 0;
2182       nErr++;
2183     }
2184     sqlite3SelectDelete(db, pSel);
2185   } else {
2186     nErr++;
2187   }
2188 #endif /* SQLITE_OMIT_VIEW */
2189   return nErr;
2190 }
2191 #endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
2192 
2193 #ifndef SQLITE_OMIT_VIEW
2194 /*
2195 ** Clear the column names from every VIEW in database idx.
2196 */
2197 static void sqliteViewResetAll(sqlite3 *db, int idx){
2198   HashElem *i;
2199   assert( sqlite3SchemaMutexHeld(db, idx, 0) );
2200   if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
2201   for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
2202     Table *pTab = sqliteHashData(i);
2203     if( pTab->pSelect ){
2204       sqliteDeleteColumnNames(db, pTab);
2205       pTab->aCol = 0;
2206       pTab->nCol = 0;
2207     }
2208   }
2209   DbClearProperty(db, idx, DB_UnresetViews);
2210 }
2211 #else
2212 # define sqliteViewResetAll(A,B)
2213 #endif /* SQLITE_OMIT_VIEW */
2214 
2215 /*
2216 ** This function is called by the VDBE to adjust the internal schema
2217 ** used by SQLite when the btree layer moves a table root page. The
2218 ** root-page of a table or index in database iDb has changed from iFrom
2219 ** to iTo.
2220 **
2221 ** Ticket #1728:  The symbol table might still contain information
2222 ** on tables and/or indices that are the process of being deleted.
2223 ** If you are unlucky, one of those deleted indices or tables might
2224 ** have the same rootpage number as the real table or index that is
2225 ** being moved.  So we cannot stop searching after the first match
2226 ** because the first match might be for one of the deleted indices
2227 ** or tables and not the table/index that is actually being moved.
2228 ** We must continue looping until all tables and indices with
2229 ** rootpage==iFrom have been converted to have a rootpage of iTo
2230 ** in order to be certain that we got the right one.
2231 */
2232 #ifndef SQLITE_OMIT_AUTOVACUUM
2233 void sqlite3RootPageMoved(sqlite3 *db, int iDb, int iFrom, int iTo){
2234   HashElem *pElem;
2235   Hash *pHash;
2236   Db *pDb;
2237 
2238   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
2239   pDb = &db->aDb[iDb];
2240   pHash = &pDb->pSchema->tblHash;
2241   for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
2242     Table *pTab = sqliteHashData(pElem);
2243     if( pTab->tnum==iFrom ){
2244       pTab->tnum = iTo;
2245     }
2246   }
2247   pHash = &pDb->pSchema->idxHash;
2248   for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
2249     Index *pIdx = sqliteHashData(pElem);
2250     if( pIdx->tnum==iFrom ){
2251       pIdx->tnum = iTo;
2252     }
2253   }
2254 }
2255 #endif
2256 
2257 /*
2258 ** Write code to erase the table with root-page iTable from database iDb.
2259 ** Also write code to modify the sqlite_master table and internal schema
2260 ** if a root-page of another table is moved by the btree-layer whilst
2261 ** erasing iTable (this can happen with an auto-vacuum database).
2262 */
2263 static void destroyRootPage(Parse *pParse, int iTable, int iDb){
2264   Vdbe *v = sqlite3GetVdbe(pParse);
2265   int r1 = sqlite3GetTempReg(pParse);
2266   sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
2267   sqlite3MayAbort(pParse);
2268 #ifndef SQLITE_OMIT_AUTOVACUUM
2269   /* OP_Destroy stores an in integer r1. If this integer
2270   ** is non-zero, then it is the root page number of a table moved to
2271   ** location iTable. The following code modifies the sqlite_master table to
2272   ** reflect this.
2273   **
2274   ** The "#NNN" in the SQL is a special constant that means whatever value
2275   ** is in register NNN.  See grammar rules associated with the TK_REGISTER
2276   ** token for additional information.
2277   */
2278   sqlite3NestedParse(pParse,
2279      "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d",
2280      pParse->db->aDb[iDb].zName, SCHEMA_TABLE(iDb), iTable, r1, r1);
2281 #endif
2282   sqlite3ReleaseTempReg(pParse, r1);
2283 }
2284 
2285 /*
2286 ** Write VDBE code to erase table pTab and all associated indices on disk.
2287 ** Code to update the sqlite_master tables and internal schema definitions
2288 ** in case a root-page belonging to another table is moved by the btree layer
2289 ** is also added (this can happen with an auto-vacuum database).
2290 */
2291 static void destroyTable(Parse *pParse, Table *pTab){
2292 #ifdef SQLITE_OMIT_AUTOVACUUM
2293   Index *pIdx;
2294   int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
2295   destroyRootPage(pParse, pTab->tnum, iDb);
2296   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
2297     destroyRootPage(pParse, pIdx->tnum, iDb);
2298   }
2299 #else
2300   /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
2301   ** is not defined), then it is important to call OP_Destroy on the
2302   ** table and index root-pages in order, starting with the numerically
2303   ** largest root-page number. This guarantees that none of the root-pages
2304   ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
2305   ** following were coded:
2306   **
2307   ** OP_Destroy 4 0
2308   ** ...
2309   ** OP_Destroy 5 0
2310   **
2311   ** and root page 5 happened to be the largest root-page number in the
2312   ** database, then root page 5 would be moved to page 4 by the
2313   ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
2314   ** a free-list page.
2315   */
2316   int iTab = pTab->tnum;
2317   int iDestroyed = 0;
2318 
2319   while( 1 ){
2320     Index *pIdx;
2321     int iLargest = 0;
2322 
2323     if( iDestroyed==0 || iTab<iDestroyed ){
2324       iLargest = iTab;
2325     }
2326     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
2327       int iIdx = pIdx->tnum;
2328       assert( pIdx->pSchema==pTab->pSchema );
2329       if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
2330         iLargest = iIdx;
2331       }
2332     }
2333     if( iLargest==0 ){
2334       return;
2335     }else{
2336       int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
2337       assert( iDb>=0 && iDb<pParse->db->nDb );
2338       destroyRootPage(pParse, iLargest, iDb);
2339       iDestroyed = iLargest;
2340     }
2341   }
2342 #endif
2343 }
2344 
2345 /*
2346 ** Remove entries from the sqlite_statN tables (for N in (1,2,3))
2347 ** after a DROP INDEX or DROP TABLE command.
2348 */
2349 static void sqlite3ClearStatTables(
2350   Parse *pParse,         /* The parsing context */
2351   int iDb,               /* The database number */
2352   const char *zType,     /* "idx" or "tbl" */
2353   const char *zName      /* Name of index or table */
2354 ){
2355   int i;
2356   const char *zDbName = pParse->db->aDb[iDb].zName;
2357   for(i=1; i<=4; i++){
2358     char zTab[24];
2359     sqlite3_snprintf(sizeof(zTab),zTab,"sqlite_stat%d",i);
2360     if( sqlite3FindTable(pParse->db, zTab, zDbName) ){
2361       sqlite3NestedParse(pParse,
2362         "DELETE FROM %Q.%s WHERE %s=%Q",
2363         zDbName, zTab, zType, zName
2364       );
2365     }
2366   }
2367 }
2368 
2369 /*
2370 ** Generate code to drop a table.
2371 */
2372 void sqlite3CodeDropTable(Parse *pParse, Table *pTab, int iDb, int isView){
2373   Vdbe *v;
2374   sqlite3 *db = pParse->db;
2375   Trigger *pTrigger;
2376   Db *pDb = &db->aDb[iDb];
2377 
2378   v = sqlite3GetVdbe(pParse);
2379   assert( v!=0 );
2380   sqlite3BeginWriteOperation(pParse, 1, iDb);
2381 
2382 #ifndef SQLITE_OMIT_VIRTUALTABLE
2383   if( IsVirtual(pTab) ){
2384     sqlite3VdbeAddOp0(v, OP_VBegin);
2385   }
2386 #endif
2387 
2388   /* Drop all triggers associated with the table being dropped. Code
2389   ** is generated to remove entries from sqlite_master and/or
2390   ** sqlite_temp_master if required.
2391   */
2392   pTrigger = sqlite3TriggerList(pParse, pTab);
2393   while( pTrigger ){
2394     assert( pTrigger->pSchema==pTab->pSchema ||
2395         pTrigger->pSchema==db->aDb[1].pSchema );
2396     sqlite3DropTriggerPtr(pParse, pTrigger);
2397     pTrigger = pTrigger->pNext;
2398   }
2399 
2400 #ifndef SQLITE_OMIT_AUTOINCREMENT
2401   /* Remove any entries of the sqlite_sequence table associated with
2402   ** the table being dropped. This is done before the table is dropped
2403   ** at the btree level, in case the sqlite_sequence table needs to
2404   ** move as a result of the drop (can happen in auto-vacuum mode).
2405   */
2406   if( pTab->tabFlags & TF_Autoincrement ){
2407     sqlite3NestedParse(pParse,
2408       "DELETE FROM %Q.sqlite_sequence WHERE name=%Q",
2409       pDb->zName, pTab->zName
2410     );
2411   }
2412 #endif
2413 
2414   /* Drop all SQLITE_MASTER table and index entries that refer to the
2415   ** table. The program name loops through the master table and deletes
2416   ** every row that refers to a table of the same name as the one being
2417   ** dropped. Triggers are handled separately because a trigger can be
2418   ** created in the temp database that refers to a table in another
2419   ** database.
2420   */
2421   sqlite3NestedParse(pParse,
2422       "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
2423       pDb->zName, SCHEMA_TABLE(iDb), pTab->zName);
2424   if( !isView && !IsVirtual(pTab) ){
2425     destroyTable(pParse, pTab);
2426   }
2427 
2428   /* Remove the table entry from SQLite's internal schema and modify
2429   ** the schema cookie.
2430   */
2431   if( IsVirtual(pTab) ){
2432     sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
2433   }
2434   sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
2435   sqlite3ChangeCookie(pParse, iDb);
2436   sqliteViewResetAll(db, iDb);
2437 }
2438 
2439 /*
2440 ** This routine is called to do the work of a DROP TABLE statement.
2441 ** pName is the name of the table to be dropped.
2442 */
2443 void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
2444   Table *pTab;
2445   Vdbe *v;
2446   sqlite3 *db = pParse->db;
2447   int iDb;
2448 
2449   if( db->mallocFailed ){
2450     goto exit_drop_table;
2451   }
2452   assert( pParse->nErr==0 );
2453   assert( pName->nSrc==1 );
2454   if( noErr ) db->suppressErr++;
2455   pTab = sqlite3LocateTableItem(pParse, isView, &pName->a[0]);
2456   if( noErr ) db->suppressErr--;
2457 
2458   if( pTab==0 ){
2459     if( noErr ) sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
2460     goto exit_drop_table;
2461   }
2462   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
2463   assert( iDb>=0 && iDb<db->nDb );
2464 
2465   /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
2466   ** it is initialized.
2467   */
2468   if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){
2469     goto exit_drop_table;
2470   }
2471 #ifndef SQLITE_OMIT_AUTHORIZATION
2472   {
2473     int code;
2474     const char *zTab = SCHEMA_TABLE(iDb);
2475     const char *zDb = db->aDb[iDb].zName;
2476     const char *zArg2 = 0;
2477     if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
2478       goto exit_drop_table;
2479     }
2480     if( isView ){
2481       if( !OMIT_TEMPDB && iDb==1 ){
2482         code = SQLITE_DROP_TEMP_VIEW;
2483       }else{
2484         code = SQLITE_DROP_VIEW;
2485       }
2486 #ifndef SQLITE_OMIT_VIRTUALTABLE
2487     }else if( IsVirtual(pTab) ){
2488       code = SQLITE_DROP_VTABLE;
2489       zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName;
2490 #endif
2491     }else{
2492       if( !OMIT_TEMPDB && iDb==1 ){
2493         code = SQLITE_DROP_TEMP_TABLE;
2494       }else{
2495         code = SQLITE_DROP_TABLE;
2496       }
2497     }
2498     if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
2499       goto exit_drop_table;
2500     }
2501     if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
2502       goto exit_drop_table;
2503     }
2504   }
2505 #endif
2506   if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
2507     && sqlite3StrNICmp(pTab->zName, "sqlite_stat", 11)!=0 ){
2508     sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
2509     goto exit_drop_table;
2510   }
2511 
2512 #ifndef SQLITE_OMIT_VIEW
2513   /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
2514   ** on a table.
2515   */
2516   if( isView && pTab->pSelect==0 ){
2517     sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
2518     goto exit_drop_table;
2519   }
2520   if( !isView && pTab->pSelect ){
2521     sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
2522     goto exit_drop_table;
2523   }
2524 #endif
2525 
2526   /* Generate code to remove the table from the master table
2527   ** on disk.
2528   */
2529   v = sqlite3GetVdbe(pParse);
2530   if( v ){
2531     sqlite3BeginWriteOperation(pParse, 1, iDb);
2532     sqlite3ClearStatTables(pParse, iDb, "tbl", pTab->zName);
2533     sqlite3FkDropTable(pParse, pName, pTab);
2534     sqlite3CodeDropTable(pParse, pTab, iDb, isView);
2535   }
2536 
2537 exit_drop_table:
2538   sqlite3SrcListDelete(db, pName);
2539 }
2540 
2541 /*
2542 ** This routine is called to create a new foreign key on the table
2543 ** currently under construction.  pFromCol determines which columns
2544 ** in the current table point to the foreign key.  If pFromCol==0 then
2545 ** connect the key to the last column inserted.  pTo is the name of
2546 ** the table referred to (a.k.a the "parent" table).  pToCol is a list
2547 ** of tables in the parent pTo table.  flags contains all
2548 ** information about the conflict resolution algorithms specified
2549 ** in the ON DELETE, ON UPDATE and ON INSERT clauses.
2550 **
2551 ** An FKey structure is created and added to the table currently
2552 ** under construction in the pParse->pNewTable field.
2553 **
2554 ** The foreign key is set for IMMEDIATE processing.  A subsequent call
2555 ** to sqlite3DeferForeignKey() might change this to DEFERRED.
2556 */
2557 void sqlite3CreateForeignKey(
2558   Parse *pParse,       /* Parsing context */
2559   ExprList *pFromCol,  /* Columns in this table that point to other table */
2560   Token *pTo,          /* Name of the other table */
2561   ExprList *pToCol,    /* Columns in the other table */
2562   int flags            /* Conflict resolution algorithms. */
2563 ){
2564   sqlite3 *db = pParse->db;
2565 #ifndef SQLITE_OMIT_FOREIGN_KEY
2566   FKey *pFKey = 0;
2567   FKey *pNextTo;
2568   Table *p = pParse->pNewTable;
2569   int nByte;
2570   int i;
2571   int nCol;
2572   char *z;
2573 
2574   assert( pTo!=0 );
2575   if( p==0 || IN_DECLARE_VTAB ) goto fk_end;
2576   if( pFromCol==0 ){
2577     int iCol = p->nCol-1;
2578     if( NEVER(iCol<0) ) goto fk_end;
2579     if( pToCol && pToCol->nExpr!=1 ){
2580       sqlite3ErrorMsg(pParse, "foreign key on %s"
2581          " should reference only one column of table %T",
2582          p->aCol[iCol].zName, pTo);
2583       goto fk_end;
2584     }
2585     nCol = 1;
2586   }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
2587     sqlite3ErrorMsg(pParse,
2588         "number of columns in foreign key does not match the number of "
2589         "columns in the referenced table");
2590     goto fk_end;
2591   }else{
2592     nCol = pFromCol->nExpr;
2593   }
2594   nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1;
2595   if( pToCol ){
2596     for(i=0; i<pToCol->nExpr; i++){
2597       nByte += sqlite3Strlen30(pToCol->a[i].zName) + 1;
2598     }
2599   }
2600   pFKey = sqlite3DbMallocZero(db, nByte );
2601   if( pFKey==0 ){
2602     goto fk_end;
2603   }
2604   pFKey->pFrom = p;
2605   pFKey->pNextFrom = p->pFKey;
2606   z = (char*)&pFKey->aCol[nCol];
2607   pFKey->zTo = z;
2608   memcpy(z, pTo->z, pTo->n);
2609   z[pTo->n] = 0;
2610   sqlite3Dequote(z);
2611   z += pTo->n+1;
2612   pFKey->nCol = nCol;
2613   if( pFromCol==0 ){
2614     pFKey->aCol[0].iFrom = p->nCol-1;
2615   }else{
2616     for(i=0; i<nCol; i++){
2617       int j;
2618       for(j=0; j<p->nCol; j++){
2619         if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
2620           pFKey->aCol[i].iFrom = j;
2621           break;
2622         }
2623       }
2624       if( j>=p->nCol ){
2625         sqlite3ErrorMsg(pParse,
2626           "unknown column \"%s\" in foreign key definition",
2627           pFromCol->a[i].zName);
2628         goto fk_end;
2629       }
2630     }
2631   }
2632   if( pToCol ){
2633     for(i=0; i<nCol; i++){
2634       int n = sqlite3Strlen30(pToCol->a[i].zName);
2635       pFKey->aCol[i].zCol = z;
2636       memcpy(z, pToCol->a[i].zName, n);
2637       z[n] = 0;
2638       z += n+1;
2639     }
2640   }
2641   pFKey->isDeferred = 0;
2642   pFKey->aAction[0] = (u8)(flags & 0xff);            /* ON DELETE action */
2643   pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff);    /* ON UPDATE action */
2644 
2645   assert( sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
2646   pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash,
2647       pFKey->zTo, (void *)pFKey
2648   );
2649   if( pNextTo==pFKey ){
2650     db->mallocFailed = 1;
2651     goto fk_end;
2652   }
2653   if( pNextTo ){
2654     assert( pNextTo->pPrevTo==0 );
2655     pFKey->pNextTo = pNextTo;
2656     pNextTo->pPrevTo = pFKey;
2657   }
2658 
2659   /* Link the foreign key to the table as the last step.
2660   */
2661   p->pFKey = pFKey;
2662   pFKey = 0;
2663 
2664 fk_end:
2665   sqlite3DbFree(db, pFKey);
2666 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
2667   sqlite3ExprListDelete(db, pFromCol);
2668   sqlite3ExprListDelete(db, pToCol);
2669 }
2670 
2671 /*
2672 ** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
2673 ** clause is seen as part of a foreign key definition.  The isDeferred
2674 ** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
2675 ** The behavior of the most recently created foreign key is adjusted
2676 ** accordingly.
2677 */
2678 void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
2679 #ifndef SQLITE_OMIT_FOREIGN_KEY
2680   Table *pTab;
2681   FKey *pFKey;
2682   if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
2683   assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */
2684   pFKey->isDeferred = (u8)isDeferred;
2685 #endif
2686 }
2687 
2688 /*
2689 ** Generate code that will erase and refill index *pIdx.  This is
2690 ** used to initialize a newly created index or to recompute the
2691 ** content of an index in response to a REINDEX command.
2692 **
2693 ** if memRootPage is not negative, it means that the index is newly
2694 ** created.  The register specified by memRootPage contains the
2695 ** root page number of the index.  If memRootPage is negative, then
2696 ** the index already exists and must be cleared before being refilled and
2697 ** the root page number of the index is taken from pIndex->tnum.
2698 */
2699 static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
2700   Table *pTab = pIndex->pTable;  /* The table that is indexed */
2701   int iTab = pParse->nTab++;     /* Btree cursor used for pTab */
2702   int iIdx = pParse->nTab++;     /* Btree cursor used for pIndex */
2703   int iSorter;                   /* Cursor opened by OpenSorter (if in use) */
2704   int addr1;                     /* Address of top of loop */
2705   int addr2;                     /* Address to jump to for next iteration */
2706   int tnum;                      /* Root page of index */
2707   int iPartIdxLabel;             /* Jump to this label to skip a row */
2708   Vdbe *v;                       /* Generate code into this virtual machine */
2709   KeyInfo *pKey;                 /* KeyInfo for index */
2710   int regRecord;                 /* Register holding assembled index record */
2711   sqlite3 *db = pParse->db;      /* The database connection */
2712   int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
2713 
2714 #ifndef SQLITE_OMIT_AUTHORIZATION
2715   if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
2716       db->aDb[iDb].zName ) ){
2717     return;
2718   }
2719 #endif
2720 
2721   /* Require a write-lock on the table to perform this operation */
2722   sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
2723 
2724   v = sqlite3GetVdbe(pParse);
2725   if( v==0 ) return;
2726   if( memRootPage>=0 ){
2727     tnum = memRootPage;
2728   }else{
2729     tnum = pIndex->tnum;
2730   }
2731   pKey = sqlite3KeyInfoOfIndex(pParse, pIndex);
2732 
2733   /* Open the sorter cursor if we are to use one. */
2734   iSorter = pParse->nTab++;
2735   sqlite3VdbeAddOp4(v, OP_SorterOpen, iSorter, 0, pIndex->nKeyCol, (char*)
2736                     sqlite3KeyInfoRef(pKey), P4_KEYINFO);
2737 
2738   /* Open the table. Loop through all rows of the table, inserting index
2739   ** records into the sorter. */
2740   sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
2741   addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0); VdbeCoverage(v);
2742   regRecord = sqlite3GetTempReg(pParse);
2743 
2744   sqlite3GenerateIndexKey(pParse,pIndex,iTab,regRecord,0,&iPartIdxLabel,0,0);
2745   sqlite3VdbeAddOp2(v, OP_SorterInsert, iSorter, regRecord);
2746   sqlite3ResolvePartIdxLabel(pParse, iPartIdxLabel);
2747   sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1); VdbeCoverage(v);
2748   sqlite3VdbeJumpHere(v, addr1);
2749   if( memRootPage<0 ) sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
2750   sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb,
2751                     (char *)pKey, P4_KEYINFO);
2752   sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR|((memRootPage>=0)?OPFLAG_P2ISREG:0));
2753 
2754   addr1 = sqlite3VdbeAddOp2(v, OP_SorterSort, iSorter, 0); VdbeCoverage(v);
2755   assert( pKey!=0 || db->mallocFailed || pParse->nErr );
2756   if( IsUniqueIndex(pIndex) && pKey!=0 ){
2757     int j2 = sqlite3VdbeCurrentAddr(v) + 3;
2758     sqlite3VdbeAddOp2(v, OP_Goto, 0, j2);
2759     addr2 = sqlite3VdbeCurrentAddr(v);
2760     sqlite3VdbeAddOp4Int(v, OP_SorterCompare, iSorter, j2, regRecord,
2761                          pIndex->nKeyCol); VdbeCoverage(v);
2762     sqlite3UniqueConstraint(pParse, OE_Abort, pIndex);
2763   }else{
2764     addr2 = sqlite3VdbeCurrentAddr(v);
2765   }
2766   sqlite3VdbeAddOp3(v, OP_SorterData, iSorter, regRecord, iIdx);
2767   sqlite3VdbeAddOp3(v, OP_IdxInsert, iIdx, regRecord, 1);
2768   sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
2769   sqlite3ReleaseTempReg(pParse, regRecord);
2770   sqlite3VdbeAddOp2(v, OP_SorterNext, iSorter, addr2); VdbeCoverage(v);
2771   sqlite3VdbeJumpHere(v, addr1);
2772 
2773   sqlite3VdbeAddOp1(v, OP_Close, iTab);
2774   sqlite3VdbeAddOp1(v, OP_Close, iIdx);
2775   sqlite3VdbeAddOp1(v, OP_Close, iSorter);
2776 }
2777 
2778 /*
2779 ** Allocate heap space to hold an Index object with nCol columns.
2780 **
2781 ** Increase the allocation size to provide an extra nExtra bytes
2782 ** of 8-byte aligned space after the Index object and return a
2783 ** pointer to this extra space in *ppExtra.
2784 */
2785 Index *sqlite3AllocateIndexObject(
2786   sqlite3 *db,         /* Database connection */
2787   i16 nCol,            /* Total number of columns in the index */
2788   int nExtra,          /* Number of bytes of extra space to alloc */
2789   char **ppExtra       /* Pointer to the "extra" space */
2790 ){
2791   Index *p;            /* Allocated index object */
2792   int nByte;           /* Bytes of space for Index object + arrays */
2793 
2794   nByte = ROUND8(sizeof(Index)) +              /* Index structure  */
2795           ROUND8(sizeof(char*)*nCol) +         /* Index.azColl     */
2796           ROUND8(sizeof(LogEst)*(nCol+1) +     /* Index.aiRowLogEst   */
2797                  sizeof(i16)*nCol +            /* Index.aiColumn   */
2798                  sizeof(u8)*nCol);             /* Index.aSortOrder */
2799   p = sqlite3DbMallocZero(db, nByte + nExtra);
2800   if( p ){
2801     char *pExtra = ((char*)p)+ROUND8(sizeof(Index));
2802     p->azColl = (char**)pExtra;       pExtra += ROUND8(sizeof(char*)*nCol);
2803     p->aiRowLogEst = (LogEst*)pExtra; pExtra += sizeof(LogEst)*(nCol+1);
2804     p->aiColumn = (i16*)pExtra;       pExtra += sizeof(i16)*nCol;
2805     p->aSortOrder = (u8*)pExtra;
2806     p->nColumn = nCol;
2807     p->nKeyCol = nCol - 1;
2808     *ppExtra = ((char*)p) + nByte;
2809   }
2810   return p;
2811 }
2812 
2813 /*
2814 ** Create a new index for an SQL table.  pName1.pName2 is the name of the index
2815 ** and pTblList is the name of the table that is to be indexed.  Both will
2816 ** be NULL for a primary key or an index that is created to satisfy a
2817 ** UNIQUE constraint.  If pTable and pIndex are NULL, use pParse->pNewTable
2818 ** as the table to be indexed.  pParse->pNewTable is a table that is
2819 ** currently being constructed by a CREATE TABLE statement.
2820 **
2821 ** pList is a list of columns to be indexed.  pList will be NULL if this
2822 ** is a primary key or unique-constraint on the most recent column added
2823 ** to the table currently under construction.
2824 **
2825 ** If the index is created successfully, return a pointer to the new Index
2826 ** structure. This is used by sqlite3AddPrimaryKey() to mark the index
2827 ** as the tables primary key (Index.idxType==SQLITE_IDXTYPE_PRIMARYKEY)
2828 */
2829 Index *sqlite3CreateIndex(
2830   Parse *pParse,     /* All information about this parse */
2831   Token *pName1,     /* First part of index name. May be NULL */
2832   Token *pName2,     /* Second part of index name. May be NULL */
2833   SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
2834   ExprList *pList,   /* A list of columns to be indexed */
2835   int onError,       /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
2836   Token *pStart,     /* The CREATE token that begins this statement */
2837   Expr *pPIWhere,    /* WHERE clause for partial indices */
2838   int sortOrder,     /* Sort order of primary key when pList==NULL */
2839   int ifNotExist     /* Omit error if index already exists */
2840 ){
2841   Index *pRet = 0;     /* Pointer to return */
2842   Table *pTab = 0;     /* Table to be indexed */
2843   Index *pIndex = 0;   /* The index to be created */
2844   char *zName = 0;     /* Name of the index */
2845   int nName;           /* Number of characters in zName */
2846   int i, j;
2847   DbFixer sFix;        /* For assigning database names to pTable */
2848   int sortOrderMask;   /* 1 to honor DESC in index.  0 to ignore. */
2849   sqlite3 *db = pParse->db;
2850   Db *pDb;             /* The specific table containing the indexed database */
2851   int iDb;             /* Index of the database that is being written */
2852   Token *pName = 0;    /* Unqualified name of the index to create */
2853   struct ExprList_item *pListItem; /* For looping over pList */
2854   const Column *pTabCol;           /* A column in the table */
2855   int nExtra = 0;                  /* Space allocated for zExtra[] */
2856   int nExtraCol;                   /* Number of extra columns needed */
2857   char *zExtra = 0;                /* Extra space after the Index object */
2858   Index *pPk = 0;      /* PRIMARY KEY index for WITHOUT ROWID tables */
2859 
2860   assert( pParse->nErr==0 );      /* Never called with prior errors */
2861   if( db->mallocFailed || IN_DECLARE_VTAB ){
2862     goto exit_create_index;
2863   }
2864   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
2865     goto exit_create_index;
2866   }
2867 
2868   /*
2869   ** Find the table that is to be indexed.  Return early if not found.
2870   */
2871   if( pTblName!=0 ){
2872 
2873     /* Use the two-part index name to determine the database
2874     ** to search for the table. 'Fix' the table name to this db
2875     ** before looking up the table.
2876     */
2877     assert( pName1 && pName2 );
2878     iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
2879     if( iDb<0 ) goto exit_create_index;
2880     assert( pName && pName->z );
2881 
2882 #ifndef SQLITE_OMIT_TEMPDB
2883     /* If the index name was unqualified, check if the table
2884     ** is a temp table. If so, set the database to 1. Do not do this
2885     ** if initialising a database schema.
2886     */
2887     if( !db->init.busy ){
2888       pTab = sqlite3SrcListLookup(pParse, pTblName);
2889       if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
2890         iDb = 1;
2891       }
2892     }
2893 #endif
2894 
2895     sqlite3FixInit(&sFix, pParse, iDb, "index", pName);
2896     if( sqlite3FixSrcList(&sFix, pTblName) ){
2897       /* Because the parser constructs pTblName from a single identifier,
2898       ** sqlite3FixSrcList can never fail. */
2899       assert(0);
2900     }
2901     pTab = sqlite3LocateTableItem(pParse, 0, &pTblName->a[0]);
2902     assert( db->mallocFailed==0 || pTab==0 );
2903     if( pTab==0 ) goto exit_create_index;
2904     if( iDb==1 && db->aDb[iDb].pSchema!=pTab->pSchema ){
2905       sqlite3ErrorMsg(pParse,
2906            "cannot create a TEMP index on non-TEMP table \"%s\"",
2907            pTab->zName);
2908       goto exit_create_index;
2909     }
2910     if( !HasRowid(pTab) ) pPk = sqlite3PrimaryKeyIndex(pTab);
2911   }else{
2912     assert( pName==0 );
2913     assert( pStart==0 );
2914     pTab = pParse->pNewTable;
2915     if( !pTab ) goto exit_create_index;
2916     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
2917   }
2918   pDb = &db->aDb[iDb];
2919 
2920   assert( pTab!=0 );
2921   assert( pParse->nErr==0 );
2922   if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
2923        && db->init.busy==0
2924 #if SQLITE_USER_AUTHENTICATION
2925        && sqlite3UserAuthTable(pTab->zName)==0
2926 #endif
2927        && sqlite3StrNICmp(&pTab->zName[7],"altertab_",9)!=0 ){
2928     sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
2929     goto exit_create_index;
2930   }
2931 #ifndef SQLITE_OMIT_VIEW
2932   if( pTab->pSelect ){
2933     sqlite3ErrorMsg(pParse, "views may not be indexed");
2934     goto exit_create_index;
2935   }
2936 #endif
2937 #ifndef SQLITE_OMIT_VIRTUALTABLE
2938   if( IsVirtual(pTab) ){
2939     sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
2940     goto exit_create_index;
2941   }
2942 #endif
2943 
2944   /*
2945   ** Find the name of the index.  Make sure there is not already another
2946   ** index or table with the same name.
2947   **
2948   ** Exception:  If we are reading the names of permanent indices from the
2949   ** sqlite_master table (because some other process changed the schema) and
2950   ** one of the index names collides with the name of a temporary table or
2951   ** index, then we will continue to process this index.
2952   **
2953   ** If pName==0 it means that we are
2954   ** dealing with a primary key or UNIQUE constraint.  We have to invent our
2955   ** own name.
2956   */
2957   if( pName ){
2958     zName = sqlite3NameFromToken(db, pName);
2959     if( zName==0 ) goto exit_create_index;
2960     assert( pName->z!=0 );
2961     if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
2962       goto exit_create_index;
2963     }
2964     if( !db->init.busy ){
2965       if( sqlite3FindTable(db, zName, 0)!=0 ){
2966         sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
2967         goto exit_create_index;
2968       }
2969     }
2970     if( sqlite3FindIndex(db, zName, pDb->zName)!=0 ){
2971       if( !ifNotExist ){
2972         sqlite3ErrorMsg(pParse, "index %s already exists", zName);
2973       }else{
2974         assert( !db->init.busy );
2975         sqlite3CodeVerifySchema(pParse, iDb);
2976       }
2977       goto exit_create_index;
2978     }
2979   }else{
2980     int n;
2981     Index *pLoop;
2982     for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
2983     zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n);
2984     if( zName==0 ){
2985       goto exit_create_index;
2986     }
2987   }
2988 
2989   /* Check for authorization to create an index.
2990   */
2991 #ifndef SQLITE_OMIT_AUTHORIZATION
2992   {
2993     const char *zDb = pDb->zName;
2994     if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
2995       goto exit_create_index;
2996     }
2997     i = SQLITE_CREATE_INDEX;
2998     if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
2999     if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
3000       goto exit_create_index;
3001     }
3002   }
3003 #endif
3004 
3005   /* If pList==0, it means this routine was called to make a primary
3006   ** key out of the last column added to the table under construction.
3007   ** So create a fake list to simulate this.
3008   */
3009   if( pList==0 ){
3010     pList = sqlite3ExprListAppend(pParse, 0, 0);
3011     if( pList==0 ) goto exit_create_index;
3012     pList->a[0].zName = sqlite3DbStrDup(pParse->db,
3013                                         pTab->aCol[pTab->nCol-1].zName);
3014     pList->a[0].sortOrder = (u8)sortOrder;
3015   }
3016 
3017   /* Figure out how many bytes of space are required to store explicitly
3018   ** specified collation sequence names.
3019   */
3020   for(i=0; i<pList->nExpr; i++){
3021     Expr *pExpr = pList->a[i].pExpr;
3022     if( pExpr ){
3023       assert( pExpr->op==TK_COLLATE );
3024       nExtra += (1 + sqlite3Strlen30(pExpr->u.zToken));
3025     }
3026   }
3027 
3028   /*
3029   ** Allocate the index structure.
3030   */
3031   nName = sqlite3Strlen30(zName);
3032   nExtraCol = pPk ? pPk->nKeyCol : 1;
3033   pIndex = sqlite3AllocateIndexObject(db, pList->nExpr + nExtraCol,
3034                                       nName + nExtra + 1, &zExtra);
3035   if( db->mallocFailed ){
3036     goto exit_create_index;
3037   }
3038   assert( EIGHT_BYTE_ALIGNMENT(pIndex->aiRowLogEst) );
3039   assert( EIGHT_BYTE_ALIGNMENT(pIndex->azColl) );
3040   pIndex->zName = zExtra;
3041   zExtra += nName + 1;
3042   memcpy(pIndex->zName, zName, nName+1);
3043   pIndex->pTable = pTab;
3044   pIndex->onError = (u8)onError;
3045   pIndex->uniqNotNull = onError!=OE_None;
3046   pIndex->idxType = pName ? SQLITE_IDXTYPE_APPDEF : SQLITE_IDXTYPE_UNIQUE;
3047   pIndex->pSchema = db->aDb[iDb].pSchema;
3048   pIndex->nKeyCol = pList->nExpr;
3049   if( pPIWhere ){
3050     sqlite3ResolveSelfReference(pParse, pTab, NC_PartIdx, pPIWhere, 0);
3051     pIndex->pPartIdxWhere = pPIWhere;
3052     pPIWhere = 0;
3053   }
3054   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
3055 
3056   /* Check to see if we should honor DESC requests on index columns
3057   */
3058   if( pDb->pSchema->file_format>=4 ){
3059     sortOrderMask = -1;   /* Honor DESC */
3060   }else{
3061     sortOrderMask = 0;    /* Ignore DESC */
3062   }
3063 
3064   /* Scan the names of the columns of the table to be indexed and
3065   ** load the column indices into the Index structure.  Report an error
3066   ** if any column is not found.
3067   **
3068   ** TODO:  Add a test to make sure that the same column is not named
3069   ** more than once within the same index.  Only the first instance of
3070   ** the column will ever be used by the optimizer.  Note that using the
3071   ** same column more than once cannot be an error because that would
3072   ** break backwards compatibility - it needs to be a warning.
3073   */
3074   for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){
3075     const char *zColName = pListItem->zName;
3076     int requestedSortOrder;
3077     char *zColl;                   /* Collation sequence name */
3078 
3079     for(j=0, pTabCol=pTab->aCol; j<pTab->nCol; j++, pTabCol++){
3080       if( sqlite3StrICmp(zColName, pTabCol->zName)==0 ) break;
3081     }
3082     if( j>=pTab->nCol ){
3083       sqlite3ErrorMsg(pParse, "table %s has no column named %s",
3084         pTab->zName, zColName);
3085       pParse->checkSchema = 1;
3086       goto exit_create_index;
3087     }
3088     assert( j<=0x7fff );
3089     pIndex->aiColumn[i] = (i16)j;
3090     if( pListItem->pExpr ){
3091       int nColl;
3092       assert( pListItem->pExpr->op==TK_COLLATE );
3093       zColl = pListItem->pExpr->u.zToken;
3094       nColl = sqlite3Strlen30(zColl) + 1;
3095       assert( nExtra>=nColl );
3096       memcpy(zExtra, zColl, nColl);
3097       zColl = zExtra;
3098       zExtra += nColl;
3099       nExtra -= nColl;
3100     }else{
3101       zColl = pTab->aCol[j].zColl;
3102       if( !zColl ) zColl = "BINARY";
3103     }
3104     if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){
3105       goto exit_create_index;
3106     }
3107     pIndex->azColl[i] = zColl;
3108     requestedSortOrder = pListItem->sortOrder & sortOrderMask;
3109     pIndex->aSortOrder[i] = (u8)requestedSortOrder;
3110     if( pTab->aCol[j].notNull==0 ) pIndex->uniqNotNull = 0;
3111   }
3112   if( pPk ){
3113     for(j=0; j<pPk->nKeyCol; j++){
3114       int x = pPk->aiColumn[j];
3115       if( hasColumn(pIndex->aiColumn, pIndex->nKeyCol, x) ){
3116         pIndex->nColumn--;
3117       }else{
3118         pIndex->aiColumn[i] = x;
3119         pIndex->azColl[i] = pPk->azColl[j];
3120         pIndex->aSortOrder[i] = pPk->aSortOrder[j];
3121         i++;
3122       }
3123     }
3124     assert( i==pIndex->nColumn );
3125   }else{
3126     pIndex->aiColumn[i] = -1;
3127     pIndex->azColl[i] = "BINARY";
3128   }
3129   sqlite3DefaultRowEst(pIndex);
3130   if( pParse->pNewTable==0 ) estimateIndexWidth(pIndex);
3131 
3132   if( pTab==pParse->pNewTable ){
3133     /* This routine has been called to create an automatic index as a
3134     ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
3135     ** a PRIMARY KEY or UNIQUE clause following the column definitions.
3136     ** i.e. one of:
3137     **
3138     ** CREATE TABLE t(x PRIMARY KEY, y);
3139     ** CREATE TABLE t(x, y, UNIQUE(x, y));
3140     **
3141     ** Either way, check to see if the table already has such an index. If
3142     ** so, don't bother creating this one. This only applies to
3143     ** automatically created indices. Users can do as they wish with
3144     ** explicit indices.
3145     **
3146     ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent
3147     ** (and thus suppressing the second one) even if they have different
3148     ** sort orders.
3149     **
3150     ** If there are different collating sequences or if the columns of
3151     ** the constraint occur in different orders, then the constraints are
3152     ** considered distinct and both result in separate indices.
3153     */
3154     Index *pIdx;
3155     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
3156       int k;
3157       assert( IsUniqueIndex(pIdx) );
3158       assert( pIdx->idxType!=SQLITE_IDXTYPE_APPDEF );
3159       assert( IsUniqueIndex(pIndex) );
3160 
3161       if( pIdx->nKeyCol!=pIndex->nKeyCol ) continue;
3162       for(k=0; k<pIdx->nKeyCol; k++){
3163         const char *z1;
3164         const char *z2;
3165         if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
3166         z1 = pIdx->azColl[k];
3167         z2 = pIndex->azColl[k];
3168         if( z1!=z2 && sqlite3StrICmp(z1, z2) ) break;
3169       }
3170       if( k==pIdx->nKeyCol ){
3171         if( pIdx->onError!=pIndex->onError ){
3172           /* This constraint creates the same index as a previous
3173           ** constraint specified somewhere in the CREATE TABLE statement.
3174           ** However the ON CONFLICT clauses are different. If both this
3175           ** constraint and the previous equivalent constraint have explicit
3176           ** ON CONFLICT clauses this is an error. Otherwise, use the
3177           ** explicitly specified behavior for the index.
3178           */
3179           if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
3180             sqlite3ErrorMsg(pParse,
3181                 "conflicting ON CONFLICT clauses specified", 0);
3182           }
3183           if( pIdx->onError==OE_Default ){
3184             pIdx->onError = pIndex->onError;
3185           }
3186         }
3187         goto exit_create_index;
3188       }
3189     }
3190   }
3191 
3192   /* Link the new Index structure to its table and to the other
3193   ** in-memory database structures.
3194   */
3195   if( db->init.busy ){
3196     Index *p;
3197     assert( sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
3198     p = sqlite3HashInsert(&pIndex->pSchema->idxHash,
3199                           pIndex->zName, pIndex);
3200     if( p ){
3201       assert( p==pIndex );  /* Malloc must have failed */
3202       db->mallocFailed = 1;
3203       goto exit_create_index;
3204     }
3205     db->flags |= SQLITE_InternChanges;
3206     if( pTblName!=0 ){
3207       pIndex->tnum = db->init.newTnum;
3208     }
3209   }
3210 
3211   /* If this is the initial CREATE INDEX statement (or CREATE TABLE if the
3212   ** index is an implied index for a UNIQUE or PRIMARY KEY constraint) then
3213   ** emit code to allocate the index rootpage on disk and make an entry for
3214   ** the index in the sqlite_master table and populate the index with
3215   ** content.  But, do not do this if we are simply reading the sqlite_master
3216   ** table to parse the schema, or if this index is the PRIMARY KEY index
3217   ** of a WITHOUT ROWID table.
3218   **
3219   ** If pTblName==0 it means this index is generated as an implied PRIMARY KEY
3220   ** or UNIQUE index in a CREATE TABLE statement.  Since the table
3221   ** has just been created, it contains no data and the index initialization
3222   ** step can be skipped.
3223   */
3224   else if( pParse->nErr==0 && (HasRowid(pTab) || pTblName!=0) ){
3225     Vdbe *v;
3226     char *zStmt;
3227     int iMem = ++pParse->nMem;
3228 
3229     v = sqlite3GetVdbe(pParse);
3230     if( v==0 ) goto exit_create_index;
3231 
3232 
3233     /* Create the rootpage for the index
3234     */
3235     sqlite3BeginWriteOperation(pParse, 1, iDb);
3236     sqlite3VdbeAddOp2(v, OP_CreateIndex, iDb, iMem);
3237 
3238     /* Gather the complete text of the CREATE INDEX statement into
3239     ** the zStmt variable
3240     */
3241     if( pStart ){
3242       int n = (int)(pParse->sLastToken.z - pName->z) + pParse->sLastToken.n;
3243       if( pName->z[n-1]==';' ) n--;
3244       /* A named index with an explicit CREATE INDEX statement */
3245       zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
3246         onError==OE_None ? "" : " UNIQUE", n, pName->z);
3247     }else{
3248       /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
3249       /* zStmt = sqlite3MPrintf(""); */
3250       zStmt = 0;
3251     }
3252 
3253     /* Add an entry in sqlite_master for this index
3254     */
3255     sqlite3NestedParse(pParse,
3256         "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);",
3257         db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
3258         pIndex->zName,
3259         pTab->zName,
3260         iMem,
3261         zStmt
3262     );
3263     sqlite3DbFree(db, zStmt);
3264 
3265     /* Fill the index with data and reparse the schema. Code an OP_Expire
3266     ** to invalidate all pre-compiled statements.
3267     */
3268     if( pTblName ){
3269       sqlite3RefillIndex(pParse, pIndex, iMem);
3270       sqlite3ChangeCookie(pParse, iDb);
3271       sqlite3VdbeAddParseSchemaOp(v, iDb,
3272          sqlite3MPrintf(db, "name='%q' AND type='index'", pIndex->zName));
3273       sqlite3VdbeAddOp1(v, OP_Expire, 0);
3274     }
3275   }
3276 
3277   /* When adding an index to the list of indices for a table, make
3278   ** sure all indices labeled OE_Replace come after all those labeled
3279   ** OE_Ignore.  This is necessary for the correct constraint check
3280   ** processing (in sqlite3GenerateConstraintChecks()) as part of
3281   ** UPDATE and INSERT statements.
3282   */
3283   if( db->init.busy || pTblName==0 ){
3284     if( onError!=OE_Replace || pTab->pIndex==0
3285          || pTab->pIndex->onError==OE_Replace){
3286       pIndex->pNext = pTab->pIndex;
3287       pTab->pIndex = pIndex;
3288     }else{
3289       Index *pOther = pTab->pIndex;
3290       while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
3291         pOther = pOther->pNext;
3292       }
3293       pIndex->pNext = pOther->pNext;
3294       pOther->pNext = pIndex;
3295     }
3296     pRet = pIndex;
3297     pIndex = 0;
3298   }
3299 
3300   /* Clean up before exiting */
3301 exit_create_index:
3302   if( pIndex ) freeIndex(db, pIndex);
3303   sqlite3ExprDelete(db, pPIWhere);
3304   sqlite3ExprListDelete(db, pList);
3305   sqlite3SrcListDelete(db, pTblName);
3306   sqlite3DbFree(db, zName);
3307   return pRet;
3308 }
3309 
3310 /*
3311 ** Fill the Index.aiRowEst[] array with default information - information
3312 ** to be used when we have not run the ANALYZE command.
3313 **
3314 ** aiRowEst[0] is supposed to contain the number of elements in the index.
3315 ** Since we do not know, guess 1 million.  aiRowEst[1] is an estimate of the
3316 ** number of rows in the table that match any particular value of the
3317 ** first column of the index.  aiRowEst[2] is an estimate of the number
3318 ** of rows that match any particular combination of the first 2 columns
3319 ** of the index.  And so forth.  It must always be the case that
3320 *
3321 **           aiRowEst[N]<=aiRowEst[N-1]
3322 **           aiRowEst[N]>=1
3323 **
3324 ** Apart from that, we have little to go on besides intuition as to
3325 ** how aiRowEst[] should be initialized.  The numbers generated here
3326 ** are based on typical values found in actual indices.
3327 */
3328 void sqlite3DefaultRowEst(Index *pIdx){
3329   /*                10,  9,  8,  7,  6 */
3330   LogEst aVal[] = { 33, 32, 30, 28, 26 };
3331   LogEst *a = pIdx->aiRowLogEst;
3332   int nCopy = MIN(ArraySize(aVal), pIdx->nKeyCol);
3333   int i;
3334 
3335   /* Set the first entry (number of rows in the index) to the estimated
3336   ** number of rows in the table. Or 10, if the estimated number of rows
3337   ** in the table is less than that.  */
3338   a[0] = pIdx->pTable->nRowLogEst;
3339   if( a[0]<33 ) a[0] = 33;        assert( 33==sqlite3LogEst(10) );
3340 
3341   /* Estimate that a[1] is 10, a[2] is 9, a[3] is 8, a[4] is 7, a[5] is
3342   ** 6 and each subsequent value (if any) is 5.  */
3343   memcpy(&a[1], aVal, nCopy*sizeof(LogEst));
3344   for(i=nCopy+1; i<=pIdx->nKeyCol; i++){
3345     a[i] = 23;                    assert( 23==sqlite3LogEst(5) );
3346   }
3347 
3348   assert( 0==sqlite3LogEst(1) );
3349   if( IsUniqueIndex(pIdx) ) a[pIdx->nKeyCol] = 0;
3350 }
3351 
3352 /*
3353 ** This routine will drop an existing named index.  This routine
3354 ** implements the DROP INDEX statement.
3355 */
3356 void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
3357   Index *pIndex;
3358   Vdbe *v;
3359   sqlite3 *db = pParse->db;
3360   int iDb;
3361 
3362   assert( pParse->nErr==0 );   /* Never called with prior errors */
3363   if( db->mallocFailed ){
3364     goto exit_drop_index;
3365   }
3366   assert( pName->nSrc==1 );
3367   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
3368     goto exit_drop_index;
3369   }
3370   pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
3371   if( pIndex==0 ){
3372     if( !ifExists ){
3373       sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
3374     }else{
3375       sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
3376     }
3377     pParse->checkSchema = 1;
3378     goto exit_drop_index;
3379   }
3380   if( pIndex->idxType!=SQLITE_IDXTYPE_APPDEF ){
3381     sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
3382       "or PRIMARY KEY constraint cannot be dropped", 0);
3383     goto exit_drop_index;
3384   }
3385   iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
3386 #ifndef SQLITE_OMIT_AUTHORIZATION
3387   {
3388     int code = SQLITE_DROP_INDEX;
3389     Table *pTab = pIndex->pTable;
3390     const char *zDb = db->aDb[iDb].zName;
3391     const char *zTab = SCHEMA_TABLE(iDb);
3392     if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
3393       goto exit_drop_index;
3394     }
3395     if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
3396     if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
3397       goto exit_drop_index;
3398     }
3399   }
3400 #endif
3401 
3402   /* Generate code to remove the index and from the master table */
3403   v = sqlite3GetVdbe(pParse);
3404   if( v ){
3405     sqlite3BeginWriteOperation(pParse, 1, iDb);
3406     sqlite3NestedParse(pParse,
3407        "DELETE FROM %Q.%s WHERE name=%Q AND type='index'",
3408        db->aDb[iDb].zName, SCHEMA_TABLE(iDb), pIndex->zName
3409     );
3410     sqlite3ClearStatTables(pParse, iDb, "idx", pIndex->zName);
3411     sqlite3ChangeCookie(pParse, iDb);
3412     destroyRootPage(pParse, pIndex->tnum, iDb);
3413     sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
3414   }
3415 
3416 exit_drop_index:
3417   sqlite3SrcListDelete(db, pName);
3418 }
3419 
3420 /*
3421 ** pArray is a pointer to an array of objects. Each object in the
3422 ** array is szEntry bytes in size. This routine uses sqlite3DbRealloc()
3423 ** to extend the array so that there is space for a new object at the end.
3424 **
3425 ** When this function is called, *pnEntry contains the current size of
3426 ** the array (in entries - so the allocation is ((*pnEntry) * szEntry) bytes
3427 ** in total).
3428 **
3429 ** If the realloc() is successful (i.e. if no OOM condition occurs), the
3430 ** space allocated for the new object is zeroed, *pnEntry updated to
3431 ** reflect the new size of the array and a pointer to the new allocation
3432 ** returned. *pIdx is set to the index of the new array entry in this case.
3433 **
3434 ** Otherwise, if the realloc() fails, *pIdx is set to -1, *pnEntry remains
3435 ** unchanged and a copy of pArray returned.
3436 */
3437 void *sqlite3ArrayAllocate(
3438   sqlite3 *db,      /* Connection to notify of malloc failures */
3439   void *pArray,     /* Array of objects.  Might be reallocated */
3440   int szEntry,      /* Size of each object in the array */
3441   int *pnEntry,     /* Number of objects currently in use */
3442   int *pIdx         /* Write the index of a new slot here */
3443 ){
3444   char *z;
3445   int n = *pnEntry;
3446   if( (n & (n-1))==0 ){
3447     int sz = (n==0) ? 1 : 2*n;
3448     void *pNew = sqlite3DbRealloc(db, pArray, sz*szEntry);
3449     if( pNew==0 ){
3450       *pIdx = -1;
3451       return pArray;
3452     }
3453     pArray = pNew;
3454   }
3455   z = (char*)pArray;
3456   memset(&z[n * szEntry], 0, szEntry);
3457   *pIdx = n;
3458   ++*pnEntry;
3459   return pArray;
3460 }
3461 
3462 /*
3463 ** Append a new element to the given IdList.  Create a new IdList if
3464 ** need be.
3465 **
3466 ** A new IdList is returned, or NULL if malloc() fails.
3467 */
3468 IdList *sqlite3IdListAppend(sqlite3 *db, IdList *pList, Token *pToken){
3469   int i;
3470   if( pList==0 ){
3471     pList = sqlite3DbMallocZero(db, sizeof(IdList) );
3472     if( pList==0 ) return 0;
3473   }
3474   pList->a = sqlite3ArrayAllocate(
3475       db,
3476       pList->a,
3477       sizeof(pList->a[0]),
3478       &pList->nId,
3479       &i
3480   );
3481   if( i<0 ){
3482     sqlite3IdListDelete(db, pList);
3483     return 0;
3484   }
3485   pList->a[i].zName = sqlite3NameFromToken(db, pToken);
3486   return pList;
3487 }
3488 
3489 /*
3490 ** Delete an IdList.
3491 */
3492 void sqlite3IdListDelete(sqlite3 *db, IdList *pList){
3493   int i;
3494   if( pList==0 ) return;
3495   for(i=0; i<pList->nId; i++){
3496     sqlite3DbFree(db, pList->a[i].zName);
3497   }
3498   sqlite3DbFree(db, pList->a);
3499   sqlite3DbFree(db, pList);
3500 }
3501 
3502 /*
3503 ** Return the index in pList of the identifier named zId.  Return -1
3504 ** if not found.
3505 */
3506 int sqlite3IdListIndex(IdList *pList, const char *zName){
3507   int i;
3508   if( pList==0 ) return -1;
3509   for(i=0; i<pList->nId; i++){
3510     if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
3511   }
3512   return -1;
3513 }
3514 
3515 /*
3516 ** Expand the space allocated for the given SrcList object by
3517 ** creating nExtra new slots beginning at iStart.  iStart is zero based.
3518 ** New slots are zeroed.
3519 **
3520 ** For example, suppose a SrcList initially contains two entries: A,B.
3521 ** To append 3 new entries onto the end, do this:
3522 **
3523 **    sqlite3SrcListEnlarge(db, pSrclist, 3, 2);
3524 **
3525 ** After the call above it would contain:  A, B, nil, nil, nil.
3526 ** If the iStart argument had been 1 instead of 2, then the result
3527 ** would have been:  A, nil, nil, nil, B.  To prepend the new slots,
3528 ** the iStart value would be 0.  The result then would
3529 ** be: nil, nil, nil, A, B.
3530 **
3531 ** If a memory allocation fails the SrcList is unchanged.  The
3532 ** db->mallocFailed flag will be set to true.
3533 */
3534 SrcList *sqlite3SrcListEnlarge(
3535   sqlite3 *db,       /* Database connection to notify of OOM errors */
3536   SrcList *pSrc,     /* The SrcList to be enlarged */
3537   int nExtra,        /* Number of new slots to add to pSrc->a[] */
3538   int iStart         /* Index in pSrc->a[] of first new slot */
3539 ){
3540   int i;
3541 
3542   /* Sanity checking on calling parameters */
3543   assert( iStart>=0 );
3544   assert( nExtra>=1 );
3545   assert( pSrc!=0 );
3546   assert( iStart<=pSrc->nSrc );
3547 
3548   /* Allocate additional space if needed */
3549   if( (u32)pSrc->nSrc+nExtra>pSrc->nAlloc ){
3550     SrcList *pNew;
3551     int nAlloc = pSrc->nSrc+nExtra;
3552     int nGot;
3553     pNew = sqlite3DbRealloc(db, pSrc,
3554                sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) );
3555     if( pNew==0 ){
3556       assert( db->mallocFailed );
3557       return pSrc;
3558     }
3559     pSrc = pNew;
3560     nGot = (sqlite3DbMallocSize(db, pNew) - sizeof(*pSrc))/sizeof(pSrc->a[0])+1;
3561     pSrc->nAlloc = nGot;
3562   }
3563 
3564   /* Move existing slots that come after the newly inserted slots
3565   ** out of the way */
3566   for(i=pSrc->nSrc-1; i>=iStart; i--){
3567     pSrc->a[i+nExtra] = pSrc->a[i];
3568   }
3569   pSrc->nSrc += nExtra;
3570 
3571   /* Zero the newly allocated slots */
3572   memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
3573   for(i=iStart; i<iStart+nExtra; i++){
3574     pSrc->a[i].iCursor = -1;
3575   }
3576 
3577   /* Return a pointer to the enlarged SrcList */
3578   return pSrc;
3579 }
3580 
3581 
3582 /*
3583 ** Append a new table name to the given SrcList.  Create a new SrcList if
3584 ** need be.  A new entry is created in the SrcList even if pTable is NULL.
3585 **
3586 ** A SrcList is returned, or NULL if there is an OOM error.  The returned
3587 ** SrcList might be the same as the SrcList that was input or it might be
3588 ** a new one.  If an OOM error does occurs, then the prior value of pList
3589 ** that is input to this routine is automatically freed.
3590 **
3591 ** If pDatabase is not null, it means that the table has an optional
3592 ** database name prefix.  Like this:  "database.table".  The pDatabase
3593 ** points to the table name and the pTable points to the database name.
3594 ** The SrcList.a[].zName field is filled with the table name which might
3595 ** come from pTable (if pDatabase is NULL) or from pDatabase.
3596 ** SrcList.a[].zDatabase is filled with the database name from pTable,
3597 ** or with NULL if no database is specified.
3598 **
3599 ** In other words, if call like this:
3600 **
3601 **         sqlite3SrcListAppend(D,A,B,0);
3602 **
3603 ** Then B is a table name and the database name is unspecified.  If called
3604 ** like this:
3605 **
3606 **         sqlite3SrcListAppend(D,A,B,C);
3607 **
3608 ** Then C is the table name and B is the database name.  If C is defined
3609 ** then so is B.  In other words, we never have a case where:
3610 **
3611 **         sqlite3SrcListAppend(D,A,0,C);
3612 **
3613 ** Both pTable and pDatabase are assumed to be quoted.  They are dequoted
3614 ** before being added to the SrcList.
3615 */
3616 SrcList *sqlite3SrcListAppend(
3617   sqlite3 *db,        /* Connection to notify of malloc failures */
3618   SrcList *pList,     /* Append to this SrcList. NULL creates a new SrcList */
3619   Token *pTable,      /* Table to append */
3620   Token *pDatabase    /* Database of the table */
3621 ){
3622   struct SrcList_item *pItem;
3623   assert( pDatabase==0 || pTable!=0 );  /* Cannot have C without B */
3624   if( pList==0 ){
3625     pList = sqlite3DbMallocZero(db, sizeof(SrcList) );
3626     if( pList==0 ) return 0;
3627     pList->nAlloc = 1;
3628   }
3629   pList = sqlite3SrcListEnlarge(db, pList, 1, pList->nSrc);
3630   if( db->mallocFailed ){
3631     sqlite3SrcListDelete(db, pList);
3632     return 0;
3633   }
3634   pItem = &pList->a[pList->nSrc-1];
3635   if( pDatabase && pDatabase->z==0 ){
3636     pDatabase = 0;
3637   }
3638   if( pDatabase ){
3639     Token *pTemp = pDatabase;
3640     pDatabase = pTable;
3641     pTable = pTemp;
3642   }
3643   pItem->zName = sqlite3NameFromToken(db, pTable);
3644   pItem->zDatabase = sqlite3NameFromToken(db, pDatabase);
3645   return pList;
3646 }
3647 
3648 /*
3649 ** Assign VdbeCursor index numbers to all tables in a SrcList
3650 */
3651 void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
3652   int i;
3653   struct SrcList_item *pItem;
3654   assert(pList || pParse->db->mallocFailed );
3655   if( pList ){
3656     for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
3657       if( pItem->iCursor>=0 ) break;
3658       pItem->iCursor = pParse->nTab++;
3659       if( pItem->pSelect ){
3660         sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
3661       }
3662     }
3663   }
3664 }
3665 
3666 /*
3667 ** Delete an entire SrcList including all its substructure.
3668 */
3669 void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){
3670   int i;
3671   struct SrcList_item *pItem;
3672   if( pList==0 ) return;
3673   for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
3674     sqlite3DbFree(db, pItem->zDatabase);
3675     sqlite3DbFree(db, pItem->zName);
3676     sqlite3DbFree(db, pItem->zAlias);
3677     sqlite3DbFree(db, pItem->zIndex);
3678     sqlite3DeleteTable(db, pItem->pTab);
3679     sqlite3SelectDelete(db, pItem->pSelect);
3680     sqlite3ExprDelete(db, pItem->pOn);
3681     sqlite3IdListDelete(db, pItem->pUsing);
3682   }
3683   sqlite3DbFree(db, pList);
3684 }
3685 
3686 /*
3687 ** This routine is called by the parser to add a new term to the
3688 ** end of a growing FROM clause.  The "p" parameter is the part of
3689 ** the FROM clause that has already been constructed.  "p" is NULL
3690 ** if this is the first term of the FROM clause.  pTable and pDatabase
3691 ** are the name of the table and database named in the FROM clause term.
3692 ** pDatabase is NULL if the database name qualifier is missing - the
3693 ** usual case.  If the term has an alias, then pAlias points to the
3694 ** alias token.  If the term is a subquery, then pSubquery is the
3695 ** SELECT statement that the subquery encodes.  The pTable and
3696 ** pDatabase parameters are NULL for subqueries.  The pOn and pUsing
3697 ** parameters are the content of the ON and USING clauses.
3698 **
3699 ** Return a new SrcList which encodes is the FROM with the new
3700 ** term added.
3701 */
3702 SrcList *sqlite3SrcListAppendFromTerm(
3703   Parse *pParse,          /* Parsing context */
3704   SrcList *p,             /* The left part of the FROM clause already seen */
3705   Token *pTable,          /* Name of the table to add to the FROM clause */
3706   Token *pDatabase,       /* Name of the database containing pTable */
3707   Token *pAlias,          /* The right-hand side of the AS subexpression */
3708   Select *pSubquery,      /* A subquery used in place of a table name */
3709   Expr *pOn,              /* The ON clause of a join */
3710   IdList *pUsing          /* The USING clause of a join */
3711 ){
3712   struct SrcList_item *pItem;
3713   sqlite3 *db = pParse->db;
3714   if( !p && (pOn || pUsing) ){
3715     sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s",
3716       (pOn ? "ON" : "USING")
3717     );
3718     goto append_from_error;
3719   }
3720   p = sqlite3SrcListAppend(db, p, pTable, pDatabase);
3721   if( p==0 || NEVER(p->nSrc==0) ){
3722     goto append_from_error;
3723   }
3724   pItem = &p->a[p->nSrc-1];
3725   assert( pAlias!=0 );
3726   if( pAlias->n ){
3727     pItem->zAlias = sqlite3NameFromToken(db, pAlias);
3728   }
3729   pItem->pSelect = pSubquery;
3730   pItem->pOn = pOn;
3731   pItem->pUsing = pUsing;
3732   return p;
3733 
3734  append_from_error:
3735   assert( p==0 );
3736   sqlite3ExprDelete(db, pOn);
3737   sqlite3IdListDelete(db, pUsing);
3738   sqlite3SelectDelete(db, pSubquery);
3739   return 0;
3740 }
3741 
3742 /*
3743 ** Add an INDEXED BY or NOT INDEXED clause to the most recently added
3744 ** element of the source-list passed as the second argument.
3745 */
3746 void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){
3747   assert( pIndexedBy!=0 );
3748   if( p && ALWAYS(p->nSrc>0) ){
3749     struct SrcList_item *pItem = &p->a[p->nSrc-1];
3750     assert( pItem->notIndexed==0 && pItem->zIndex==0 );
3751     if( pIndexedBy->n==1 && !pIndexedBy->z ){
3752       /* A "NOT INDEXED" clause was supplied. See parse.y
3753       ** construct "indexed_opt" for details. */
3754       pItem->notIndexed = 1;
3755     }else{
3756       pItem->zIndex = sqlite3NameFromToken(pParse->db, pIndexedBy);
3757     }
3758   }
3759 }
3760 
3761 /*
3762 ** When building up a FROM clause in the parser, the join operator
3763 ** is initially attached to the left operand.  But the code generator
3764 ** expects the join operator to be on the right operand.  This routine
3765 ** Shifts all join operators from left to right for an entire FROM
3766 ** clause.
3767 **
3768 ** Example: Suppose the join is like this:
3769 **
3770 **           A natural cross join B
3771 **
3772 ** The operator is "natural cross join".  The A and B operands are stored
3773 ** in p->a[0] and p->a[1], respectively.  The parser initially stores the
3774 ** operator with A.  This routine shifts that operator over to B.
3775 */
3776 void sqlite3SrcListShiftJoinType(SrcList *p){
3777   if( p ){
3778     int i;
3779     assert( p->a || p->nSrc==0 );
3780     for(i=p->nSrc-1; i>0; i--){
3781       p->a[i].jointype = p->a[i-1].jointype;
3782     }
3783     p->a[0].jointype = 0;
3784   }
3785 }
3786 
3787 /*
3788 ** Begin a transaction
3789 */
3790 void sqlite3BeginTransaction(Parse *pParse, int type){
3791   sqlite3 *db;
3792   Vdbe *v;
3793   int i;
3794 
3795   assert( pParse!=0 );
3796   db = pParse->db;
3797   assert( db!=0 );
3798 /*  if( db->aDb[0].pBt==0 ) return; */
3799   if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){
3800     return;
3801   }
3802   v = sqlite3GetVdbe(pParse);
3803   if( !v ) return;
3804   if( type!=TK_DEFERRED ){
3805     for(i=0; i<db->nDb; i++){
3806       sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
3807       sqlite3VdbeUsesBtree(v, i);
3808     }
3809   }
3810   sqlite3VdbeAddOp2(v, OP_AutoCommit, 0, 0);
3811 }
3812 
3813 /*
3814 ** Commit a transaction
3815 */
3816 void sqlite3CommitTransaction(Parse *pParse){
3817   Vdbe *v;
3818 
3819   assert( pParse!=0 );
3820   assert( pParse->db!=0 );
3821   if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ){
3822     return;
3823   }
3824   v = sqlite3GetVdbe(pParse);
3825   if( v ){
3826     sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 0);
3827   }
3828 }
3829 
3830 /*
3831 ** Rollback a transaction
3832 */
3833 void sqlite3RollbackTransaction(Parse *pParse){
3834   Vdbe *v;
3835 
3836   assert( pParse!=0 );
3837   assert( pParse->db!=0 );
3838   if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ){
3839     return;
3840   }
3841   v = sqlite3GetVdbe(pParse);
3842   if( v ){
3843     sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 1);
3844   }
3845 }
3846 
3847 /*
3848 ** This function is called by the parser when it parses a command to create,
3849 ** release or rollback an SQL savepoint.
3850 */
3851 void sqlite3Savepoint(Parse *pParse, int op, Token *pName){
3852   char *zName = sqlite3NameFromToken(pParse->db, pName);
3853   if( zName ){
3854     Vdbe *v = sqlite3GetVdbe(pParse);
3855 #ifndef SQLITE_OMIT_AUTHORIZATION
3856     static const char * const az[] = { "BEGIN", "RELEASE", "ROLLBACK" };
3857     assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 );
3858 #endif
3859     if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){
3860       sqlite3DbFree(pParse->db, zName);
3861       return;
3862     }
3863     sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC);
3864   }
3865 }
3866 
3867 /*
3868 ** Make sure the TEMP database is open and available for use.  Return
3869 ** the number of errors.  Leave any error messages in the pParse structure.
3870 */
3871 int sqlite3OpenTempDatabase(Parse *pParse){
3872   sqlite3 *db = pParse->db;
3873   if( db->aDb[1].pBt==0 && !pParse->explain ){
3874     int rc;
3875     Btree *pBt;
3876     static const int flags =
3877           SQLITE_OPEN_READWRITE |
3878           SQLITE_OPEN_CREATE |
3879           SQLITE_OPEN_EXCLUSIVE |
3880           SQLITE_OPEN_DELETEONCLOSE |
3881           SQLITE_OPEN_TEMP_DB;
3882 
3883     rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pBt, 0, flags);
3884     if( rc!=SQLITE_OK ){
3885       sqlite3ErrorMsg(pParse, "unable to open a temporary database "
3886         "file for storing temporary tables");
3887       pParse->rc = rc;
3888       return 1;
3889     }
3890     db->aDb[1].pBt = pBt;
3891     assert( db->aDb[1].pSchema );
3892     if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){
3893       db->mallocFailed = 1;
3894       return 1;
3895     }
3896   }
3897   return 0;
3898 }
3899 
3900 /*
3901 ** Record the fact that the schema cookie will need to be verified
3902 ** for database iDb.  The code to actually verify the schema cookie
3903 ** will occur at the end of the top-level VDBE and will be generated
3904 ** later, by sqlite3FinishCoding().
3905 */
3906 void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
3907   Parse *pToplevel = sqlite3ParseToplevel(pParse);
3908   sqlite3 *db = pToplevel->db;
3909 
3910   assert( iDb>=0 && iDb<db->nDb );
3911   assert( db->aDb[iDb].pBt!=0 || iDb==1 );
3912   assert( iDb<SQLITE_MAX_ATTACHED+2 );
3913   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
3914   if( DbMaskTest(pToplevel->cookieMask, iDb)==0 ){
3915     DbMaskSet(pToplevel->cookieMask, iDb);
3916     pToplevel->cookieValue[iDb] = db->aDb[iDb].pSchema->schema_cookie;
3917     if( !OMIT_TEMPDB && iDb==1 ){
3918       sqlite3OpenTempDatabase(pToplevel);
3919     }
3920   }
3921 }
3922 
3923 /*
3924 ** If argument zDb is NULL, then call sqlite3CodeVerifySchema() for each
3925 ** attached database. Otherwise, invoke it for the database named zDb only.
3926 */
3927 void sqlite3CodeVerifyNamedSchema(Parse *pParse, const char *zDb){
3928   sqlite3 *db = pParse->db;
3929   int i;
3930   for(i=0; i<db->nDb; i++){
3931     Db *pDb = &db->aDb[i];
3932     if( pDb->pBt && (!zDb || 0==sqlite3StrICmp(zDb, pDb->zName)) ){
3933       sqlite3CodeVerifySchema(pParse, i);
3934     }
3935   }
3936 }
3937 
3938 /*
3939 ** Generate VDBE code that prepares for doing an operation that
3940 ** might change the database.
3941 **
3942 ** This routine starts a new transaction if we are not already within
3943 ** a transaction.  If we are already within a transaction, then a checkpoint
3944 ** is set if the setStatement parameter is true.  A checkpoint should
3945 ** be set for operations that might fail (due to a constraint) part of
3946 ** the way through and which will need to undo some writes without having to
3947 ** rollback the whole transaction.  For operations where all constraints
3948 ** can be checked before any changes are made to the database, it is never
3949 ** necessary to undo a write and the checkpoint should not be set.
3950 */
3951 void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
3952   Parse *pToplevel = sqlite3ParseToplevel(pParse);
3953   sqlite3CodeVerifySchema(pParse, iDb);
3954   DbMaskSet(pToplevel->writeMask, iDb);
3955   pToplevel->isMultiWrite |= setStatement;
3956 }
3957 
3958 /*
3959 ** Indicate that the statement currently under construction might write
3960 ** more than one entry (example: deleting one row then inserting another,
3961 ** inserting multiple rows in a table, or inserting a row and index entries.)
3962 ** If an abort occurs after some of these writes have completed, then it will
3963 ** be necessary to undo the completed writes.
3964 */
3965 void sqlite3MultiWrite(Parse *pParse){
3966   Parse *pToplevel = sqlite3ParseToplevel(pParse);
3967   pToplevel->isMultiWrite = 1;
3968 }
3969 
3970 /*
3971 ** The code generator calls this routine if is discovers that it is
3972 ** possible to abort a statement prior to completion.  In order to
3973 ** perform this abort without corrupting the database, we need to make
3974 ** sure that the statement is protected by a statement transaction.
3975 **
3976 ** Technically, we only need to set the mayAbort flag if the
3977 ** isMultiWrite flag was previously set.  There is a time dependency
3978 ** such that the abort must occur after the multiwrite.  This makes
3979 ** some statements involving the REPLACE conflict resolution algorithm
3980 ** go a little faster.  But taking advantage of this time dependency
3981 ** makes it more difficult to prove that the code is correct (in
3982 ** particular, it prevents us from writing an effective
3983 ** implementation of sqlite3AssertMayAbort()) and so we have chosen
3984 ** to take the safe route and skip the optimization.
3985 */
3986 void sqlite3MayAbort(Parse *pParse){
3987   Parse *pToplevel = sqlite3ParseToplevel(pParse);
3988   pToplevel->mayAbort = 1;
3989 }
3990 
3991 /*
3992 ** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT
3993 ** error. The onError parameter determines which (if any) of the statement
3994 ** and/or current transaction is rolled back.
3995 */
3996 void sqlite3HaltConstraint(
3997   Parse *pParse,    /* Parsing context */
3998   int errCode,      /* extended error code */
3999   int onError,      /* Constraint type */
4000   char *p4,         /* Error message */
4001   i8 p4type,        /* P4_STATIC or P4_TRANSIENT */
4002   u8 p5Errmsg       /* P5_ErrMsg type */
4003 ){
4004   Vdbe *v = sqlite3GetVdbe(pParse);
4005   assert( (errCode&0xff)==SQLITE_CONSTRAINT );
4006   if( onError==OE_Abort ){
4007     sqlite3MayAbort(pParse);
4008   }
4009   sqlite3VdbeAddOp4(v, OP_Halt, errCode, onError, 0, p4, p4type);
4010   if( p5Errmsg ) sqlite3VdbeChangeP5(v, p5Errmsg);
4011 }
4012 
4013 /*
4014 ** Code an OP_Halt due to UNIQUE or PRIMARY KEY constraint violation.
4015 */
4016 void sqlite3UniqueConstraint(
4017   Parse *pParse,    /* Parsing context */
4018   int onError,      /* Constraint type */
4019   Index *pIdx       /* The index that triggers the constraint */
4020 ){
4021   char *zErr;
4022   int j;
4023   StrAccum errMsg;
4024   Table *pTab = pIdx->pTable;
4025 
4026   sqlite3StrAccumInit(&errMsg, 0, 0, 200);
4027   errMsg.db = pParse->db;
4028   for(j=0; j<pIdx->nKeyCol; j++){
4029     char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
4030     if( j ) sqlite3StrAccumAppend(&errMsg, ", ", 2);
4031     sqlite3StrAccumAppendAll(&errMsg, pTab->zName);
4032     sqlite3StrAccumAppend(&errMsg, ".", 1);
4033     sqlite3StrAccumAppendAll(&errMsg, zCol);
4034   }
4035   zErr = sqlite3StrAccumFinish(&errMsg);
4036   sqlite3HaltConstraint(pParse,
4037     IsPrimaryKeyIndex(pIdx) ? SQLITE_CONSTRAINT_PRIMARYKEY
4038                             : SQLITE_CONSTRAINT_UNIQUE,
4039     onError, zErr, P4_DYNAMIC, P5_ConstraintUnique);
4040 }
4041 
4042 
4043 /*
4044 ** Code an OP_Halt due to non-unique rowid.
4045 */
4046 void sqlite3RowidConstraint(
4047   Parse *pParse,    /* Parsing context */
4048   int onError,      /* Conflict resolution algorithm */
4049   Table *pTab       /* The table with the non-unique rowid */
4050 ){
4051   char *zMsg;
4052   int rc;
4053   if( pTab->iPKey>=0 ){
4054     zMsg = sqlite3MPrintf(pParse->db, "%s.%s", pTab->zName,
4055                           pTab->aCol[pTab->iPKey].zName);
4056     rc = SQLITE_CONSTRAINT_PRIMARYKEY;
4057   }else{
4058     zMsg = sqlite3MPrintf(pParse->db, "%s.rowid", pTab->zName);
4059     rc = SQLITE_CONSTRAINT_ROWID;
4060   }
4061   sqlite3HaltConstraint(pParse, rc, onError, zMsg, P4_DYNAMIC,
4062                         P5_ConstraintUnique);
4063 }
4064 
4065 /*
4066 ** Check to see if pIndex uses the collating sequence pColl.  Return
4067 ** true if it does and false if it does not.
4068 */
4069 #ifndef SQLITE_OMIT_REINDEX
4070 static int collationMatch(const char *zColl, Index *pIndex){
4071   int i;
4072   assert( zColl!=0 );
4073   for(i=0; i<pIndex->nColumn; i++){
4074     const char *z = pIndex->azColl[i];
4075     assert( z!=0 || pIndex->aiColumn[i]<0 );
4076     if( pIndex->aiColumn[i]>=0 && 0==sqlite3StrICmp(z, zColl) ){
4077       return 1;
4078     }
4079   }
4080   return 0;
4081 }
4082 #endif
4083 
4084 /*
4085 ** Recompute all indices of pTab that use the collating sequence pColl.
4086 ** If pColl==0 then recompute all indices of pTab.
4087 */
4088 #ifndef SQLITE_OMIT_REINDEX
4089 static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
4090   Index *pIndex;              /* An index associated with pTab */
4091 
4092   for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
4093     if( zColl==0 || collationMatch(zColl, pIndex) ){
4094       int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
4095       sqlite3BeginWriteOperation(pParse, 0, iDb);
4096       sqlite3RefillIndex(pParse, pIndex, -1);
4097     }
4098   }
4099 }
4100 #endif
4101 
4102 /*
4103 ** Recompute all indices of all tables in all databases where the
4104 ** indices use the collating sequence pColl.  If pColl==0 then recompute
4105 ** all indices everywhere.
4106 */
4107 #ifndef SQLITE_OMIT_REINDEX
4108 static void reindexDatabases(Parse *pParse, char const *zColl){
4109   Db *pDb;                    /* A single database */
4110   int iDb;                    /* The database index number */
4111   sqlite3 *db = pParse->db;   /* The database connection */
4112   HashElem *k;                /* For looping over tables in pDb */
4113   Table *pTab;                /* A table in the database */
4114 
4115   assert( sqlite3BtreeHoldsAllMutexes(db) );  /* Needed for schema access */
4116   for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
4117     assert( pDb!=0 );
4118     for(k=sqliteHashFirst(&pDb->pSchema->tblHash);  k; k=sqliteHashNext(k)){
4119       pTab = (Table*)sqliteHashData(k);
4120       reindexTable(pParse, pTab, zColl);
4121     }
4122   }
4123 }
4124 #endif
4125 
4126 /*
4127 ** Generate code for the REINDEX command.
4128 **
4129 **        REINDEX                            -- 1
4130 **        REINDEX  <collation>               -- 2
4131 **        REINDEX  ?<database>.?<tablename>  -- 3
4132 **        REINDEX  ?<database>.?<indexname>  -- 4
4133 **
4134 ** Form 1 causes all indices in all attached databases to be rebuilt.
4135 ** Form 2 rebuilds all indices in all databases that use the named
4136 ** collating function.  Forms 3 and 4 rebuild the named index or all
4137 ** indices associated with the named table.
4138 */
4139 #ifndef SQLITE_OMIT_REINDEX
4140 void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
4141   CollSeq *pColl;             /* Collating sequence to be reindexed, or NULL */
4142   char *z;                    /* Name of a table or index */
4143   const char *zDb;            /* Name of the database */
4144   Table *pTab;                /* A table in the database */
4145   Index *pIndex;              /* An index associated with pTab */
4146   int iDb;                    /* The database index number */
4147   sqlite3 *db = pParse->db;   /* The database connection */
4148   Token *pObjName;            /* Name of the table or index to be reindexed */
4149 
4150   /* Read the database schema. If an error occurs, leave an error message
4151   ** and code in pParse and return NULL. */
4152   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
4153     return;
4154   }
4155 
4156   if( pName1==0 ){
4157     reindexDatabases(pParse, 0);
4158     return;
4159   }else if( NEVER(pName2==0) || pName2->z==0 ){
4160     char *zColl;
4161     assert( pName1->z );
4162     zColl = sqlite3NameFromToken(pParse->db, pName1);
4163     if( !zColl ) return;
4164     pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
4165     if( pColl ){
4166       reindexDatabases(pParse, zColl);
4167       sqlite3DbFree(db, zColl);
4168       return;
4169     }
4170     sqlite3DbFree(db, zColl);
4171   }
4172   iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
4173   if( iDb<0 ) return;
4174   z = sqlite3NameFromToken(db, pObjName);
4175   if( z==0 ) return;
4176   zDb = db->aDb[iDb].zName;
4177   pTab = sqlite3FindTable(db, z, zDb);
4178   if( pTab ){
4179     reindexTable(pParse, pTab, 0);
4180     sqlite3DbFree(db, z);
4181     return;
4182   }
4183   pIndex = sqlite3FindIndex(db, z, zDb);
4184   sqlite3DbFree(db, z);
4185   if( pIndex ){
4186     sqlite3BeginWriteOperation(pParse, 0, iDb);
4187     sqlite3RefillIndex(pParse, pIndex, -1);
4188     return;
4189   }
4190   sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
4191 }
4192 #endif
4193 
4194 /*
4195 ** Return a KeyInfo structure that is appropriate for the given Index.
4196 **
4197 ** The KeyInfo structure for an index is cached in the Index object.
4198 ** So there might be multiple references to the returned pointer.  The
4199 ** caller should not try to modify the KeyInfo object.
4200 **
4201 ** The caller should invoke sqlite3KeyInfoUnref() on the returned object
4202 ** when it has finished using it.
4203 */
4204 KeyInfo *sqlite3KeyInfoOfIndex(Parse *pParse, Index *pIdx){
4205   int i;
4206   int nCol = pIdx->nColumn;
4207   int nKey = pIdx->nKeyCol;
4208   KeyInfo *pKey;
4209   if( pParse->nErr ) return 0;
4210   if( pIdx->uniqNotNull ){
4211     pKey = sqlite3KeyInfoAlloc(pParse->db, nKey, nCol-nKey);
4212   }else{
4213     pKey = sqlite3KeyInfoAlloc(pParse->db, nCol, 0);
4214   }
4215   if( pKey ){
4216     assert( sqlite3KeyInfoIsWriteable(pKey) );
4217     for(i=0; i<nCol; i++){
4218       char *zColl = pIdx->azColl[i];
4219       assert( zColl!=0 );
4220       pKey->aColl[i] = strcmp(zColl,"BINARY")==0 ? 0 :
4221                         sqlite3LocateCollSeq(pParse, zColl);
4222       pKey->aSortOrder[i] = pIdx->aSortOrder[i];
4223     }
4224     if( pParse->nErr ){
4225       sqlite3KeyInfoUnref(pKey);
4226       pKey = 0;
4227     }
4228   }
4229   return pKey;
4230 }
4231 
4232 #ifndef SQLITE_OMIT_CTE
4233 /*
4234 ** This routine is invoked once per CTE by the parser while parsing a
4235 ** WITH clause.
4236 */
4237 With *sqlite3WithAdd(
4238   Parse *pParse,          /* Parsing context */
4239   With *pWith,            /* Existing WITH clause, or NULL */
4240   Token *pName,           /* Name of the common-table */
4241   ExprList *pArglist,     /* Optional column name list for the table */
4242   Select *pQuery          /* Query used to initialize the table */
4243 ){
4244   sqlite3 *db = pParse->db;
4245   With *pNew;
4246   char *zName;
4247 
4248   /* Check that the CTE name is unique within this WITH clause. If
4249   ** not, store an error in the Parse structure. */
4250   zName = sqlite3NameFromToken(pParse->db, pName);
4251   if( zName && pWith ){
4252     int i;
4253     for(i=0; i<pWith->nCte; i++){
4254       if( sqlite3StrICmp(zName, pWith->a[i].zName)==0 ){
4255         sqlite3ErrorMsg(pParse, "duplicate WITH table name: %s", zName);
4256       }
4257     }
4258   }
4259 
4260   if( pWith ){
4261     int nByte = sizeof(*pWith) + (sizeof(pWith->a[1]) * pWith->nCte);
4262     pNew = sqlite3DbRealloc(db, pWith, nByte);
4263   }else{
4264     pNew = sqlite3DbMallocZero(db, sizeof(*pWith));
4265   }
4266   assert( zName!=0 || pNew==0 );
4267   assert( db->mallocFailed==0 || pNew==0 );
4268 
4269   if( pNew==0 ){
4270     sqlite3ExprListDelete(db, pArglist);
4271     sqlite3SelectDelete(db, pQuery);
4272     sqlite3DbFree(db, zName);
4273     pNew = pWith;
4274   }else{
4275     pNew->a[pNew->nCte].pSelect = pQuery;
4276     pNew->a[pNew->nCte].pCols = pArglist;
4277     pNew->a[pNew->nCte].zName = zName;
4278     pNew->a[pNew->nCte].zErr = 0;
4279     pNew->nCte++;
4280   }
4281 
4282   return pNew;
4283 }
4284 
4285 /*
4286 ** Free the contents of the With object passed as the second argument.
4287 */
4288 void sqlite3WithDelete(sqlite3 *db, With *pWith){
4289   if( pWith ){
4290     int i;
4291     for(i=0; i<pWith->nCte; i++){
4292       struct Cte *pCte = &pWith->a[i];
4293       sqlite3ExprListDelete(db, pCte->pCols);
4294       sqlite3SelectDelete(db, pCte->pSelect);
4295       sqlite3DbFree(db, pCte->zName);
4296     }
4297     sqlite3DbFree(db, pWith);
4298   }
4299 }
4300 #endif /* !defined(SQLITE_OMIT_CTE) */
4301