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