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