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