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