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