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