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