xref: /sqlite-3.40.0/src/build.c (revision 60176fa9)
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 ){
1652     sqlite3SelectDelete(db, pSelect);
1653     return;
1654   }
1655   assert( pParse->nErr==0 ); /* If sqlite3StartTable return non-NULL then
1656                              ** there could not have been an error */
1657   sqlite3TwoPartName(pParse, pName1, pName2, &pName);
1658   iDb = sqlite3SchemaToIndex(db, p->pSchema);
1659   if( sqlite3FixInit(&sFix, pParse, iDb, "view", pName)
1660     && sqlite3FixSelect(&sFix, pSelect)
1661   ){
1662     sqlite3SelectDelete(db, pSelect);
1663     return;
1664   }
1665 
1666   /* Make a copy of the entire SELECT statement that defines the view.
1667   ** This will force all the Expr.token.z values to be dynamically
1668   ** allocated rather than point to the input string - which means that
1669   ** they will persist after the current sqlite3_exec() call returns.
1670   */
1671   p->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
1672   sqlite3SelectDelete(db, pSelect);
1673   if( db->mallocFailed ){
1674     return;
1675   }
1676   if( !db->init.busy ){
1677     sqlite3ViewGetColumnNames(pParse, p);
1678   }
1679 
1680   /* Locate the end of the CREATE VIEW statement.  Make sEnd point to
1681   ** the end.
1682   */
1683   sEnd = pParse->sLastToken;
1684   if( ALWAYS(sEnd.z[0]!=0) && sEnd.z[0]!=';' ){
1685     sEnd.z += sEnd.n;
1686   }
1687   sEnd.n = 0;
1688   n = (int)(sEnd.z - pBegin->z);
1689   z = pBegin->z;
1690   while( ALWAYS(n>0) && sqlite3Isspace(z[n-1]) ){ n--; }
1691   sEnd.z = &z[n-1];
1692   sEnd.n = 1;
1693 
1694   /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
1695   sqlite3EndTable(pParse, 0, &sEnd, 0);
1696   return;
1697 }
1698 #endif /* SQLITE_OMIT_VIEW */
1699 
1700 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
1701 /*
1702 ** The Table structure pTable is really a VIEW.  Fill in the names of
1703 ** the columns of the view in the pTable structure.  Return the number
1704 ** of errors.  If an error is seen leave an error message in pParse->zErrMsg.
1705 */
1706 int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
1707   Table *pSelTab;   /* A fake table from which we get the result set */
1708   Select *pSel;     /* Copy of the SELECT that implements the view */
1709   int nErr = 0;     /* Number of errors encountered */
1710   int n;            /* Temporarily holds the number of cursors assigned */
1711   sqlite3 *db = pParse->db;  /* Database connection for malloc errors */
1712   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
1713 
1714   assert( pTable );
1715 
1716 #ifndef SQLITE_OMIT_VIRTUALTABLE
1717   if( sqlite3VtabCallConnect(pParse, pTable) ){
1718     return SQLITE_ERROR;
1719   }
1720   if( IsVirtual(pTable) ) return 0;
1721 #endif
1722 
1723 #ifndef SQLITE_OMIT_VIEW
1724   /* A positive nCol means the columns names for this view are
1725   ** already known.
1726   */
1727   if( pTable->nCol>0 ) return 0;
1728 
1729   /* A negative nCol is a special marker meaning that we are currently
1730   ** trying to compute the column names.  If we enter this routine with
1731   ** a negative nCol, it means two or more views form a loop, like this:
1732   **
1733   **     CREATE VIEW one AS SELECT * FROM two;
1734   **     CREATE VIEW two AS SELECT * FROM one;
1735   **
1736   ** Actually, the error above is now caught prior to reaching this point.
1737   ** But the following test is still important as it does come up
1738   ** in the following:
1739   **
1740   **     CREATE TABLE main.ex1(a);
1741   **     CREATE TEMP VIEW ex1 AS SELECT a FROM ex1;
1742   **     SELECT * FROM temp.ex1;
1743   */
1744   if( pTable->nCol<0 ){
1745     sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
1746     return 1;
1747   }
1748   assert( pTable->nCol>=0 );
1749 
1750   /* If we get this far, it means we need to compute the table names.
1751   ** Note that the call to sqlite3ResultSetOfSelect() will expand any
1752   ** "*" elements in the results set of the view and will assign cursors
1753   ** to the elements of the FROM clause.  But we do not want these changes
1754   ** to be permanent.  So the computation is done on a copy of the SELECT
1755   ** statement that defines the view.
1756   */
1757   assert( pTable->pSelect );
1758   pSel = sqlite3SelectDup(db, pTable->pSelect, 0);
1759   if( pSel ){
1760     u8 enableLookaside = db->lookaside.bEnabled;
1761     n = pParse->nTab;
1762     sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
1763     pTable->nCol = -1;
1764     db->lookaside.bEnabled = 0;
1765 #ifndef SQLITE_OMIT_AUTHORIZATION
1766     xAuth = db->xAuth;
1767     db->xAuth = 0;
1768     pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
1769     db->xAuth = xAuth;
1770 #else
1771     pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
1772 #endif
1773     db->lookaside.bEnabled = enableLookaside;
1774     pParse->nTab = n;
1775     if( pSelTab ){
1776       assert( pTable->aCol==0 );
1777       pTable->nCol = pSelTab->nCol;
1778       pTable->aCol = pSelTab->aCol;
1779       pSelTab->nCol = 0;
1780       pSelTab->aCol = 0;
1781       sqlite3DeleteTable(db, pSelTab);
1782       pTable->pSchema->flags |= DB_UnresetViews;
1783     }else{
1784       pTable->nCol = 0;
1785       nErr++;
1786     }
1787     sqlite3SelectDelete(db, pSel);
1788   } else {
1789     nErr++;
1790   }
1791 #endif /* SQLITE_OMIT_VIEW */
1792   return nErr;
1793 }
1794 #endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
1795 
1796 #ifndef SQLITE_OMIT_VIEW
1797 /*
1798 ** Clear the column names from every VIEW in database idx.
1799 */
1800 static void sqliteViewResetAll(sqlite3 *db, int idx){
1801   HashElem *i;
1802   if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
1803   for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
1804     Table *pTab = sqliteHashData(i);
1805     if( pTab->pSelect ){
1806       sqliteDeleteColumnNames(db, pTab);
1807       pTab->aCol = 0;
1808       pTab->nCol = 0;
1809     }
1810   }
1811   DbClearProperty(db, idx, DB_UnresetViews);
1812 }
1813 #else
1814 # define sqliteViewResetAll(A,B)
1815 #endif /* SQLITE_OMIT_VIEW */
1816 
1817 /*
1818 ** This function is called by the VDBE to adjust the internal schema
1819 ** used by SQLite when the btree layer moves a table root page. The
1820 ** root-page of a table or index in database iDb has changed from iFrom
1821 ** to iTo.
1822 **
1823 ** Ticket #1728:  The symbol table might still contain information
1824 ** on tables and/or indices that are the process of being deleted.
1825 ** If you are unlucky, one of those deleted indices or tables might
1826 ** have the same rootpage number as the real table or index that is
1827 ** being moved.  So we cannot stop searching after the first match
1828 ** because the first match might be for one of the deleted indices
1829 ** or tables and not the table/index that is actually being moved.
1830 ** We must continue looping until all tables and indices with
1831 ** rootpage==iFrom have been converted to have a rootpage of iTo
1832 ** in order to be certain that we got the right one.
1833 */
1834 #ifndef SQLITE_OMIT_AUTOVACUUM
1835 void sqlite3RootPageMoved(Db *pDb, int iFrom, int iTo){
1836   HashElem *pElem;
1837   Hash *pHash;
1838 
1839   pHash = &pDb->pSchema->tblHash;
1840   for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
1841     Table *pTab = sqliteHashData(pElem);
1842     if( pTab->tnum==iFrom ){
1843       pTab->tnum = iTo;
1844     }
1845   }
1846   pHash = &pDb->pSchema->idxHash;
1847   for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
1848     Index *pIdx = sqliteHashData(pElem);
1849     if( pIdx->tnum==iFrom ){
1850       pIdx->tnum = iTo;
1851     }
1852   }
1853 }
1854 #endif
1855 
1856 /*
1857 ** Write code to erase the table with root-page iTable from database iDb.
1858 ** Also write code to modify the sqlite_master table and internal schema
1859 ** if a root-page of another table is moved by the btree-layer whilst
1860 ** erasing iTable (this can happen with an auto-vacuum database).
1861 */
1862 static void destroyRootPage(Parse *pParse, int iTable, int iDb){
1863   Vdbe *v = sqlite3GetVdbe(pParse);
1864   int r1 = sqlite3GetTempReg(pParse);
1865   sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
1866   sqlite3MayAbort(pParse);
1867 #ifndef SQLITE_OMIT_AUTOVACUUM
1868   /* OP_Destroy stores an in integer r1. If this integer
1869   ** is non-zero, then it is the root page number of a table moved to
1870   ** location iTable. The following code modifies the sqlite_master table to
1871   ** reflect this.
1872   **
1873   ** The "#NNN" in the SQL is a special constant that means whatever value
1874   ** is in register NNN.  See grammar rules associated with the TK_REGISTER
1875   ** token for additional information.
1876   */
1877   sqlite3NestedParse(pParse,
1878      "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d",
1879      pParse->db->aDb[iDb].zName, SCHEMA_TABLE(iDb), iTable, r1, r1);
1880 #endif
1881   sqlite3ReleaseTempReg(pParse, r1);
1882 }
1883 
1884 /*
1885 ** Write VDBE code to erase table pTab and all associated indices on disk.
1886 ** Code to update the sqlite_master tables and internal schema definitions
1887 ** in case a root-page belonging to another table is moved by the btree layer
1888 ** is also added (this can happen with an auto-vacuum database).
1889 */
1890 static void destroyTable(Parse *pParse, Table *pTab){
1891 #ifdef SQLITE_OMIT_AUTOVACUUM
1892   Index *pIdx;
1893   int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
1894   destroyRootPage(pParse, pTab->tnum, iDb);
1895   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
1896     destroyRootPage(pParse, pIdx->tnum, iDb);
1897   }
1898 #else
1899   /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
1900   ** is not defined), then it is important to call OP_Destroy on the
1901   ** table and index root-pages in order, starting with the numerically
1902   ** largest root-page number. This guarantees that none of the root-pages
1903   ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
1904   ** following were coded:
1905   **
1906   ** OP_Destroy 4 0
1907   ** ...
1908   ** OP_Destroy 5 0
1909   **
1910   ** and root page 5 happened to be the largest root-page number in the
1911   ** database, then root page 5 would be moved to page 4 by the
1912   ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
1913   ** a free-list page.
1914   */
1915   int iTab = pTab->tnum;
1916   int iDestroyed = 0;
1917 
1918   while( 1 ){
1919     Index *pIdx;
1920     int iLargest = 0;
1921 
1922     if( iDestroyed==0 || iTab<iDestroyed ){
1923       iLargest = iTab;
1924     }
1925     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
1926       int iIdx = pIdx->tnum;
1927       assert( pIdx->pSchema==pTab->pSchema );
1928       if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
1929         iLargest = iIdx;
1930       }
1931     }
1932     if( iLargest==0 ){
1933       return;
1934     }else{
1935       int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
1936       destroyRootPage(pParse, iLargest, iDb);
1937       iDestroyed = iLargest;
1938     }
1939   }
1940 #endif
1941 }
1942 
1943 /*
1944 ** This routine is called to do the work of a DROP TABLE statement.
1945 ** pName is the name of the table to be dropped.
1946 */
1947 void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
1948   Table *pTab;
1949   Vdbe *v;
1950   sqlite3 *db = pParse->db;
1951   int iDb;
1952 
1953   if( db->mallocFailed ){
1954     goto exit_drop_table;
1955   }
1956   assert( pParse->nErr==0 );
1957   assert( pName->nSrc==1 );
1958   if( noErr ) db->suppressErr++;
1959   pTab = sqlite3LocateTable(pParse, isView,
1960                             pName->a[0].zName, pName->a[0].zDatabase);
1961   if( noErr ) db->suppressErr--;
1962 
1963   if( pTab==0 ){
1964     goto exit_drop_table;
1965   }
1966   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
1967   assert( iDb>=0 && iDb<db->nDb );
1968 
1969   /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
1970   ** it is initialized.
1971   */
1972   if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){
1973     goto exit_drop_table;
1974   }
1975 #ifndef SQLITE_OMIT_AUTHORIZATION
1976   {
1977     int code;
1978     const char *zTab = SCHEMA_TABLE(iDb);
1979     const char *zDb = db->aDb[iDb].zName;
1980     const char *zArg2 = 0;
1981     if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
1982       goto exit_drop_table;
1983     }
1984     if( isView ){
1985       if( !OMIT_TEMPDB && iDb==1 ){
1986         code = SQLITE_DROP_TEMP_VIEW;
1987       }else{
1988         code = SQLITE_DROP_VIEW;
1989       }
1990 #ifndef SQLITE_OMIT_VIRTUALTABLE
1991     }else if( IsVirtual(pTab) ){
1992       code = SQLITE_DROP_VTABLE;
1993       zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName;
1994 #endif
1995     }else{
1996       if( !OMIT_TEMPDB && iDb==1 ){
1997         code = SQLITE_DROP_TEMP_TABLE;
1998       }else{
1999         code = SQLITE_DROP_TABLE;
2000       }
2001     }
2002     if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
2003       goto exit_drop_table;
2004     }
2005     if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
2006       goto exit_drop_table;
2007     }
2008   }
2009 #endif
2010   if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
2011     sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
2012     goto exit_drop_table;
2013   }
2014 
2015 #ifndef SQLITE_OMIT_VIEW
2016   /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
2017   ** on a table.
2018   */
2019   if( isView && pTab->pSelect==0 ){
2020     sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
2021     goto exit_drop_table;
2022   }
2023   if( !isView && pTab->pSelect ){
2024     sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
2025     goto exit_drop_table;
2026   }
2027 #endif
2028 
2029   /* Generate code to remove the table from the master table
2030   ** on disk.
2031   */
2032   v = sqlite3GetVdbe(pParse);
2033   if( v ){
2034     Trigger *pTrigger;
2035     Db *pDb = &db->aDb[iDb];
2036     sqlite3BeginWriteOperation(pParse, 1, iDb);
2037 
2038 #ifndef SQLITE_OMIT_VIRTUALTABLE
2039     if( IsVirtual(pTab) ){
2040       sqlite3VdbeAddOp0(v, OP_VBegin);
2041     }
2042 #endif
2043     sqlite3FkDropTable(pParse, pName, pTab);
2044 
2045     /* Drop all triggers associated with the table being dropped. Code
2046     ** is generated to remove entries from sqlite_master and/or
2047     ** sqlite_temp_master if required.
2048     */
2049     pTrigger = sqlite3TriggerList(pParse, pTab);
2050     while( pTrigger ){
2051       assert( pTrigger->pSchema==pTab->pSchema ||
2052           pTrigger->pSchema==db->aDb[1].pSchema );
2053       sqlite3DropTriggerPtr(pParse, pTrigger);
2054       pTrigger = pTrigger->pNext;
2055     }
2056 
2057 #ifndef SQLITE_OMIT_AUTOINCREMENT
2058     /* Remove any entries of the sqlite_sequence table associated with
2059     ** the table being dropped. This is done before the table is dropped
2060     ** at the btree level, in case the sqlite_sequence table needs to
2061     ** move as a result of the drop (can happen in auto-vacuum mode).
2062     */
2063     if( pTab->tabFlags & TF_Autoincrement ){
2064       sqlite3NestedParse(pParse,
2065         "DELETE FROM %s.sqlite_sequence WHERE name=%Q",
2066         pDb->zName, pTab->zName
2067       );
2068     }
2069 #endif
2070 
2071     /* Drop all SQLITE_MASTER table and index entries that refer to the
2072     ** table. The program name loops through the master table and deletes
2073     ** every row that refers to a table of the same name as the one being
2074     ** dropped. Triggers are handled seperately because a trigger can be
2075     ** created in the temp database that refers to a table in another
2076     ** database.
2077     */
2078     sqlite3NestedParse(pParse,
2079         "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
2080         pDb->zName, SCHEMA_TABLE(iDb), pTab->zName);
2081 
2082     /* Drop any statistics from the sqlite_stat1 table, if it exists */
2083     if( sqlite3FindTable(db, "sqlite_stat1", db->aDb[iDb].zName) ){
2084       sqlite3NestedParse(pParse,
2085         "DELETE FROM %Q.sqlite_stat1 WHERE tbl=%Q", pDb->zName, pTab->zName
2086       );
2087     }
2088 
2089     if( !isView && !IsVirtual(pTab) ){
2090       destroyTable(pParse, pTab);
2091     }
2092 
2093     /* Remove the table entry from SQLite's internal schema and modify
2094     ** the schema cookie.
2095     */
2096     if( IsVirtual(pTab) ){
2097       sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
2098     }
2099     sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
2100     sqlite3ChangeCookie(pParse, iDb);
2101   }
2102   sqliteViewResetAll(db, iDb);
2103 
2104 exit_drop_table:
2105   sqlite3SrcListDelete(db, pName);
2106 }
2107 
2108 /*
2109 ** This routine is called to create a new foreign key on the table
2110 ** currently under construction.  pFromCol determines which columns
2111 ** in the current table point to the foreign key.  If pFromCol==0 then
2112 ** connect the key to the last column inserted.  pTo is the name of
2113 ** the table referred to.  pToCol is a list of tables in the other
2114 ** pTo table that the foreign key points to.  flags contains all
2115 ** information about the conflict resolution algorithms specified
2116 ** in the ON DELETE, ON UPDATE and ON INSERT clauses.
2117 **
2118 ** An FKey structure is created and added to the table currently
2119 ** under construction in the pParse->pNewTable field.
2120 **
2121 ** The foreign key is set for IMMEDIATE processing.  A subsequent call
2122 ** to sqlite3DeferForeignKey() might change this to DEFERRED.
2123 */
2124 void sqlite3CreateForeignKey(
2125   Parse *pParse,       /* Parsing context */
2126   ExprList *pFromCol,  /* Columns in this table that point to other table */
2127   Token *pTo,          /* Name of the other table */
2128   ExprList *pToCol,    /* Columns in the other table */
2129   int flags            /* Conflict resolution algorithms. */
2130 ){
2131   sqlite3 *db = pParse->db;
2132 #ifndef SQLITE_OMIT_FOREIGN_KEY
2133   FKey *pFKey = 0;
2134   FKey *pNextTo;
2135   Table *p = pParse->pNewTable;
2136   int nByte;
2137   int i;
2138   int nCol;
2139   char *z;
2140 
2141   assert( pTo!=0 );
2142   if( p==0 || IN_DECLARE_VTAB ) goto fk_end;
2143   if( pFromCol==0 ){
2144     int iCol = p->nCol-1;
2145     if( NEVER(iCol<0) ) goto fk_end;
2146     if( pToCol && pToCol->nExpr!=1 ){
2147       sqlite3ErrorMsg(pParse, "foreign key on %s"
2148          " should reference only one column of table %T",
2149          p->aCol[iCol].zName, pTo);
2150       goto fk_end;
2151     }
2152     nCol = 1;
2153   }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
2154     sqlite3ErrorMsg(pParse,
2155         "number of columns in foreign key does not match the number of "
2156         "columns in the referenced table");
2157     goto fk_end;
2158   }else{
2159     nCol = pFromCol->nExpr;
2160   }
2161   nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1;
2162   if( pToCol ){
2163     for(i=0; i<pToCol->nExpr; i++){
2164       nByte += sqlite3Strlen30(pToCol->a[i].zName) + 1;
2165     }
2166   }
2167   pFKey = sqlite3DbMallocZero(db, nByte );
2168   if( pFKey==0 ){
2169     goto fk_end;
2170   }
2171   pFKey->pFrom = p;
2172   pFKey->pNextFrom = p->pFKey;
2173   z = (char*)&pFKey->aCol[nCol];
2174   pFKey->zTo = z;
2175   memcpy(z, pTo->z, pTo->n);
2176   z[pTo->n] = 0;
2177   sqlite3Dequote(z);
2178   z += pTo->n+1;
2179   pFKey->nCol = nCol;
2180   if( pFromCol==0 ){
2181     pFKey->aCol[0].iFrom = p->nCol-1;
2182   }else{
2183     for(i=0; i<nCol; i++){
2184       int j;
2185       for(j=0; j<p->nCol; j++){
2186         if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
2187           pFKey->aCol[i].iFrom = j;
2188           break;
2189         }
2190       }
2191       if( j>=p->nCol ){
2192         sqlite3ErrorMsg(pParse,
2193           "unknown column \"%s\" in foreign key definition",
2194           pFromCol->a[i].zName);
2195         goto fk_end;
2196       }
2197     }
2198   }
2199   if( pToCol ){
2200     for(i=0; i<nCol; i++){
2201       int n = sqlite3Strlen30(pToCol->a[i].zName);
2202       pFKey->aCol[i].zCol = z;
2203       memcpy(z, pToCol->a[i].zName, n);
2204       z[n] = 0;
2205       z += n+1;
2206     }
2207   }
2208   pFKey->isDeferred = 0;
2209   pFKey->aAction[0] = (u8)(flags & 0xff);            /* ON DELETE action */
2210   pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff);    /* ON UPDATE action */
2211 
2212   pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash,
2213       pFKey->zTo, sqlite3Strlen30(pFKey->zTo), (void *)pFKey
2214   );
2215   if( pNextTo==pFKey ){
2216     db->mallocFailed = 1;
2217     goto fk_end;
2218   }
2219   if( pNextTo ){
2220     assert( pNextTo->pPrevTo==0 );
2221     pFKey->pNextTo = pNextTo;
2222     pNextTo->pPrevTo = pFKey;
2223   }
2224 
2225   /* Link the foreign key to the table as the last step.
2226   */
2227   p->pFKey = pFKey;
2228   pFKey = 0;
2229 
2230 fk_end:
2231   sqlite3DbFree(db, pFKey);
2232 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
2233   sqlite3ExprListDelete(db, pFromCol);
2234   sqlite3ExprListDelete(db, pToCol);
2235 }
2236 
2237 /*
2238 ** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
2239 ** clause is seen as part of a foreign key definition.  The isDeferred
2240 ** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
2241 ** The behavior of the most recently created foreign key is adjusted
2242 ** accordingly.
2243 */
2244 void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
2245 #ifndef SQLITE_OMIT_FOREIGN_KEY
2246   Table *pTab;
2247   FKey *pFKey;
2248   if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
2249   assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */
2250   pFKey->isDeferred = (u8)isDeferred;
2251 #endif
2252 }
2253 
2254 /*
2255 ** Generate code that will erase and refill index *pIdx.  This is
2256 ** used to initialize a newly created index or to recompute the
2257 ** content of an index in response to a REINDEX command.
2258 **
2259 ** if memRootPage is not negative, it means that the index is newly
2260 ** created.  The register specified by memRootPage contains the
2261 ** root page number of the index.  If memRootPage is negative, then
2262 ** the index already exists and must be cleared before being refilled and
2263 ** the root page number of the index is taken from pIndex->tnum.
2264 */
2265 static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
2266   Table *pTab = pIndex->pTable;  /* The table that is indexed */
2267   int iTab = pParse->nTab++;     /* Btree cursor used for pTab */
2268   int iIdx = pParse->nTab++;     /* Btree cursor used for pIndex */
2269   int addr1;                     /* Address of top of loop */
2270   int tnum;                      /* Root page of index */
2271   Vdbe *v;                       /* Generate code into this virtual machine */
2272   KeyInfo *pKey;                 /* KeyInfo for index */
2273   int regIdxKey;                 /* Registers containing the index key */
2274   int regRecord;                 /* Register holding assemblied index record */
2275   sqlite3 *db = pParse->db;      /* The database connection */
2276   int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
2277 
2278 #ifndef SQLITE_OMIT_AUTHORIZATION
2279   if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
2280       db->aDb[iDb].zName ) ){
2281     return;
2282   }
2283 #endif
2284 
2285   /* Require a write-lock on the table to perform this operation */
2286   sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
2287 
2288   v = sqlite3GetVdbe(pParse);
2289   if( v==0 ) return;
2290   if( memRootPage>=0 ){
2291     tnum = memRootPage;
2292   }else{
2293     tnum = pIndex->tnum;
2294     sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
2295   }
2296   pKey = sqlite3IndexKeyinfo(pParse, pIndex);
2297   sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb,
2298                     (char *)pKey, P4_KEYINFO_HANDOFF);
2299   if( memRootPage>=0 ){
2300     sqlite3VdbeChangeP5(v, 1);
2301   }
2302   sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
2303   addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0);
2304   regRecord = sqlite3GetTempReg(pParse);
2305   regIdxKey = sqlite3GenerateIndexKey(pParse, pIndex, iTab, regRecord, 1);
2306   if( pIndex->onError!=OE_None ){
2307     const int regRowid = regIdxKey + pIndex->nColumn;
2308     const int j2 = sqlite3VdbeCurrentAddr(v) + 2;
2309     void * const pRegKey = SQLITE_INT_TO_PTR(regIdxKey);
2310 
2311     /* The registers accessed by the OP_IsUnique opcode were allocated
2312     ** using sqlite3GetTempRange() inside of the sqlite3GenerateIndexKey()
2313     ** call above. Just before that function was freed they were released
2314     ** (made available to the compiler for reuse) using
2315     ** sqlite3ReleaseTempRange(). So in some ways having the OP_IsUnique
2316     ** opcode use the values stored within seems dangerous. However, since
2317     ** we can be sure that no other temp registers have been allocated
2318     ** since sqlite3ReleaseTempRange() was called, it is safe to do so.
2319     */
2320     sqlite3VdbeAddOp4(v, OP_IsUnique, iIdx, j2, regRowid, pRegKey, P4_INT32);
2321     sqlite3HaltConstraint(
2322         pParse, OE_Abort, "indexed columns are not unique", P4_STATIC);
2323   }
2324   sqlite3VdbeAddOp2(v, OP_IdxInsert, iIdx, regRecord);
2325   sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
2326   sqlite3ReleaseTempReg(pParse, regRecord);
2327   sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1);
2328   sqlite3VdbeJumpHere(v, addr1);
2329   sqlite3VdbeAddOp1(v, OP_Close, iTab);
2330   sqlite3VdbeAddOp1(v, OP_Close, iIdx);
2331 }
2332 
2333 /*
2334 ** Create a new index for an SQL table.  pName1.pName2 is the name of the index
2335 ** and pTblList is the name of the table that is to be indexed.  Both will
2336 ** be NULL for a primary key or an index that is created to satisfy a
2337 ** UNIQUE constraint.  If pTable and pIndex are NULL, use pParse->pNewTable
2338 ** as the table to be indexed.  pParse->pNewTable is a table that is
2339 ** currently being constructed by a CREATE TABLE statement.
2340 **
2341 ** pList is a list of columns to be indexed.  pList will be NULL if this
2342 ** is a primary key or unique-constraint on the most recent column added
2343 ** to the table currently under construction.
2344 **
2345 ** If the index is created successfully, return a pointer to the new Index
2346 ** structure. This is used by sqlite3AddPrimaryKey() to mark the index
2347 ** as the tables primary key (Index.autoIndex==2).
2348 */
2349 Index *sqlite3CreateIndex(
2350   Parse *pParse,     /* All information about this parse */
2351   Token *pName1,     /* First part of index name. May be NULL */
2352   Token *pName2,     /* Second part of index name. May be NULL */
2353   SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
2354   ExprList *pList,   /* A list of columns to be indexed */
2355   int onError,       /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
2356   Token *pStart,     /* The CREATE token that begins this statement */
2357   Token *pEnd,       /* The ")" that closes the CREATE INDEX statement */
2358   int sortOrder,     /* Sort order of primary key when pList==NULL */
2359   int ifNotExist     /* Omit error if index already exists */
2360 ){
2361   Index *pRet = 0;     /* Pointer to return */
2362   Table *pTab = 0;     /* Table to be indexed */
2363   Index *pIndex = 0;   /* The index to be created */
2364   char *zName = 0;     /* Name of the index */
2365   int nName;           /* Number of characters in zName */
2366   int i, j;
2367   Token nullId;        /* Fake token for an empty ID list */
2368   DbFixer sFix;        /* For assigning database names to pTable */
2369   int sortOrderMask;   /* 1 to honor DESC in index.  0 to ignore. */
2370   sqlite3 *db = pParse->db;
2371   Db *pDb;             /* The specific table containing the indexed database */
2372   int iDb;             /* Index of the database that is being written */
2373   Token *pName = 0;    /* Unqualified name of the index to create */
2374   struct ExprList_item *pListItem; /* For looping over pList */
2375   int nCol;
2376   int nExtra = 0;
2377   char *zExtra;
2378 
2379   assert( pStart==0 || pEnd!=0 ); /* pEnd must be non-NULL if pStart is */
2380   assert( pParse->nErr==0 );      /* Never called with prior errors */
2381   if( db->mallocFailed || IN_DECLARE_VTAB ){
2382     goto exit_create_index;
2383   }
2384   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
2385     goto exit_create_index;
2386   }
2387 
2388   /*
2389   ** Find the table that is to be indexed.  Return early if not found.
2390   */
2391   if( pTblName!=0 ){
2392 
2393     /* Use the two-part index name to determine the database
2394     ** to search for the table. 'Fix' the table name to this db
2395     ** before looking up the table.
2396     */
2397     assert( pName1 && pName2 );
2398     iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
2399     if( iDb<0 ) goto exit_create_index;
2400 
2401 #ifndef SQLITE_OMIT_TEMPDB
2402     /* If the index name was unqualified, check if the the table
2403     ** is a temp table. If so, set the database to 1. Do not do this
2404     ** if initialising a database schema.
2405     */
2406     if( !db->init.busy ){
2407       pTab = sqlite3SrcListLookup(pParse, pTblName);
2408       if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
2409         iDb = 1;
2410       }
2411     }
2412 #endif
2413 
2414     if( sqlite3FixInit(&sFix, pParse, iDb, "index", pName) &&
2415         sqlite3FixSrcList(&sFix, pTblName)
2416     ){
2417       /* Because the parser constructs pTblName from a single identifier,
2418       ** sqlite3FixSrcList can never fail. */
2419       assert(0);
2420     }
2421     pTab = sqlite3LocateTable(pParse, 0, pTblName->a[0].zName,
2422         pTblName->a[0].zDatabase);
2423     if( !pTab || db->mallocFailed ) goto exit_create_index;
2424     assert( db->aDb[iDb].pSchema==pTab->pSchema );
2425   }else{
2426     assert( pName==0 );
2427     pTab = pParse->pNewTable;
2428     if( !pTab ) goto exit_create_index;
2429     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
2430   }
2431   pDb = &db->aDb[iDb];
2432 
2433   assert( pTab!=0 );
2434   assert( pParse->nErr==0 );
2435   if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
2436        && memcmp(&pTab->zName[7],"altertab_",9)!=0 ){
2437     sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
2438     goto exit_create_index;
2439   }
2440 #ifndef SQLITE_OMIT_VIEW
2441   if( pTab->pSelect ){
2442     sqlite3ErrorMsg(pParse, "views may not be indexed");
2443     goto exit_create_index;
2444   }
2445 #endif
2446 #ifndef SQLITE_OMIT_VIRTUALTABLE
2447   if( IsVirtual(pTab) ){
2448     sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
2449     goto exit_create_index;
2450   }
2451 #endif
2452 
2453   /*
2454   ** Find the name of the index.  Make sure there is not already another
2455   ** index or table with the same name.
2456   **
2457   ** Exception:  If we are reading the names of permanent indices from the
2458   ** sqlite_master table (because some other process changed the schema) and
2459   ** one of the index names collides with the name of a temporary table or
2460   ** index, then we will continue to process this index.
2461   **
2462   ** If pName==0 it means that we are
2463   ** dealing with a primary key or UNIQUE constraint.  We have to invent our
2464   ** own name.
2465   */
2466   if( pName ){
2467     zName = sqlite3NameFromToken(db, pName);
2468     if( zName==0 ) goto exit_create_index;
2469     if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
2470       goto exit_create_index;
2471     }
2472     if( !db->init.busy ){
2473       if( sqlite3FindTable(db, zName, 0)!=0 ){
2474         sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
2475         goto exit_create_index;
2476       }
2477     }
2478     if( sqlite3FindIndex(db, zName, pDb->zName)!=0 ){
2479       if( !ifNotExist ){
2480         sqlite3ErrorMsg(pParse, "index %s already exists", zName);
2481       }
2482       goto exit_create_index;
2483     }
2484   }else{
2485     int n;
2486     Index *pLoop;
2487     for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
2488     zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n);
2489     if( zName==0 ){
2490       goto exit_create_index;
2491     }
2492   }
2493 
2494   /* Check for authorization to create an index.
2495   */
2496 #ifndef SQLITE_OMIT_AUTHORIZATION
2497   {
2498     const char *zDb = pDb->zName;
2499     if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
2500       goto exit_create_index;
2501     }
2502     i = SQLITE_CREATE_INDEX;
2503     if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
2504     if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
2505       goto exit_create_index;
2506     }
2507   }
2508 #endif
2509 
2510   /* If pList==0, it means this routine was called to make a primary
2511   ** key out of the last column added to the table under construction.
2512   ** So create a fake list to simulate this.
2513   */
2514   if( pList==0 ){
2515     nullId.z = pTab->aCol[pTab->nCol-1].zName;
2516     nullId.n = sqlite3Strlen30((char*)nullId.z);
2517     pList = sqlite3ExprListAppend(pParse, 0, 0);
2518     if( pList==0 ) goto exit_create_index;
2519     sqlite3ExprListSetName(pParse, pList, &nullId, 0);
2520     pList->a[0].sortOrder = (u8)sortOrder;
2521   }
2522 
2523   /* Figure out how many bytes of space are required to store explicitly
2524   ** specified collation sequence names.
2525   */
2526   for(i=0; i<pList->nExpr; i++){
2527     Expr *pExpr = pList->a[i].pExpr;
2528     if( pExpr ){
2529       CollSeq *pColl = pExpr->pColl;
2530       /* Either pColl!=0 or there was an OOM failure.  But if an OOM
2531       ** failure we have quit before reaching this point. */
2532       if( ALWAYS(pColl) ){
2533         nExtra += (1 + sqlite3Strlen30(pColl->zName));
2534       }
2535     }
2536   }
2537 
2538   /*
2539   ** Allocate the index structure.
2540   */
2541   nName = sqlite3Strlen30(zName);
2542   nCol = pList->nExpr;
2543   pIndex = sqlite3DbMallocZero(db,
2544       sizeof(Index) +              /* Index structure  */
2545       sizeof(int)*nCol +           /* Index.aiColumn   */
2546       sizeof(int)*(nCol+1) +       /* Index.aiRowEst   */
2547       sizeof(char *)*nCol +        /* Index.azColl     */
2548       sizeof(u8)*nCol +            /* Index.aSortOrder */
2549       nName + 1 +                  /* Index.zName      */
2550       nExtra                       /* Collation sequence names */
2551   );
2552   if( db->mallocFailed ){
2553     goto exit_create_index;
2554   }
2555   pIndex->azColl = (char**)(&pIndex[1]);
2556   pIndex->aiColumn = (int *)(&pIndex->azColl[nCol]);
2557   pIndex->aiRowEst = (unsigned *)(&pIndex->aiColumn[nCol]);
2558   pIndex->aSortOrder = (u8 *)(&pIndex->aiRowEst[nCol+1]);
2559   pIndex->zName = (char *)(&pIndex->aSortOrder[nCol]);
2560   zExtra = (char *)(&pIndex->zName[nName+1]);
2561   memcpy(pIndex->zName, zName, nName+1);
2562   pIndex->pTable = pTab;
2563   pIndex->nColumn = pList->nExpr;
2564   pIndex->onError = (u8)onError;
2565   pIndex->autoIndex = (u8)(pName==0);
2566   pIndex->pSchema = db->aDb[iDb].pSchema;
2567 
2568   /* Check to see if we should honor DESC requests on index columns
2569   */
2570   if( pDb->pSchema->file_format>=4 ){
2571     sortOrderMask = -1;   /* Honor DESC */
2572   }else{
2573     sortOrderMask = 0;    /* Ignore DESC */
2574   }
2575 
2576   /* Scan the names of the columns of the table to be indexed and
2577   ** load the column indices into the Index structure.  Report an error
2578   ** if any column is not found.
2579   **
2580   ** TODO:  Add a test to make sure that the same column is not named
2581   ** more than once within the same index.  Only the first instance of
2582   ** the column will ever be used by the optimizer.  Note that using the
2583   ** same column more than once cannot be an error because that would
2584   ** break backwards compatibility - it needs to be a warning.
2585   */
2586   for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){
2587     const char *zColName = pListItem->zName;
2588     Column *pTabCol;
2589     int requestedSortOrder;
2590     char *zColl;                   /* Collation sequence name */
2591 
2592     for(j=0, pTabCol=pTab->aCol; j<pTab->nCol; j++, pTabCol++){
2593       if( sqlite3StrICmp(zColName, pTabCol->zName)==0 ) break;
2594     }
2595     if( j>=pTab->nCol ){
2596       sqlite3ErrorMsg(pParse, "table %s has no column named %s",
2597         pTab->zName, zColName);
2598       pParse->checkSchema = 1;
2599       goto exit_create_index;
2600     }
2601     pIndex->aiColumn[i] = j;
2602     /* Justification of the ALWAYS(pListItem->pExpr->pColl):  Because of
2603     ** the way the "idxlist" non-terminal is constructed by the parser,
2604     ** if pListItem->pExpr is not null then either pListItem->pExpr->pColl
2605     ** must exist or else there must have been an OOM error.  But if there
2606     ** was an OOM error, we would never reach this point. */
2607     if( pListItem->pExpr && ALWAYS(pListItem->pExpr->pColl) ){
2608       int nColl;
2609       zColl = pListItem->pExpr->pColl->zName;
2610       nColl = sqlite3Strlen30(zColl) + 1;
2611       assert( nExtra>=nColl );
2612       memcpy(zExtra, zColl, nColl);
2613       zColl = zExtra;
2614       zExtra += nColl;
2615       nExtra -= nColl;
2616     }else{
2617       zColl = pTab->aCol[j].zColl;
2618       if( !zColl ){
2619         zColl = db->pDfltColl->zName;
2620       }
2621     }
2622     if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){
2623       goto exit_create_index;
2624     }
2625     pIndex->azColl[i] = zColl;
2626     requestedSortOrder = pListItem->sortOrder & sortOrderMask;
2627     pIndex->aSortOrder[i] = (u8)requestedSortOrder;
2628   }
2629   sqlite3DefaultRowEst(pIndex);
2630 
2631   if( pTab==pParse->pNewTable ){
2632     /* This routine has been called to create an automatic index as a
2633     ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
2634     ** a PRIMARY KEY or UNIQUE clause following the column definitions.
2635     ** i.e. one of:
2636     **
2637     ** CREATE TABLE t(x PRIMARY KEY, y);
2638     ** CREATE TABLE t(x, y, UNIQUE(x, y));
2639     **
2640     ** Either way, check to see if the table already has such an index. If
2641     ** so, don't bother creating this one. This only applies to
2642     ** automatically created indices. Users can do as they wish with
2643     ** explicit indices.
2644     **
2645     ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent
2646     ** (and thus suppressing the second one) even if they have different
2647     ** sort orders.
2648     **
2649     ** If there are different collating sequences or if the columns of
2650     ** the constraint occur in different orders, then the constraints are
2651     ** considered distinct and both result in separate indices.
2652     */
2653     Index *pIdx;
2654     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
2655       int k;
2656       assert( pIdx->onError!=OE_None );
2657       assert( pIdx->autoIndex );
2658       assert( pIndex->onError!=OE_None );
2659 
2660       if( pIdx->nColumn!=pIndex->nColumn ) continue;
2661       for(k=0; k<pIdx->nColumn; k++){
2662         const char *z1;
2663         const char *z2;
2664         if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
2665         z1 = pIdx->azColl[k];
2666         z2 = pIndex->azColl[k];
2667         if( z1!=z2 && sqlite3StrICmp(z1, z2) ) break;
2668       }
2669       if( k==pIdx->nColumn ){
2670         if( pIdx->onError!=pIndex->onError ){
2671           /* This constraint creates the same index as a previous
2672           ** constraint specified somewhere in the CREATE TABLE statement.
2673           ** However the ON CONFLICT clauses are different. If both this
2674           ** constraint and the previous equivalent constraint have explicit
2675           ** ON CONFLICT clauses this is an error. Otherwise, use the
2676           ** explicitly specified behaviour for the index.
2677           */
2678           if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
2679             sqlite3ErrorMsg(pParse,
2680                 "conflicting ON CONFLICT clauses specified", 0);
2681           }
2682           if( pIdx->onError==OE_Default ){
2683             pIdx->onError = pIndex->onError;
2684           }
2685         }
2686         goto exit_create_index;
2687       }
2688     }
2689   }
2690 
2691   /* Link the new Index structure to its table and to the other
2692   ** in-memory database structures.
2693   */
2694   if( db->init.busy ){
2695     Index *p;
2696     p = sqlite3HashInsert(&pIndex->pSchema->idxHash,
2697                           pIndex->zName, sqlite3Strlen30(pIndex->zName),
2698                           pIndex);
2699     if( p ){
2700       assert( p==pIndex );  /* Malloc must have failed */
2701       db->mallocFailed = 1;
2702       goto exit_create_index;
2703     }
2704     db->flags |= SQLITE_InternChanges;
2705     if( pTblName!=0 ){
2706       pIndex->tnum = db->init.newTnum;
2707     }
2708   }
2709 
2710   /* If the db->init.busy is 0 then create the index on disk.  This
2711   ** involves writing the index into the master table and filling in the
2712   ** index with the current table contents.
2713   **
2714   ** The db->init.busy is 0 when the user first enters a CREATE INDEX
2715   ** command.  db->init.busy is 1 when a database is opened and
2716   ** CREATE INDEX statements are read out of the master table.  In
2717   ** the latter case the index already exists on disk, which is why
2718   ** we don't want to recreate it.
2719   **
2720   ** If pTblName==0 it means this index is generated as a primary key
2721   ** or UNIQUE constraint of a CREATE TABLE statement.  Since the table
2722   ** has just been created, it contains no data and the index initialization
2723   ** step can be skipped.
2724   */
2725   else{ /* if( db->init.busy==0 ) */
2726     Vdbe *v;
2727     char *zStmt;
2728     int iMem = ++pParse->nMem;
2729 
2730     v = sqlite3GetVdbe(pParse);
2731     if( v==0 ) goto exit_create_index;
2732 
2733 
2734     /* Create the rootpage for the index
2735     */
2736     sqlite3BeginWriteOperation(pParse, 1, iDb);
2737     sqlite3VdbeAddOp2(v, OP_CreateIndex, iDb, iMem);
2738 
2739     /* Gather the complete text of the CREATE INDEX statement into
2740     ** the zStmt variable
2741     */
2742     if( pStart ){
2743       assert( pEnd!=0 );
2744       /* A named index with an explicit CREATE INDEX statement */
2745       zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
2746         onError==OE_None ? "" : " UNIQUE",
2747         pEnd->z - pName->z + 1,
2748         pName->z);
2749     }else{
2750       /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
2751       /* zStmt = sqlite3MPrintf(""); */
2752       zStmt = 0;
2753     }
2754 
2755     /* Add an entry in sqlite_master for this index
2756     */
2757     sqlite3NestedParse(pParse,
2758         "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);",
2759         db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
2760         pIndex->zName,
2761         pTab->zName,
2762         iMem,
2763         zStmt
2764     );
2765     sqlite3DbFree(db, zStmt);
2766 
2767     /* Fill the index with data and reparse the schema. Code an OP_Expire
2768     ** to invalidate all pre-compiled statements.
2769     */
2770     if( pTblName ){
2771       sqlite3RefillIndex(pParse, pIndex, iMem);
2772       sqlite3ChangeCookie(pParse, iDb);
2773       sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0,
2774          sqlite3MPrintf(db, "name='%q'", pIndex->zName), P4_DYNAMIC);
2775       sqlite3VdbeAddOp1(v, OP_Expire, 0);
2776     }
2777   }
2778 
2779   /* When adding an index to the list of indices for a table, make
2780   ** sure all indices labeled OE_Replace come after all those labeled
2781   ** OE_Ignore.  This is necessary for the correct constraint check
2782   ** processing (in sqlite3GenerateConstraintChecks()) as part of
2783   ** UPDATE and INSERT statements.
2784   */
2785   if( db->init.busy || pTblName==0 ){
2786     if( onError!=OE_Replace || pTab->pIndex==0
2787          || pTab->pIndex->onError==OE_Replace){
2788       pIndex->pNext = pTab->pIndex;
2789       pTab->pIndex = pIndex;
2790     }else{
2791       Index *pOther = pTab->pIndex;
2792       while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
2793         pOther = pOther->pNext;
2794       }
2795       pIndex->pNext = pOther->pNext;
2796       pOther->pNext = pIndex;
2797     }
2798     pRet = pIndex;
2799     pIndex = 0;
2800   }
2801 
2802   /* Clean up before exiting */
2803 exit_create_index:
2804   if( pIndex ){
2805     sqlite3DbFree(db, pIndex->zColAff);
2806     sqlite3DbFree(db, pIndex);
2807   }
2808   sqlite3ExprListDelete(db, pList);
2809   sqlite3SrcListDelete(db, pTblName);
2810   sqlite3DbFree(db, zName);
2811   return pRet;
2812 }
2813 
2814 /*
2815 ** Fill the Index.aiRowEst[] array with default information - information
2816 ** to be used when we have not run the ANALYZE command.
2817 **
2818 ** aiRowEst[0] is suppose to contain the number of elements in the index.
2819 ** Since we do not know, guess 1 million.  aiRowEst[1] is an estimate of the
2820 ** number of rows in the table that match any particular value of the
2821 ** first column of the index.  aiRowEst[2] is an estimate of the number
2822 ** of rows that match any particular combiniation of the first 2 columns
2823 ** of the index.  And so forth.  It must always be the case that
2824 *
2825 **           aiRowEst[N]<=aiRowEst[N-1]
2826 **           aiRowEst[N]>=1
2827 **
2828 ** Apart from that, we have little to go on besides intuition as to
2829 ** how aiRowEst[] should be initialized.  The numbers generated here
2830 ** are based on typical values found in actual indices.
2831 */
2832 void sqlite3DefaultRowEst(Index *pIdx){
2833   unsigned *a = pIdx->aiRowEst;
2834   int i;
2835   assert( a!=0 );
2836   a[0] = 1000000;
2837   for(i=pIdx->nColumn; i>=5; i--){
2838     a[i] = 5;
2839   }
2840   while( i>=1 ){
2841     a[i] = 11 - i;
2842     i--;
2843   }
2844   if( pIdx->onError!=OE_None ){
2845     a[pIdx->nColumn] = 1;
2846   }
2847 }
2848 
2849 /*
2850 ** This routine will drop an existing named index.  This routine
2851 ** implements the DROP INDEX statement.
2852 */
2853 void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
2854   Index *pIndex;
2855   Vdbe *v;
2856   sqlite3 *db = pParse->db;
2857   int iDb;
2858 
2859   assert( pParse->nErr==0 );   /* Never called with prior errors */
2860   if( db->mallocFailed ){
2861     goto exit_drop_index;
2862   }
2863   assert( pName->nSrc==1 );
2864   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
2865     goto exit_drop_index;
2866   }
2867   pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
2868   if( pIndex==0 ){
2869     if( !ifExists ){
2870       sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
2871     }
2872     pParse->checkSchema = 1;
2873     goto exit_drop_index;
2874   }
2875   if( pIndex->autoIndex ){
2876     sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
2877       "or PRIMARY KEY constraint cannot be dropped", 0);
2878     goto exit_drop_index;
2879   }
2880   iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
2881 #ifndef SQLITE_OMIT_AUTHORIZATION
2882   {
2883     int code = SQLITE_DROP_INDEX;
2884     Table *pTab = pIndex->pTable;
2885     const char *zDb = db->aDb[iDb].zName;
2886     const char *zTab = SCHEMA_TABLE(iDb);
2887     if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
2888       goto exit_drop_index;
2889     }
2890     if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
2891     if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
2892       goto exit_drop_index;
2893     }
2894   }
2895 #endif
2896 
2897   /* Generate code to remove the index and from the master table */
2898   v = sqlite3GetVdbe(pParse);
2899   if( v ){
2900     sqlite3BeginWriteOperation(pParse, 1, iDb);
2901     sqlite3NestedParse(pParse,
2902        "DELETE FROM %Q.%s WHERE name=%Q",
2903        db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
2904        pIndex->zName
2905     );
2906     if( sqlite3FindTable(db, "sqlite_stat1", db->aDb[iDb].zName) ){
2907       sqlite3NestedParse(pParse,
2908         "DELETE FROM %Q.sqlite_stat1 WHERE idx=%Q",
2909         db->aDb[iDb].zName, pIndex->zName
2910       );
2911     }
2912     sqlite3ChangeCookie(pParse, iDb);
2913     destroyRootPage(pParse, pIndex->tnum, iDb);
2914     sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
2915   }
2916 
2917 exit_drop_index:
2918   sqlite3SrcListDelete(db, pName);
2919 }
2920 
2921 /*
2922 ** pArray is a pointer to an array of objects.  Each object in the
2923 ** array is szEntry bytes in size.  This routine allocates a new
2924 ** object on the end of the array.
2925 **
2926 ** *pnEntry is the number of entries already in use.  *pnAlloc is
2927 ** the previously allocated size of the array.  initSize is the
2928 ** suggested initial array size allocation.
2929 **
2930 ** The index of the new entry is returned in *pIdx.
2931 **
2932 ** This routine returns a pointer to the array of objects.  This
2933 ** might be the same as the pArray parameter or it might be a different
2934 ** pointer if the array was resized.
2935 */
2936 void *sqlite3ArrayAllocate(
2937   sqlite3 *db,      /* Connection to notify of malloc failures */
2938   void *pArray,     /* Array of objects.  Might be reallocated */
2939   int szEntry,      /* Size of each object in the array */
2940   int initSize,     /* Suggested initial allocation, in elements */
2941   int *pnEntry,     /* Number of objects currently in use */
2942   int *pnAlloc,     /* Current size of the allocation, in elements */
2943   int *pIdx         /* Write the index of a new slot here */
2944 ){
2945   char *z;
2946   if( *pnEntry >= *pnAlloc ){
2947     void *pNew;
2948     int newSize;
2949     newSize = (*pnAlloc)*2 + initSize;
2950     pNew = sqlite3DbRealloc(db, pArray, newSize*szEntry);
2951     if( pNew==0 ){
2952       *pIdx = -1;
2953       return pArray;
2954     }
2955     *pnAlloc = sqlite3DbMallocSize(db, pNew)/szEntry;
2956     pArray = pNew;
2957   }
2958   z = (char*)pArray;
2959   memset(&z[*pnEntry * szEntry], 0, szEntry);
2960   *pIdx = *pnEntry;
2961   ++*pnEntry;
2962   return pArray;
2963 }
2964 
2965 /*
2966 ** Append a new element to the given IdList.  Create a new IdList if
2967 ** need be.
2968 **
2969 ** A new IdList is returned, or NULL if malloc() fails.
2970 */
2971 IdList *sqlite3IdListAppend(sqlite3 *db, IdList *pList, Token *pToken){
2972   int i;
2973   if( pList==0 ){
2974     pList = sqlite3DbMallocZero(db, sizeof(IdList) );
2975     if( pList==0 ) return 0;
2976     pList->nAlloc = 0;
2977   }
2978   pList->a = sqlite3ArrayAllocate(
2979       db,
2980       pList->a,
2981       sizeof(pList->a[0]),
2982       5,
2983       &pList->nId,
2984       &pList->nAlloc,
2985       &i
2986   );
2987   if( i<0 ){
2988     sqlite3IdListDelete(db, pList);
2989     return 0;
2990   }
2991   pList->a[i].zName = sqlite3NameFromToken(db, pToken);
2992   return pList;
2993 }
2994 
2995 /*
2996 ** Delete an IdList.
2997 */
2998 void sqlite3IdListDelete(sqlite3 *db, IdList *pList){
2999   int i;
3000   if( pList==0 ) return;
3001   for(i=0; i<pList->nId; i++){
3002     sqlite3DbFree(db, pList->a[i].zName);
3003   }
3004   sqlite3DbFree(db, pList->a);
3005   sqlite3DbFree(db, pList);
3006 }
3007 
3008 /*
3009 ** Return the index in pList of the identifier named zId.  Return -1
3010 ** if not found.
3011 */
3012 int sqlite3IdListIndex(IdList *pList, const char *zName){
3013   int i;
3014   if( pList==0 ) return -1;
3015   for(i=0; i<pList->nId; i++){
3016     if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
3017   }
3018   return -1;
3019 }
3020 
3021 /*
3022 ** Expand the space allocated for the given SrcList object by
3023 ** creating nExtra new slots beginning at iStart.  iStart is zero based.
3024 ** New slots are zeroed.
3025 **
3026 ** For example, suppose a SrcList initially contains two entries: A,B.
3027 ** To append 3 new entries onto the end, do this:
3028 **
3029 **    sqlite3SrcListEnlarge(db, pSrclist, 3, 2);
3030 **
3031 ** After the call above it would contain:  A, B, nil, nil, nil.
3032 ** If the iStart argument had been 1 instead of 2, then the result
3033 ** would have been:  A, nil, nil, nil, B.  To prepend the new slots,
3034 ** the iStart value would be 0.  The result then would
3035 ** be: nil, nil, nil, A, B.
3036 **
3037 ** If a memory allocation fails the SrcList is unchanged.  The
3038 ** db->mallocFailed flag will be set to true.
3039 */
3040 SrcList *sqlite3SrcListEnlarge(
3041   sqlite3 *db,       /* Database connection to notify of OOM errors */
3042   SrcList *pSrc,     /* The SrcList to be enlarged */
3043   int nExtra,        /* Number of new slots to add to pSrc->a[] */
3044   int iStart         /* Index in pSrc->a[] of first new slot */
3045 ){
3046   int i;
3047 
3048   /* Sanity checking on calling parameters */
3049   assert( iStart>=0 );
3050   assert( nExtra>=1 );
3051   assert( pSrc!=0 );
3052   assert( iStart<=pSrc->nSrc );
3053 
3054   /* Allocate additional space if needed */
3055   if( pSrc->nSrc+nExtra>pSrc->nAlloc ){
3056     SrcList *pNew;
3057     int nAlloc = pSrc->nSrc+nExtra;
3058     int nGot;
3059     pNew = sqlite3DbRealloc(db, pSrc,
3060                sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) );
3061     if( pNew==0 ){
3062       assert( db->mallocFailed );
3063       return pSrc;
3064     }
3065     pSrc = pNew;
3066     nGot = (sqlite3DbMallocSize(db, pNew) - sizeof(*pSrc))/sizeof(pSrc->a[0])+1;
3067     pSrc->nAlloc = (u16)nGot;
3068   }
3069 
3070   /* Move existing slots that come after the newly inserted slots
3071   ** out of the way */
3072   for(i=pSrc->nSrc-1; i>=iStart; i--){
3073     pSrc->a[i+nExtra] = pSrc->a[i];
3074   }
3075   pSrc->nSrc += (i16)nExtra;
3076 
3077   /* Zero the newly allocated slots */
3078   memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
3079   for(i=iStart; i<iStart+nExtra; i++){
3080     pSrc->a[i].iCursor = -1;
3081   }
3082 
3083   /* Return a pointer to the enlarged SrcList */
3084   return pSrc;
3085 }
3086 
3087 
3088 /*
3089 ** Append a new table name to the given SrcList.  Create a new SrcList if
3090 ** need be.  A new entry is created in the SrcList even if pTable is NULL.
3091 **
3092 ** A SrcList is returned, or NULL if there is an OOM error.  The returned
3093 ** SrcList might be the same as the SrcList that was input or it might be
3094 ** a new one.  If an OOM error does occurs, then the prior value of pList
3095 ** that is input to this routine is automatically freed.
3096 **
3097 ** If pDatabase is not null, it means that the table has an optional
3098 ** database name prefix.  Like this:  "database.table".  The pDatabase
3099 ** points to the table name and the pTable points to the database name.
3100 ** The SrcList.a[].zName field is filled with the table name which might
3101 ** come from pTable (if pDatabase is NULL) or from pDatabase.
3102 ** SrcList.a[].zDatabase is filled with the database name from pTable,
3103 ** or with NULL if no database is specified.
3104 **
3105 ** In other words, if call like this:
3106 **
3107 **         sqlite3SrcListAppend(D,A,B,0);
3108 **
3109 ** Then B is a table name and the database name is unspecified.  If called
3110 ** like this:
3111 **
3112 **         sqlite3SrcListAppend(D,A,B,C);
3113 **
3114 ** Then C is the table name and B is the database name.  If C is defined
3115 ** then so is B.  In other words, we never have a case where:
3116 **
3117 **         sqlite3SrcListAppend(D,A,0,C);
3118 **
3119 ** Both pTable and pDatabase are assumed to be quoted.  They are dequoted
3120 ** before being added to the SrcList.
3121 */
3122 SrcList *sqlite3SrcListAppend(
3123   sqlite3 *db,        /* Connection to notify of malloc failures */
3124   SrcList *pList,     /* Append to this SrcList. NULL creates a new SrcList */
3125   Token *pTable,      /* Table to append */
3126   Token *pDatabase    /* Database of the table */
3127 ){
3128   struct SrcList_item *pItem;
3129   assert( pDatabase==0 || pTable!=0 );  /* Cannot have C without B */
3130   if( pList==0 ){
3131     pList = sqlite3DbMallocZero(db, sizeof(SrcList) );
3132     if( pList==0 ) return 0;
3133     pList->nAlloc = 1;
3134   }
3135   pList = sqlite3SrcListEnlarge(db, pList, 1, pList->nSrc);
3136   if( db->mallocFailed ){
3137     sqlite3SrcListDelete(db, pList);
3138     return 0;
3139   }
3140   pItem = &pList->a[pList->nSrc-1];
3141   if( pDatabase && pDatabase->z==0 ){
3142     pDatabase = 0;
3143   }
3144   if( pDatabase ){
3145     Token *pTemp = pDatabase;
3146     pDatabase = pTable;
3147     pTable = pTemp;
3148   }
3149   pItem->zName = sqlite3NameFromToken(db, pTable);
3150   pItem->zDatabase = sqlite3NameFromToken(db, pDatabase);
3151   return pList;
3152 }
3153 
3154 /*
3155 ** Assign VdbeCursor index numbers to all tables in a SrcList
3156 */
3157 void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
3158   int i;
3159   struct SrcList_item *pItem;
3160   assert(pList || pParse->db->mallocFailed );
3161   if( pList ){
3162     for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
3163       if( pItem->iCursor>=0 ) break;
3164       pItem->iCursor = pParse->nTab++;
3165       if( pItem->pSelect ){
3166         sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
3167       }
3168     }
3169   }
3170 }
3171 
3172 /*
3173 ** Delete an entire SrcList including all its substructure.
3174 */
3175 void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){
3176   int i;
3177   struct SrcList_item *pItem;
3178   if( pList==0 ) return;
3179   for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
3180     sqlite3DbFree(db, pItem->zDatabase);
3181     sqlite3DbFree(db, pItem->zName);
3182     sqlite3DbFree(db, pItem->zAlias);
3183     sqlite3DbFree(db, pItem->zIndex);
3184     sqlite3DeleteTable(db, pItem->pTab);
3185     sqlite3SelectDelete(db, pItem->pSelect);
3186     sqlite3ExprDelete(db, pItem->pOn);
3187     sqlite3IdListDelete(db, pItem->pUsing);
3188   }
3189   sqlite3DbFree(db, pList);
3190 }
3191 
3192 /*
3193 ** This routine is called by the parser to add a new term to the
3194 ** end of a growing FROM clause.  The "p" parameter is the part of
3195 ** the FROM clause that has already been constructed.  "p" is NULL
3196 ** if this is the first term of the FROM clause.  pTable and pDatabase
3197 ** are the name of the table and database named in the FROM clause term.
3198 ** pDatabase is NULL if the database name qualifier is missing - the
3199 ** usual case.  If the term has a alias, then pAlias points to the
3200 ** alias token.  If the term is a subquery, then pSubquery is the
3201 ** SELECT statement that the subquery encodes.  The pTable and
3202 ** pDatabase parameters are NULL for subqueries.  The pOn and pUsing
3203 ** parameters are the content of the ON and USING clauses.
3204 **
3205 ** Return a new SrcList which encodes is the FROM with the new
3206 ** term added.
3207 */
3208 SrcList *sqlite3SrcListAppendFromTerm(
3209   Parse *pParse,          /* Parsing context */
3210   SrcList *p,             /* The left part of the FROM clause already seen */
3211   Token *pTable,          /* Name of the table to add to the FROM clause */
3212   Token *pDatabase,       /* Name of the database containing pTable */
3213   Token *pAlias,          /* The right-hand side of the AS subexpression */
3214   Select *pSubquery,      /* A subquery used in place of a table name */
3215   Expr *pOn,              /* The ON clause of a join */
3216   IdList *pUsing          /* The USING clause of a join */
3217 ){
3218   struct SrcList_item *pItem;
3219   sqlite3 *db = pParse->db;
3220   if( !p && (pOn || pUsing) ){
3221     sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s",
3222       (pOn ? "ON" : "USING")
3223     );
3224     goto append_from_error;
3225   }
3226   p = sqlite3SrcListAppend(db, p, pTable, pDatabase);
3227   if( p==0 || NEVER(p->nSrc==0) ){
3228     goto append_from_error;
3229   }
3230   pItem = &p->a[p->nSrc-1];
3231   assert( pAlias!=0 );
3232   if( pAlias->n ){
3233     pItem->zAlias = sqlite3NameFromToken(db, pAlias);
3234   }
3235   pItem->pSelect = pSubquery;
3236   pItem->pOn = pOn;
3237   pItem->pUsing = pUsing;
3238   return p;
3239 
3240  append_from_error:
3241   assert( p==0 );
3242   sqlite3ExprDelete(db, pOn);
3243   sqlite3IdListDelete(db, pUsing);
3244   sqlite3SelectDelete(db, pSubquery);
3245   return 0;
3246 }
3247 
3248 /*
3249 ** Add an INDEXED BY or NOT INDEXED clause to the most recently added
3250 ** element of the source-list passed as the second argument.
3251 */
3252 void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){
3253   assert( pIndexedBy!=0 );
3254   if( p && ALWAYS(p->nSrc>0) ){
3255     struct SrcList_item *pItem = &p->a[p->nSrc-1];
3256     assert( pItem->notIndexed==0 && pItem->zIndex==0 );
3257     if( pIndexedBy->n==1 && !pIndexedBy->z ){
3258       /* A "NOT INDEXED" clause was supplied. See parse.y
3259       ** construct "indexed_opt" for details. */
3260       pItem->notIndexed = 1;
3261     }else{
3262       pItem->zIndex = sqlite3NameFromToken(pParse->db, pIndexedBy);
3263     }
3264   }
3265 }
3266 
3267 /*
3268 ** When building up a FROM clause in the parser, the join operator
3269 ** is initially attached to the left operand.  But the code generator
3270 ** expects the join operator to be on the right operand.  This routine
3271 ** Shifts all join operators from left to right for an entire FROM
3272 ** clause.
3273 **
3274 ** Example: Suppose the join is like this:
3275 **
3276 **           A natural cross join B
3277 **
3278 ** The operator is "natural cross join".  The A and B operands are stored
3279 ** in p->a[0] and p->a[1], respectively.  The parser initially stores the
3280 ** operator with A.  This routine shifts that operator over to B.
3281 */
3282 void sqlite3SrcListShiftJoinType(SrcList *p){
3283   if( p && p->a ){
3284     int i;
3285     for(i=p->nSrc-1; i>0; i--){
3286       p->a[i].jointype = p->a[i-1].jointype;
3287     }
3288     p->a[0].jointype = 0;
3289   }
3290 }
3291 
3292 /*
3293 ** Begin a transaction
3294 */
3295 void sqlite3BeginTransaction(Parse *pParse, int type){
3296   sqlite3 *db;
3297   Vdbe *v;
3298   int i;
3299 
3300   assert( pParse!=0 );
3301   db = pParse->db;
3302   assert( db!=0 );
3303 /*  if( db->aDb[0].pBt==0 ) return; */
3304   if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){
3305     return;
3306   }
3307   v = sqlite3GetVdbe(pParse);
3308   if( !v ) return;
3309   if( type!=TK_DEFERRED ){
3310     for(i=0; i<db->nDb; i++){
3311       sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
3312       sqlite3VdbeUsesBtree(v, i);
3313     }
3314   }
3315   sqlite3VdbeAddOp2(v, OP_AutoCommit, 0, 0);
3316 }
3317 
3318 /*
3319 ** Commit a transaction
3320 */
3321 void sqlite3CommitTransaction(Parse *pParse){
3322   sqlite3 *db;
3323   Vdbe *v;
3324 
3325   assert( pParse!=0 );
3326   db = pParse->db;
3327   assert( db!=0 );
3328 /*  if( db->aDb[0].pBt==0 ) return; */
3329   if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ){
3330     return;
3331   }
3332   v = sqlite3GetVdbe(pParse);
3333   if( v ){
3334     sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 0);
3335   }
3336 }
3337 
3338 /*
3339 ** Rollback a transaction
3340 */
3341 void sqlite3RollbackTransaction(Parse *pParse){
3342   sqlite3 *db;
3343   Vdbe *v;
3344 
3345   assert( pParse!=0 );
3346   db = pParse->db;
3347   assert( db!=0 );
3348 /*  if( db->aDb[0].pBt==0 ) return; */
3349   if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ){
3350     return;
3351   }
3352   v = sqlite3GetVdbe(pParse);
3353   if( v ){
3354     sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 1);
3355   }
3356 }
3357 
3358 /*
3359 ** This function is called by the parser when it parses a command to create,
3360 ** release or rollback an SQL savepoint.
3361 */
3362 void sqlite3Savepoint(Parse *pParse, int op, Token *pName){
3363   char *zName = sqlite3NameFromToken(pParse->db, pName);
3364   if( zName ){
3365     Vdbe *v = sqlite3GetVdbe(pParse);
3366 #ifndef SQLITE_OMIT_AUTHORIZATION
3367     static const char * const az[] = { "BEGIN", "RELEASE", "ROLLBACK" };
3368     assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 );
3369 #endif
3370     if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){
3371       sqlite3DbFree(pParse->db, zName);
3372       return;
3373     }
3374     sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC);
3375   }
3376 }
3377 
3378 /*
3379 ** Make sure the TEMP database is open and available for use.  Return
3380 ** the number of errors.  Leave any error messages in the pParse structure.
3381 */
3382 int sqlite3OpenTempDatabase(Parse *pParse){
3383   sqlite3 *db = pParse->db;
3384   if( db->aDb[1].pBt==0 && !pParse->explain ){
3385     int rc;
3386     Btree *pBt;
3387     static const int flags =
3388           SQLITE_OPEN_READWRITE |
3389           SQLITE_OPEN_CREATE |
3390           SQLITE_OPEN_EXCLUSIVE |
3391           SQLITE_OPEN_DELETEONCLOSE |
3392           SQLITE_OPEN_TEMP_DB;
3393 
3394     rc = sqlite3BtreeFactory(db, 0, 0, SQLITE_DEFAULT_CACHE_SIZE, flags, &pBt);
3395     if( rc!=SQLITE_OK ){
3396       sqlite3ErrorMsg(pParse, "unable to open a temporary database "
3397         "file for storing temporary tables");
3398       pParse->rc = rc;
3399       return 1;
3400     }
3401     db->aDb[1].pBt = pBt;
3402     assert( db->aDb[1].pSchema );
3403     if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){
3404       db->mallocFailed = 1;
3405       return 1;
3406     }
3407   }
3408   return 0;
3409 }
3410 
3411 /*
3412 ** Generate VDBE code that will verify the schema cookie and start
3413 ** a read-transaction for all named database files.
3414 **
3415 ** It is important that all schema cookies be verified and all
3416 ** read transactions be started before anything else happens in
3417 ** the VDBE program.  But this routine can be called after much other
3418 ** code has been generated.  So here is what we do:
3419 **
3420 ** The first time this routine is called, we code an OP_Goto that
3421 ** will jump to a subroutine at the end of the program.  Then we
3422 ** record every database that needs its schema verified in the
3423 ** pParse->cookieMask field.  Later, after all other code has been
3424 ** generated, the subroutine that does the cookie verifications and
3425 ** starts the transactions will be coded and the OP_Goto P2 value
3426 ** will be made to point to that subroutine.  The generation of the
3427 ** cookie verification subroutine code happens in sqlite3FinishCoding().
3428 **
3429 ** If iDb<0 then code the OP_Goto only - don't set flag to verify the
3430 ** schema on any databases.  This can be used to position the OP_Goto
3431 ** early in the code, before we know if any database tables will be used.
3432 */
3433 void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
3434   Parse *pToplevel = sqlite3ParseToplevel(pParse);
3435 
3436   if( pToplevel->cookieGoto==0 ){
3437     Vdbe *v = sqlite3GetVdbe(pToplevel);
3438     if( v==0 ) return;  /* This only happens if there was a prior error */
3439     pToplevel->cookieGoto = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0)+1;
3440   }
3441   if( iDb>=0 ){
3442     sqlite3 *db = pToplevel->db;
3443     int mask;
3444 
3445     assert( iDb<db->nDb );
3446     assert( db->aDb[iDb].pBt!=0 || iDb==1 );
3447     assert( iDb<SQLITE_MAX_ATTACHED+2 );
3448     mask = 1<<iDb;
3449     if( (pToplevel->cookieMask & mask)==0 ){
3450       pToplevel->cookieMask |= mask;
3451       pToplevel->cookieValue[iDb] = db->aDb[iDb].pSchema->schema_cookie;
3452       if( !OMIT_TEMPDB && iDb==1 ){
3453         sqlite3OpenTempDatabase(pToplevel);
3454       }
3455     }
3456   }
3457 }
3458 
3459 /*
3460 ** Generate VDBE code that prepares for doing an operation that
3461 ** might change the database.
3462 **
3463 ** This routine starts a new transaction if we are not already within
3464 ** a transaction.  If we are already within a transaction, then a checkpoint
3465 ** is set if the setStatement parameter is true.  A checkpoint should
3466 ** be set for operations that might fail (due to a constraint) part of
3467 ** the way through and which will need to undo some writes without having to
3468 ** rollback the whole transaction.  For operations where all constraints
3469 ** can be checked before any changes are made to the database, it is never
3470 ** necessary to undo a write and the checkpoint should not be set.
3471 */
3472 void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
3473   Parse *pToplevel = sqlite3ParseToplevel(pParse);
3474   sqlite3CodeVerifySchema(pParse, iDb);
3475   pToplevel->writeMask |= 1<<iDb;
3476   pToplevel->isMultiWrite |= setStatement;
3477 }
3478 
3479 /*
3480 ** Indicate that the statement currently under construction might write
3481 ** more than one entry (example: deleting one row then inserting another,
3482 ** inserting multiple rows in a table, or inserting a row and index entries.)
3483 ** If an abort occurs after some of these writes have completed, then it will
3484 ** be necessary to undo the completed writes.
3485 */
3486 void sqlite3MultiWrite(Parse *pParse){
3487   Parse *pToplevel = sqlite3ParseToplevel(pParse);
3488   pToplevel->isMultiWrite = 1;
3489 }
3490 
3491 /*
3492 ** The code generator calls this routine if is discovers that it is
3493 ** possible to abort a statement prior to completion.  In order to
3494 ** perform this abort without corrupting the database, we need to make
3495 ** sure that the statement is protected by a statement transaction.
3496 **
3497 ** Technically, we only need to set the mayAbort flag if the
3498 ** isMultiWrite flag was previously set.  There is a time dependency
3499 ** such that the abort must occur after the multiwrite.  This makes
3500 ** some statements involving the REPLACE conflict resolution algorithm
3501 ** go a little faster.  But taking advantage of this time dependency
3502 ** makes it more difficult to prove that the code is correct (in
3503 ** particular, it prevents us from writing an effective
3504 ** implementation of sqlite3AssertMayAbort()) and so we have chosen
3505 ** to take the safe route and skip the optimization.
3506 */
3507 void sqlite3MayAbort(Parse *pParse){
3508   Parse *pToplevel = sqlite3ParseToplevel(pParse);
3509   pToplevel->mayAbort = 1;
3510 }
3511 
3512 /*
3513 ** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT
3514 ** error. The onError parameter determines which (if any) of the statement
3515 ** and/or current transaction is rolled back.
3516 */
3517 void sqlite3HaltConstraint(Parse *pParse, int onError, char *p4, int p4type){
3518   Vdbe *v = sqlite3GetVdbe(pParse);
3519   if( onError==OE_Abort ){
3520     sqlite3MayAbort(pParse);
3521   }
3522   sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, onError, 0, p4, p4type);
3523 }
3524 
3525 /*
3526 ** Check to see if pIndex uses the collating sequence pColl.  Return
3527 ** true if it does and false if it does not.
3528 */
3529 #ifndef SQLITE_OMIT_REINDEX
3530 static int collationMatch(const char *zColl, Index *pIndex){
3531   int i;
3532   assert( zColl!=0 );
3533   for(i=0; i<pIndex->nColumn; i++){
3534     const char *z = pIndex->azColl[i];
3535     assert( z!=0 );
3536     if( 0==sqlite3StrICmp(z, zColl) ){
3537       return 1;
3538     }
3539   }
3540   return 0;
3541 }
3542 #endif
3543 
3544 /*
3545 ** Recompute all indices of pTab that use the collating sequence pColl.
3546 ** If pColl==0 then recompute all indices of pTab.
3547 */
3548 #ifndef SQLITE_OMIT_REINDEX
3549 static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
3550   Index *pIndex;              /* An index associated with pTab */
3551 
3552   for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
3553     if( zColl==0 || collationMatch(zColl, pIndex) ){
3554       int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
3555       sqlite3BeginWriteOperation(pParse, 0, iDb);
3556       sqlite3RefillIndex(pParse, pIndex, -1);
3557     }
3558   }
3559 }
3560 #endif
3561 
3562 /*
3563 ** Recompute all indices of all tables in all databases where the
3564 ** indices use the collating sequence pColl.  If pColl==0 then recompute
3565 ** all indices everywhere.
3566 */
3567 #ifndef SQLITE_OMIT_REINDEX
3568 static void reindexDatabases(Parse *pParse, char const *zColl){
3569   Db *pDb;                    /* A single database */
3570   int iDb;                    /* The database index number */
3571   sqlite3 *db = pParse->db;   /* The database connection */
3572   HashElem *k;                /* For looping over tables in pDb */
3573   Table *pTab;                /* A table in the database */
3574 
3575   for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
3576     assert( pDb!=0 );
3577     for(k=sqliteHashFirst(&pDb->pSchema->tblHash);  k; k=sqliteHashNext(k)){
3578       pTab = (Table*)sqliteHashData(k);
3579       reindexTable(pParse, pTab, zColl);
3580     }
3581   }
3582 }
3583 #endif
3584 
3585 /*
3586 ** Generate code for the REINDEX command.
3587 **
3588 **        REINDEX                            -- 1
3589 **        REINDEX  <collation>               -- 2
3590 **        REINDEX  ?<database>.?<tablename>  -- 3
3591 **        REINDEX  ?<database>.?<indexname>  -- 4
3592 **
3593 ** Form 1 causes all indices in all attached databases to be rebuilt.
3594 ** Form 2 rebuilds all indices in all databases that use the named
3595 ** collating function.  Forms 3 and 4 rebuild the named index or all
3596 ** indices associated with the named table.
3597 */
3598 #ifndef SQLITE_OMIT_REINDEX
3599 void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
3600   CollSeq *pColl;             /* Collating sequence to be reindexed, or NULL */
3601   char *z;                    /* Name of a table or index */
3602   const char *zDb;            /* Name of the database */
3603   Table *pTab;                /* A table in the database */
3604   Index *pIndex;              /* An index associated with pTab */
3605   int iDb;                    /* The database index number */
3606   sqlite3 *db = pParse->db;   /* The database connection */
3607   Token *pObjName;            /* Name of the table or index to be reindexed */
3608 
3609   /* Read the database schema. If an error occurs, leave an error message
3610   ** and code in pParse and return NULL. */
3611   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
3612     return;
3613   }
3614 
3615   if( pName1==0 ){
3616     reindexDatabases(pParse, 0);
3617     return;
3618   }else if( NEVER(pName2==0) || pName2->z==0 ){
3619     char *zColl;
3620     assert( pName1->z );
3621     zColl = sqlite3NameFromToken(pParse->db, pName1);
3622     if( !zColl ) return;
3623     pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
3624     if( pColl ){
3625       reindexDatabases(pParse, zColl);
3626       sqlite3DbFree(db, zColl);
3627       return;
3628     }
3629     sqlite3DbFree(db, zColl);
3630   }
3631   iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
3632   if( iDb<0 ) return;
3633   z = sqlite3NameFromToken(db, pObjName);
3634   if( z==0 ) return;
3635   zDb = db->aDb[iDb].zName;
3636   pTab = sqlite3FindTable(db, z, zDb);
3637   if( pTab ){
3638     reindexTable(pParse, pTab, 0);
3639     sqlite3DbFree(db, z);
3640     return;
3641   }
3642   pIndex = sqlite3FindIndex(db, z, zDb);
3643   sqlite3DbFree(db, z);
3644   if( pIndex ){
3645     sqlite3BeginWriteOperation(pParse, 0, iDb);
3646     sqlite3RefillIndex(pParse, pIndex, -1);
3647     return;
3648   }
3649   sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
3650 }
3651 #endif
3652 
3653 /*
3654 ** Return a dynamicly allocated KeyInfo structure that can be used
3655 ** with OP_OpenRead or OP_OpenWrite to access database index pIdx.
3656 **
3657 ** If successful, a pointer to the new structure is returned. In this case
3658 ** the caller is responsible for calling sqlite3DbFree(db, ) on the returned
3659 ** pointer. If an error occurs (out of memory or missing collation
3660 ** sequence), NULL is returned and the state of pParse updated to reflect
3661 ** the error.
3662 */
3663 KeyInfo *sqlite3IndexKeyinfo(Parse *pParse, Index *pIdx){
3664   int i;
3665   int nCol = pIdx->nColumn;
3666   int nBytes = sizeof(KeyInfo) + (nCol-1)*sizeof(CollSeq*) + nCol;
3667   sqlite3 *db = pParse->db;
3668   KeyInfo *pKey = (KeyInfo *)sqlite3DbMallocZero(db, nBytes);
3669 
3670   if( pKey ){
3671     pKey->db = pParse->db;
3672     pKey->aSortOrder = (u8 *)&(pKey->aColl[nCol]);
3673     assert( &pKey->aSortOrder[nCol]==&(((u8 *)pKey)[nBytes]) );
3674     for(i=0; i<nCol; i++){
3675       char *zColl = pIdx->azColl[i];
3676       assert( zColl );
3677       pKey->aColl[i] = sqlite3LocateCollSeq(pParse, zColl);
3678       pKey->aSortOrder[i] = pIdx->aSortOrder[i];
3679     }
3680     pKey->nField = (u16)nCol;
3681   }
3682 
3683   if( pParse->nErr ){
3684     sqlite3DbFree(db, pKey);
3685     pKey = 0;
3686   }
3687   return pKey;
3688 }
3689