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