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