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