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