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