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