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