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