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