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