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