xref: /sqlite-3.40.0/src/build.c (revision 9c0fee29)
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   testcase( pParse->earlyCleanup );
1329   if( db->mallocFailed ) return;
1330   pRet->retTrig.zName = RETURNING_TRIGGER_NAME;
1331   pRet->retTrig.op = TK_RETURNING;
1332   pRet->retTrig.tr_tm = TRIGGER_AFTER;
1333   pRet->retTrig.bReturning = 1;
1334   pRet->retTrig.pSchema = db->aDb[1].pSchema;
1335   pRet->retTrig.step_list = &pRet->retTStep;
1336   pRet->retTStep.op = TK_RETURNING;
1337   pRet->retTStep.pTrig = &pRet->retTrig;
1338   pRet->retTStep.pExprList = pList;
1339   pHash = &(db->aDb[1].pSchema->trigHash);
1340   assert( sqlite3HashFind(pHash, RETURNING_TRIGGER_NAME)==0 || pParse->nErr );
1341   if( sqlite3HashInsert(pHash, RETURNING_TRIGGER_NAME, &pRet->retTrig)
1342           ==&pRet->retTrig ){
1343     sqlite3OomFault(db);
1344   }
1345 }
1346 
1347 /*
1348 ** Add a new column to the table currently being constructed.
1349 **
1350 ** The parser calls this routine once for each column declaration
1351 ** in a CREATE TABLE statement.  sqlite3StartTable() gets called
1352 ** first to get things going.  Then this routine is called for each
1353 ** column.
1354 */
1355 void sqlite3AddColumn(Parse *pParse, Token *pName, Token *pType){
1356   Table *p;
1357   int i;
1358   char *z;
1359   char *zType;
1360   Column *pCol;
1361   sqlite3 *db = pParse->db;
1362   u8 hName;
1363 
1364   if( (p = pParse->pNewTable)==0 ) return;
1365   if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){
1366     sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
1367     return;
1368   }
1369   z = sqlite3DbMallocRaw(db, pName->n + pType->n + 2);
1370   if( z==0 ) return;
1371   if( IN_RENAME_OBJECT ) sqlite3RenameTokenMap(pParse, (void*)z, pName);
1372   memcpy(z, pName->z, pName->n);
1373   z[pName->n] = 0;
1374   sqlite3Dequote(z);
1375   hName = sqlite3StrIHash(z);
1376   for(i=0; i<p->nCol; i++){
1377     if( p->aCol[i].hName==hName && sqlite3StrICmp(z, p->aCol[i].zName)==0 ){
1378       sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
1379       sqlite3DbFree(db, z);
1380       return;
1381     }
1382   }
1383   if( (p->nCol & 0x7)==0 ){
1384     Column *aNew;
1385     aNew = sqlite3DbRealloc(db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0]));
1386     if( aNew==0 ){
1387       sqlite3DbFree(db, z);
1388       return;
1389     }
1390     p->aCol = aNew;
1391   }
1392   pCol = &p->aCol[p->nCol];
1393   memset(pCol, 0, sizeof(p->aCol[0]));
1394   pCol->zName = z;
1395   pCol->hName = hName;
1396   sqlite3ColumnPropertiesFromName(p, pCol);
1397 
1398   if( pType->n==0 ){
1399     /* If there is no type specified, columns have the default affinity
1400     ** 'BLOB' with a default size of 4 bytes. */
1401     pCol->affinity = SQLITE_AFF_BLOB;
1402     pCol->szEst = 1;
1403 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
1404     if( 4>=sqlite3GlobalConfig.szSorterRef ){
1405       pCol->colFlags |= COLFLAG_SORTERREF;
1406     }
1407 #endif
1408   }else{
1409     zType = z + sqlite3Strlen30(z) + 1;
1410     memcpy(zType, pType->z, pType->n);
1411     zType[pType->n] = 0;
1412     sqlite3Dequote(zType);
1413     pCol->affinity = sqlite3AffinityType(zType, pCol);
1414     pCol->colFlags |= COLFLAG_HASTYPE;
1415   }
1416   p->nCol++;
1417   p->nNVCol++;
1418   pParse->constraintName.n = 0;
1419 }
1420 
1421 /*
1422 ** This routine is called by the parser while in the middle of
1423 ** parsing a CREATE TABLE statement.  A "NOT NULL" constraint has
1424 ** been seen on a column.  This routine sets the notNull flag on
1425 ** the column currently under construction.
1426 */
1427 void sqlite3AddNotNull(Parse *pParse, int onError){
1428   Table *p;
1429   Column *pCol;
1430   p = pParse->pNewTable;
1431   if( p==0 || NEVER(p->nCol<1) ) return;
1432   pCol = &p->aCol[p->nCol-1];
1433   pCol->notNull = (u8)onError;
1434   p->tabFlags |= TF_HasNotNull;
1435 
1436   /* Set the uniqNotNull flag on any UNIQUE or PK indexes already created
1437   ** on this column.  */
1438   if( pCol->colFlags & COLFLAG_UNIQUE ){
1439     Index *pIdx;
1440     for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
1441       assert( pIdx->nKeyCol==1 && pIdx->onError!=OE_None );
1442       if( pIdx->aiColumn[0]==p->nCol-1 ){
1443         pIdx->uniqNotNull = 1;
1444       }
1445     }
1446   }
1447 }
1448 
1449 /*
1450 ** Scan the column type name zType (length nType) and return the
1451 ** associated affinity type.
1452 **
1453 ** This routine does a case-independent search of zType for the
1454 ** substrings in the following table. If one of the substrings is
1455 ** found, the corresponding affinity is returned. If zType contains
1456 ** more than one of the substrings, entries toward the top of
1457 ** the table take priority. For example, if zType is 'BLOBINT',
1458 ** SQLITE_AFF_INTEGER is returned.
1459 **
1460 ** Substring     | Affinity
1461 ** --------------------------------
1462 ** 'INT'         | SQLITE_AFF_INTEGER
1463 ** 'CHAR'        | SQLITE_AFF_TEXT
1464 ** 'CLOB'        | SQLITE_AFF_TEXT
1465 ** 'TEXT'        | SQLITE_AFF_TEXT
1466 ** 'BLOB'        | SQLITE_AFF_BLOB
1467 ** 'REAL'        | SQLITE_AFF_REAL
1468 ** 'FLOA'        | SQLITE_AFF_REAL
1469 ** 'DOUB'        | SQLITE_AFF_REAL
1470 **
1471 ** If none of the substrings in the above table are found,
1472 ** SQLITE_AFF_NUMERIC is returned.
1473 */
1474 char sqlite3AffinityType(const char *zIn, Column *pCol){
1475   u32 h = 0;
1476   char aff = SQLITE_AFF_NUMERIC;
1477   const char *zChar = 0;
1478 
1479   assert( zIn!=0 );
1480   while( zIn[0] ){
1481     h = (h<<8) + sqlite3UpperToLower[(*zIn)&0xff];
1482     zIn++;
1483     if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){             /* CHAR */
1484       aff = SQLITE_AFF_TEXT;
1485       zChar = zIn;
1486     }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){       /* CLOB */
1487       aff = SQLITE_AFF_TEXT;
1488     }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){       /* TEXT */
1489       aff = SQLITE_AFF_TEXT;
1490     }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b')          /* BLOB */
1491         && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
1492       aff = SQLITE_AFF_BLOB;
1493       if( zIn[0]=='(' ) zChar = zIn;
1494 #ifndef SQLITE_OMIT_FLOATING_POINT
1495     }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l')          /* REAL */
1496         && aff==SQLITE_AFF_NUMERIC ){
1497       aff = SQLITE_AFF_REAL;
1498     }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a')          /* FLOA */
1499         && aff==SQLITE_AFF_NUMERIC ){
1500       aff = SQLITE_AFF_REAL;
1501     }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b')          /* DOUB */
1502         && aff==SQLITE_AFF_NUMERIC ){
1503       aff = SQLITE_AFF_REAL;
1504 #endif
1505     }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){    /* INT */
1506       aff = SQLITE_AFF_INTEGER;
1507       break;
1508     }
1509   }
1510 
1511   /* If pCol is not NULL, store an estimate of the field size.  The
1512   ** estimate is scaled so that the size of an integer is 1.  */
1513   if( pCol ){
1514     int v = 0;   /* default size is approx 4 bytes */
1515     if( aff<SQLITE_AFF_NUMERIC ){
1516       if( zChar ){
1517         while( zChar[0] ){
1518           if( sqlite3Isdigit(zChar[0]) ){
1519             /* BLOB(k), VARCHAR(k), CHAR(k) -> r=(k/4+1) */
1520             sqlite3GetInt32(zChar, &v);
1521             break;
1522           }
1523           zChar++;
1524         }
1525       }else{
1526         v = 16;   /* BLOB, TEXT, CLOB -> r=5  (approx 20 bytes)*/
1527       }
1528     }
1529 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
1530     if( v>=sqlite3GlobalConfig.szSorterRef ){
1531       pCol->colFlags |= COLFLAG_SORTERREF;
1532     }
1533 #endif
1534     v = v/4 + 1;
1535     if( v>255 ) v = 255;
1536     pCol->szEst = v;
1537   }
1538   return aff;
1539 }
1540 
1541 /*
1542 ** The expression is the default value for the most recently added column
1543 ** of the table currently under construction.
1544 **
1545 ** Default value expressions must be constant.  Raise an exception if this
1546 ** is not the case.
1547 **
1548 ** This routine is called by the parser while in the middle of
1549 ** parsing a CREATE TABLE statement.
1550 */
1551 void sqlite3AddDefaultValue(
1552   Parse *pParse,           /* Parsing context */
1553   Expr *pExpr,             /* The parsed expression of the default value */
1554   const char *zStart,      /* Start of the default value text */
1555   const char *zEnd         /* First character past end of defaut value text */
1556 ){
1557   Table *p;
1558   Column *pCol;
1559   sqlite3 *db = pParse->db;
1560   p = pParse->pNewTable;
1561   if( p!=0 ){
1562     int isInit = db->init.busy && db->init.iDb!=1;
1563     pCol = &(p->aCol[p->nCol-1]);
1564     if( !sqlite3ExprIsConstantOrFunction(pExpr, isInit) ){
1565       sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
1566           pCol->zName);
1567 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
1568     }else if( pCol->colFlags & COLFLAG_GENERATED ){
1569       testcase( pCol->colFlags & COLFLAG_VIRTUAL );
1570       testcase( pCol->colFlags & COLFLAG_STORED );
1571       sqlite3ErrorMsg(pParse, "cannot use DEFAULT on a generated column");
1572 #endif
1573     }else{
1574       /* A copy of pExpr is used instead of the original, as pExpr contains
1575       ** tokens that point to volatile memory.
1576       */
1577       Expr x;
1578       sqlite3ExprDelete(db, pCol->pDflt);
1579       memset(&x, 0, sizeof(x));
1580       x.op = TK_SPAN;
1581       x.u.zToken = sqlite3DbSpanDup(db, zStart, zEnd);
1582       x.pLeft = pExpr;
1583       x.flags = EP_Skip;
1584       pCol->pDflt = sqlite3ExprDup(db, &x, EXPRDUP_REDUCE);
1585       sqlite3DbFree(db, x.u.zToken);
1586     }
1587   }
1588   if( IN_RENAME_OBJECT ){
1589     sqlite3RenameExprUnmap(pParse, pExpr);
1590   }
1591   sqlite3ExprDelete(db, pExpr);
1592 }
1593 
1594 /*
1595 ** Backwards Compatibility Hack:
1596 **
1597 ** Historical versions of SQLite accepted strings as column names in
1598 ** indexes and PRIMARY KEY constraints and in UNIQUE constraints.  Example:
1599 **
1600 **     CREATE TABLE xyz(a,b,c,d,e,PRIMARY KEY('a'),UNIQUE('b','c' COLLATE trim)
1601 **     CREATE INDEX abc ON xyz('c','d' DESC,'e' COLLATE nocase DESC);
1602 **
1603 ** This is goofy.  But to preserve backwards compatibility we continue to
1604 ** accept it.  This routine does the necessary conversion.  It converts
1605 ** the expression given in its argument from a TK_STRING into a TK_ID
1606 ** if the expression is just a TK_STRING with an optional COLLATE clause.
1607 ** If the expression is anything other than TK_STRING, the expression is
1608 ** unchanged.
1609 */
1610 static void sqlite3StringToId(Expr *p){
1611   if( p->op==TK_STRING ){
1612     p->op = TK_ID;
1613   }else if( p->op==TK_COLLATE && p->pLeft->op==TK_STRING ){
1614     p->pLeft->op = TK_ID;
1615   }
1616 }
1617 
1618 /*
1619 ** Tag the given column as being part of the PRIMARY KEY
1620 */
1621 static void makeColumnPartOfPrimaryKey(Parse *pParse, Column *pCol){
1622   pCol->colFlags |= COLFLAG_PRIMKEY;
1623 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
1624   if( pCol->colFlags & COLFLAG_GENERATED ){
1625     testcase( pCol->colFlags & COLFLAG_VIRTUAL );
1626     testcase( pCol->colFlags & COLFLAG_STORED );
1627     sqlite3ErrorMsg(pParse,
1628       "generated columns cannot be part of the PRIMARY KEY");
1629   }
1630 #endif
1631 }
1632 
1633 /*
1634 ** Designate the PRIMARY KEY for the table.  pList is a list of names
1635 ** of columns that form the primary key.  If pList is NULL, then the
1636 ** most recently added column of the table is the primary key.
1637 **
1638 ** A table can have at most one primary key.  If the table already has
1639 ** a primary key (and this is the second primary key) then create an
1640 ** error.
1641 **
1642 ** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
1643 ** then we will try to use that column as the rowid.  Set the Table.iPKey
1644 ** field of the table under construction to be the index of the
1645 ** INTEGER PRIMARY KEY column.  Table.iPKey is set to -1 if there is
1646 ** no INTEGER PRIMARY KEY.
1647 **
1648 ** If the key is not an INTEGER PRIMARY KEY, then create a unique
1649 ** index for the key.  No index is created for INTEGER PRIMARY KEYs.
1650 */
1651 void sqlite3AddPrimaryKey(
1652   Parse *pParse,    /* Parsing context */
1653   ExprList *pList,  /* List of field names to be indexed */
1654   int onError,      /* What to do with a uniqueness conflict */
1655   int autoInc,      /* True if the AUTOINCREMENT keyword is present */
1656   int sortOrder     /* SQLITE_SO_ASC or SQLITE_SO_DESC */
1657 ){
1658   Table *pTab = pParse->pNewTable;
1659   Column *pCol = 0;
1660   int iCol = -1, i;
1661   int nTerm;
1662   if( pTab==0 ) goto primary_key_exit;
1663   if( pTab->tabFlags & TF_HasPrimaryKey ){
1664     sqlite3ErrorMsg(pParse,
1665       "table \"%s\" has more than one primary key", pTab->zName);
1666     goto primary_key_exit;
1667   }
1668   pTab->tabFlags |= TF_HasPrimaryKey;
1669   if( pList==0 ){
1670     iCol = pTab->nCol - 1;
1671     pCol = &pTab->aCol[iCol];
1672     makeColumnPartOfPrimaryKey(pParse, pCol);
1673     nTerm = 1;
1674   }else{
1675     nTerm = pList->nExpr;
1676     for(i=0; i<nTerm; i++){
1677       Expr *pCExpr = sqlite3ExprSkipCollate(pList->a[i].pExpr);
1678       assert( pCExpr!=0 );
1679       sqlite3StringToId(pCExpr);
1680       if( pCExpr->op==TK_ID ){
1681         const char *zCName = pCExpr->u.zToken;
1682         for(iCol=0; iCol<pTab->nCol; iCol++){
1683           if( sqlite3StrICmp(zCName, pTab->aCol[iCol].zName)==0 ){
1684             pCol = &pTab->aCol[iCol];
1685             makeColumnPartOfPrimaryKey(pParse, pCol);
1686             break;
1687           }
1688         }
1689       }
1690     }
1691   }
1692   if( nTerm==1
1693    && pCol
1694    && sqlite3StrICmp(sqlite3ColumnType(pCol,""), "INTEGER")==0
1695    && sortOrder!=SQLITE_SO_DESC
1696   ){
1697     if( IN_RENAME_OBJECT && pList ){
1698       Expr *pCExpr = sqlite3ExprSkipCollate(pList->a[0].pExpr);
1699       sqlite3RenameTokenRemap(pParse, &pTab->iPKey, pCExpr);
1700     }
1701     pTab->iPKey = iCol;
1702     pTab->keyConf = (u8)onError;
1703     assert( autoInc==0 || autoInc==1 );
1704     pTab->tabFlags |= autoInc*TF_Autoincrement;
1705     if( pList ) pParse->iPkSortOrder = pList->a[0].sortFlags;
1706     (void)sqlite3HasExplicitNulls(pParse, pList);
1707   }else if( autoInc ){
1708 #ifndef SQLITE_OMIT_AUTOINCREMENT
1709     sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
1710        "INTEGER PRIMARY KEY");
1711 #endif
1712   }else{
1713     sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0,
1714                            0, sortOrder, 0, SQLITE_IDXTYPE_PRIMARYKEY);
1715     pList = 0;
1716   }
1717 
1718 primary_key_exit:
1719   sqlite3ExprListDelete(pParse->db, pList);
1720   return;
1721 }
1722 
1723 /*
1724 ** Add a new CHECK constraint to the table currently under construction.
1725 */
1726 void sqlite3AddCheckConstraint(
1727   Parse *pParse,      /* Parsing context */
1728   Expr *pCheckExpr,   /* The check expression */
1729   const char *zStart, /* Opening "(" */
1730   const char *zEnd    /* Closing ")" */
1731 ){
1732 #ifndef SQLITE_OMIT_CHECK
1733   Table *pTab = pParse->pNewTable;
1734   sqlite3 *db = pParse->db;
1735   if( pTab && !IN_DECLARE_VTAB
1736    && !sqlite3BtreeIsReadonly(db->aDb[db->init.iDb].pBt)
1737   ){
1738     pTab->pCheck = sqlite3ExprListAppend(pParse, pTab->pCheck, pCheckExpr);
1739     if( pParse->constraintName.n ){
1740       sqlite3ExprListSetName(pParse, pTab->pCheck, &pParse->constraintName, 1);
1741     }else{
1742       Token t;
1743       for(zStart++; sqlite3Isspace(zStart[0]); zStart++){}
1744       while( sqlite3Isspace(zEnd[-1]) ){ zEnd--; }
1745       t.z = zStart;
1746       t.n = (int)(zEnd - t.z);
1747       sqlite3ExprListSetName(pParse, pTab->pCheck, &t, 1);
1748     }
1749   }else
1750 #endif
1751   {
1752     sqlite3ExprDelete(pParse->db, pCheckExpr);
1753   }
1754 }
1755 
1756 /*
1757 ** Set the collation function of the most recently parsed table column
1758 ** to the CollSeq given.
1759 */
1760 void sqlite3AddCollateType(Parse *pParse, Token *pToken){
1761   Table *p;
1762   int i;
1763   char *zColl;              /* Dequoted name of collation sequence */
1764   sqlite3 *db;
1765 
1766   if( (p = pParse->pNewTable)==0 || IN_RENAME_OBJECT ) return;
1767   i = p->nCol-1;
1768   db = pParse->db;
1769   zColl = sqlite3NameFromToken(db, pToken);
1770   if( !zColl ) return;
1771 
1772   if( sqlite3LocateCollSeq(pParse, zColl) ){
1773     Index *pIdx;
1774     sqlite3DbFree(db, p->aCol[i].zColl);
1775     p->aCol[i].zColl = zColl;
1776 
1777     /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
1778     ** then an index may have been created on this column before the
1779     ** collation type was added. Correct this if it is the case.
1780     */
1781     for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
1782       assert( pIdx->nKeyCol==1 );
1783       if( pIdx->aiColumn[0]==i ){
1784         pIdx->azColl[0] = p->aCol[i].zColl;
1785       }
1786     }
1787   }else{
1788     sqlite3DbFree(db, zColl);
1789   }
1790 }
1791 
1792 /* Change the most recently parsed column to be a GENERATED ALWAYS AS
1793 ** column.
1794 */
1795 void sqlite3AddGenerated(Parse *pParse, Expr *pExpr, Token *pType){
1796 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
1797   u8 eType = COLFLAG_VIRTUAL;
1798   Table *pTab = pParse->pNewTable;
1799   Column *pCol;
1800   if( pTab==0 ){
1801     /* generated column in an CREATE TABLE IF NOT EXISTS that already exists */
1802     goto generated_done;
1803   }
1804   pCol = &(pTab->aCol[pTab->nCol-1]);
1805   if( IN_DECLARE_VTAB ){
1806     sqlite3ErrorMsg(pParse, "virtual tables cannot use computed columns");
1807     goto generated_done;
1808   }
1809   if( pCol->pDflt ) goto generated_error;
1810   if( pType ){
1811     if( pType->n==7 && sqlite3StrNICmp("virtual",pType->z,7)==0 ){
1812       /* no-op */
1813     }else if( pType->n==6 && sqlite3StrNICmp("stored",pType->z,6)==0 ){
1814       eType = COLFLAG_STORED;
1815     }else{
1816       goto generated_error;
1817     }
1818   }
1819   if( eType==COLFLAG_VIRTUAL ) pTab->nNVCol--;
1820   pCol->colFlags |= eType;
1821   assert( TF_HasVirtual==COLFLAG_VIRTUAL );
1822   assert( TF_HasStored==COLFLAG_STORED );
1823   pTab->tabFlags |= eType;
1824   if( pCol->colFlags & COLFLAG_PRIMKEY ){
1825     makeColumnPartOfPrimaryKey(pParse, pCol); /* For the error message */
1826   }
1827   pCol->pDflt = pExpr;
1828   pExpr = 0;
1829   goto generated_done;
1830 
1831 generated_error:
1832   sqlite3ErrorMsg(pParse, "error in generated column \"%s\"",
1833                   pCol->zName);
1834 generated_done:
1835   sqlite3ExprDelete(pParse->db, pExpr);
1836 #else
1837   /* Throw and error for the GENERATED ALWAYS AS clause if the
1838   ** SQLITE_OMIT_GENERATED_COLUMNS compile-time option is used. */
1839   sqlite3ErrorMsg(pParse, "generated columns not supported");
1840   sqlite3ExprDelete(pParse->db, pExpr);
1841 #endif
1842 }
1843 
1844 /*
1845 ** Generate code that will increment the schema cookie.
1846 **
1847 ** The schema cookie is used to determine when the schema for the
1848 ** database changes.  After each schema change, the cookie value
1849 ** changes.  When a process first reads the schema it records the
1850 ** cookie.  Thereafter, whenever it goes to access the database,
1851 ** it checks the cookie to make sure the schema has not changed
1852 ** since it was last read.
1853 **
1854 ** This plan is not completely bullet-proof.  It is possible for
1855 ** the schema to change multiple times and for the cookie to be
1856 ** set back to prior value.  But schema changes are infrequent
1857 ** and the probability of hitting the same cookie value is only
1858 ** 1 chance in 2^32.  So we're safe enough.
1859 **
1860 ** IMPLEMENTATION-OF: R-34230-56049 SQLite automatically increments
1861 ** the schema-version whenever the schema changes.
1862 */
1863 void sqlite3ChangeCookie(Parse *pParse, int iDb){
1864   sqlite3 *db = pParse->db;
1865   Vdbe *v = pParse->pVdbe;
1866   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
1867   sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION,
1868                    (int)(1+(unsigned)db->aDb[iDb].pSchema->schema_cookie));
1869 }
1870 
1871 /*
1872 ** Measure the number of characters needed to output the given
1873 ** identifier.  The number returned includes any quotes used
1874 ** but does not include the null terminator.
1875 **
1876 ** The estimate is conservative.  It might be larger that what is
1877 ** really needed.
1878 */
1879 static int identLength(const char *z){
1880   int n;
1881   for(n=0; *z; n++, z++){
1882     if( *z=='"' ){ n++; }
1883   }
1884   return n + 2;
1885 }
1886 
1887 /*
1888 ** The first parameter is a pointer to an output buffer. The second
1889 ** parameter is a pointer to an integer that contains the offset at
1890 ** which to write into the output buffer. This function copies the
1891 ** nul-terminated string pointed to by the third parameter, zSignedIdent,
1892 ** to the specified offset in the buffer and updates *pIdx to refer
1893 ** to the first byte after the last byte written before returning.
1894 **
1895 ** If the string zSignedIdent consists entirely of alpha-numeric
1896 ** characters, does not begin with a digit and is not an SQL keyword,
1897 ** then it is copied to the output buffer exactly as it is. Otherwise,
1898 ** it is quoted using double-quotes.
1899 */
1900 static void identPut(char *z, int *pIdx, char *zSignedIdent){
1901   unsigned char *zIdent = (unsigned char*)zSignedIdent;
1902   int i, j, needQuote;
1903   i = *pIdx;
1904 
1905   for(j=0; zIdent[j]; j++){
1906     if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
1907   }
1908   needQuote = sqlite3Isdigit(zIdent[0])
1909             || sqlite3KeywordCode(zIdent, j)!=TK_ID
1910             || zIdent[j]!=0
1911             || j==0;
1912 
1913   if( needQuote ) z[i++] = '"';
1914   for(j=0; zIdent[j]; j++){
1915     z[i++] = zIdent[j];
1916     if( zIdent[j]=='"' ) z[i++] = '"';
1917   }
1918   if( needQuote ) z[i++] = '"';
1919   z[i] = 0;
1920   *pIdx = i;
1921 }
1922 
1923 /*
1924 ** Generate a CREATE TABLE statement appropriate for the given
1925 ** table.  Memory to hold the text of the statement is obtained
1926 ** from sqliteMalloc() and must be freed by the calling function.
1927 */
1928 static char *createTableStmt(sqlite3 *db, Table *p){
1929   int i, k, n;
1930   char *zStmt;
1931   char *zSep, *zSep2, *zEnd;
1932   Column *pCol;
1933   n = 0;
1934   for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
1935     n += identLength(pCol->zName) + 5;
1936   }
1937   n += identLength(p->zName);
1938   if( n<50 ){
1939     zSep = "";
1940     zSep2 = ",";
1941     zEnd = ")";
1942   }else{
1943     zSep = "\n  ";
1944     zSep2 = ",\n  ";
1945     zEnd = "\n)";
1946   }
1947   n += 35 + 6*p->nCol;
1948   zStmt = sqlite3DbMallocRaw(0, n);
1949   if( zStmt==0 ){
1950     sqlite3OomFault(db);
1951     return 0;
1952   }
1953   sqlite3_snprintf(n, zStmt, "CREATE TABLE ");
1954   k = sqlite3Strlen30(zStmt);
1955   identPut(zStmt, &k, p->zName);
1956   zStmt[k++] = '(';
1957   for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
1958     static const char * const azType[] = {
1959         /* SQLITE_AFF_BLOB    */ "",
1960         /* SQLITE_AFF_TEXT    */ " TEXT",
1961         /* SQLITE_AFF_NUMERIC */ " NUM",
1962         /* SQLITE_AFF_INTEGER */ " INT",
1963         /* SQLITE_AFF_REAL    */ " REAL"
1964     };
1965     int len;
1966     const char *zType;
1967 
1968     sqlite3_snprintf(n-k, &zStmt[k], zSep);
1969     k += sqlite3Strlen30(&zStmt[k]);
1970     zSep = zSep2;
1971     identPut(zStmt, &k, pCol->zName);
1972     assert( pCol->affinity-SQLITE_AFF_BLOB >= 0 );
1973     assert( pCol->affinity-SQLITE_AFF_BLOB < ArraySize(azType) );
1974     testcase( pCol->affinity==SQLITE_AFF_BLOB );
1975     testcase( pCol->affinity==SQLITE_AFF_TEXT );
1976     testcase( pCol->affinity==SQLITE_AFF_NUMERIC );
1977     testcase( pCol->affinity==SQLITE_AFF_INTEGER );
1978     testcase( pCol->affinity==SQLITE_AFF_REAL );
1979 
1980     zType = azType[pCol->affinity - SQLITE_AFF_BLOB];
1981     len = sqlite3Strlen30(zType);
1982     assert( pCol->affinity==SQLITE_AFF_BLOB
1983             || pCol->affinity==sqlite3AffinityType(zType, 0) );
1984     memcpy(&zStmt[k], zType, len);
1985     k += len;
1986     assert( k<=n );
1987   }
1988   sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
1989   return zStmt;
1990 }
1991 
1992 /*
1993 ** Resize an Index object to hold N columns total.  Return SQLITE_OK
1994 ** on success and SQLITE_NOMEM on an OOM error.
1995 */
1996 static int resizeIndexObject(sqlite3 *db, Index *pIdx, int N){
1997   char *zExtra;
1998   int nByte;
1999   if( pIdx->nColumn>=N ) return SQLITE_OK;
2000   assert( pIdx->isResized==0 );
2001   nByte = (sizeof(char*) + sizeof(LogEst) + sizeof(i16) + 1)*N;
2002   zExtra = sqlite3DbMallocZero(db, nByte);
2003   if( zExtra==0 ) return SQLITE_NOMEM_BKPT;
2004   memcpy(zExtra, pIdx->azColl, sizeof(char*)*pIdx->nColumn);
2005   pIdx->azColl = (const char**)zExtra;
2006   zExtra += sizeof(char*)*N;
2007   memcpy(zExtra, pIdx->aiRowLogEst, sizeof(LogEst)*(pIdx->nKeyCol+1));
2008   pIdx->aiRowLogEst = (LogEst*)zExtra;
2009   zExtra += sizeof(LogEst)*N;
2010   memcpy(zExtra, pIdx->aiColumn, sizeof(i16)*pIdx->nColumn);
2011   pIdx->aiColumn = (i16*)zExtra;
2012   zExtra += sizeof(i16)*N;
2013   memcpy(zExtra, pIdx->aSortOrder, pIdx->nColumn);
2014   pIdx->aSortOrder = (u8*)zExtra;
2015   pIdx->nColumn = N;
2016   pIdx->isResized = 1;
2017   return SQLITE_OK;
2018 }
2019 
2020 /*
2021 ** Estimate the total row width for a table.
2022 */
2023 static void estimateTableWidth(Table *pTab){
2024   unsigned wTable = 0;
2025   const Column *pTabCol;
2026   int i;
2027   for(i=pTab->nCol, pTabCol=pTab->aCol; i>0; i--, pTabCol++){
2028     wTable += pTabCol->szEst;
2029   }
2030   if( pTab->iPKey<0 ) wTable++;
2031   pTab->szTabRow = sqlite3LogEst(wTable*4);
2032 }
2033 
2034 /*
2035 ** Estimate the average size of a row for an index.
2036 */
2037 static void estimateIndexWidth(Index *pIdx){
2038   unsigned wIndex = 0;
2039   int i;
2040   const Column *aCol = pIdx->pTable->aCol;
2041   for(i=0; i<pIdx->nColumn; i++){
2042     i16 x = pIdx->aiColumn[i];
2043     assert( x<pIdx->pTable->nCol );
2044     wIndex += x<0 ? 1 : aCol[pIdx->aiColumn[i]].szEst;
2045   }
2046   pIdx->szIdxRow = sqlite3LogEst(wIndex*4);
2047 }
2048 
2049 /* Return true if column number x is any of the first nCol entries of aiCol[].
2050 ** This is used to determine if the column number x appears in any of the
2051 ** first nCol entries of an index.
2052 */
2053 static int hasColumn(const i16 *aiCol, int nCol, int x){
2054   while( nCol-- > 0 ){
2055     assert( aiCol[0]>=0 );
2056     if( x==*(aiCol++) ){
2057       return 1;
2058     }
2059   }
2060   return 0;
2061 }
2062 
2063 /*
2064 ** Return true if any of the first nKey entries of index pIdx exactly
2065 ** match the iCol-th entry of pPk.  pPk is always a WITHOUT ROWID
2066 ** PRIMARY KEY index.  pIdx is an index on the same table.  pIdx may
2067 ** or may not be the same index as pPk.
2068 **
2069 ** The first nKey entries of pIdx are guaranteed to be ordinary columns,
2070 ** not a rowid or expression.
2071 **
2072 ** This routine differs from hasColumn() in that both the column and the
2073 ** collating sequence must match for this routine, but for hasColumn() only
2074 ** the column name must match.
2075 */
2076 static int isDupColumn(Index *pIdx, int nKey, Index *pPk, int iCol){
2077   int i, j;
2078   assert( nKey<=pIdx->nColumn );
2079   assert( iCol<MAX(pPk->nColumn,pPk->nKeyCol) );
2080   assert( pPk->idxType==SQLITE_IDXTYPE_PRIMARYKEY );
2081   assert( pPk->pTable->tabFlags & TF_WithoutRowid );
2082   assert( pPk->pTable==pIdx->pTable );
2083   testcase( pPk==pIdx );
2084   j = pPk->aiColumn[iCol];
2085   assert( j!=XN_ROWID && j!=XN_EXPR );
2086   for(i=0; i<nKey; i++){
2087     assert( pIdx->aiColumn[i]>=0 || j>=0 );
2088     if( pIdx->aiColumn[i]==j
2089      && sqlite3StrICmp(pIdx->azColl[i], pPk->azColl[iCol])==0
2090     ){
2091       return 1;
2092     }
2093   }
2094   return 0;
2095 }
2096 
2097 /* Recompute the colNotIdxed field of the Index.
2098 **
2099 ** colNotIdxed is a bitmask that has a 0 bit representing each indexed
2100 ** columns that are within the first 63 columns of the table.  The
2101 ** high-order bit of colNotIdxed is always 1.  All unindexed columns
2102 ** of the table have a 1.
2103 **
2104 ** 2019-10-24:  For the purpose of this computation, virtual columns are
2105 ** not considered to be covered by the index, even if they are in the
2106 ** index, because we do not trust the logic in whereIndexExprTrans() to be
2107 ** able to find all instances of a reference to the indexed table column
2108 ** and convert them into references to the index.  Hence we always want
2109 ** the actual table at hand in order to recompute the virtual column, if
2110 ** necessary.
2111 **
2112 ** The colNotIdxed mask is AND-ed with the SrcList.a[].colUsed mask
2113 ** to determine if the index is covering index.
2114 */
2115 static void recomputeColumnsNotIndexed(Index *pIdx){
2116   Bitmask m = 0;
2117   int j;
2118   Table *pTab = pIdx->pTable;
2119   for(j=pIdx->nColumn-1; j>=0; j--){
2120     int x = pIdx->aiColumn[j];
2121     if( x>=0 && (pTab->aCol[x].colFlags & COLFLAG_VIRTUAL)==0 ){
2122       testcase( x==BMS-1 );
2123       testcase( x==BMS-2 );
2124       if( x<BMS-1 ) m |= MASKBIT(x);
2125     }
2126   }
2127   pIdx->colNotIdxed = ~m;
2128   assert( (pIdx->colNotIdxed>>63)==1 );
2129 }
2130 
2131 /*
2132 ** This routine runs at the end of parsing a CREATE TABLE statement that
2133 ** has a WITHOUT ROWID clause.  The job of this routine is to convert both
2134 ** internal schema data structures and the generated VDBE code so that they
2135 ** are appropriate for a WITHOUT ROWID table instead of a rowid table.
2136 ** Changes include:
2137 **
2138 **     (1)  Set all columns of the PRIMARY KEY schema object to be NOT NULL.
2139 **     (2)  Convert P3 parameter of the OP_CreateBtree from BTREE_INTKEY
2140 **          into BTREE_BLOBKEY.
2141 **     (3)  Bypass the creation of the sqlite_schema table entry
2142 **          for the PRIMARY KEY as the primary key index is now
2143 **          identified by the sqlite_schema table entry of the table itself.
2144 **     (4)  Set the Index.tnum of the PRIMARY KEY Index object in the
2145 **          schema to the rootpage from the main table.
2146 **     (5)  Add all table columns to the PRIMARY KEY Index object
2147 **          so that the PRIMARY KEY is a covering index.  The surplus
2148 **          columns are part of KeyInfo.nAllField and are not used for
2149 **          sorting or lookup or uniqueness checks.
2150 **     (6)  Replace the rowid tail on all automatically generated UNIQUE
2151 **          indices with the PRIMARY KEY columns.
2152 **
2153 ** For virtual tables, only (1) is performed.
2154 */
2155 static void convertToWithoutRowidTable(Parse *pParse, Table *pTab){
2156   Index *pIdx;
2157   Index *pPk;
2158   int nPk;
2159   int nExtra;
2160   int i, j;
2161   sqlite3 *db = pParse->db;
2162   Vdbe *v = pParse->pVdbe;
2163 
2164   /* Mark every PRIMARY KEY column as NOT NULL (except for imposter tables)
2165   */
2166   if( !db->init.imposterTable ){
2167     for(i=0; i<pTab->nCol; i++){
2168       if( (pTab->aCol[i].colFlags & COLFLAG_PRIMKEY)!=0 ){
2169         pTab->aCol[i].notNull = OE_Abort;
2170       }
2171     }
2172     pTab->tabFlags |= TF_HasNotNull;
2173   }
2174 
2175   /* Convert the P3 operand of the OP_CreateBtree opcode from BTREE_INTKEY
2176   ** into BTREE_BLOBKEY.
2177   */
2178   assert( !pParse->bReturning );
2179   if( pParse->u1.addrCrTab ){
2180     assert( v );
2181     sqlite3VdbeChangeP3(v, pParse->u1.addrCrTab, BTREE_BLOBKEY);
2182   }
2183 
2184   /* Locate the PRIMARY KEY index.  Or, if this table was originally
2185   ** an INTEGER PRIMARY KEY table, create a new PRIMARY KEY index.
2186   */
2187   if( pTab->iPKey>=0 ){
2188     ExprList *pList;
2189     Token ipkToken;
2190     sqlite3TokenInit(&ipkToken, pTab->aCol[pTab->iPKey].zName);
2191     pList = sqlite3ExprListAppend(pParse, 0,
2192                   sqlite3ExprAlloc(db, TK_ID, &ipkToken, 0));
2193     if( pList==0 ) return;
2194     if( IN_RENAME_OBJECT ){
2195       sqlite3RenameTokenRemap(pParse, pList->a[0].pExpr, &pTab->iPKey);
2196     }
2197     pList->a[0].sortFlags = pParse->iPkSortOrder;
2198     assert( pParse->pNewTable==pTab );
2199     pTab->iPKey = -1;
2200     sqlite3CreateIndex(pParse, 0, 0, 0, pList, pTab->keyConf, 0, 0, 0, 0,
2201                        SQLITE_IDXTYPE_PRIMARYKEY);
2202     if( db->mallocFailed || pParse->nErr ) return;
2203     pPk = sqlite3PrimaryKeyIndex(pTab);
2204     assert( pPk->nKeyCol==1 );
2205   }else{
2206     pPk = sqlite3PrimaryKeyIndex(pTab);
2207     assert( pPk!=0 );
2208 
2209     /*
2210     ** Remove all redundant columns from the PRIMARY KEY.  For example, change
2211     ** "PRIMARY KEY(a,b,a,b,c,b,c,d)" into just "PRIMARY KEY(a,b,c,d)".  Later
2212     ** code assumes the PRIMARY KEY contains no repeated columns.
2213     */
2214     for(i=j=1; i<pPk->nKeyCol; i++){
2215       if( isDupColumn(pPk, j, pPk, i) ){
2216         pPk->nColumn--;
2217       }else{
2218         testcase( hasColumn(pPk->aiColumn, j, pPk->aiColumn[i]) );
2219         pPk->azColl[j] = pPk->azColl[i];
2220         pPk->aSortOrder[j] = pPk->aSortOrder[i];
2221         pPk->aiColumn[j++] = pPk->aiColumn[i];
2222       }
2223     }
2224     pPk->nKeyCol = j;
2225   }
2226   assert( pPk!=0 );
2227   pPk->isCovering = 1;
2228   if( !db->init.imposterTable ) pPk->uniqNotNull = 1;
2229   nPk = pPk->nColumn = pPk->nKeyCol;
2230 
2231   /* Bypass the creation of the PRIMARY KEY btree and the sqlite_schema
2232   ** table entry. This is only required if currently generating VDBE
2233   ** code for a CREATE TABLE (not when parsing one as part of reading
2234   ** a database schema).  */
2235   if( v && pPk->tnum>0 ){
2236     assert( db->init.busy==0 );
2237     sqlite3VdbeChangeOpcode(v, (int)pPk->tnum, OP_Goto);
2238   }
2239 
2240   /* The root page of the PRIMARY KEY is the table root page */
2241   pPk->tnum = pTab->tnum;
2242 
2243   /* Update the in-memory representation of all UNIQUE indices by converting
2244   ** the final rowid column into one or more columns of the PRIMARY KEY.
2245   */
2246   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
2247     int n;
2248     if( IsPrimaryKeyIndex(pIdx) ) continue;
2249     for(i=n=0; i<nPk; i++){
2250       if( !isDupColumn(pIdx, pIdx->nKeyCol, pPk, i) ){
2251         testcase( hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) );
2252         n++;
2253       }
2254     }
2255     if( n==0 ){
2256       /* This index is a superset of the primary key */
2257       pIdx->nColumn = pIdx->nKeyCol;
2258       continue;
2259     }
2260     if( resizeIndexObject(db, pIdx, pIdx->nKeyCol+n) ) return;
2261     for(i=0, j=pIdx->nKeyCol; i<nPk; i++){
2262       if( !isDupColumn(pIdx, pIdx->nKeyCol, pPk, i) ){
2263         testcase( hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) );
2264         pIdx->aiColumn[j] = pPk->aiColumn[i];
2265         pIdx->azColl[j] = pPk->azColl[i];
2266         if( pPk->aSortOrder[i] ){
2267           /* See ticket https://www.sqlite.org/src/info/bba7b69f9849b5bf */
2268           pIdx->bAscKeyBug = 1;
2269         }
2270         j++;
2271       }
2272     }
2273     assert( pIdx->nColumn>=pIdx->nKeyCol+n );
2274     assert( pIdx->nColumn>=j );
2275   }
2276 
2277   /* Add all table columns to the PRIMARY KEY index
2278   */
2279   nExtra = 0;
2280   for(i=0; i<pTab->nCol; i++){
2281     if( !hasColumn(pPk->aiColumn, nPk, i)
2282      && (pTab->aCol[i].colFlags & COLFLAG_VIRTUAL)==0 ) nExtra++;
2283   }
2284   if( resizeIndexObject(db, pPk, nPk+nExtra) ) return;
2285   for(i=0, j=nPk; i<pTab->nCol; i++){
2286     if( !hasColumn(pPk->aiColumn, j, i)
2287      && (pTab->aCol[i].colFlags & COLFLAG_VIRTUAL)==0
2288     ){
2289       assert( j<pPk->nColumn );
2290       pPk->aiColumn[j] = i;
2291       pPk->azColl[j] = sqlite3StrBINARY;
2292       j++;
2293     }
2294   }
2295   assert( pPk->nColumn==j );
2296   assert( pTab->nNVCol<=j );
2297   recomputeColumnsNotIndexed(pPk);
2298 }
2299 
2300 
2301 #ifndef SQLITE_OMIT_VIRTUALTABLE
2302 /*
2303 ** Return true if pTab is a virtual table and zName is a shadow table name
2304 ** for that virtual table.
2305 */
2306 int sqlite3IsShadowTableOf(sqlite3 *db, Table *pTab, const char *zName){
2307   int nName;                    /* Length of zName */
2308   Module *pMod;                 /* Module for the virtual table */
2309 
2310   if( !IsVirtual(pTab) ) return 0;
2311   nName = sqlite3Strlen30(pTab->zName);
2312   if( sqlite3_strnicmp(zName, pTab->zName, nName)!=0 ) return 0;
2313   if( zName[nName]!='_' ) return 0;
2314   pMod = (Module*)sqlite3HashFind(&db->aModule, pTab->azModuleArg[0]);
2315   if( pMod==0 ) return 0;
2316   if( pMod->pModule->iVersion<3 ) return 0;
2317   if( pMod->pModule->xShadowName==0 ) return 0;
2318   return pMod->pModule->xShadowName(zName+nName+1);
2319 }
2320 #endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
2321 
2322 #ifndef SQLITE_OMIT_VIRTUALTABLE
2323 /*
2324 ** Return true if zName is a shadow table name in the current database
2325 ** connection.
2326 **
2327 ** zName is temporarily modified while this routine is running, but is
2328 ** restored to its original value prior to this routine returning.
2329 */
2330 int sqlite3ShadowTableName(sqlite3 *db, const char *zName){
2331   char *zTail;                  /* Pointer to the last "_" in zName */
2332   Table *pTab;                  /* Table that zName is a shadow of */
2333   zTail = strrchr(zName, '_');
2334   if( zTail==0 ) return 0;
2335   *zTail = 0;
2336   pTab = sqlite3FindTable(db, zName, 0);
2337   *zTail = '_';
2338   if( pTab==0 ) return 0;
2339   if( !IsVirtual(pTab) ) return 0;
2340   return sqlite3IsShadowTableOf(db, pTab, zName);
2341 }
2342 #endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
2343 
2344 
2345 #ifdef SQLITE_DEBUG
2346 /*
2347 ** Mark all nodes of an expression as EP_Immutable, indicating that
2348 ** they should not be changed.  Expressions attached to a table or
2349 ** index definition are tagged this way to help ensure that we do
2350 ** not pass them into code generator routines by mistake.
2351 */
2352 static int markImmutableExprStep(Walker *pWalker, Expr *pExpr){
2353   ExprSetVVAProperty(pExpr, EP_Immutable);
2354   return WRC_Continue;
2355 }
2356 static void markExprListImmutable(ExprList *pList){
2357   if( pList ){
2358     Walker w;
2359     memset(&w, 0, sizeof(w));
2360     w.xExprCallback = markImmutableExprStep;
2361     w.xSelectCallback = sqlite3SelectWalkNoop;
2362     w.xSelectCallback2 = 0;
2363     sqlite3WalkExprList(&w, pList);
2364   }
2365 }
2366 #else
2367 #define markExprListImmutable(X)  /* no-op */
2368 #endif /* SQLITE_DEBUG */
2369 
2370 
2371 /*
2372 ** This routine is called to report the final ")" that terminates
2373 ** a CREATE TABLE statement.
2374 **
2375 ** The table structure that other action routines have been building
2376 ** is added to the internal hash tables, assuming no errors have
2377 ** occurred.
2378 **
2379 ** An entry for the table is made in the schema table on disk, unless
2380 ** this is a temporary table or db->init.busy==1.  When db->init.busy==1
2381 ** it means we are reading the sqlite_schema table because we just
2382 ** connected to the database or because the sqlite_schema table has
2383 ** recently changed, so the entry for this table already exists in
2384 ** the sqlite_schema table.  We do not want to create it again.
2385 **
2386 ** If the pSelect argument is not NULL, it means that this routine
2387 ** was called to create a table generated from a
2388 ** "CREATE TABLE ... AS SELECT ..." statement.  The column names of
2389 ** the new table will match the result set of the SELECT.
2390 */
2391 void sqlite3EndTable(
2392   Parse *pParse,          /* Parse context */
2393   Token *pCons,           /* The ',' token after the last column defn. */
2394   Token *pEnd,            /* The ')' before options in the CREATE TABLE */
2395   u8 tabOpts,             /* Extra table options. Usually 0. */
2396   Select *pSelect         /* Select from a "CREATE ... AS SELECT" */
2397 ){
2398   Table *p;                 /* The new table */
2399   sqlite3 *db = pParse->db; /* The database connection */
2400   int iDb;                  /* Database in which the table lives */
2401   Index *pIdx;              /* An implied index of the table */
2402 
2403   if( pEnd==0 && pSelect==0 ){
2404     return;
2405   }
2406   assert( !db->mallocFailed );
2407   p = pParse->pNewTable;
2408   if( p==0 ) return;
2409 
2410   if( pSelect==0 && sqlite3ShadowTableName(db, p->zName) ){
2411     p->tabFlags |= TF_Shadow;
2412   }
2413 
2414   /* If the db->init.busy is 1 it means we are reading the SQL off the
2415   ** "sqlite_schema" or "sqlite_temp_schema" table on the disk.
2416   ** So do not write to the disk again.  Extract the root page number
2417   ** for the table from the db->init.newTnum field.  (The page number
2418   ** should have been put there by the sqliteOpenCb routine.)
2419   **
2420   ** If the root page number is 1, that means this is the sqlite_schema
2421   ** table itself.  So mark it read-only.
2422   */
2423   if( db->init.busy ){
2424     if( pSelect ){
2425       sqlite3ErrorMsg(pParse, "");
2426       return;
2427     }
2428     p->tnum = db->init.newTnum;
2429     if( p->tnum==1 ) p->tabFlags |= TF_Readonly;
2430   }
2431 
2432   assert( (p->tabFlags & TF_HasPrimaryKey)==0
2433        || p->iPKey>=0 || sqlite3PrimaryKeyIndex(p)!=0 );
2434   assert( (p->tabFlags & TF_HasPrimaryKey)!=0
2435        || (p->iPKey<0 && sqlite3PrimaryKeyIndex(p)==0) );
2436 
2437   /* Special processing for WITHOUT ROWID Tables */
2438   if( tabOpts & TF_WithoutRowid ){
2439     if( (p->tabFlags & TF_Autoincrement) ){
2440       sqlite3ErrorMsg(pParse,
2441           "AUTOINCREMENT not allowed on WITHOUT ROWID tables");
2442       return;
2443     }
2444     if( (p->tabFlags & TF_HasPrimaryKey)==0 ){
2445       sqlite3ErrorMsg(pParse, "PRIMARY KEY missing on table %s", p->zName);
2446       return;
2447     }
2448     p->tabFlags |= TF_WithoutRowid | TF_NoVisibleRowid;
2449     convertToWithoutRowidTable(pParse, p);
2450   }
2451   iDb = sqlite3SchemaToIndex(db, p->pSchema);
2452 
2453 #ifndef SQLITE_OMIT_CHECK
2454   /* Resolve names in all CHECK constraint expressions.
2455   */
2456   if( p->pCheck ){
2457     sqlite3ResolveSelfReference(pParse, p, NC_IsCheck, 0, p->pCheck);
2458     if( pParse->nErr ){
2459       /* If errors are seen, delete the CHECK constraints now, else they might
2460       ** actually be used if PRAGMA writable_schema=ON is set. */
2461       sqlite3ExprListDelete(db, p->pCheck);
2462       p->pCheck = 0;
2463     }else{
2464       markExprListImmutable(p->pCheck);
2465     }
2466   }
2467 #endif /* !defined(SQLITE_OMIT_CHECK) */
2468 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
2469   if( p->tabFlags & TF_HasGenerated ){
2470     int ii, nNG = 0;
2471     testcase( p->tabFlags & TF_HasVirtual );
2472     testcase( p->tabFlags & TF_HasStored );
2473     for(ii=0; ii<p->nCol; ii++){
2474       u32 colFlags = p->aCol[ii].colFlags;
2475       if( (colFlags & COLFLAG_GENERATED)!=0 ){
2476         Expr *pX = p->aCol[ii].pDflt;
2477         testcase( colFlags & COLFLAG_VIRTUAL );
2478         testcase( colFlags & COLFLAG_STORED );
2479         if( sqlite3ResolveSelfReference(pParse, p, NC_GenCol, pX, 0) ){
2480           /* If there are errors in resolving the expression, change the
2481           ** expression to a NULL.  This prevents code generators that operate
2482           ** on the expression from inserting extra parts into the expression
2483           ** tree that have been allocated from lookaside memory, which is
2484           ** illegal in a schema and will lead to errors or heap corruption
2485           ** when the database connection closes. */
2486           sqlite3ExprDelete(db, pX);
2487           p->aCol[ii].pDflt = sqlite3ExprAlloc(db, TK_NULL, 0, 0);
2488         }
2489       }else{
2490         nNG++;
2491       }
2492     }
2493     if( nNG==0 ){
2494       sqlite3ErrorMsg(pParse, "must have at least one non-generated column");
2495       return;
2496     }
2497   }
2498 #endif
2499 
2500   /* Estimate the average row size for the table and for all implied indices */
2501   estimateTableWidth(p);
2502   for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
2503     estimateIndexWidth(pIdx);
2504   }
2505 
2506   /* If not initializing, then create a record for the new table
2507   ** in the schema table of the database.
2508   **
2509   ** If this is a TEMPORARY table, write the entry into the auxiliary
2510   ** file instead of into the main database file.
2511   */
2512   if( !db->init.busy ){
2513     int n;
2514     Vdbe *v;
2515     char *zType;    /* "view" or "table" */
2516     char *zType2;   /* "VIEW" or "TABLE" */
2517     char *zStmt;    /* Text of the CREATE TABLE or CREATE VIEW statement */
2518 
2519     v = sqlite3GetVdbe(pParse);
2520     if( NEVER(v==0) ) return;
2521 
2522     sqlite3VdbeAddOp1(v, OP_Close, 0);
2523 
2524     /*
2525     ** Initialize zType for the new view or table.
2526     */
2527     if( p->pSelect==0 ){
2528       /* A regular table */
2529       zType = "table";
2530       zType2 = "TABLE";
2531 #ifndef SQLITE_OMIT_VIEW
2532     }else{
2533       /* A view */
2534       zType = "view";
2535       zType2 = "VIEW";
2536 #endif
2537     }
2538 
2539     /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
2540     ** statement to populate the new table. The root-page number for the
2541     ** new table is in register pParse->regRoot.
2542     **
2543     ** Once the SELECT has been coded by sqlite3Select(), it is in a
2544     ** suitable state to query for the column names and types to be used
2545     ** by the new table.
2546     **
2547     ** A shared-cache write-lock is not required to write to the new table,
2548     ** as a schema-lock must have already been obtained to create it. Since
2549     ** a schema-lock excludes all other database users, the write-lock would
2550     ** be redundant.
2551     */
2552     if( pSelect ){
2553       SelectDest dest;    /* Where the SELECT should store results */
2554       int regYield;       /* Register holding co-routine entry-point */
2555       int addrTop;        /* Top of the co-routine */
2556       int regRec;         /* A record to be insert into the new table */
2557       int regRowid;       /* Rowid of the next row to insert */
2558       int addrInsLoop;    /* Top of the loop for inserting rows */
2559       Table *pSelTab;     /* A table that describes the SELECT results */
2560 
2561       regYield = ++pParse->nMem;
2562       regRec = ++pParse->nMem;
2563       regRowid = ++pParse->nMem;
2564       assert(pParse->nTab==1);
2565       sqlite3MayAbort(pParse);
2566       sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb);
2567       sqlite3VdbeChangeP5(v, OPFLAG_P2ISREG);
2568       pParse->nTab = 2;
2569       addrTop = sqlite3VdbeCurrentAddr(v) + 1;
2570       sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, addrTop);
2571       if( pParse->nErr ) return;
2572       pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect, SQLITE_AFF_BLOB);
2573       if( pSelTab==0 ) return;
2574       assert( p->aCol==0 );
2575       p->nCol = p->nNVCol = pSelTab->nCol;
2576       p->aCol = pSelTab->aCol;
2577       pSelTab->nCol = 0;
2578       pSelTab->aCol = 0;
2579       sqlite3DeleteTable(db, pSelTab);
2580       sqlite3SelectDestInit(&dest, SRT_Coroutine, regYield);
2581       sqlite3Select(pParse, pSelect, &dest);
2582       if( pParse->nErr ) return;
2583       sqlite3VdbeEndCoroutine(v, regYield);
2584       sqlite3VdbeJumpHere(v, addrTop - 1);
2585       addrInsLoop = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
2586       VdbeCoverage(v);
2587       sqlite3VdbeAddOp3(v, OP_MakeRecord, dest.iSdst, dest.nSdst, regRec);
2588       sqlite3TableAffinity(v, p, 0);
2589       sqlite3VdbeAddOp2(v, OP_NewRowid, 1, regRowid);
2590       sqlite3VdbeAddOp3(v, OP_Insert, 1, regRec, regRowid);
2591       sqlite3VdbeGoto(v, addrInsLoop);
2592       sqlite3VdbeJumpHere(v, addrInsLoop);
2593       sqlite3VdbeAddOp1(v, OP_Close, 1);
2594     }
2595 
2596     /* Compute the complete text of the CREATE statement */
2597     if( pSelect ){
2598       zStmt = createTableStmt(db, p);
2599     }else{
2600       Token *pEnd2 = tabOpts ? &pParse->sLastToken : pEnd;
2601       n = (int)(pEnd2->z - pParse->sNameToken.z);
2602       if( pEnd2->z[0]!=';' ) n += pEnd2->n;
2603       zStmt = sqlite3MPrintf(db,
2604           "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
2605       );
2606     }
2607 
2608     /* A slot for the record has already been allocated in the
2609     ** schema table.  We just need to update that slot with all
2610     ** the information we've collected.
2611     */
2612     sqlite3NestedParse(pParse,
2613       "UPDATE %Q." DFLT_SCHEMA_TABLE
2614       " SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q"
2615       " WHERE rowid=#%d",
2616       db->aDb[iDb].zDbSName,
2617       zType,
2618       p->zName,
2619       p->zName,
2620       pParse->regRoot,
2621       zStmt,
2622       pParse->regRowid
2623     );
2624     sqlite3DbFree(db, zStmt);
2625     sqlite3ChangeCookie(pParse, iDb);
2626 
2627 #ifndef SQLITE_OMIT_AUTOINCREMENT
2628     /* Check to see if we need to create an sqlite_sequence table for
2629     ** keeping track of autoincrement keys.
2630     */
2631     if( (p->tabFlags & TF_Autoincrement)!=0 ){
2632       Db *pDb = &db->aDb[iDb];
2633       assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
2634       if( pDb->pSchema->pSeqTab==0 ){
2635         sqlite3NestedParse(pParse,
2636           "CREATE TABLE %Q.sqlite_sequence(name,seq)",
2637           pDb->zDbSName
2638         );
2639       }
2640     }
2641 #endif
2642 
2643     /* Reparse everything to update our internal data structures */
2644     sqlite3VdbeAddParseSchemaOp(v, iDb,
2645            sqlite3MPrintf(db, "tbl_name='%q' AND type!='trigger'", p->zName),0);
2646   }
2647 
2648   /* Add the table to the in-memory representation of the database.
2649   */
2650   if( db->init.busy ){
2651     Table *pOld;
2652     Schema *pSchema = p->pSchema;
2653     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
2654     pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName, p);
2655     if( pOld ){
2656       assert( p==pOld );  /* Malloc must have failed inside HashInsert() */
2657       sqlite3OomFault(db);
2658       return;
2659     }
2660     pParse->pNewTable = 0;
2661     db->mDbFlags |= DBFLAG_SchemaChange;
2662   }
2663 
2664 #ifndef SQLITE_OMIT_ALTERTABLE
2665   if( !pSelect && !p->pSelect ){
2666     assert( pCons && pEnd );
2667     if( pCons->z==0 ){
2668       pCons = pEnd;
2669     }
2670     p->addColOffset = 13 + (int)(pCons->z - pParse->sNameToken.z);
2671   }
2672 #endif
2673 }
2674 
2675 #ifndef SQLITE_OMIT_VIEW
2676 /*
2677 ** The parser calls this routine in order to create a new VIEW
2678 */
2679 void sqlite3CreateView(
2680   Parse *pParse,     /* The parsing context */
2681   Token *pBegin,     /* The CREATE token that begins the statement */
2682   Token *pName1,     /* The token that holds the name of the view */
2683   Token *pName2,     /* The token that holds the name of the view */
2684   ExprList *pCNames, /* Optional list of view column names */
2685   Select *pSelect,   /* A SELECT statement that will become the new view */
2686   int isTemp,        /* TRUE for a TEMPORARY view */
2687   int noErr          /* Suppress error messages if VIEW already exists */
2688 ){
2689   Table *p;
2690   int n;
2691   const char *z;
2692   Token sEnd;
2693   DbFixer sFix;
2694   Token *pName = 0;
2695   int iDb;
2696   sqlite3 *db = pParse->db;
2697 
2698   if( pParse->nVar>0 ){
2699     sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
2700     goto create_view_fail;
2701   }
2702   sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
2703   p = pParse->pNewTable;
2704   if( p==0 || pParse->nErr ) goto create_view_fail;
2705   sqlite3TwoPartName(pParse, pName1, pName2, &pName);
2706   iDb = sqlite3SchemaToIndex(db, p->pSchema);
2707   sqlite3FixInit(&sFix, pParse, iDb, "view", pName);
2708   if( sqlite3FixSelect(&sFix, pSelect) ) goto create_view_fail;
2709 
2710   /* Make a copy of the entire SELECT statement that defines the view.
2711   ** This will force all the Expr.token.z values to be dynamically
2712   ** allocated rather than point to the input string - which means that
2713   ** they will persist after the current sqlite3_exec() call returns.
2714   */
2715   pSelect->selFlags |= SF_View;
2716   if( IN_RENAME_OBJECT ){
2717     p->pSelect = pSelect;
2718     pSelect = 0;
2719   }else{
2720     p->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
2721   }
2722   p->pCheck = sqlite3ExprListDup(db, pCNames, EXPRDUP_REDUCE);
2723   if( db->mallocFailed ) goto create_view_fail;
2724 
2725   /* Locate the end of the CREATE VIEW statement.  Make sEnd point to
2726   ** the end.
2727   */
2728   sEnd = pParse->sLastToken;
2729   assert( sEnd.z[0]!=0 || sEnd.n==0 );
2730   if( sEnd.z[0]!=';' ){
2731     sEnd.z += sEnd.n;
2732   }
2733   sEnd.n = 0;
2734   n = (int)(sEnd.z - pBegin->z);
2735   assert( n>0 );
2736   z = pBegin->z;
2737   while( sqlite3Isspace(z[n-1]) ){ n--; }
2738   sEnd.z = &z[n-1];
2739   sEnd.n = 1;
2740 
2741   /* Use sqlite3EndTable() to add the view to the schema table */
2742   sqlite3EndTable(pParse, 0, &sEnd, 0, 0);
2743 
2744 create_view_fail:
2745   sqlite3SelectDelete(db, pSelect);
2746   if( IN_RENAME_OBJECT ){
2747     sqlite3RenameExprlistUnmap(pParse, pCNames);
2748   }
2749   sqlite3ExprListDelete(db, pCNames);
2750   return;
2751 }
2752 #endif /* SQLITE_OMIT_VIEW */
2753 
2754 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
2755 /*
2756 ** The Table structure pTable is really a VIEW.  Fill in the names of
2757 ** the columns of the view in the pTable structure.  Return the number
2758 ** of errors.  If an error is seen leave an error message in pParse->zErrMsg.
2759 */
2760 int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
2761   Table *pSelTab;   /* A fake table from which we get the result set */
2762   Select *pSel;     /* Copy of the SELECT that implements the view */
2763   int nErr = 0;     /* Number of errors encountered */
2764   int n;            /* Temporarily holds the number of cursors assigned */
2765   sqlite3 *db = pParse->db;  /* Database connection for malloc errors */
2766 #ifndef SQLITE_OMIT_VIRTUALTABLE
2767   int rc;
2768 #endif
2769 #ifndef SQLITE_OMIT_AUTHORIZATION
2770   sqlite3_xauth xAuth;       /* Saved xAuth pointer */
2771 #endif
2772 
2773   assert( pTable );
2774 
2775 #ifndef SQLITE_OMIT_VIRTUALTABLE
2776   db->nSchemaLock++;
2777   rc = sqlite3VtabCallConnect(pParse, pTable);
2778   db->nSchemaLock--;
2779   if( rc ){
2780     return 1;
2781   }
2782   if( IsVirtual(pTable) ) return 0;
2783 #endif
2784 
2785 #ifndef SQLITE_OMIT_VIEW
2786   /* A positive nCol means the columns names for this view are
2787   ** already known.
2788   */
2789   if( pTable->nCol>0 ) return 0;
2790 
2791   /* A negative nCol is a special marker meaning that we are currently
2792   ** trying to compute the column names.  If we enter this routine with
2793   ** a negative nCol, it means two or more views form a loop, like this:
2794   **
2795   **     CREATE VIEW one AS SELECT * FROM two;
2796   **     CREATE VIEW two AS SELECT * FROM one;
2797   **
2798   ** Actually, the error above is now caught prior to reaching this point.
2799   ** But the following test is still important as it does come up
2800   ** in the following:
2801   **
2802   **     CREATE TABLE main.ex1(a);
2803   **     CREATE TEMP VIEW ex1 AS SELECT a FROM ex1;
2804   **     SELECT * FROM temp.ex1;
2805   */
2806   if( pTable->nCol<0 ){
2807     sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
2808     return 1;
2809   }
2810   assert( pTable->nCol>=0 );
2811 
2812   /* If we get this far, it means we need to compute the table names.
2813   ** Note that the call to sqlite3ResultSetOfSelect() will expand any
2814   ** "*" elements in the results set of the view and will assign cursors
2815   ** to the elements of the FROM clause.  But we do not want these changes
2816   ** to be permanent.  So the computation is done on a copy of the SELECT
2817   ** statement that defines the view.
2818   */
2819   assert( pTable->pSelect );
2820   pSel = sqlite3SelectDup(db, pTable->pSelect, 0);
2821   if( pSel ){
2822     u8 eParseMode = pParse->eParseMode;
2823     pParse->eParseMode = PARSE_MODE_NORMAL;
2824     n = pParse->nTab;
2825     sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
2826     pTable->nCol = -1;
2827     DisableLookaside;
2828 #ifndef SQLITE_OMIT_AUTHORIZATION
2829     xAuth = db->xAuth;
2830     db->xAuth = 0;
2831     pSelTab = sqlite3ResultSetOfSelect(pParse, pSel, SQLITE_AFF_NONE);
2832     db->xAuth = xAuth;
2833 #else
2834     pSelTab = sqlite3ResultSetOfSelect(pParse, pSel, SQLITE_AFF_NONE);
2835 #endif
2836     pParse->nTab = n;
2837     if( pSelTab==0 ){
2838       pTable->nCol = 0;
2839       nErr++;
2840     }else if( pTable->pCheck ){
2841       /* CREATE VIEW name(arglist) AS ...
2842       ** The names of the columns in the table are taken from
2843       ** arglist which is stored in pTable->pCheck.  The pCheck field
2844       ** normally holds CHECK constraints on an ordinary table, but for
2845       ** a VIEW it holds the list of column names.
2846       */
2847       sqlite3ColumnsFromExprList(pParse, pTable->pCheck,
2848                                  &pTable->nCol, &pTable->aCol);
2849       if( db->mallocFailed==0
2850        && pParse->nErr==0
2851        && pTable->nCol==pSel->pEList->nExpr
2852       ){
2853         sqlite3SelectAddColumnTypeAndCollation(pParse, pTable, pSel,
2854                                                SQLITE_AFF_NONE);
2855       }
2856     }else{
2857       /* CREATE VIEW name AS...  without an argument list.  Construct
2858       ** the column names from the SELECT statement that defines the view.
2859       */
2860       assert( pTable->aCol==0 );
2861       pTable->nCol = pSelTab->nCol;
2862       pTable->aCol = pSelTab->aCol;
2863       pTable->tabFlags |= (pSelTab->tabFlags & COLFLAG_NOINSERT);
2864       pSelTab->nCol = 0;
2865       pSelTab->aCol = 0;
2866       assert( sqlite3SchemaMutexHeld(db, 0, pTable->pSchema) );
2867     }
2868     pTable->nNVCol = pTable->nCol;
2869     sqlite3DeleteTable(db, pSelTab);
2870     sqlite3SelectDelete(db, pSel);
2871     EnableLookaside;
2872     pParse->eParseMode = eParseMode;
2873   } else {
2874     nErr++;
2875   }
2876   pTable->pSchema->schemaFlags |= DB_UnresetViews;
2877   if( db->mallocFailed ){
2878     sqlite3DeleteColumnNames(db, pTable);
2879     pTable->aCol = 0;
2880     pTable->nCol = 0;
2881   }
2882 #endif /* SQLITE_OMIT_VIEW */
2883   return nErr;
2884 }
2885 #endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
2886 
2887 #ifndef SQLITE_OMIT_VIEW
2888 /*
2889 ** Clear the column names from every VIEW in database idx.
2890 */
2891 static void sqliteViewResetAll(sqlite3 *db, int idx){
2892   HashElem *i;
2893   assert( sqlite3SchemaMutexHeld(db, idx, 0) );
2894   if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
2895   for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
2896     Table *pTab = sqliteHashData(i);
2897     if( pTab->pSelect ){
2898       sqlite3DeleteColumnNames(db, pTab);
2899       pTab->aCol = 0;
2900       pTab->nCol = 0;
2901     }
2902   }
2903   DbClearProperty(db, idx, DB_UnresetViews);
2904 }
2905 #else
2906 # define sqliteViewResetAll(A,B)
2907 #endif /* SQLITE_OMIT_VIEW */
2908 
2909 /*
2910 ** This function is called by the VDBE to adjust the internal schema
2911 ** used by SQLite when the btree layer moves a table root page. The
2912 ** root-page of a table or index in database iDb has changed from iFrom
2913 ** to iTo.
2914 **
2915 ** Ticket #1728:  The symbol table might still contain information
2916 ** on tables and/or indices that are the process of being deleted.
2917 ** If you are unlucky, one of those deleted indices or tables might
2918 ** have the same rootpage number as the real table or index that is
2919 ** being moved.  So we cannot stop searching after the first match
2920 ** because the first match might be for one of the deleted indices
2921 ** or tables and not the table/index that is actually being moved.
2922 ** We must continue looping until all tables and indices with
2923 ** rootpage==iFrom have been converted to have a rootpage of iTo
2924 ** in order to be certain that we got the right one.
2925 */
2926 #ifndef SQLITE_OMIT_AUTOVACUUM
2927 void sqlite3RootPageMoved(sqlite3 *db, int iDb, Pgno iFrom, Pgno iTo){
2928   HashElem *pElem;
2929   Hash *pHash;
2930   Db *pDb;
2931 
2932   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
2933   pDb = &db->aDb[iDb];
2934   pHash = &pDb->pSchema->tblHash;
2935   for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
2936     Table *pTab = sqliteHashData(pElem);
2937     if( pTab->tnum==iFrom ){
2938       pTab->tnum = iTo;
2939     }
2940   }
2941   pHash = &pDb->pSchema->idxHash;
2942   for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
2943     Index *pIdx = sqliteHashData(pElem);
2944     if( pIdx->tnum==iFrom ){
2945       pIdx->tnum = iTo;
2946     }
2947   }
2948 }
2949 #endif
2950 
2951 /*
2952 ** Write code to erase the table with root-page iTable from database iDb.
2953 ** Also write code to modify the sqlite_schema table and internal schema
2954 ** if a root-page of another table is moved by the btree-layer whilst
2955 ** erasing iTable (this can happen with an auto-vacuum database).
2956 */
2957 static void destroyRootPage(Parse *pParse, int iTable, int iDb){
2958   Vdbe *v = sqlite3GetVdbe(pParse);
2959   int r1 = sqlite3GetTempReg(pParse);
2960   if( iTable<2 ) sqlite3ErrorMsg(pParse, "corrupt schema");
2961   sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
2962   sqlite3MayAbort(pParse);
2963 #ifndef SQLITE_OMIT_AUTOVACUUM
2964   /* OP_Destroy stores an in integer r1. If this integer
2965   ** is non-zero, then it is the root page number of a table moved to
2966   ** location iTable. The following code modifies the sqlite_schema table to
2967   ** reflect this.
2968   **
2969   ** The "#NNN" in the SQL is a special constant that means whatever value
2970   ** is in register NNN.  See grammar rules associated with the TK_REGISTER
2971   ** token for additional information.
2972   */
2973   sqlite3NestedParse(pParse,
2974      "UPDATE %Q." DFLT_SCHEMA_TABLE
2975      " SET rootpage=%d WHERE #%d AND rootpage=#%d",
2976      pParse->db->aDb[iDb].zDbSName, iTable, r1, r1);
2977 #endif
2978   sqlite3ReleaseTempReg(pParse, r1);
2979 }
2980 
2981 /*
2982 ** Write VDBE code to erase table pTab and all associated indices on disk.
2983 ** Code to update the sqlite_schema tables and internal schema definitions
2984 ** in case a root-page belonging to another table is moved by the btree layer
2985 ** is also added (this can happen with an auto-vacuum database).
2986 */
2987 static void destroyTable(Parse *pParse, Table *pTab){
2988   /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
2989   ** is not defined), then it is important to call OP_Destroy on the
2990   ** table and index root-pages in order, starting with the numerically
2991   ** largest root-page number. This guarantees that none of the root-pages
2992   ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
2993   ** following were coded:
2994   **
2995   ** OP_Destroy 4 0
2996   ** ...
2997   ** OP_Destroy 5 0
2998   **
2999   ** and root page 5 happened to be the largest root-page number in the
3000   ** database, then root page 5 would be moved to page 4 by the
3001   ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
3002   ** a free-list page.
3003   */
3004   Pgno iTab = pTab->tnum;
3005   Pgno iDestroyed = 0;
3006 
3007   while( 1 ){
3008     Index *pIdx;
3009     Pgno iLargest = 0;
3010 
3011     if( iDestroyed==0 || iTab<iDestroyed ){
3012       iLargest = iTab;
3013     }
3014     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
3015       Pgno iIdx = pIdx->tnum;
3016       assert( pIdx->pSchema==pTab->pSchema );
3017       if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
3018         iLargest = iIdx;
3019       }
3020     }
3021     if( iLargest==0 ){
3022       return;
3023     }else{
3024       int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
3025       assert( iDb>=0 && iDb<pParse->db->nDb );
3026       destroyRootPage(pParse, iLargest, iDb);
3027       iDestroyed = iLargest;
3028     }
3029   }
3030 }
3031 
3032 /*
3033 ** Remove entries from the sqlite_statN tables (for N in (1,2,3))
3034 ** after a DROP INDEX or DROP TABLE command.
3035 */
3036 static void sqlite3ClearStatTables(
3037   Parse *pParse,         /* The parsing context */
3038   int iDb,               /* The database number */
3039   const char *zType,     /* "idx" or "tbl" */
3040   const char *zName      /* Name of index or table */
3041 ){
3042   int i;
3043   const char *zDbName = pParse->db->aDb[iDb].zDbSName;
3044   for(i=1; i<=4; i++){
3045     char zTab[24];
3046     sqlite3_snprintf(sizeof(zTab),zTab,"sqlite_stat%d",i);
3047     if( sqlite3FindTable(pParse->db, zTab, zDbName) ){
3048       sqlite3NestedParse(pParse,
3049         "DELETE FROM %Q.%s WHERE %s=%Q",
3050         zDbName, zTab, zType, zName
3051       );
3052     }
3053   }
3054 }
3055 
3056 /*
3057 ** Generate code to drop a table.
3058 */
3059 void sqlite3CodeDropTable(Parse *pParse, Table *pTab, int iDb, int isView){
3060   Vdbe *v;
3061   sqlite3 *db = pParse->db;
3062   Trigger *pTrigger;
3063   Db *pDb = &db->aDb[iDb];
3064 
3065   v = sqlite3GetVdbe(pParse);
3066   assert( v!=0 );
3067   sqlite3BeginWriteOperation(pParse, 1, iDb);
3068 
3069 #ifndef SQLITE_OMIT_VIRTUALTABLE
3070   if( IsVirtual(pTab) ){
3071     sqlite3VdbeAddOp0(v, OP_VBegin);
3072   }
3073 #endif
3074 
3075   /* Drop all triggers associated with the table being dropped. Code
3076   ** is generated to remove entries from sqlite_schema and/or
3077   ** sqlite_temp_schema if required.
3078   */
3079   pTrigger = sqlite3TriggerList(pParse, pTab);
3080   while( pTrigger ){
3081     assert( pTrigger->pSchema==pTab->pSchema ||
3082         pTrigger->pSchema==db->aDb[1].pSchema );
3083     sqlite3DropTriggerPtr(pParse, pTrigger);
3084     pTrigger = pTrigger->pNext;
3085   }
3086 
3087 #ifndef SQLITE_OMIT_AUTOINCREMENT
3088   /* Remove any entries of the sqlite_sequence table associated with
3089   ** the table being dropped. This is done before the table is dropped
3090   ** at the btree level, in case the sqlite_sequence table needs to
3091   ** move as a result of the drop (can happen in auto-vacuum mode).
3092   */
3093   if( pTab->tabFlags & TF_Autoincrement ){
3094     sqlite3NestedParse(pParse,
3095       "DELETE FROM %Q.sqlite_sequence WHERE name=%Q",
3096       pDb->zDbSName, pTab->zName
3097     );
3098   }
3099 #endif
3100 
3101   /* Drop all entries in the schema table that refer to the
3102   ** table. The program name loops through the schema table and deletes
3103   ** every row that refers to a table of the same name as the one being
3104   ** dropped. Triggers are handled separately because a trigger can be
3105   ** created in the temp database that refers to a table in another
3106   ** database.
3107   */
3108   sqlite3NestedParse(pParse,
3109       "DELETE FROM %Q." DFLT_SCHEMA_TABLE
3110       " WHERE tbl_name=%Q and type!='trigger'",
3111       pDb->zDbSName, pTab->zName);
3112   if( !isView && !IsVirtual(pTab) ){
3113     destroyTable(pParse, pTab);
3114   }
3115 
3116   /* Remove the table entry from SQLite's internal schema and modify
3117   ** the schema cookie.
3118   */
3119   if( IsVirtual(pTab) ){
3120     sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
3121     sqlite3MayAbort(pParse);
3122   }
3123   sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
3124   sqlite3ChangeCookie(pParse, iDb);
3125   sqliteViewResetAll(db, iDb);
3126 }
3127 
3128 /*
3129 ** Return TRUE if shadow tables should be read-only in the current
3130 ** context.
3131 */
3132 int sqlite3ReadOnlyShadowTables(sqlite3 *db){
3133 #ifndef SQLITE_OMIT_VIRTUALTABLE
3134   if( (db->flags & SQLITE_Defensive)!=0
3135    && db->pVtabCtx==0
3136    && db->nVdbeExec==0
3137   ){
3138     return 1;
3139   }
3140 #endif
3141   return 0;
3142 }
3143 
3144 /*
3145 ** Return true if it is not allowed to drop the given table
3146 */
3147 static int tableMayNotBeDropped(sqlite3 *db, Table *pTab){
3148   if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
3149     if( sqlite3StrNICmp(pTab->zName+7, "stat", 4)==0 ) return 0;
3150     if( sqlite3StrNICmp(pTab->zName+7, "parameters", 10)==0 ) return 0;
3151     return 1;
3152   }
3153   if( (pTab->tabFlags & TF_Shadow)!=0 && sqlite3ReadOnlyShadowTables(db) ){
3154     return 1;
3155   }
3156   return 0;
3157 }
3158 
3159 /*
3160 ** This routine is called to do the work of a DROP TABLE statement.
3161 ** pName is the name of the table to be dropped.
3162 */
3163 void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
3164   Table *pTab;
3165   Vdbe *v;
3166   sqlite3 *db = pParse->db;
3167   int iDb;
3168 
3169   if( db->mallocFailed ){
3170     goto exit_drop_table;
3171   }
3172   assert( pParse->nErr==0 );
3173   assert( pName->nSrc==1 );
3174   if( sqlite3ReadSchema(pParse) ) goto exit_drop_table;
3175   if( noErr ) db->suppressErr++;
3176   assert( isView==0 || isView==LOCATE_VIEW );
3177   pTab = sqlite3LocateTableItem(pParse, isView, &pName->a[0]);
3178   if( noErr ) db->suppressErr--;
3179 
3180   if( pTab==0 ){
3181     if( noErr ) sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
3182     goto exit_drop_table;
3183   }
3184   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
3185   assert( iDb>=0 && iDb<db->nDb );
3186 
3187   /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
3188   ** it is initialized.
3189   */
3190   if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){
3191     goto exit_drop_table;
3192   }
3193 #ifndef SQLITE_OMIT_AUTHORIZATION
3194   {
3195     int code;
3196     const char *zTab = SCHEMA_TABLE(iDb);
3197     const char *zDb = db->aDb[iDb].zDbSName;
3198     const char *zArg2 = 0;
3199     if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
3200       goto exit_drop_table;
3201     }
3202     if( isView ){
3203       if( !OMIT_TEMPDB && iDb==1 ){
3204         code = SQLITE_DROP_TEMP_VIEW;
3205       }else{
3206         code = SQLITE_DROP_VIEW;
3207       }
3208 #ifndef SQLITE_OMIT_VIRTUALTABLE
3209     }else if( IsVirtual(pTab) ){
3210       code = SQLITE_DROP_VTABLE;
3211       zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName;
3212 #endif
3213     }else{
3214       if( !OMIT_TEMPDB && iDb==1 ){
3215         code = SQLITE_DROP_TEMP_TABLE;
3216       }else{
3217         code = SQLITE_DROP_TABLE;
3218       }
3219     }
3220     if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
3221       goto exit_drop_table;
3222     }
3223     if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
3224       goto exit_drop_table;
3225     }
3226   }
3227 #endif
3228   if( tableMayNotBeDropped(db, pTab) ){
3229     sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
3230     goto exit_drop_table;
3231   }
3232 
3233 #ifndef SQLITE_OMIT_VIEW
3234   /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
3235   ** on a table.
3236   */
3237   if( isView && pTab->pSelect==0 ){
3238     sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
3239     goto exit_drop_table;
3240   }
3241   if( !isView && pTab->pSelect ){
3242     sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
3243     goto exit_drop_table;
3244   }
3245 #endif
3246 
3247   /* Generate code to remove the table from the schema table
3248   ** on disk.
3249   */
3250   v = sqlite3GetVdbe(pParse);
3251   if( v ){
3252     sqlite3BeginWriteOperation(pParse, 1, iDb);
3253     if( !isView ){
3254       sqlite3ClearStatTables(pParse, iDb, "tbl", pTab->zName);
3255       sqlite3FkDropTable(pParse, pName, pTab);
3256     }
3257     sqlite3CodeDropTable(pParse, pTab, iDb, isView);
3258   }
3259 
3260 exit_drop_table:
3261   sqlite3SrcListDelete(db, pName);
3262 }
3263 
3264 /*
3265 ** This routine is called to create a new foreign key on the table
3266 ** currently under construction.  pFromCol determines which columns
3267 ** in the current table point to the foreign key.  If pFromCol==0 then
3268 ** connect the key to the last column inserted.  pTo is the name of
3269 ** the table referred to (a.k.a the "parent" table).  pToCol is a list
3270 ** of tables in the parent pTo table.  flags contains all
3271 ** information about the conflict resolution algorithms specified
3272 ** in the ON DELETE, ON UPDATE and ON INSERT clauses.
3273 **
3274 ** An FKey structure is created and added to the table currently
3275 ** under construction in the pParse->pNewTable field.
3276 **
3277 ** The foreign key is set for IMMEDIATE processing.  A subsequent call
3278 ** to sqlite3DeferForeignKey() might change this to DEFERRED.
3279 */
3280 void sqlite3CreateForeignKey(
3281   Parse *pParse,       /* Parsing context */
3282   ExprList *pFromCol,  /* Columns in this table that point to other table */
3283   Token *pTo,          /* Name of the other table */
3284   ExprList *pToCol,    /* Columns in the other table */
3285   int flags            /* Conflict resolution algorithms. */
3286 ){
3287   sqlite3 *db = pParse->db;
3288 #ifndef SQLITE_OMIT_FOREIGN_KEY
3289   FKey *pFKey = 0;
3290   FKey *pNextTo;
3291   Table *p = pParse->pNewTable;
3292   int nByte;
3293   int i;
3294   int nCol;
3295   char *z;
3296 
3297   assert( pTo!=0 );
3298   if( p==0 || IN_DECLARE_VTAB ) goto fk_end;
3299   if( pFromCol==0 ){
3300     int iCol = p->nCol-1;
3301     if( NEVER(iCol<0) ) goto fk_end;
3302     if( pToCol && pToCol->nExpr!=1 ){
3303       sqlite3ErrorMsg(pParse, "foreign key on %s"
3304          " should reference only one column of table %T",
3305          p->aCol[iCol].zName, pTo);
3306       goto fk_end;
3307     }
3308     nCol = 1;
3309   }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
3310     sqlite3ErrorMsg(pParse,
3311         "number of columns in foreign key does not match the number of "
3312         "columns in the referenced table");
3313     goto fk_end;
3314   }else{
3315     nCol = pFromCol->nExpr;
3316   }
3317   nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1;
3318   if( pToCol ){
3319     for(i=0; i<pToCol->nExpr; i++){
3320       nByte += sqlite3Strlen30(pToCol->a[i].zEName) + 1;
3321     }
3322   }
3323   pFKey = sqlite3DbMallocZero(db, nByte );
3324   if( pFKey==0 ){
3325     goto fk_end;
3326   }
3327   pFKey->pFrom = p;
3328   pFKey->pNextFrom = p->pFKey;
3329   z = (char*)&pFKey->aCol[nCol];
3330   pFKey->zTo = z;
3331   if( IN_RENAME_OBJECT ){
3332     sqlite3RenameTokenMap(pParse, (void*)z, pTo);
3333   }
3334   memcpy(z, pTo->z, pTo->n);
3335   z[pTo->n] = 0;
3336   sqlite3Dequote(z);
3337   z += pTo->n+1;
3338   pFKey->nCol = nCol;
3339   if( pFromCol==0 ){
3340     pFKey->aCol[0].iFrom = p->nCol-1;
3341   }else{
3342     for(i=0; i<nCol; i++){
3343       int j;
3344       for(j=0; j<p->nCol; j++){
3345         if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zEName)==0 ){
3346           pFKey->aCol[i].iFrom = j;
3347           break;
3348         }
3349       }
3350       if( j>=p->nCol ){
3351         sqlite3ErrorMsg(pParse,
3352           "unknown column \"%s\" in foreign key definition",
3353           pFromCol->a[i].zEName);
3354         goto fk_end;
3355       }
3356       if( IN_RENAME_OBJECT ){
3357         sqlite3RenameTokenRemap(pParse, &pFKey->aCol[i], pFromCol->a[i].zEName);
3358       }
3359     }
3360   }
3361   if( pToCol ){
3362     for(i=0; i<nCol; i++){
3363       int n = sqlite3Strlen30(pToCol->a[i].zEName);
3364       pFKey->aCol[i].zCol = z;
3365       if( IN_RENAME_OBJECT ){
3366         sqlite3RenameTokenRemap(pParse, z, pToCol->a[i].zEName);
3367       }
3368       memcpy(z, pToCol->a[i].zEName, n);
3369       z[n] = 0;
3370       z += n+1;
3371     }
3372   }
3373   pFKey->isDeferred = 0;
3374   pFKey->aAction[0] = (u8)(flags & 0xff);            /* ON DELETE action */
3375   pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff);    /* ON UPDATE action */
3376 
3377   assert( sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
3378   pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash,
3379       pFKey->zTo, (void *)pFKey
3380   );
3381   if( pNextTo==pFKey ){
3382     sqlite3OomFault(db);
3383     goto fk_end;
3384   }
3385   if( pNextTo ){
3386     assert( pNextTo->pPrevTo==0 );
3387     pFKey->pNextTo = pNextTo;
3388     pNextTo->pPrevTo = pFKey;
3389   }
3390 
3391   /* Link the foreign key to the table as the last step.
3392   */
3393   p->pFKey = pFKey;
3394   pFKey = 0;
3395 
3396 fk_end:
3397   sqlite3DbFree(db, pFKey);
3398 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
3399   sqlite3ExprListDelete(db, pFromCol);
3400   sqlite3ExprListDelete(db, pToCol);
3401 }
3402 
3403 /*
3404 ** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
3405 ** clause is seen as part of a foreign key definition.  The isDeferred
3406 ** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
3407 ** The behavior of the most recently created foreign key is adjusted
3408 ** accordingly.
3409 */
3410 void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
3411 #ifndef SQLITE_OMIT_FOREIGN_KEY
3412   Table *pTab;
3413   FKey *pFKey;
3414   if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
3415   assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */
3416   pFKey->isDeferred = (u8)isDeferred;
3417 #endif
3418 }
3419 
3420 /*
3421 ** Generate code that will erase and refill index *pIdx.  This is
3422 ** used to initialize a newly created index or to recompute the
3423 ** content of an index in response to a REINDEX command.
3424 **
3425 ** if memRootPage is not negative, it means that the index is newly
3426 ** created.  The register specified by memRootPage contains the
3427 ** root page number of the index.  If memRootPage is negative, then
3428 ** the index already exists and must be cleared before being refilled and
3429 ** the root page number of the index is taken from pIndex->tnum.
3430 */
3431 static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
3432   Table *pTab = pIndex->pTable;  /* The table that is indexed */
3433   int iTab = pParse->nTab++;     /* Btree cursor used for pTab */
3434   int iIdx = pParse->nTab++;     /* Btree cursor used for pIndex */
3435   int iSorter;                   /* Cursor opened by OpenSorter (if in use) */
3436   int addr1;                     /* Address of top of loop */
3437   int addr2;                     /* Address to jump to for next iteration */
3438   Pgno tnum;                     /* Root page of index */
3439   int iPartIdxLabel;             /* Jump to this label to skip a row */
3440   Vdbe *v;                       /* Generate code into this virtual machine */
3441   KeyInfo *pKey;                 /* KeyInfo for index */
3442   int regRecord;                 /* Register holding assembled index record */
3443   sqlite3 *db = pParse->db;      /* The database connection */
3444   int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
3445 
3446 #ifndef SQLITE_OMIT_AUTHORIZATION
3447   if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
3448       db->aDb[iDb].zDbSName ) ){
3449     return;
3450   }
3451 #endif
3452 
3453   /* Require a write-lock on the table to perform this operation */
3454   sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
3455 
3456   v = sqlite3GetVdbe(pParse);
3457   if( v==0 ) return;
3458   if( memRootPage>=0 ){
3459     tnum = (Pgno)memRootPage;
3460   }else{
3461     tnum = pIndex->tnum;
3462   }
3463   pKey = sqlite3KeyInfoOfIndex(pParse, pIndex);
3464   assert( pKey!=0 || db->mallocFailed || pParse->nErr );
3465 
3466   /* Open the sorter cursor if we are to use one. */
3467   iSorter = pParse->nTab++;
3468   sqlite3VdbeAddOp4(v, OP_SorterOpen, iSorter, 0, pIndex->nKeyCol, (char*)
3469                     sqlite3KeyInfoRef(pKey), P4_KEYINFO);
3470 
3471   /* Open the table. Loop through all rows of the table, inserting index
3472   ** records into the sorter. */
3473   sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
3474   addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0); VdbeCoverage(v);
3475   regRecord = sqlite3GetTempReg(pParse);
3476   sqlite3MultiWrite(pParse);
3477 
3478   sqlite3GenerateIndexKey(pParse,pIndex,iTab,regRecord,0,&iPartIdxLabel,0,0);
3479   sqlite3VdbeAddOp2(v, OP_SorterInsert, iSorter, regRecord);
3480   sqlite3ResolvePartIdxLabel(pParse, iPartIdxLabel);
3481   sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1); VdbeCoverage(v);
3482   sqlite3VdbeJumpHere(v, addr1);
3483   if( memRootPage<0 ) sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
3484   sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, (int)tnum, iDb,
3485                     (char *)pKey, P4_KEYINFO);
3486   sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR|((memRootPage>=0)?OPFLAG_P2ISREG:0));
3487 
3488   addr1 = sqlite3VdbeAddOp2(v, OP_SorterSort, iSorter, 0); VdbeCoverage(v);
3489   if( IsUniqueIndex(pIndex) ){
3490     int j2 = sqlite3VdbeGoto(v, 1);
3491     addr2 = sqlite3VdbeCurrentAddr(v);
3492     sqlite3VdbeVerifyAbortable(v, OE_Abort);
3493     sqlite3VdbeAddOp4Int(v, OP_SorterCompare, iSorter, j2, regRecord,
3494                          pIndex->nKeyCol); VdbeCoverage(v);
3495     sqlite3UniqueConstraint(pParse, OE_Abort, pIndex);
3496     sqlite3VdbeJumpHere(v, j2);
3497   }else{
3498     /* Most CREATE INDEX and REINDEX statements that are not UNIQUE can not
3499     ** abort. The exception is if one of the indexed expressions contains a
3500     ** user function that throws an exception when it is evaluated. But the
3501     ** overhead of adding a statement journal to a CREATE INDEX statement is
3502     ** very small (since most of the pages written do not contain content that
3503     ** needs to be restored if the statement aborts), so we call
3504     ** sqlite3MayAbort() for all CREATE INDEX statements.  */
3505     sqlite3MayAbort(pParse);
3506     addr2 = sqlite3VdbeCurrentAddr(v);
3507   }
3508   sqlite3VdbeAddOp3(v, OP_SorterData, iSorter, regRecord, iIdx);
3509   if( !pIndex->bAscKeyBug ){
3510     /* This OP_SeekEnd opcode makes index insert for a REINDEX go much
3511     ** faster by avoiding unnecessary seeks.  But the optimization does
3512     ** not work for UNIQUE constraint indexes on WITHOUT ROWID tables
3513     ** with DESC primary keys, since those indexes have there keys in
3514     ** a different order from the main table.
3515     ** See ticket: https://www.sqlite.org/src/info/bba7b69f9849b5bf
3516     */
3517     sqlite3VdbeAddOp1(v, OP_SeekEnd, iIdx);
3518   }
3519   sqlite3VdbeAddOp2(v, OP_IdxInsert, iIdx, regRecord);
3520   sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
3521   sqlite3ReleaseTempReg(pParse, regRecord);
3522   sqlite3VdbeAddOp2(v, OP_SorterNext, iSorter, addr2); VdbeCoverage(v);
3523   sqlite3VdbeJumpHere(v, addr1);
3524 
3525   sqlite3VdbeAddOp1(v, OP_Close, iTab);
3526   sqlite3VdbeAddOp1(v, OP_Close, iIdx);
3527   sqlite3VdbeAddOp1(v, OP_Close, iSorter);
3528 }
3529 
3530 /*
3531 ** Allocate heap space to hold an Index object with nCol columns.
3532 **
3533 ** Increase the allocation size to provide an extra nExtra bytes
3534 ** of 8-byte aligned space after the Index object and return a
3535 ** pointer to this extra space in *ppExtra.
3536 */
3537 Index *sqlite3AllocateIndexObject(
3538   sqlite3 *db,         /* Database connection */
3539   i16 nCol,            /* Total number of columns in the index */
3540   int nExtra,          /* Number of bytes of extra space to alloc */
3541   char **ppExtra       /* Pointer to the "extra" space */
3542 ){
3543   Index *p;            /* Allocated index object */
3544   int nByte;           /* Bytes of space for Index object + arrays */
3545 
3546   nByte = ROUND8(sizeof(Index)) +              /* Index structure  */
3547           ROUND8(sizeof(char*)*nCol) +         /* Index.azColl     */
3548           ROUND8(sizeof(LogEst)*(nCol+1) +     /* Index.aiRowLogEst   */
3549                  sizeof(i16)*nCol +            /* Index.aiColumn   */
3550                  sizeof(u8)*nCol);             /* Index.aSortOrder */
3551   p = sqlite3DbMallocZero(db, nByte + nExtra);
3552   if( p ){
3553     char *pExtra = ((char*)p)+ROUND8(sizeof(Index));
3554     p->azColl = (const char**)pExtra; pExtra += ROUND8(sizeof(char*)*nCol);
3555     p->aiRowLogEst = (LogEst*)pExtra; pExtra += sizeof(LogEst)*(nCol+1);
3556     p->aiColumn = (i16*)pExtra;       pExtra += sizeof(i16)*nCol;
3557     p->aSortOrder = (u8*)pExtra;
3558     p->nColumn = nCol;
3559     p->nKeyCol = nCol - 1;
3560     *ppExtra = ((char*)p) + nByte;
3561   }
3562   return p;
3563 }
3564 
3565 /*
3566 ** If expression list pList contains an expression that was parsed with
3567 ** an explicit "NULLS FIRST" or "NULLS LAST" clause, leave an error in
3568 ** pParse and return non-zero. Otherwise, return zero.
3569 */
3570 int sqlite3HasExplicitNulls(Parse *pParse, ExprList *pList){
3571   if( pList ){
3572     int i;
3573     for(i=0; i<pList->nExpr; i++){
3574       if( pList->a[i].bNulls ){
3575         u8 sf = pList->a[i].sortFlags;
3576         sqlite3ErrorMsg(pParse, "unsupported use of NULLS %s",
3577             (sf==0 || sf==3) ? "FIRST" : "LAST"
3578         );
3579         return 1;
3580       }
3581     }
3582   }
3583   return 0;
3584 }
3585 
3586 /*
3587 ** Create a new index for an SQL table.  pName1.pName2 is the name of the index
3588 ** and pTblList is the name of the table that is to be indexed.  Both will
3589 ** be NULL for a primary key or an index that is created to satisfy a
3590 ** UNIQUE constraint.  If pTable and pIndex are NULL, use pParse->pNewTable
3591 ** as the table to be indexed.  pParse->pNewTable is a table that is
3592 ** currently being constructed by a CREATE TABLE statement.
3593 **
3594 ** pList is a list of columns to be indexed.  pList will be NULL if this
3595 ** is a primary key or unique-constraint on the most recent column added
3596 ** to the table currently under construction.
3597 */
3598 void sqlite3CreateIndex(
3599   Parse *pParse,     /* All information about this parse */
3600   Token *pName1,     /* First part of index name. May be NULL */
3601   Token *pName2,     /* Second part of index name. May be NULL */
3602   SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
3603   ExprList *pList,   /* A list of columns to be indexed */
3604   int onError,       /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
3605   Token *pStart,     /* The CREATE token that begins this statement */
3606   Expr *pPIWhere,    /* WHERE clause for partial indices */
3607   int sortOrder,     /* Sort order of primary key when pList==NULL */
3608   int ifNotExist,    /* Omit error if index already exists */
3609   u8 idxType         /* The index type */
3610 ){
3611   Table *pTab = 0;     /* Table to be indexed */
3612   Index *pIndex = 0;   /* The index to be created */
3613   char *zName = 0;     /* Name of the index */
3614   int nName;           /* Number of characters in zName */
3615   int i, j;
3616   DbFixer sFix;        /* For assigning database names to pTable */
3617   int sortOrderMask;   /* 1 to honor DESC in index.  0 to ignore. */
3618   sqlite3 *db = pParse->db;
3619   Db *pDb;             /* The specific table containing the indexed database */
3620   int iDb;             /* Index of the database that is being written */
3621   Token *pName = 0;    /* Unqualified name of the index to create */
3622   struct ExprList_item *pListItem; /* For looping over pList */
3623   int nExtra = 0;                  /* Space allocated for zExtra[] */
3624   int nExtraCol;                   /* Number of extra columns needed */
3625   char *zExtra = 0;                /* Extra space after the Index object */
3626   Index *pPk = 0;      /* PRIMARY KEY index for WITHOUT ROWID tables */
3627 
3628   if( db->mallocFailed || pParse->nErr>0 ){
3629     goto exit_create_index;
3630   }
3631   if( IN_DECLARE_VTAB && idxType!=SQLITE_IDXTYPE_PRIMARYKEY ){
3632     goto exit_create_index;
3633   }
3634   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
3635     goto exit_create_index;
3636   }
3637   if( sqlite3HasExplicitNulls(pParse, pList) ){
3638     goto exit_create_index;
3639   }
3640 
3641   /*
3642   ** Find the table that is to be indexed.  Return early if not found.
3643   */
3644   if( pTblName!=0 ){
3645 
3646     /* Use the two-part index name to determine the database
3647     ** to search for the table. 'Fix' the table name to this db
3648     ** before looking up the table.
3649     */
3650     assert( pName1 && pName2 );
3651     iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
3652     if( iDb<0 ) goto exit_create_index;
3653     assert( pName && pName->z );
3654 
3655 #ifndef SQLITE_OMIT_TEMPDB
3656     /* If the index name was unqualified, check if the table
3657     ** is a temp table. If so, set the database to 1. Do not do this
3658     ** if initialising a database schema.
3659     */
3660     if( !db->init.busy ){
3661       pTab = sqlite3SrcListLookup(pParse, pTblName);
3662       if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
3663         iDb = 1;
3664       }
3665     }
3666 #endif
3667 
3668     sqlite3FixInit(&sFix, pParse, iDb, "index", pName);
3669     if( sqlite3FixSrcList(&sFix, pTblName) ){
3670       /* Because the parser constructs pTblName from a single identifier,
3671       ** sqlite3FixSrcList can never fail. */
3672       assert(0);
3673     }
3674     pTab = sqlite3LocateTableItem(pParse, 0, &pTblName->a[0]);
3675     assert( db->mallocFailed==0 || pTab==0 );
3676     if( pTab==0 ) goto exit_create_index;
3677     if( iDb==1 && db->aDb[iDb].pSchema!=pTab->pSchema ){
3678       sqlite3ErrorMsg(pParse,
3679            "cannot create a TEMP index on non-TEMP table \"%s\"",
3680            pTab->zName);
3681       goto exit_create_index;
3682     }
3683     if( !HasRowid(pTab) ) pPk = sqlite3PrimaryKeyIndex(pTab);
3684   }else{
3685     assert( pName==0 );
3686     assert( pStart==0 );
3687     pTab = pParse->pNewTable;
3688     if( !pTab ) goto exit_create_index;
3689     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
3690   }
3691   pDb = &db->aDb[iDb];
3692 
3693   assert( pTab!=0 );
3694   assert( pParse->nErr==0 );
3695   if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
3696        && db->init.busy==0
3697        && pTblName!=0
3698 #if SQLITE_USER_AUTHENTICATION
3699        && sqlite3UserAuthTable(pTab->zName)==0
3700 #endif
3701   ){
3702     sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
3703     goto exit_create_index;
3704   }
3705 #ifndef SQLITE_OMIT_VIEW
3706   if( pTab->pSelect ){
3707     sqlite3ErrorMsg(pParse, "views may not be indexed");
3708     goto exit_create_index;
3709   }
3710 #endif
3711 #ifndef SQLITE_OMIT_VIRTUALTABLE
3712   if( IsVirtual(pTab) ){
3713     sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
3714     goto exit_create_index;
3715   }
3716 #endif
3717 
3718   /*
3719   ** Find the name of the index.  Make sure there is not already another
3720   ** index or table with the same name.
3721   **
3722   ** Exception:  If we are reading the names of permanent indices from the
3723   ** sqlite_schema table (because some other process changed the schema) and
3724   ** one of the index names collides with the name of a temporary table or
3725   ** index, then we will continue to process this index.
3726   **
3727   ** If pName==0 it means that we are
3728   ** dealing with a primary key or UNIQUE constraint.  We have to invent our
3729   ** own name.
3730   */
3731   if( pName ){
3732     zName = sqlite3NameFromToken(db, pName);
3733     if( zName==0 ) goto exit_create_index;
3734     assert( pName->z!=0 );
3735     if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName,"index",pTab->zName) ){
3736       goto exit_create_index;
3737     }
3738     if( !IN_RENAME_OBJECT ){
3739       if( !db->init.busy ){
3740         if( sqlite3FindTable(db, zName, 0)!=0 ){
3741           sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
3742           goto exit_create_index;
3743         }
3744       }
3745       if( sqlite3FindIndex(db, zName, pDb->zDbSName)!=0 ){
3746         if( !ifNotExist ){
3747           sqlite3ErrorMsg(pParse, "index %s already exists", zName);
3748         }else{
3749           assert( !db->init.busy );
3750           sqlite3CodeVerifySchema(pParse, iDb);
3751         }
3752         goto exit_create_index;
3753       }
3754     }
3755   }else{
3756     int n;
3757     Index *pLoop;
3758     for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
3759     zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n);
3760     if( zName==0 ){
3761       goto exit_create_index;
3762     }
3763 
3764     /* Automatic index names generated from within sqlite3_declare_vtab()
3765     ** must have names that are distinct from normal automatic index names.
3766     ** The following statement converts "sqlite3_autoindex..." into
3767     ** "sqlite3_butoindex..." in order to make the names distinct.
3768     ** The "vtab_err.test" test demonstrates the need of this statement. */
3769     if( IN_SPECIAL_PARSE ) zName[7]++;
3770   }
3771 
3772   /* Check for authorization to create an index.
3773   */
3774 #ifndef SQLITE_OMIT_AUTHORIZATION
3775   if( !IN_RENAME_OBJECT ){
3776     const char *zDb = pDb->zDbSName;
3777     if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
3778       goto exit_create_index;
3779     }
3780     i = SQLITE_CREATE_INDEX;
3781     if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
3782     if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
3783       goto exit_create_index;
3784     }
3785   }
3786 #endif
3787 
3788   /* If pList==0, it means this routine was called to make a primary
3789   ** key out of the last column added to the table under construction.
3790   ** So create a fake list to simulate this.
3791   */
3792   if( pList==0 ){
3793     Token prevCol;
3794     Column *pCol = &pTab->aCol[pTab->nCol-1];
3795     pCol->colFlags |= COLFLAG_UNIQUE;
3796     sqlite3TokenInit(&prevCol, pCol->zName);
3797     pList = sqlite3ExprListAppend(pParse, 0,
3798               sqlite3ExprAlloc(db, TK_ID, &prevCol, 0));
3799     if( pList==0 ) goto exit_create_index;
3800     assert( pList->nExpr==1 );
3801     sqlite3ExprListSetSortOrder(pList, sortOrder, SQLITE_SO_UNDEFINED);
3802   }else{
3803     sqlite3ExprListCheckLength(pParse, pList, "index");
3804     if( pParse->nErr ) goto exit_create_index;
3805   }
3806 
3807   /* Figure out how many bytes of space are required to store explicitly
3808   ** specified collation sequence names.
3809   */
3810   for(i=0; i<pList->nExpr; i++){
3811     Expr *pExpr = pList->a[i].pExpr;
3812     assert( pExpr!=0 );
3813     if( pExpr->op==TK_COLLATE ){
3814       nExtra += (1 + sqlite3Strlen30(pExpr->u.zToken));
3815     }
3816   }
3817 
3818   /*
3819   ** Allocate the index structure.
3820   */
3821   nName = sqlite3Strlen30(zName);
3822   nExtraCol = pPk ? pPk->nKeyCol : 1;
3823   assert( pList->nExpr + nExtraCol <= 32767 /* Fits in i16 */ );
3824   pIndex = sqlite3AllocateIndexObject(db, pList->nExpr + nExtraCol,
3825                                       nName + nExtra + 1, &zExtra);
3826   if( db->mallocFailed ){
3827     goto exit_create_index;
3828   }
3829   assert( EIGHT_BYTE_ALIGNMENT(pIndex->aiRowLogEst) );
3830   assert( EIGHT_BYTE_ALIGNMENT(pIndex->azColl) );
3831   pIndex->zName = zExtra;
3832   zExtra += nName + 1;
3833   memcpy(pIndex->zName, zName, nName+1);
3834   pIndex->pTable = pTab;
3835   pIndex->onError = (u8)onError;
3836   pIndex->uniqNotNull = onError!=OE_None;
3837   pIndex->idxType = idxType;
3838   pIndex->pSchema = db->aDb[iDb].pSchema;
3839   pIndex->nKeyCol = pList->nExpr;
3840   if( pPIWhere ){
3841     sqlite3ResolveSelfReference(pParse, pTab, NC_PartIdx, pPIWhere, 0);
3842     pIndex->pPartIdxWhere = pPIWhere;
3843     pPIWhere = 0;
3844   }
3845   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
3846 
3847   /* Check to see if we should honor DESC requests on index columns
3848   */
3849   if( pDb->pSchema->file_format>=4 ){
3850     sortOrderMask = -1;   /* Honor DESC */
3851   }else{
3852     sortOrderMask = 0;    /* Ignore DESC */
3853   }
3854 
3855   /* Analyze the list of expressions that form the terms of the index and
3856   ** report any errors.  In the common case where the expression is exactly
3857   ** a table column, store that column in aiColumn[].  For general expressions,
3858   ** populate pIndex->aColExpr and store XN_EXPR (-2) in aiColumn[].
3859   **
3860   ** TODO: Issue a warning if two or more columns of the index are identical.
3861   ** TODO: Issue a warning if the table primary key is used as part of the
3862   ** index key.
3863   */
3864   pListItem = pList->a;
3865   if( IN_RENAME_OBJECT ){
3866     pIndex->aColExpr = pList;
3867     pList = 0;
3868   }
3869   for(i=0; i<pIndex->nKeyCol; i++, pListItem++){
3870     Expr *pCExpr;                  /* The i-th index expression */
3871     int requestedSortOrder;        /* ASC or DESC on the i-th expression */
3872     const char *zColl;             /* Collation sequence name */
3873 
3874     sqlite3StringToId(pListItem->pExpr);
3875     sqlite3ResolveSelfReference(pParse, pTab, NC_IdxExpr, pListItem->pExpr, 0);
3876     if( pParse->nErr ) goto exit_create_index;
3877     pCExpr = sqlite3ExprSkipCollate(pListItem->pExpr);
3878     if( pCExpr->op!=TK_COLUMN ){
3879       if( pTab==pParse->pNewTable ){
3880         sqlite3ErrorMsg(pParse, "expressions prohibited in PRIMARY KEY and "
3881                                 "UNIQUE constraints");
3882         goto exit_create_index;
3883       }
3884       if( pIndex->aColExpr==0 ){
3885         pIndex->aColExpr = pList;
3886         pList = 0;
3887       }
3888       j = XN_EXPR;
3889       pIndex->aiColumn[i] = XN_EXPR;
3890       pIndex->uniqNotNull = 0;
3891     }else{
3892       j = pCExpr->iColumn;
3893       assert( j<=0x7fff );
3894       if( j<0 ){
3895         j = pTab->iPKey;
3896       }else{
3897         if( pTab->aCol[j].notNull==0 ){
3898           pIndex->uniqNotNull = 0;
3899         }
3900         if( pTab->aCol[j].colFlags & COLFLAG_VIRTUAL ){
3901           pIndex->bHasVCol = 1;
3902         }
3903       }
3904       pIndex->aiColumn[i] = (i16)j;
3905     }
3906     zColl = 0;
3907     if( pListItem->pExpr->op==TK_COLLATE ){
3908       int nColl;
3909       zColl = pListItem->pExpr->u.zToken;
3910       nColl = sqlite3Strlen30(zColl) + 1;
3911       assert( nExtra>=nColl );
3912       memcpy(zExtra, zColl, nColl);
3913       zColl = zExtra;
3914       zExtra += nColl;
3915       nExtra -= nColl;
3916     }else if( j>=0 ){
3917       zColl = pTab->aCol[j].zColl;
3918     }
3919     if( !zColl ) zColl = sqlite3StrBINARY;
3920     if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){
3921       goto exit_create_index;
3922     }
3923     pIndex->azColl[i] = zColl;
3924     requestedSortOrder = pListItem->sortFlags & sortOrderMask;
3925     pIndex->aSortOrder[i] = (u8)requestedSortOrder;
3926   }
3927 
3928   /* Append the table key to the end of the index.  For WITHOUT ROWID
3929   ** tables (when pPk!=0) this will be the declared PRIMARY KEY.  For
3930   ** normal tables (when pPk==0) this will be the rowid.
3931   */
3932   if( pPk ){
3933     for(j=0; j<pPk->nKeyCol; j++){
3934       int x = pPk->aiColumn[j];
3935       assert( x>=0 );
3936       if( isDupColumn(pIndex, pIndex->nKeyCol, pPk, j) ){
3937         pIndex->nColumn--;
3938       }else{
3939         testcase( hasColumn(pIndex->aiColumn,pIndex->nKeyCol,x) );
3940         pIndex->aiColumn[i] = x;
3941         pIndex->azColl[i] = pPk->azColl[j];
3942         pIndex->aSortOrder[i] = pPk->aSortOrder[j];
3943         i++;
3944       }
3945     }
3946     assert( i==pIndex->nColumn );
3947   }else{
3948     pIndex->aiColumn[i] = XN_ROWID;
3949     pIndex->azColl[i] = sqlite3StrBINARY;
3950   }
3951   sqlite3DefaultRowEst(pIndex);
3952   if( pParse->pNewTable==0 ) estimateIndexWidth(pIndex);
3953 
3954   /* If this index contains every column of its table, then mark
3955   ** it as a covering index */
3956   assert( HasRowid(pTab)
3957       || pTab->iPKey<0 || sqlite3TableColumnToIndex(pIndex, pTab->iPKey)>=0 );
3958   recomputeColumnsNotIndexed(pIndex);
3959   if( pTblName!=0 && pIndex->nColumn>=pTab->nCol ){
3960     pIndex->isCovering = 1;
3961     for(j=0; j<pTab->nCol; j++){
3962       if( j==pTab->iPKey ) continue;
3963       if( sqlite3TableColumnToIndex(pIndex,j)>=0 ) continue;
3964       pIndex->isCovering = 0;
3965       break;
3966     }
3967   }
3968 
3969   if( pTab==pParse->pNewTable ){
3970     /* This routine has been called to create an automatic index as a
3971     ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
3972     ** a PRIMARY KEY or UNIQUE clause following the column definitions.
3973     ** i.e. one of:
3974     **
3975     ** CREATE TABLE t(x PRIMARY KEY, y);
3976     ** CREATE TABLE t(x, y, UNIQUE(x, y));
3977     **
3978     ** Either way, check to see if the table already has such an index. If
3979     ** so, don't bother creating this one. This only applies to
3980     ** automatically created indices. Users can do as they wish with
3981     ** explicit indices.
3982     **
3983     ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent
3984     ** (and thus suppressing the second one) even if they have different
3985     ** sort orders.
3986     **
3987     ** If there are different collating sequences or if the columns of
3988     ** the constraint occur in different orders, then the constraints are
3989     ** considered distinct and both result in separate indices.
3990     */
3991     Index *pIdx;
3992     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
3993       int k;
3994       assert( IsUniqueIndex(pIdx) );
3995       assert( pIdx->idxType!=SQLITE_IDXTYPE_APPDEF );
3996       assert( IsUniqueIndex(pIndex) );
3997 
3998       if( pIdx->nKeyCol!=pIndex->nKeyCol ) continue;
3999       for(k=0; k<pIdx->nKeyCol; k++){
4000         const char *z1;
4001         const char *z2;
4002         assert( pIdx->aiColumn[k]>=0 );
4003         if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
4004         z1 = pIdx->azColl[k];
4005         z2 = pIndex->azColl[k];
4006         if( sqlite3StrICmp(z1, z2) ) break;
4007       }
4008       if( k==pIdx->nKeyCol ){
4009         if( pIdx->onError!=pIndex->onError ){
4010           /* This constraint creates the same index as a previous
4011           ** constraint specified somewhere in the CREATE TABLE statement.
4012           ** However the ON CONFLICT clauses are different. If both this
4013           ** constraint and the previous equivalent constraint have explicit
4014           ** ON CONFLICT clauses this is an error. Otherwise, use the
4015           ** explicitly specified behavior for the index.
4016           */
4017           if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
4018             sqlite3ErrorMsg(pParse,
4019                 "conflicting ON CONFLICT clauses specified", 0);
4020           }
4021           if( pIdx->onError==OE_Default ){
4022             pIdx->onError = pIndex->onError;
4023           }
4024         }
4025         if( idxType==SQLITE_IDXTYPE_PRIMARYKEY ) pIdx->idxType = idxType;
4026         if( IN_RENAME_OBJECT ){
4027           pIndex->pNext = pParse->pNewIndex;
4028           pParse->pNewIndex = pIndex;
4029           pIndex = 0;
4030         }
4031         goto exit_create_index;
4032       }
4033     }
4034   }
4035 
4036   if( !IN_RENAME_OBJECT ){
4037 
4038     /* Link the new Index structure to its table and to the other
4039     ** in-memory database structures.
4040     */
4041     assert( pParse->nErr==0 );
4042     if( db->init.busy ){
4043       Index *p;
4044       assert( !IN_SPECIAL_PARSE );
4045       assert( sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
4046       if( pTblName!=0 ){
4047         pIndex->tnum = db->init.newTnum;
4048         if( sqlite3IndexHasDuplicateRootPage(pIndex) ){
4049           sqlite3ErrorMsg(pParse, "invalid rootpage");
4050           pParse->rc = SQLITE_CORRUPT_BKPT;
4051           goto exit_create_index;
4052         }
4053       }
4054       p = sqlite3HashInsert(&pIndex->pSchema->idxHash,
4055           pIndex->zName, pIndex);
4056       if( p ){
4057         assert( p==pIndex );  /* Malloc must have failed */
4058         sqlite3OomFault(db);
4059         goto exit_create_index;
4060       }
4061       db->mDbFlags |= DBFLAG_SchemaChange;
4062     }
4063 
4064     /* If this is the initial CREATE INDEX statement (or CREATE TABLE if the
4065     ** index is an implied index for a UNIQUE or PRIMARY KEY constraint) then
4066     ** emit code to allocate the index rootpage on disk and make an entry for
4067     ** the index in the sqlite_schema table and populate the index with
4068     ** content.  But, do not do this if we are simply reading the sqlite_schema
4069     ** table to parse the schema, or if this index is the PRIMARY KEY index
4070     ** of a WITHOUT ROWID table.
4071     **
4072     ** If pTblName==0 it means this index is generated as an implied PRIMARY KEY
4073     ** or UNIQUE index in a CREATE TABLE statement.  Since the table
4074     ** has just been created, it contains no data and the index initialization
4075     ** step can be skipped.
4076     */
4077     else if( HasRowid(pTab) || pTblName!=0 ){
4078       Vdbe *v;
4079       char *zStmt;
4080       int iMem = ++pParse->nMem;
4081 
4082       v = sqlite3GetVdbe(pParse);
4083       if( v==0 ) goto exit_create_index;
4084 
4085       sqlite3BeginWriteOperation(pParse, 1, iDb);
4086 
4087       /* Create the rootpage for the index using CreateIndex. But before
4088       ** doing so, code a Noop instruction and store its address in
4089       ** Index.tnum. This is required in case this index is actually a
4090       ** PRIMARY KEY and the table is actually a WITHOUT ROWID table. In
4091       ** that case the convertToWithoutRowidTable() routine will replace
4092       ** the Noop with a Goto to jump over the VDBE code generated below. */
4093       pIndex->tnum = (Pgno)sqlite3VdbeAddOp0(v, OP_Noop);
4094       sqlite3VdbeAddOp3(v, OP_CreateBtree, iDb, iMem, BTREE_BLOBKEY);
4095 
4096       /* Gather the complete text of the CREATE INDEX statement into
4097       ** the zStmt variable
4098       */
4099       assert( pName!=0 || pStart==0 );
4100       if( pStart ){
4101         int n = (int)(pParse->sLastToken.z - pName->z) + pParse->sLastToken.n;
4102         if( pName->z[n-1]==';' ) n--;
4103         /* A named index with an explicit CREATE INDEX statement */
4104         zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
4105             onError==OE_None ? "" : " UNIQUE", n, pName->z);
4106       }else{
4107         /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
4108         /* zStmt = sqlite3MPrintf(""); */
4109         zStmt = 0;
4110       }
4111 
4112       /* Add an entry in sqlite_schema for this index
4113       */
4114       sqlite3NestedParse(pParse,
4115           "INSERT INTO %Q." DFLT_SCHEMA_TABLE " VALUES('index',%Q,%Q,#%d,%Q);",
4116           db->aDb[iDb].zDbSName,
4117           pIndex->zName,
4118           pTab->zName,
4119           iMem,
4120           zStmt
4121           );
4122       sqlite3DbFree(db, zStmt);
4123 
4124       /* Fill the index with data and reparse the schema. Code an OP_Expire
4125       ** to invalidate all pre-compiled statements.
4126       */
4127       if( pTblName ){
4128         sqlite3RefillIndex(pParse, pIndex, iMem);
4129         sqlite3ChangeCookie(pParse, iDb);
4130         sqlite3VdbeAddParseSchemaOp(v, iDb,
4131             sqlite3MPrintf(db, "name='%q' AND type='index'", pIndex->zName), 0);
4132         sqlite3VdbeAddOp2(v, OP_Expire, 0, 1);
4133       }
4134 
4135       sqlite3VdbeJumpHere(v, (int)pIndex->tnum);
4136     }
4137   }
4138   if( db->init.busy || pTblName==0 ){
4139     pIndex->pNext = pTab->pIndex;
4140     pTab->pIndex = pIndex;
4141     pIndex = 0;
4142   }
4143   else if( IN_RENAME_OBJECT ){
4144     assert( pParse->pNewIndex==0 );
4145     pParse->pNewIndex = pIndex;
4146     pIndex = 0;
4147   }
4148 
4149   /* Clean up before exiting */
4150 exit_create_index:
4151   if( pIndex ) sqlite3FreeIndex(db, pIndex);
4152   if( pTab ){  /* Ensure all REPLACE indexes are at the end of the list */
4153     Index **ppFrom = &pTab->pIndex;
4154     Index *pThis;
4155     for(ppFrom=&pTab->pIndex; (pThis = *ppFrom)!=0; ppFrom=&pThis->pNext){
4156       Index *pNext;
4157       if( pThis->onError!=OE_Replace ) continue;
4158       while( (pNext = pThis->pNext)!=0 && pNext->onError!=OE_Replace ){
4159         *ppFrom = pNext;
4160         pThis->pNext = pNext->pNext;
4161         pNext->pNext = pThis;
4162         ppFrom = &pNext->pNext;
4163       }
4164       break;
4165     }
4166   }
4167   sqlite3ExprDelete(db, pPIWhere);
4168   sqlite3ExprListDelete(db, pList);
4169   sqlite3SrcListDelete(db, pTblName);
4170   sqlite3DbFree(db, zName);
4171 }
4172 
4173 /*
4174 ** Fill the Index.aiRowEst[] array with default information - information
4175 ** to be used when we have not run the ANALYZE command.
4176 **
4177 ** aiRowEst[0] is supposed to contain the number of elements in the index.
4178 ** Since we do not know, guess 1 million.  aiRowEst[1] is an estimate of the
4179 ** number of rows in the table that match any particular value of the
4180 ** first column of the index.  aiRowEst[2] is an estimate of the number
4181 ** of rows that match any particular combination of the first 2 columns
4182 ** of the index.  And so forth.  It must always be the case that
4183 *
4184 **           aiRowEst[N]<=aiRowEst[N-1]
4185 **           aiRowEst[N]>=1
4186 **
4187 ** Apart from that, we have little to go on besides intuition as to
4188 ** how aiRowEst[] should be initialized.  The numbers generated here
4189 ** are based on typical values found in actual indices.
4190 */
4191 void sqlite3DefaultRowEst(Index *pIdx){
4192                /*                10,  9,  8,  7,  6 */
4193   static const LogEst aVal[] = { 33, 32, 30, 28, 26 };
4194   LogEst *a = pIdx->aiRowLogEst;
4195   LogEst x;
4196   int nCopy = MIN(ArraySize(aVal), pIdx->nKeyCol);
4197   int i;
4198 
4199   /* Indexes with default row estimates should not have stat1 data */
4200   assert( !pIdx->hasStat1 );
4201 
4202   /* Set the first entry (number of rows in the index) to the estimated
4203   ** number of rows in the table, or half the number of rows in the table
4204   ** for a partial index.
4205   **
4206   ** 2020-05-27:  If some of the stat data is coming from the sqlite_stat1
4207   ** table but other parts we are having to guess at, then do not let the
4208   ** estimated number of rows in the table be less than 1000 (LogEst 99).
4209   ** Failure to do this can cause the indexes for which we do not have
4210   ** stat1 data to be ignored by the query planner.
4211   */
4212   x = pIdx->pTable->nRowLogEst;
4213   assert( 99==sqlite3LogEst(1000) );
4214   if( x<99 ){
4215     pIdx->pTable->nRowLogEst = x = 99;
4216   }
4217   if( pIdx->pPartIdxWhere!=0 ) x -= 10;  assert( 10==sqlite3LogEst(2) );
4218   a[0] = x;
4219 
4220   /* Estimate that a[1] is 10, a[2] is 9, a[3] is 8, a[4] is 7, a[5] is
4221   ** 6 and each subsequent value (if any) is 5.  */
4222   memcpy(&a[1], aVal, nCopy*sizeof(LogEst));
4223   for(i=nCopy+1; i<=pIdx->nKeyCol; i++){
4224     a[i] = 23;                    assert( 23==sqlite3LogEst(5) );
4225   }
4226 
4227   assert( 0==sqlite3LogEst(1) );
4228   if( IsUniqueIndex(pIdx) ) a[pIdx->nKeyCol] = 0;
4229 }
4230 
4231 /*
4232 ** This routine will drop an existing named index.  This routine
4233 ** implements the DROP INDEX statement.
4234 */
4235 void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
4236   Index *pIndex;
4237   Vdbe *v;
4238   sqlite3 *db = pParse->db;
4239   int iDb;
4240 
4241   assert( pParse->nErr==0 );   /* Never called with prior errors */
4242   if( db->mallocFailed ){
4243     goto exit_drop_index;
4244   }
4245   assert( pName->nSrc==1 );
4246   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
4247     goto exit_drop_index;
4248   }
4249   pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
4250   if( pIndex==0 ){
4251     if( !ifExists ){
4252       sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
4253     }else{
4254       sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
4255     }
4256     pParse->checkSchema = 1;
4257     goto exit_drop_index;
4258   }
4259   if( pIndex->idxType!=SQLITE_IDXTYPE_APPDEF ){
4260     sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
4261       "or PRIMARY KEY constraint cannot be dropped", 0);
4262     goto exit_drop_index;
4263   }
4264   iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
4265 #ifndef SQLITE_OMIT_AUTHORIZATION
4266   {
4267     int code = SQLITE_DROP_INDEX;
4268     Table *pTab = pIndex->pTable;
4269     const char *zDb = db->aDb[iDb].zDbSName;
4270     const char *zTab = SCHEMA_TABLE(iDb);
4271     if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
4272       goto exit_drop_index;
4273     }
4274     if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
4275     if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
4276       goto exit_drop_index;
4277     }
4278   }
4279 #endif
4280 
4281   /* Generate code to remove the index and from the schema table */
4282   v = sqlite3GetVdbe(pParse);
4283   if( v ){
4284     sqlite3BeginWriteOperation(pParse, 1, iDb);
4285     sqlite3NestedParse(pParse,
4286        "DELETE FROM %Q." DFLT_SCHEMA_TABLE " WHERE name=%Q AND type='index'",
4287        db->aDb[iDb].zDbSName, pIndex->zName
4288     );
4289     sqlite3ClearStatTables(pParse, iDb, "idx", pIndex->zName);
4290     sqlite3ChangeCookie(pParse, iDb);
4291     destroyRootPage(pParse, pIndex->tnum, iDb);
4292     sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
4293   }
4294 
4295 exit_drop_index:
4296   sqlite3SrcListDelete(db, pName);
4297 }
4298 
4299 /*
4300 ** pArray is a pointer to an array of objects. Each object in the
4301 ** array is szEntry bytes in size. This routine uses sqlite3DbRealloc()
4302 ** to extend the array so that there is space for a new object at the end.
4303 **
4304 ** When this function is called, *pnEntry contains the current size of
4305 ** the array (in entries - so the allocation is ((*pnEntry) * szEntry) bytes
4306 ** in total).
4307 **
4308 ** If the realloc() is successful (i.e. if no OOM condition occurs), the
4309 ** space allocated for the new object is zeroed, *pnEntry updated to
4310 ** reflect the new size of the array and a pointer to the new allocation
4311 ** returned. *pIdx is set to the index of the new array entry in this case.
4312 **
4313 ** Otherwise, if the realloc() fails, *pIdx is set to -1, *pnEntry remains
4314 ** unchanged and a copy of pArray returned.
4315 */
4316 void *sqlite3ArrayAllocate(
4317   sqlite3 *db,      /* Connection to notify of malloc failures */
4318   void *pArray,     /* Array of objects.  Might be reallocated */
4319   int szEntry,      /* Size of each object in the array */
4320   int *pnEntry,     /* Number of objects currently in use */
4321   int *pIdx         /* Write the index of a new slot here */
4322 ){
4323   char *z;
4324   sqlite3_int64 n = *pIdx = *pnEntry;
4325   if( (n & (n-1))==0 ){
4326     sqlite3_int64 sz = (n==0) ? 1 : 2*n;
4327     void *pNew = sqlite3DbRealloc(db, pArray, sz*szEntry);
4328     if( pNew==0 ){
4329       *pIdx = -1;
4330       return pArray;
4331     }
4332     pArray = pNew;
4333   }
4334   z = (char*)pArray;
4335   memset(&z[n * szEntry], 0, szEntry);
4336   ++*pnEntry;
4337   return pArray;
4338 }
4339 
4340 /*
4341 ** Append a new element to the given IdList.  Create a new IdList if
4342 ** need be.
4343 **
4344 ** A new IdList is returned, or NULL if malloc() fails.
4345 */
4346 IdList *sqlite3IdListAppend(Parse *pParse, IdList *pList, Token *pToken){
4347   sqlite3 *db = pParse->db;
4348   int i;
4349   if( pList==0 ){
4350     pList = sqlite3DbMallocZero(db, sizeof(IdList) );
4351     if( pList==0 ) return 0;
4352   }
4353   pList->a = sqlite3ArrayAllocate(
4354       db,
4355       pList->a,
4356       sizeof(pList->a[0]),
4357       &pList->nId,
4358       &i
4359   );
4360   if( i<0 ){
4361     sqlite3IdListDelete(db, pList);
4362     return 0;
4363   }
4364   pList->a[i].zName = sqlite3NameFromToken(db, pToken);
4365   if( IN_RENAME_OBJECT && pList->a[i].zName ){
4366     sqlite3RenameTokenMap(pParse, (void*)pList->a[i].zName, pToken);
4367   }
4368   return pList;
4369 }
4370 
4371 /*
4372 ** Delete an IdList.
4373 */
4374 void sqlite3IdListDelete(sqlite3 *db, IdList *pList){
4375   int i;
4376   if( pList==0 ) return;
4377   for(i=0; i<pList->nId; i++){
4378     sqlite3DbFree(db, pList->a[i].zName);
4379   }
4380   sqlite3DbFree(db, pList->a);
4381   sqlite3DbFreeNN(db, pList);
4382 }
4383 
4384 /*
4385 ** Return the index in pList of the identifier named zId.  Return -1
4386 ** if not found.
4387 */
4388 int sqlite3IdListIndex(IdList *pList, const char *zName){
4389   int i;
4390   if( pList==0 ) return -1;
4391   for(i=0; i<pList->nId; i++){
4392     if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
4393   }
4394   return -1;
4395 }
4396 
4397 /*
4398 ** Maximum size of a SrcList object.
4399 ** The SrcList object is used to represent the FROM clause of a
4400 ** SELECT statement, and the query planner cannot deal with more
4401 ** than 64 tables in a join.  So any value larger than 64 here
4402 ** is sufficient for most uses.  Smaller values, like say 10, are
4403 ** appropriate for small and memory-limited applications.
4404 */
4405 #ifndef SQLITE_MAX_SRCLIST
4406 # define SQLITE_MAX_SRCLIST 200
4407 #endif
4408 
4409 /*
4410 ** Expand the space allocated for the given SrcList object by
4411 ** creating nExtra new slots beginning at iStart.  iStart is zero based.
4412 ** New slots are zeroed.
4413 **
4414 ** For example, suppose a SrcList initially contains two entries: A,B.
4415 ** To append 3 new entries onto the end, do this:
4416 **
4417 **    sqlite3SrcListEnlarge(db, pSrclist, 3, 2);
4418 **
4419 ** After the call above it would contain:  A, B, nil, nil, nil.
4420 ** If the iStart argument had been 1 instead of 2, then the result
4421 ** would have been:  A, nil, nil, nil, B.  To prepend the new slots,
4422 ** the iStart value would be 0.  The result then would
4423 ** be: nil, nil, nil, A, B.
4424 **
4425 ** If a memory allocation fails or the SrcList becomes too large, leave
4426 ** the original SrcList unchanged, return NULL, and leave an error message
4427 ** in pParse.
4428 */
4429 SrcList *sqlite3SrcListEnlarge(
4430   Parse *pParse,     /* Parsing context into which errors are reported */
4431   SrcList *pSrc,     /* The SrcList to be enlarged */
4432   int nExtra,        /* Number of new slots to add to pSrc->a[] */
4433   int iStart         /* Index in pSrc->a[] of first new slot */
4434 ){
4435   int i;
4436 
4437   /* Sanity checking on calling parameters */
4438   assert( iStart>=0 );
4439   assert( nExtra>=1 );
4440   assert( pSrc!=0 );
4441   assert( iStart<=pSrc->nSrc );
4442 
4443   /* Allocate additional space if needed */
4444   if( (u32)pSrc->nSrc+nExtra>pSrc->nAlloc ){
4445     SrcList *pNew;
4446     sqlite3_int64 nAlloc = 2*(sqlite3_int64)pSrc->nSrc+nExtra;
4447     sqlite3 *db = pParse->db;
4448 
4449     if( pSrc->nSrc+nExtra>=SQLITE_MAX_SRCLIST ){
4450       sqlite3ErrorMsg(pParse, "too many FROM clause terms, max: %d",
4451                       SQLITE_MAX_SRCLIST);
4452       return 0;
4453     }
4454     if( nAlloc>SQLITE_MAX_SRCLIST ) nAlloc = SQLITE_MAX_SRCLIST;
4455     pNew = sqlite3DbRealloc(db, pSrc,
4456                sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) );
4457     if( pNew==0 ){
4458       assert( db->mallocFailed );
4459       return 0;
4460     }
4461     pSrc = pNew;
4462     pSrc->nAlloc = nAlloc;
4463   }
4464 
4465   /* Move existing slots that come after the newly inserted slots
4466   ** out of the way */
4467   for(i=pSrc->nSrc-1; i>=iStart; i--){
4468     pSrc->a[i+nExtra] = pSrc->a[i];
4469   }
4470   pSrc->nSrc += nExtra;
4471 
4472   /* Zero the newly allocated slots */
4473   memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
4474   for(i=iStart; i<iStart+nExtra; i++){
4475     pSrc->a[i].iCursor = -1;
4476   }
4477 
4478   /* Return a pointer to the enlarged SrcList */
4479   return pSrc;
4480 }
4481 
4482 
4483 /*
4484 ** Append a new table name to the given SrcList.  Create a new SrcList if
4485 ** need be.  A new entry is created in the SrcList even if pTable is NULL.
4486 **
4487 ** A SrcList is returned, or NULL if there is an OOM error or if the
4488 ** SrcList grows to large.  The returned
4489 ** SrcList might be the same as the SrcList that was input or it might be
4490 ** a new one.  If an OOM error does occurs, then the prior value of pList
4491 ** that is input to this routine is automatically freed.
4492 **
4493 ** If pDatabase is not null, it means that the table has an optional
4494 ** database name prefix.  Like this:  "database.table".  The pDatabase
4495 ** points to the table name and the pTable points to the database name.
4496 ** The SrcList.a[].zName field is filled with the table name which might
4497 ** come from pTable (if pDatabase is NULL) or from pDatabase.
4498 ** SrcList.a[].zDatabase is filled with the database name from pTable,
4499 ** or with NULL if no database is specified.
4500 **
4501 ** In other words, if call like this:
4502 **
4503 **         sqlite3SrcListAppend(D,A,B,0);
4504 **
4505 ** Then B is a table name and the database name is unspecified.  If called
4506 ** like this:
4507 **
4508 **         sqlite3SrcListAppend(D,A,B,C);
4509 **
4510 ** Then C is the table name and B is the database name.  If C is defined
4511 ** then so is B.  In other words, we never have a case where:
4512 **
4513 **         sqlite3SrcListAppend(D,A,0,C);
4514 **
4515 ** Both pTable and pDatabase are assumed to be quoted.  They are dequoted
4516 ** before being added to the SrcList.
4517 */
4518 SrcList *sqlite3SrcListAppend(
4519   Parse *pParse,      /* Parsing context, in which errors are reported */
4520   SrcList *pList,     /* Append to this SrcList. NULL creates a new SrcList */
4521   Token *pTable,      /* Table to append */
4522   Token *pDatabase    /* Database of the table */
4523 ){
4524   SrcItem *pItem;
4525   sqlite3 *db;
4526   assert( pDatabase==0 || pTable!=0 );  /* Cannot have C without B */
4527   assert( pParse!=0 );
4528   assert( pParse->db!=0 );
4529   db = pParse->db;
4530   if( pList==0 ){
4531     pList = sqlite3DbMallocRawNN(pParse->db, sizeof(SrcList) );
4532     if( pList==0 ) return 0;
4533     pList->nAlloc = 1;
4534     pList->nSrc = 1;
4535     memset(&pList->a[0], 0, sizeof(pList->a[0]));
4536     pList->a[0].iCursor = -1;
4537   }else{
4538     SrcList *pNew = sqlite3SrcListEnlarge(pParse, pList, 1, pList->nSrc);
4539     if( pNew==0 ){
4540       sqlite3SrcListDelete(db, pList);
4541       return 0;
4542     }else{
4543       pList = pNew;
4544     }
4545   }
4546   pItem = &pList->a[pList->nSrc-1];
4547   if( pDatabase && pDatabase->z==0 ){
4548     pDatabase = 0;
4549   }
4550   if( pDatabase ){
4551     pItem->zName = sqlite3NameFromToken(db, pDatabase);
4552     pItem->zDatabase = sqlite3NameFromToken(db, pTable);
4553   }else{
4554     pItem->zName = sqlite3NameFromToken(db, pTable);
4555     pItem->zDatabase = 0;
4556   }
4557   return pList;
4558 }
4559 
4560 /*
4561 ** Assign VdbeCursor index numbers to all tables in a SrcList
4562 */
4563 void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
4564   int i;
4565   SrcItem *pItem;
4566   assert(pList || pParse->db->mallocFailed );
4567   if( pList ){
4568     for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
4569       if( pItem->iCursor>=0 ) continue;
4570       pItem->iCursor = pParse->nTab++;
4571       if( pItem->pSelect ){
4572         sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
4573       }
4574     }
4575   }
4576 }
4577 
4578 /*
4579 ** Delete an entire SrcList including all its substructure.
4580 */
4581 void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){
4582   int i;
4583   SrcItem *pItem;
4584   if( pList==0 ) return;
4585   for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
4586     if( pItem->zDatabase ) sqlite3DbFreeNN(db, pItem->zDatabase);
4587     sqlite3DbFree(db, pItem->zName);
4588     if( pItem->zAlias ) sqlite3DbFreeNN(db, pItem->zAlias);
4589     if( pItem->fg.isIndexedBy ) sqlite3DbFree(db, pItem->u1.zIndexedBy);
4590     if( pItem->fg.isTabFunc ) sqlite3ExprListDelete(db, pItem->u1.pFuncArg);
4591     sqlite3DeleteTable(db, pItem->pTab);
4592     if( pItem->pSelect ) sqlite3SelectDelete(db, pItem->pSelect);
4593     if( pItem->pOn ) sqlite3ExprDelete(db, pItem->pOn);
4594     if( pItem->pUsing ) sqlite3IdListDelete(db, pItem->pUsing);
4595   }
4596   sqlite3DbFreeNN(db, pList);
4597 }
4598 
4599 /*
4600 ** This routine is called by the parser to add a new term to the
4601 ** end of a growing FROM clause.  The "p" parameter is the part of
4602 ** the FROM clause that has already been constructed.  "p" is NULL
4603 ** if this is the first term of the FROM clause.  pTable and pDatabase
4604 ** are the name of the table and database named in the FROM clause term.
4605 ** pDatabase is NULL if the database name qualifier is missing - the
4606 ** usual case.  If the term has an alias, then pAlias points to the
4607 ** alias token.  If the term is a subquery, then pSubquery is the
4608 ** SELECT statement that the subquery encodes.  The pTable and
4609 ** pDatabase parameters are NULL for subqueries.  The pOn and pUsing
4610 ** parameters are the content of the ON and USING clauses.
4611 **
4612 ** Return a new SrcList which encodes is the FROM with the new
4613 ** term added.
4614 */
4615 SrcList *sqlite3SrcListAppendFromTerm(
4616   Parse *pParse,          /* Parsing context */
4617   SrcList *p,             /* The left part of the FROM clause already seen */
4618   Token *pTable,          /* Name of the table to add to the FROM clause */
4619   Token *pDatabase,       /* Name of the database containing pTable */
4620   Token *pAlias,          /* The right-hand side of the AS subexpression */
4621   Select *pSubquery,      /* A subquery used in place of a table name */
4622   Expr *pOn,              /* The ON clause of a join */
4623   IdList *pUsing          /* The USING clause of a join */
4624 ){
4625   SrcItem *pItem;
4626   sqlite3 *db = pParse->db;
4627   if( !p && (pOn || pUsing) ){
4628     sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s",
4629       (pOn ? "ON" : "USING")
4630     );
4631     goto append_from_error;
4632   }
4633   p = sqlite3SrcListAppend(pParse, p, pTable, pDatabase);
4634   if( p==0 ){
4635     goto append_from_error;
4636   }
4637   assert( p->nSrc>0 );
4638   pItem = &p->a[p->nSrc-1];
4639   assert( (pTable==0)==(pDatabase==0) );
4640   assert( pItem->zName==0 || pDatabase!=0 );
4641   if( IN_RENAME_OBJECT && pItem->zName ){
4642     Token *pToken = (ALWAYS(pDatabase) && pDatabase->z) ? pDatabase : pTable;
4643     sqlite3RenameTokenMap(pParse, pItem->zName, pToken);
4644   }
4645   assert( pAlias!=0 );
4646   if( pAlias->n ){
4647     pItem->zAlias = sqlite3NameFromToken(db, pAlias);
4648   }
4649   pItem->pSelect = pSubquery;
4650   pItem->pOn = pOn;
4651   pItem->pUsing = pUsing;
4652   return p;
4653 
4654  append_from_error:
4655   assert( p==0 );
4656   sqlite3ExprDelete(db, pOn);
4657   sqlite3IdListDelete(db, pUsing);
4658   sqlite3SelectDelete(db, pSubquery);
4659   return 0;
4660 }
4661 
4662 /*
4663 ** Add an INDEXED BY or NOT INDEXED clause to the most recently added
4664 ** element of the source-list passed as the second argument.
4665 */
4666 void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){
4667   assert( pIndexedBy!=0 );
4668   if( p && pIndexedBy->n>0 ){
4669     SrcItem *pItem;
4670     assert( p->nSrc>0 );
4671     pItem = &p->a[p->nSrc-1];
4672     assert( pItem->fg.notIndexed==0 );
4673     assert( pItem->fg.isIndexedBy==0 );
4674     assert( pItem->fg.isTabFunc==0 );
4675     if( pIndexedBy->n==1 && !pIndexedBy->z ){
4676       /* A "NOT INDEXED" clause was supplied. See parse.y
4677       ** construct "indexed_opt" for details. */
4678       pItem->fg.notIndexed = 1;
4679     }else{
4680       pItem->u1.zIndexedBy = sqlite3NameFromToken(pParse->db, pIndexedBy);
4681       pItem->fg.isIndexedBy = 1;
4682     }
4683   }
4684 }
4685 
4686 /*
4687 ** Append the contents of SrcList p2 to SrcList p1 and return the resulting
4688 ** SrcList. Or, if an error occurs, return NULL. In all cases, p1 and p2
4689 ** are deleted by this function.
4690 */
4691 SrcList *sqlite3SrcListAppendList(Parse *pParse, SrcList *p1, SrcList *p2){
4692   assert( p1 && p1->nSrc==1 );
4693   if( p2 ){
4694     SrcList *pNew = sqlite3SrcListEnlarge(pParse, p1, p2->nSrc, 1);
4695     if( pNew==0 ){
4696       sqlite3SrcListDelete(pParse->db, p2);
4697     }else{
4698       p1 = pNew;
4699       memcpy(&p1->a[1], p2->a, p2->nSrc*sizeof(SrcItem));
4700       sqlite3DbFree(pParse->db, p2);
4701     }
4702   }
4703   return p1;
4704 }
4705 
4706 /*
4707 ** Add the list of function arguments to the SrcList entry for a
4708 ** table-valued-function.
4709 */
4710 void sqlite3SrcListFuncArgs(Parse *pParse, SrcList *p, ExprList *pList){
4711   if( p ){
4712     SrcItem *pItem = &p->a[p->nSrc-1];
4713     assert( pItem->fg.notIndexed==0 );
4714     assert( pItem->fg.isIndexedBy==0 );
4715     assert( pItem->fg.isTabFunc==0 );
4716     pItem->u1.pFuncArg = pList;
4717     pItem->fg.isTabFunc = 1;
4718   }else{
4719     sqlite3ExprListDelete(pParse->db, pList);
4720   }
4721 }
4722 
4723 /*
4724 ** When building up a FROM clause in the parser, the join operator
4725 ** is initially attached to the left operand.  But the code generator
4726 ** expects the join operator to be on the right operand.  This routine
4727 ** Shifts all join operators from left to right for an entire FROM
4728 ** clause.
4729 **
4730 ** Example: Suppose the join is like this:
4731 **
4732 **           A natural cross join B
4733 **
4734 ** The operator is "natural cross join".  The A and B operands are stored
4735 ** in p->a[0] and p->a[1], respectively.  The parser initially stores the
4736 ** operator with A.  This routine shifts that operator over to B.
4737 */
4738 void sqlite3SrcListShiftJoinType(SrcList *p){
4739   if( p ){
4740     int i;
4741     for(i=p->nSrc-1; i>0; i--){
4742       p->a[i].fg.jointype = p->a[i-1].fg.jointype;
4743     }
4744     p->a[0].fg.jointype = 0;
4745   }
4746 }
4747 
4748 /*
4749 ** Generate VDBE code for a BEGIN statement.
4750 */
4751 void sqlite3BeginTransaction(Parse *pParse, int type){
4752   sqlite3 *db;
4753   Vdbe *v;
4754   int i;
4755 
4756   assert( pParse!=0 );
4757   db = pParse->db;
4758   assert( db!=0 );
4759   if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){
4760     return;
4761   }
4762   v = sqlite3GetVdbe(pParse);
4763   if( !v ) return;
4764   if( type!=TK_DEFERRED ){
4765     for(i=0; i<db->nDb; i++){
4766       int eTxnType;
4767       Btree *pBt = db->aDb[i].pBt;
4768       if( pBt && sqlite3BtreeIsReadonly(pBt) ){
4769         eTxnType = 0;  /* Read txn */
4770       }else if( type==TK_EXCLUSIVE ){
4771         eTxnType = 2;  /* Exclusive txn */
4772       }else{
4773         eTxnType = 1;  /* Write txn */
4774       }
4775       sqlite3VdbeAddOp2(v, OP_Transaction, i, eTxnType);
4776       sqlite3VdbeUsesBtree(v, i);
4777     }
4778   }
4779   sqlite3VdbeAddOp0(v, OP_AutoCommit);
4780 }
4781 
4782 /*
4783 ** Generate VDBE code for a COMMIT or ROLLBACK statement.
4784 ** Code for ROLLBACK is generated if eType==TK_ROLLBACK.  Otherwise
4785 ** code is generated for a COMMIT.
4786 */
4787 void sqlite3EndTransaction(Parse *pParse, int eType){
4788   Vdbe *v;
4789   int isRollback;
4790 
4791   assert( pParse!=0 );
4792   assert( pParse->db!=0 );
4793   assert( eType==TK_COMMIT || eType==TK_END || eType==TK_ROLLBACK );
4794   isRollback = eType==TK_ROLLBACK;
4795   if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION,
4796        isRollback ? "ROLLBACK" : "COMMIT", 0, 0) ){
4797     return;
4798   }
4799   v = sqlite3GetVdbe(pParse);
4800   if( v ){
4801     sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, isRollback);
4802   }
4803 }
4804 
4805 /*
4806 ** This function is called by the parser when it parses a command to create,
4807 ** release or rollback an SQL savepoint.
4808 */
4809 void sqlite3Savepoint(Parse *pParse, int op, Token *pName){
4810   char *zName = sqlite3NameFromToken(pParse->db, pName);
4811   if( zName ){
4812     Vdbe *v = sqlite3GetVdbe(pParse);
4813 #ifndef SQLITE_OMIT_AUTHORIZATION
4814     static const char * const az[] = { "BEGIN", "RELEASE", "ROLLBACK" };
4815     assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 );
4816 #endif
4817     if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){
4818       sqlite3DbFree(pParse->db, zName);
4819       return;
4820     }
4821     sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC);
4822   }
4823 }
4824 
4825 /*
4826 ** Make sure the TEMP database is open and available for use.  Return
4827 ** the number of errors.  Leave any error messages in the pParse structure.
4828 */
4829 int sqlite3OpenTempDatabase(Parse *pParse){
4830   sqlite3 *db = pParse->db;
4831   if( db->aDb[1].pBt==0 && !pParse->explain ){
4832     int rc;
4833     Btree *pBt;
4834     static const int flags =
4835           SQLITE_OPEN_READWRITE |
4836           SQLITE_OPEN_CREATE |
4837           SQLITE_OPEN_EXCLUSIVE |
4838           SQLITE_OPEN_DELETEONCLOSE |
4839           SQLITE_OPEN_TEMP_DB;
4840 
4841     rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pBt, 0, flags);
4842     if( rc!=SQLITE_OK ){
4843       sqlite3ErrorMsg(pParse, "unable to open a temporary database "
4844         "file for storing temporary tables");
4845       pParse->rc = rc;
4846       return 1;
4847     }
4848     db->aDb[1].pBt = pBt;
4849     assert( db->aDb[1].pSchema );
4850     if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, 0, 0) ){
4851       sqlite3OomFault(db);
4852       return 1;
4853     }
4854   }
4855   return 0;
4856 }
4857 
4858 /*
4859 ** Record the fact that the schema cookie will need to be verified
4860 ** for database iDb.  The code to actually verify the schema cookie
4861 ** will occur at the end of the top-level VDBE and will be generated
4862 ** later, by sqlite3FinishCoding().
4863 */
4864 static void sqlite3CodeVerifySchemaAtToplevel(Parse *pToplevel, int iDb){
4865   assert( iDb>=0 && iDb<pToplevel->db->nDb );
4866   assert( pToplevel->db->aDb[iDb].pBt!=0 || iDb==1 );
4867   assert( iDb<SQLITE_MAX_DB );
4868   assert( sqlite3SchemaMutexHeld(pToplevel->db, iDb, 0) );
4869   if( DbMaskTest(pToplevel->cookieMask, iDb)==0 ){
4870     DbMaskSet(pToplevel->cookieMask, iDb);
4871     if( !OMIT_TEMPDB && iDb==1 ){
4872       sqlite3OpenTempDatabase(pToplevel);
4873     }
4874   }
4875 }
4876 void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
4877   sqlite3CodeVerifySchemaAtToplevel(sqlite3ParseToplevel(pParse), iDb);
4878 }
4879 
4880 
4881 /*
4882 ** If argument zDb is NULL, then call sqlite3CodeVerifySchema() for each
4883 ** attached database. Otherwise, invoke it for the database named zDb only.
4884 */
4885 void sqlite3CodeVerifyNamedSchema(Parse *pParse, const char *zDb){
4886   sqlite3 *db = pParse->db;
4887   int i;
4888   for(i=0; i<db->nDb; i++){
4889     Db *pDb = &db->aDb[i];
4890     if( pDb->pBt && (!zDb || 0==sqlite3StrICmp(zDb, pDb->zDbSName)) ){
4891       sqlite3CodeVerifySchema(pParse, i);
4892     }
4893   }
4894 }
4895 
4896 /*
4897 ** Generate VDBE code that prepares for doing an operation that
4898 ** might change the database.
4899 **
4900 ** This routine starts a new transaction if we are not already within
4901 ** a transaction.  If we are already within a transaction, then a checkpoint
4902 ** is set if the setStatement parameter is true.  A checkpoint should
4903 ** be set for operations that might fail (due to a constraint) part of
4904 ** the way through and which will need to undo some writes without having to
4905 ** rollback the whole transaction.  For operations where all constraints
4906 ** can be checked before any changes are made to the database, it is never
4907 ** necessary to undo a write and the checkpoint should not be set.
4908 */
4909 void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
4910   Parse *pToplevel = sqlite3ParseToplevel(pParse);
4911   sqlite3CodeVerifySchemaAtToplevel(pToplevel, iDb);
4912   DbMaskSet(pToplevel->writeMask, iDb);
4913   pToplevel->isMultiWrite |= setStatement;
4914 }
4915 
4916 /*
4917 ** Indicate that the statement currently under construction might write
4918 ** more than one entry (example: deleting one row then inserting another,
4919 ** inserting multiple rows in a table, or inserting a row and index entries.)
4920 ** If an abort occurs after some of these writes have completed, then it will
4921 ** be necessary to undo the completed writes.
4922 */
4923 void sqlite3MultiWrite(Parse *pParse){
4924   Parse *pToplevel = sqlite3ParseToplevel(pParse);
4925   pToplevel->isMultiWrite = 1;
4926 }
4927 
4928 /*
4929 ** The code generator calls this routine if is discovers that it is
4930 ** possible to abort a statement prior to completion.  In order to
4931 ** perform this abort without corrupting the database, we need to make
4932 ** sure that the statement is protected by a statement transaction.
4933 **
4934 ** Technically, we only need to set the mayAbort flag if the
4935 ** isMultiWrite flag was previously set.  There is a time dependency
4936 ** such that the abort must occur after the multiwrite.  This makes
4937 ** some statements involving the REPLACE conflict resolution algorithm
4938 ** go a little faster.  But taking advantage of this time dependency
4939 ** makes it more difficult to prove that the code is correct (in
4940 ** particular, it prevents us from writing an effective
4941 ** implementation of sqlite3AssertMayAbort()) and so we have chosen
4942 ** to take the safe route and skip the optimization.
4943 */
4944 void sqlite3MayAbort(Parse *pParse){
4945   Parse *pToplevel = sqlite3ParseToplevel(pParse);
4946   pToplevel->mayAbort = 1;
4947 }
4948 
4949 /*
4950 ** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT
4951 ** error. The onError parameter determines which (if any) of the statement
4952 ** and/or current transaction is rolled back.
4953 */
4954 void sqlite3HaltConstraint(
4955   Parse *pParse,    /* Parsing context */
4956   int errCode,      /* extended error code */
4957   int onError,      /* Constraint type */
4958   char *p4,         /* Error message */
4959   i8 p4type,        /* P4_STATIC or P4_TRANSIENT */
4960   u8 p5Errmsg       /* P5_ErrMsg type */
4961 ){
4962   Vdbe *v;
4963   assert( pParse->pVdbe!=0 );
4964   v = sqlite3GetVdbe(pParse);
4965   assert( (errCode&0xff)==SQLITE_CONSTRAINT || pParse->nested );
4966   if( onError==OE_Abort ){
4967     sqlite3MayAbort(pParse);
4968   }
4969   sqlite3VdbeAddOp4(v, OP_Halt, errCode, onError, 0, p4, p4type);
4970   sqlite3VdbeChangeP5(v, p5Errmsg);
4971 }
4972 
4973 /*
4974 ** Code an OP_Halt due to UNIQUE or PRIMARY KEY constraint violation.
4975 */
4976 void sqlite3UniqueConstraint(
4977   Parse *pParse,    /* Parsing context */
4978   int onError,      /* Constraint type */
4979   Index *pIdx       /* The index that triggers the constraint */
4980 ){
4981   char *zErr;
4982   int j;
4983   StrAccum errMsg;
4984   Table *pTab = pIdx->pTable;
4985 
4986   sqlite3StrAccumInit(&errMsg, pParse->db, 0, 0,
4987                       pParse->db->aLimit[SQLITE_LIMIT_LENGTH]);
4988   if( pIdx->aColExpr ){
4989     sqlite3_str_appendf(&errMsg, "index '%q'", pIdx->zName);
4990   }else{
4991     for(j=0; j<pIdx->nKeyCol; j++){
4992       char *zCol;
4993       assert( pIdx->aiColumn[j]>=0 );
4994       zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
4995       if( j ) sqlite3_str_append(&errMsg, ", ", 2);
4996       sqlite3_str_appendall(&errMsg, pTab->zName);
4997       sqlite3_str_append(&errMsg, ".", 1);
4998       sqlite3_str_appendall(&errMsg, zCol);
4999     }
5000   }
5001   zErr = sqlite3StrAccumFinish(&errMsg);
5002   sqlite3HaltConstraint(pParse,
5003     IsPrimaryKeyIndex(pIdx) ? SQLITE_CONSTRAINT_PRIMARYKEY
5004                             : SQLITE_CONSTRAINT_UNIQUE,
5005     onError, zErr, P4_DYNAMIC, P5_ConstraintUnique);
5006 }
5007 
5008 
5009 /*
5010 ** Code an OP_Halt due to non-unique rowid.
5011 */
5012 void sqlite3RowidConstraint(
5013   Parse *pParse,    /* Parsing context */
5014   int onError,      /* Conflict resolution algorithm */
5015   Table *pTab       /* The table with the non-unique rowid */
5016 ){
5017   char *zMsg;
5018   int rc;
5019   if( pTab->iPKey>=0 ){
5020     zMsg = sqlite3MPrintf(pParse->db, "%s.%s", pTab->zName,
5021                           pTab->aCol[pTab->iPKey].zName);
5022     rc = SQLITE_CONSTRAINT_PRIMARYKEY;
5023   }else{
5024     zMsg = sqlite3MPrintf(pParse->db, "%s.rowid", pTab->zName);
5025     rc = SQLITE_CONSTRAINT_ROWID;
5026   }
5027   sqlite3HaltConstraint(pParse, rc, onError, zMsg, P4_DYNAMIC,
5028                         P5_ConstraintUnique);
5029 }
5030 
5031 /*
5032 ** Check to see if pIndex uses the collating sequence pColl.  Return
5033 ** true if it does and false if it does not.
5034 */
5035 #ifndef SQLITE_OMIT_REINDEX
5036 static int collationMatch(const char *zColl, Index *pIndex){
5037   int i;
5038   assert( zColl!=0 );
5039   for(i=0; i<pIndex->nColumn; i++){
5040     const char *z = pIndex->azColl[i];
5041     assert( z!=0 || pIndex->aiColumn[i]<0 );
5042     if( pIndex->aiColumn[i]>=0 && 0==sqlite3StrICmp(z, zColl) ){
5043       return 1;
5044     }
5045   }
5046   return 0;
5047 }
5048 #endif
5049 
5050 /*
5051 ** Recompute all indices of pTab that use the collating sequence pColl.
5052 ** If pColl==0 then recompute all indices of pTab.
5053 */
5054 #ifndef SQLITE_OMIT_REINDEX
5055 static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
5056   if( !IsVirtual(pTab) ){
5057     Index *pIndex;              /* An index associated with pTab */
5058 
5059     for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
5060       if( zColl==0 || collationMatch(zColl, pIndex) ){
5061         int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
5062         sqlite3BeginWriteOperation(pParse, 0, iDb);
5063         sqlite3RefillIndex(pParse, pIndex, -1);
5064       }
5065     }
5066   }
5067 }
5068 #endif
5069 
5070 /*
5071 ** Recompute all indices of all tables in all databases where the
5072 ** indices use the collating sequence pColl.  If pColl==0 then recompute
5073 ** all indices everywhere.
5074 */
5075 #ifndef SQLITE_OMIT_REINDEX
5076 static void reindexDatabases(Parse *pParse, char const *zColl){
5077   Db *pDb;                    /* A single database */
5078   int iDb;                    /* The database index number */
5079   sqlite3 *db = pParse->db;   /* The database connection */
5080   HashElem *k;                /* For looping over tables in pDb */
5081   Table *pTab;                /* A table in the database */
5082 
5083   assert( sqlite3BtreeHoldsAllMutexes(db) );  /* Needed for schema access */
5084   for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
5085     assert( pDb!=0 );
5086     for(k=sqliteHashFirst(&pDb->pSchema->tblHash);  k; k=sqliteHashNext(k)){
5087       pTab = (Table*)sqliteHashData(k);
5088       reindexTable(pParse, pTab, zColl);
5089     }
5090   }
5091 }
5092 #endif
5093 
5094 /*
5095 ** Generate code for the REINDEX command.
5096 **
5097 **        REINDEX                            -- 1
5098 **        REINDEX  <collation>               -- 2
5099 **        REINDEX  ?<database>.?<tablename>  -- 3
5100 **        REINDEX  ?<database>.?<indexname>  -- 4
5101 **
5102 ** Form 1 causes all indices in all attached databases to be rebuilt.
5103 ** Form 2 rebuilds all indices in all databases that use the named
5104 ** collating function.  Forms 3 and 4 rebuild the named index or all
5105 ** indices associated with the named table.
5106 */
5107 #ifndef SQLITE_OMIT_REINDEX
5108 void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
5109   CollSeq *pColl;             /* Collating sequence to be reindexed, or NULL */
5110   char *z;                    /* Name of a table or index */
5111   const char *zDb;            /* Name of the database */
5112   Table *pTab;                /* A table in the database */
5113   Index *pIndex;              /* An index associated with pTab */
5114   int iDb;                    /* The database index number */
5115   sqlite3 *db = pParse->db;   /* The database connection */
5116   Token *pObjName;            /* Name of the table or index to be reindexed */
5117 
5118   /* Read the database schema. If an error occurs, leave an error message
5119   ** and code in pParse and return NULL. */
5120   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
5121     return;
5122   }
5123 
5124   if( pName1==0 ){
5125     reindexDatabases(pParse, 0);
5126     return;
5127   }else if( NEVER(pName2==0) || pName2->z==0 ){
5128     char *zColl;
5129     assert( pName1->z );
5130     zColl = sqlite3NameFromToken(pParse->db, pName1);
5131     if( !zColl ) return;
5132     pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
5133     if( pColl ){
5134       reindexDatabases(pParse, zColl);
5135       sqlite3DbFree(db, zColl);
5136       return;
5137     }
5138     sqlite3DbFree(db, zColl);
5139   }
5140   iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
5141   if( iDb<0 ) return;
5142   z = sqlite3NameFromToken(db, pObjName);
5143   if( z==0 ) return;
5144   zDb = db->aDb[iDb].zDbSName;
5145   pTab = sqlite3FindTable(db, z, zDb);
5146   if( pTab ){
5147     reindexTable(pParse, pTab, 0);
5148     sqlite3DbFree(db, z);
5149     return;
5150   }
5151   pIndex = sqlite3FindIndex(db, z, zDb);
5152   sqlite3DbFree(db, z);
5153   if( pIndex ){
5154     sqlite3BeginWriteOperation(pParse, 0, iDb);
5155     sqlite3RefillIndex(pParse, pIndex, -1);
5156     return;
5157   }
5158   sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
5159 }
5160 #endif
5161 
5162 /*
5163 ** Return a KeyInfo structure that is appropriate for the given Index.
5164 **
5165 ** The caller should invoke sqlite3KeyInfoUnref() on the returned object
5166 ** when it has finished using it.
5167 */
5168 KeyInfo *sqlite3KeyInfoOfIndex(Parse *pParse, Index *pIdx){
5169   int i;
5170   int nCol = pIdx->nColumn;
5171   int nKey = pIdx->nKeyCol;
5172   KeyInfo *pKey;
5173   if( pParse->nErr ) return 0;
5174   if( pIdx->uniqNotNull ){
5175     pKey = sqlite3KeyInfoAlloc(pParse->db, nKey, nCol-nKey);
5176   }else{
5177     pKey = sqlite3KeyInfoAlloc(pParse->db, nCol, 0);
5178   }
5179   if( pKey ){
5180     assert( sqlite3KeyInfoIsWriteable(pKey) );
5181     for(i=0; i<nCol; i++){
5182       const char *zColl = pIdx->azColl[i];
5183       pKey->aColl[i] = zColl==sqlite3StrBINARY ? 0 :
5184                         sqlite3LocateCollSeq(pParse, zColl);
5185       pKey->aSortFlags[i] = pIdx->aSortOrder[i];
5186       assert( 0==(pKey->aSortFlags[i] & KEYINFO_ORDER_BIGNULL) );
5187     }
5188     if( pParse->nErr ){
5189       assert( pParse->rc==SQLITE_ERROR_MISSING_COLLSEQ );
5190       if( pIdx->bNoQuery==0 ){
5191         /* Deactivate the index because it contains an unknown collating
5192         ** sequence.  The only way to reactive the index is to reload the
5193         ** schema.  Adding the missing collating sequence later does not
5194         ** reactive the index.  The application had the chance to register
5195         ** the missing index using the collation-needed callback.  For
5196         ** simplicity, SQLite will not give the application a second chance.
5197         */
5198         pIdx->bNoQuery = 1;
5199         pParse->rc = SQLITE_ERROR_RETRY;
5200       }
5201       sqlite3KeyInfoUnref(pKey);
5202       pKey = 0;
5203     }
5204   }
5205   return pKey;
5206 }
5207 
5208 #ifndef SQLITE_OMIT_CTE
5209 /*
5210 ** Create a new CTE object
5211 */
5212 Cte *sqlite3CteNew(
5213   Parse *pParse,          /* Parsing context */
5214   Token *pName,           /* Name of the common-table */
5215   ExprList *pArglist,     /* Optional column name list for the table */
5216   Select *pQuery,         /* Query used to initialize the table */
5217   u8 eM10d                /* The MATERIALIZED flag */
5218 ){
5219   Cte *pNew;
5220   sqlite3 *db = pParse->db;
5221 
5222   pNew = sqlite3DbMallocZero(db, sizeof(*pNew));
5223   assert( pNew!=0 || db->mallocFailed );
5224 
5225   if( db->mallocFailed ){
5226     sqlite3ExprListDelete(db, pArglist);
5227     sqlite3SelectDelete(db, pQuery);
5228   }else{
5229     pNew->pSelect = pQuery;
5230     pNew->pCols = pArglist;
5231     pNew->zName = sqlite3NameFromToken(pParse->db, pName);
5232     pNew->eM10d = eM10d;
5233   }
5234   return pNew;
5235 }
5236 
5237 /*
5238 ** Clear information from a Cte object, but do not deallocate storage
5239 ** for the object itself.
5240 */
5241 static void cteClear(sqlite3 *db, Cte *pCte){
5242   assert( pCte!=0 );
5243   sqlite3ExprListDelete(db, pCte->pCols);
5244   sqlite3SelectDelete(db, pCte->pSelect);
5245   sqlite3DbFree(db, pCte->zName);
5246 }
5247 
5248 /*
5249 ** Free the contents of the CTE object passed as the second argument.
5250 */
5251 void sqlite3CteDelete(sqlite3 *db, Cte *pCte){
5252   assert( pCte!=0 );
5253   cteClear(db, pCte);
5254   sqlite3DbFree(db, pCte);
5255 }
5256 
5257 /*
5258 ** This routine is invoked once per CTE by the parser while parsing a
5259 ** WITH clause.  The CTE described by teh third argument is added to
5260 ** the WITH clause of the second argument.  If the second argument is
5261 ** NULL, then a new WITH argument is created.
5262 */
5263 With *sqlite3WithAdd(
5264   Parse *pParse,          /* Parsing context */
5265   With *pWith,            /* Existing WITH clause, or NULL */
5266   Cte *pCte               /* CTE to add to the WITH clause */
5267 ){
5268   sqlite3 *db = pParse->db;
5269   With *pNew;
5270   char *zName;
5271 
5272   if( pCte==0 ){
5273     return pWith;
5274   }
5275 
5276   /* Check that the CTE name is unique within this WITH clause. If
5277   ** not, store an error in the Parse structure. */
5278   zName = pCte->zName;
5279   if( zName && pWith ){
5280     int i;
5281     for(i=0; i<pWith->nCte; i++){
5282       if( sqlite3StrICmp(zName, pWith->a[i].zName)==0 ){
5283         sqlite3ErrorMsg(pParse, "duplicate WITH table name: %s", zName);
5284       }
5285     }
5286   }
5287 
5288   if( pWith ){
5289     sqlite3_int64 nByte = sizeof(*pWith) + (sizeof(pWith->a[1]) * pWith->nCte);
5290     pNew = sqlite3DbRealloc(db, pWith, nByte);
5291   }else{
5292     pNew = sqlite3DbMallocZero(db, sizeof(*pWith));
5293   }
5294   assert( (pNew!=0 && zName!=0) || db->mallocFailed );
5295 
5296   if( db->mallocFailed ){
5297     sqlite3CteDelete(db, pCte);
5298     pNew = pWith;
5299   }else{
5300     pNew->a[pNew->nCte++] = *pCte;
5301     sqlite3DbFree(db, pCte);
5302   }
5303 
5304   return pNew;
5305 }
5306 
5307 /*
5308 ** Free the contents of the With object passed as the second argument.
5309 */
5310 void sqlite3WithDelete(sqlite3 *db, With *pWith){
5311   if( pWith ){
5312     int i;
5313     for(i=0; i<pWith->nCte; i++){
5314       cteClear(db, &pWith->a[i]);
5315     }
5316     sqlite3DbFree(db, pWith);
5317   }
5318 }
5319 #endif /* !defined(SQLITE_OMIT_CTE) */
5320