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