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